reformat

package
v0.7.4-beta.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 19 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package reformat holds the lossless components (they repack the request denser or add caching hints without losing information). Each registers via init(); a binary blank-imports components/all to pull them in.

Index

Constants

View Source
const LookbackBlocks = schema.LookbackBlocks

LookbackBlocks is kept for importers; use schema.LookbackBlocks.

Variables

This section is empty.

Functions

func CompactToolSchemas added in v0.1.1

func CompactToolSchemas(body []byte) ([]byte, bool)

CompactToolSchemas strips JSON-Schema annotation keywords from every tool's `input_schema` in a raw request body. Returns the rewritten body and whether anything changed; any parse problem returns the input untouched (fail open).

Deterministic and memoized by digest of the incoming `tools` array — 31 schemas per call on real traffic, and the array is byte-identical on every turn of a session, so the walk runs once per distinct catalogue rather than once per request.

func FoldSearchOutput added in v0.1.1

func FoldSearchOutput(s string) string

FoldSearchOutput returns the candidate fold with the fewest tokens whose inverse reproduces s exactly, or s itself when none of them wins. Exported so a measurement harness can run the transform over captured output without a request around it.

The pick between survivors is by TOKEN count, with byte length breaking ties only. Bytes are a proxy and tokens are the thing this component exists to save, and the two survivors can disagree about the winner: a long single-character directory run is byte-heavy and token-sparse, so factoring it out (foldHitDir) wins bytes while the heading-per-file fold (foldHitPath) wins tokens. Picking by bytes returned the token-worse of the two whenever that divergence appeared, so tokens lead here. A fold that shrinks bytes but grows tokens never wins the pick.

Types

type Cacheinject

type Cacheinject struct {
	// TTL is the cache lifetime to request: "5m" (default) or "1h".
	//
	// Leave it at 5m unless the deployment shape demands otherwise. By rule 2, a 1h
	// write costs 2.0x instead of 1.25x and only pays when p = P(the entry lapses
	// before its next reuse) exceeds (2.0-1.25)/(1.25-0.1) = 65.2%.
	//
	// The denominator is the 5m WRITE rate minus the read rate, not 1 minus the read rate.
	// A lapsed entry does not re-bill at the fresh 1.0x: those tokens still carry
	// cache_control, so the provider CREATES a new entry at 1.25x. Production ttl_expiry
	// rows show it directly — cache_write averages 178,793 against fresh_input 1,712. The
	// documented figure was 83.3%, wrong by 18 points; the conclusion is unchanged. Two
	// things make p
	// small in practice: agent turns are seconds apart (measured median 7.6 s over
	// 1,905 real turns), and every READ refreshes the TTL for free — so a shared
	// prefix touched by any session at least once per 5 minutes never lapses. On the
	// benchmark sweep a new task started every ~2.3 minutes, so 5m was strictly
	// correct.
	//
	// Set "1h" when reuse is genuinely sparse: low-concurrency sweeps with long
	// tasks (task starts more than 5 minutes apart), or a deployed agent handling a
	// few sessions per hour. That is a property of the traffic, not of the code,
	// which is why it is configuration rather than a heuristic.
	TTL string `yaml:"ttl"`
}

Cacheinject places Anthropic-family `cache_control` breakpoints so the provider's KV cache is read rather than re-processed. It is a Reformat: it adds control directives, changes no model-visible content, and loses nothing.

The placement is the solution to the billed-cost minimisation, not a heuristic. Writing R=0.1, W=1.25 and plain=1.0 for the read / 5m-write / uncached multipliers, four facts decide everything:

  1. A token resent even once is cheaper written than not: W+kR < 1+k for k > (W-1)/(1-R) = 0.28. So the LAST block always gets a breakpoint.
  2. Writes are billed as a SPAN — (highest breakpoint − read point) — not per breakpoint. An extra breakpoint BELOW the top therefore costs exactly zero, and only adds a position a later turn's backward walk can land on. So never leave one of the four slots idle.
  3. The big lever is DIVERGENCE, not position. If this turn differs from the previous one at message d, every block above d is unmatchable: a trailing-only breakpoint finds nothing and the whole prefix bills at 1.0x instead of 0.1x — a 10x penalty. A breakpoint at d−1 recovers it.
  4. Anchors must sit at TURN-STABLE indices. A position is only readable on turn t+1 if it was written on turn t, so an anchor counted back from the end lands on a different message each turn and is never pre-warmed.

v1 placed a single breakpoint on the message BEFORE the newest turn, which by construction shortens the cached prefix every turn: measured +5.5% on captured SWE-bench traffic, and +9.2% when layered on an agent that already sets its own breakpoints. v2 keeps every breakpoint the caller set (so a well-behaved agent is never made worse), then spends only the leftover slots.

1h TTL is deliberately never used. It costs 2.0x instead of 1.25x to write and only pays when p = P(gap > 5 min) exceeds (2.0−1.25)/(1.25−0.1) = 65.2%. Measured over 1,905 real agent turns: p = 0.00% (median gap 7.6 s, max 75 s). 1h is for human-in-the-loop sessions, not for an autonomous agent loop.

func (Cacheinject) Enabled

func (Cacheinject) Enabled(c *components.Ctx) bool

func (Cacheinject) Name

func (Cacheinject) Name() string

func (Cacheinject) Reformat

type Cachesplit added in v0.1.1

type Cachesplit struct{}

Cachesplit is a marker component: it carries no logic of its own, and exists so a preset can enable the volatile-tail split (apply/prefixsplit.go) WITHOUT also enabling cacheinject's breakpoint placement.

The two were one config entry until #32, which separated them because their evidence is not comparable. The split is measured: −34.1% cost and 0% → 96.7% cache hit in an isolated A/B, because it moves a churning env snapshot out of a hashed prefix. Placement has never been measured at all — until #32 its breakpoints never reached the provider. So the split ships on by default and placement does not.

It is a Reformat that always skips: the actual rewrite is body-level (it edits the top-level `system` array, which components never see) and lives in `apply`, gated on this name being present. ponytail: a marker beats plumbing a new config flag through every host.

func (Cachesplit) Enabled added in v0.1.1

func (Cachesplit) Enabled(*components.Ctx) bool

func (Cachesplit) Name added in v0.1.1

func (Cachesplit) Name() string

func (Cachesplit) Reformat added in v0.1.1

Reformat is intentionally a no-op — see the type doc. The split happens in apply, which reports it here through Ctx.SystemSplit.

That flag is the whole reason this method is not a bare `rep.Skipped = true`. Every consumer of a component report — /stats, the Prometheus component counters, the dashboard's components table — answers "did this component do anything?" from Skipped. Reporting it unconditionally made the measured -34.1%-cost mechanism read "declined" on the requests where it had just run.

The dashboard's prefix-cache saving no longer reads this flag: it is priced from apply.Trace.SplitStableTokens, the size of the half the split moved, which is set on exactly the same requests and also says HOW MUCH. Keeping the report honest still matters for everything above, and for anyone comparing the two.

It is Mutated but never Acted: the split removes no content tokens, it moves them out of the hashed prefix. cacheinject reads the same way, and the dashboard has a verdict for it.

type Format

type Format struct {
	// contains filtered or unexported fields
}

Format re-encodes JSON tool outputs denser without losing data (a Reformat): pretty-printed JSON is re-marshaled compact. It's strictly lossless — same value, fewer whitespace tokens — so no stash is needed. (For a denser tabular re-encoding of uniform object arrays, see the `toon` component.)

It also descends one level into a tool-runner envelope (see descendEnvelope): the payload usually lives JSON-escaped inside a string field, where re-encoding only the envelope wins nothing.

func (Format) Enabled

func (Format) Enabled(*components.Ctx) bool

func (Format) Name

func (Format) Name() string

func (*Format) Reformat

func (f *Format) Reformat(req *schemas.BifrostChatRequest, rep *components.Report, _ *components.Ctx) error

type Searchfold added in v0.1.1

type Searchfold struct {
	// contains filtered or unexported fields
}

Searchfold folds the repeated path prefix out of search output — `rg`/`grep -rn` hit lists, `find`/`ls -1`/`rg -l` path lists — by emitting each path (or parent directory) once as a heading and the rows beneath it:

pkg/a.go:12:foo          pkg/a.go
pkg/a.go:31:foo    =>    12:foo
pkg/b.go:7:foo           31:foo
                         pkg/b.go
                         7:foo

It is a Reformat, so it must be lossless — and it is lossless BY CONSTRUCTION rather than by argument: every fold has an exact inverse, and a fold is adopted only if applying that inverse reproduces the input BYTE FOR BYTE and the result is smaller in tokens, with bytes breaking ties (see FoldSearchOutput). Anything else returns the input unchanged. No path, line number or line is ever dropped, so there is nothing to stash and no marker.

Cache safety: the fold is a pure function of the message's own text, so a message that reappears on the next turn folds to the same bytes. The already-cached prefix is byte-stable and no cached position is re-anchored, which is the same argument the other in-place components (format, toon, cmdfilter) rely on — hence no TailOnly gate, which would only make the FIRST turn's fold differ from later turns'.

Routing: none. The fold is ATTEMPTED on every tool output, and it self-verifies, so a misroute costs CPU and never correctness.

It used to pre-gate on the producing command (`rg`/`grep`/`find` folded, `cat`/build/test skipped) via schema.ToolCalls. Measured on 1,795 real captured requests through /compact, that gate was a strict loss on both axes it was supposed to trade between:

            tokens folded   unique   searchfold ms/request
with gate         234,722    5,395                   1.174
no gate           333,764    5,903                   0.509

It declined 29,737 candidate messages, and 99,042 tokens' worth of them had exactly the repeated path prefix this folds — the pairing says which command ran, not what its output looks like, and agents pipe and redirect search output through everything. It was also the more expensive path: resolving a pairing calls ToolCall.Command(), which json.Unmarshals the whole argument object per tool message, where the fold itself exits on its first line without a repeated prefix.

This is the general rule for a self-verifying fold: attempt it, keep it if the inverse reproduces the input and the result is smaller. What it does NOT license is attempting it on content that cannot possibly fold — each fold splits and rebuilds the whole string before `adopt` compares lengths, so there is no early exit and an attempt costs a full pass (measured on non-foldable output: 275 µs at 24 KB, 1.73 ms at 240 KB, 8.16 ms at 1.2 MB). So a cheap SHAPE pre-check still earns its keep, the way `format`'s not_json_shaped does — see mayCarryPathPrefix. What does not earn its keep is a pre-check that has to reconstruct request STRUCTURE, which is what the command pairing this replaced did.

func (Searchfold) Enabled added in v0.1.1

func (Searchfold) Enabled(*components.Ctx) bool

func (Searchfold) Name added in v0.1.1

func (Searchfold) Name() string

func (*Searchfold) Reformat added in v0.1.1

type TextClean added in v0.1.1

type TextClean struct {
	// contains filtered or unexported fields
}

TextClean is the lossless Reformat for PLAIN TEXT — the shape most agent tool output actually has (measured: 1,724 of 1,748 distinct tool outputs across every capture on this box are not JSON at all, so `format` and `toon` never see them). It removes three kinds of pure display noise and nothing else:

  • ANSI/VT100 escape sequences — terminal colour and cursor control, never content;
  • carriage-return redraws — a line rewritten in place by \r never displayed its earlier bytes, so keeping only the final rendered segment loses nothing the agent ever saw (a trailing \r is a CRLF separator, NOT a redraw, and is preserved).

Both transforms already existed in `extract` (an Offload), which charged them a <<cg:HASH>> marker, a stash and a 300–400 token floor: most output paid an offload price for what is a pure lossless reformat, and anything under the floor paid nothing because it was declined. As a Reformat this needs no marker, no stash and no floor, and it is a pure function of the content, so it is byte-stable across turns and process restarts — the same cache posture as `format`.

What it deliberately does NOT do. Dropping progress-bar lines and collapsing repeated lines or blocks remove real lines, so they need extract's stash to be recoverable. Trimming trailing whitespace changes meaning in a unified diff (a context line whose only content is the leading space) and in markdown (the two-space line break). Collapsing runs of blank lines is safe but MEASURED WORTHLESS: over 1,748 real tool outputs it saved 21 tokens in total, against 16,721 for the ANSI strip and 498 for the redraws (TestCorpusMeasureTextCleanBreakdown keeps that measurement runnable), so it is not worth the line of code or the argument about whether padding is content.

func (TextClean) Enabled added in v0.1.1

func (TextClean) Enabled(*components.Ctx) bool

func (TextClean) Name added in v0.1.1

func (TextClean) Name() string

func (*TextClean) Reformat added in v0.1.1

type Toolfilter added in v0.1.1

type Toolfilter struct {
	// contains filtered or unexported fields
}

Toolfilter is a marker component holding the opt-in list: `tools` is a top-level body field the pipeline never sees (components operate on `messages`), so the rewrite lives in apply — the same arrangement toolschema and cachesplit use. apply reads the list back through Removed().

The skills half lives there too, for a different reason: the listing IS in `messages`, but it sits in the cached prefix, and every rewrite of the prefix has to happen before any byte offset into the body is taken. Same place, same list, same counters. See apply.filterSkillListing.

func (Toolfilter) AlwaysDefer added in v0.6.7

func (t Toolfilter) AlwaysDefer() []string

AlwaysDefer is the account always-defer list for deferral, sorted (#878).

func (Toolfilter) Defers added in v0.6.6

func (t Toolfilter) Defers() bool

Defers reports whether tool deferral is on (`defer: auto`). The host reads it.

func (Toolfilter) Enabled added in v0.1.1

func (Toolfilter) Enabled(*components.Ctx) bool

func (Toolfilter) Keep added in v0.6.6

func (t Toolfilter) Keep() []string

Keep is the account keep list for deferral, sorted.

func (Toolfilter) Name added in v0.1.1

func (Toolfilter) Name() string

func (Toolfilter) Reformat added in v0.1.1

Reformat is a no-op: the rewrite already happened in apply, which reports it here through Ctx.FilteredDecls so this component does not read "declined" on the requests where it just acted — the mistake cachesplit's doc records.

func (Toolfilter) Removed added in v0.1.1

func (t Toolfilter) Removed() []string

Removed is the opt-in list, sorted. apply calls it; nothing else should.

type Toolschema added in v0.1.1

type Toolschema struct{}

Toolschema is a marker component: `tools` is a top-level body field the pipeline never sees (it operates on `messages`), so the rewrite lives in apply and is gated on this name being present — the same arrangement cachesplit uses for the system-array split. See CompactToolSchemas for the mechanism and the break-even.

func (Toolschema) Enabled added in v0.1.1

func (Toolschema) Enabled(*components.Ctx) bool

func (Toolschema) Name added in v0.1.1

func (Toolschema) Name() string

func (Toolschema) Reformat added in v0.1.1

Reformat is a no-op: the rewrite already happened in apply, which reports it here through Ctx.ToolSchema so this component does not read "declined" on the requests where it just ran (the mistake cachesplit's doc records).

type Toon

type Toon struct {
	// contains filtered or unexported fields
}

Toon re-encodes a JSON array of uniform, flat objects as TOON (Token-Oriented Object Notation): one header listing the field names once, then one comma-separated row per element. It drops the braces, repeated keys, and quotes that dominate a JSON array's token cost. It's a Reformat (repack in place, nothing stashed), so it must be LOSSLESS: every scalar value is preserved and stays distinguishable from every other. Ambiguity is resolved by QUOTING, not by refusing: a string that would read back as a number or a bool is quoted ("1"), a bare empty cell is null and `""` is the empty string (see scalarCell for the full cell grammar). Arrays are encoded when the element key sets match and every value is a scalar; anything nested or non-array is left untouched. Every candidate table is decoded again before it is adopted (decodeTOON) and dropped unless it reproduces the input exactly, and the pipeline's never-worse guard reverts any case that fails to shrink.

[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
=>
[2]{id,name}:
1,Alice
2,Bob

The array is rarely at the top level of a tool result: it usually sits inside a tool-runner envelope's string field (see descendEnvelope and encodeTOONIn), which is why toon looked inert on real traffic.

func (Toon) Enabled

func (Toon) Enabled(*components.Ctx) bool

func (Toon) Name

func (Toon) Name() string

func (*Toon) Reformat

func (t *Toon) Reformat(req *schemas.BifrostChatRequest, rep *components.Report, _ *components.Ctx) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL