Documentation
¶
Overview ¶
Package expand holds the host-agnostic half of reversibility (design D6, after headroom's CCR): the marker format Offload components write, the expand(id) tool definition injected per provider, and resolution of a stashed original from the Store.
The continuation LOOP that actually answers an expand tool call is host glue (the bifrost proxy wraps its chat route; a sidecar plugin does it in OnResponse) — but every host reuses ParseMarkers, ToolDef, and Resolve from here so the wire contract stays identical across integrations.
Index ¶
- Constants
- func AggregateSSE(provider string, raw []byte) (msg []byte, ok bool)
- func AnchorPoint(wire string, body []byte) (at int, fp string, ok bool)
- func Continuation(provider string, reqBody, resp []byte, resolved map[string]string) ([]byte, bool)
- func Fingerprint(msg gjson.Result) string
- func HasMarkersInMessages(body []byte) bool
- func HasPlaceholder(s string) bool
- func HasTool(provider string, body []byte) bool
- func Inject(provider, mode string, body []byte, storePersists bool) (out []byte, injected bool)
- func InsertRestored(wire string, body []byte, ins []Insertion) ([]byte, bool)
- func Marker(key string) string
- func MessagesField(wire string) string
- func NoteUnresolved(id string)
- func ParseMarkers(s string) []string
- func RecordAnchor(st store.Store, session string, a Anchor)
- func RepairToolResults(provider string, body []byte, resolve func(id string) (string, bool)) (out []byte, restored []string)
- func ResetUnresolvedForTest()
- func Resolve(s store.Store, key string) (string, bool)
- func Restorable(wire, original string) bool
- func RestoredInPlace(hashID string) string
- func RestoredText(id, original string) string
- func ToolDefRaw(provider string) json.RawMessage
- func Unavailable(hashID string) string
- func Unresolved() (malformed, missing int64)
- func WellFormedID(id string) bool
- type Anchor
- type Call
- type CallSite
- type Insertion
Constants ¶
const ( InjectAuto = "auto" InjectAlways = "always" InjectNever = "never" )
InjectMode controls whether the expand tool is advertised on outgoing requests.
"auto" (default): inject whenever the request already declares tools AND the store can persist stashes. Both conditions are properties of the SESSION, not of the turn, so the `tools` array a session sends is byte-identical on every request in it.
That stability is the whole point. `tools` sits ahead of `system` and `messages` in the provider's cache hash, so a change to the array cannot be cached against the old prefix: the first request carrying a NEW tools array re-creates the ENTIRE prefix at the write rate, not just the tail. This condition used to also require that the request carry an expandable marker, which made advertising a property of the turn: the array grew on the first turn that offloaded and shrank again on any later turn that carried no marker.
MEASURED, and narrower than an earlier version of this comment claimed. Direct probe, byte-identical 9.5k-token system block, only `tools` changed: A->A read 9,471 / write 0; A->B write 9,558 / read 0 — the whole prefix. But A->B->A->B then reads on all three, because the provider keeps BOTH lineages alive within the TTL. So the cost is ONE full-prefix write per NEW tools variant, plus a doubled write delta while it alternates — not a full miss on every flip in both directions, which is what this comment used to say.
On a real 7-turn Claude Code session the old build flipped once, at the turn the first dedup marker appeared: tools 20->21, that turn billed write 43,359 / read 0 against the 40,320-token prefix the first three turns had built ($0.0824 against $0.0071 for a comparable turn with no flip). After the fix, one tools hash across all 7 turns and that turn billed write 163 / read 43,135. Paired sessions, run in both arm orders: input cost $0.212401 -> $0.137185, a 35.4% and 35.3% saving on 0.1 pp of spread, with total input tokens up 313 — the same bytes, moved from 1.25x to 0.1x. The tool declaration's own cost is +129 tokens on the first write, included in those figures. A session that never offloads saves nothing.
It never perturbs a request that uses no tools — the riskiest case for models that penalize an unexpected tool — because `hasTools` is still required. What it DOES do is advertise on a request with nothing to expand, which is safe now for a reason that is elsewhere: an expand call that resolves nothing is answered with a placeholder tool_result and the turn completes normally (proxy.serve). It used to replay the model's raw tool_use to the client instead, which on an agent's own compaction request reads as "the summary came back empty" — three of those in a row and Claude Code disables auto-compact for the session. THAT is what the marker condition was really protecting against, and it was protecting against it in the wrong place: at the advertisement, at the cost of the prefix, rather than at the resolution, which costs one bounded round trip and only when a model asks for an id that has aged out.
"always": inject whenever the store persists, creating the tools array if absent. Differs from auto only for a request that declares NO tools, which is the case auto deliberately leaves alone.
"never": never inject (the pre-D2 behavior; pair with marker_mode: summary).
const SummaryMarker = "⟪cg⟫"
SummaryMarker is the non-resolvable sentinel an Offload component writes under marker_mode "summary": it signals "content was compacted here" — to the model and to cross-turn skip-detection — but carries no store key, so there is nothing to expand (restoration is off). The human-readable description of what was dropped stays inline in the message (the component's own note).
const ToolName = "context_guru_expand"
ToolName is the model-callable tool that retrieves offloaded content.
Variables ¶
This section is empty.
Functions ¶
func AggregateSSE ¶
AggregateSSE reconstructs the final provider message JSON from a buffered Server-Sent Events stream, so the expand loop can inspect it with ResponseCalls / Continuation (which operate on the non-streaming response shape). ok=false when the stream can't be reconstructed (unknown dialect / malformed) — the caller then streams the bytes through unchanged (fail-open).
Only the Anthropic Messages event stream is reconstructed (the streaming coding agents in scope use it). For other dialects it returns ok=false.
func AnchorPoint ¶ added in v0.5.0
AnchorPoint is the anchor for an expand answered INSIDE this request (the in-band continuation): right after the request's last message, which is where the model's reply — the turn that expanded — will sit in the client's next request. body is the request as the client sent it. ok is false when the transcript is not one an anchor can be stated in.
func Continuation ¶
Continuation builds the next request body: it appends the assistant's tool-call turn and a tool_result turn carrying each resolved original, so the model can finish with the full content in hand. resolved maps CallID -> original text. ok=false if the shapes weren't as expected (caller returns the response unchanged — fail open).
func Fingerprint ¶ added in v0.5.0
Fingerprint identifies one wire message independently of what a client changes on an old message without changing what the model reads: the hash of its canonical form (schema.CanonicalWireMessage, #783).
`cache_control` is excluded because it marks the LAST message of each request, so the message an anchor points at carries it on the turn the anchor is recorded and not afterwards. A content of one plain text block reads as its string because Claude Code sends that same message as a string once a later turn follows it (seen on 2.1.312 in the #485 probes). Everything else must match. Keys are sorted, so the client's key order does not count. Numbers are kept as their literal text: decoded as float64, two integers above 2^53 that differ would read as one, and so would the two messages.
A stored fingerprint is compared with fingerprintMatches, not with ==.
func HasMarkersInMessages ¶ added in v0.1.1
HasMarkersInMessages reports whether a request body carries a context-guru marker in its MESSAGES.
It no longer gates injection. It was the "auto" advertise condition until the tools array's byte-stability was found to be worth more than the condition bought: a per-turn advertise test makes the array a per-turn value, and `tools` sits ahead of everything in the provider's cache hash. Kept because it is exported and answers a question callers still legitimately ask — "is there anything here to expand?" — but a caller using it to decide whether to DECLARE the tool is reintroducing that miss. Original doc follows.
HasMarkersInMessages reports whether a request body carries a context-guru placeholder in content the MODEL can see and reference — the messages array and the system prompt.
It deliberately does NOT scan the whole body. The `tools` array holds our own injected expand tool, whose description quotes the marker syntax ("…replaced by a <<cg:HASH>> marker"), HTML-escaped by ToolDefRaw's encoding/json. A whole-body check therefore matched the tool we had just injected and was a tautology: every request looked marker-bearing, so every streaming response was fully buffered and the documented zero-added-latency fast path never engaged. Requiring the full marker shape is not sufficient on its own — the tool description contains the full shape too. Scoping to model-visible content is what fixes it.
func HasPlaceholder ¶
HasPlaceholder reports whether s already carries a context-guru placeholder — a resolvable <<cg:HASH>> marker (full mode) OR a SummaryMarker sentinel (summary mode). Components use it to skip content an earlier component/turn already reduced, so a later turn re-sending the same message reduces to the same bytes (provider prefix-cache stays warm).
func HasTool ¶ added in v0.1.1
HasTool reports whether body's tools array already declares the expand tool. It is the ADVERTISE test: a host must intercept expand calls exactly when this is true, or it either declares a tool whose use it ignores (the call reaches a client that has no such tool) or pays to inspect responses that cannot contain one.
func Inject ¶
Inject appends the expand tool definition to the request body's tools array in a byte-stable way, so a model that offloaded content can call context_guru_expand to get it back (closing the reversibility loop the proxy's continuation handler drives).
It is idempotent (a request that already declares the tool is returned unchanged), appends the tool LAST so the client's own tools keep their exact order and the provider prefix cache stays warm, and respects a forcing tool_choice (skips, so it never changes which tool the model is compelled to call). Fail-open: any error returns the original body with injected=false.
func InsertRestored ¶ added in v0.5.0
InsertRestored splices the restored copies into body's transcript, each before the message at its At (or at the end, for At == len). Insertions sharing an index keep their given order. Every other message keeps its exact bytes. ok is false, with body unchanged, on any shape it cannot splice.
func MessagesField ¶ added in v0.5.0
MessagesField is the body field where a dialect keeps its transcript: Responses `input`, every other dialect `messages`. The one definition the anchor code and apply share.
func NoteUnresolved ¶ added in v0.1.1
func NoteUnresolved(id string)
NoteUnresolved classifies one failed resolution and counts it. Exported because both halves of reversibility reach it — the request-path repair in this package, and the proxy's response-side continuation loop — and a defect counted in only one of them would read as half as bad.
func ParseMarkers ¶
ParseMarkers returns the distinct store keys referenced by any markers in s, in first-seen order.
func RecordAnchor ¶ added in v0.5.0
RecordAnchor stores a for session, unless an anchor for the same id is already recorded: the FIRST place the content came back is where it stays, so a repeated expand of the same id does not move it.
func RepairToolResults ¶ added in v0.1.1
func RepairToolResults(provider string, body []byte, resolve func(id string) (string, bool)) (out []byte, restored []string)
RepairToolResults answers, on the way UPSTREAM, an expand call the CLIENT had to answer itself.
No client implements context_guru_expand: it is this proxy's tool, advertised by this proxy, and this proxy's marker text is what tells the model to call it. So a client that receives the call answers with its own error — Claude Code's is `<tool_use_error>Error: No such tool available: context_guru_expand</tool_use_error>` — and the model concludes the content it asked for cannot be had.
The response side intercepts the call wherever it can (see proxy/ssepeek.go), but some cases are structural: the model batched expand with a tool only the client owns, the continuation round cap, an event stream that will not reconstruct, and a bypassed request carrying markers minted on an earlier turn. Every one of them ends up here, on the next request, which is the single place all of them pass through — so there is one repair rather than six.
resolve returns the stored original for a marker id; ids it cannot resolve get Unavailable, which at least tells the model the content aged out instead of inviting it to retry a tool that "does not exist". restored holds the originals actually recovered, for the caller's accounting.
It is deliberately idempotent and byte-stable: the client keeps its own copy of the error, so the same transcript arrives needing the same repair on every later turn, and repairing it to the same bytes each time is what keeps the provider's prefix cache warm.
func ResetUnresolvedForTest ¶ added in v0.6.2
func ResetUnresolvedForTest()
ResetUnresolvedForTest zeroes both counters. They are process-global, and the proxy's test binary records real failures into them (TestExpandUnresolvedSeriesRender does, on purpose) — so a `-count>1` run would see iteration 2 start from iteration 1's counts and fail on its at-zero assertions.
func Resolve ¶
Resolve returns the original stashed under key, or ("",false) if it's gone (expired/evicted). Callers must handle the miss gracefully — an expired original silently turns a lossless offload lossy (headroom's known TTL edge).
func Restorable ¶ added in v0.5.0
Restorable reports whether original can be restored as a text message on wire.
func RestoredInPlace ¶ added in v0.2.0
RestoredInPlace is what a repaired tool_result carries INSTEAD of a second copy of the content.
The repair used to write the original into the tool_result, and the same call marks that content kept-verbatim — so the offloaders also leave the ORIGINAL message uncompacted at its own position. Both mechanisms are individually right and together they sent the tool output UPSTREAM TWICE, on every turn, for the rest of the session. Measured on a 200-line output through the codesafe preset: 252 bytes when the content is compacted and no expand round-trip exists, against 21,511 bytes with one — two full copies, permanently. That is far larger than the one-off prefix flip #201 describes, and it is why this is a defect and not a preference.
The note names the id, so it is accurate either way: the content is in the transcript above, verbatim if kept-verbatim held, and behind a resolvable marker if it did not. It cannot go stale, because MarkKeptVerbatim is re-applied for every restored original on every repair turn BEFORE the pipeline reads the transcript — the same call that writes this note re-establishes the mark.
func RestoredText ¶ added in v0.5.0
RestoredText is the restored copy as the model reads it: the marker it expanded, said to be answered, then the original. A pure function of (id, original), so every turn inserts the same bytes.
func ToolDefRaw ¶
func ToolDefRaw(provider string) json.RawMessage
ToolDefRaw returns the expand tool definition for a provider as deterministic JSON bytes (stable key order). Inject appends these to the request's tools array.
func Unavailable ¶ added in v0.1.1
Unavailable is what a caller substitutes for an id the store no longer holds. One string for both halves of reversibility — the continuation loop and RepairToolResults — because an aged-out stash must read the same to the model however it was noticed.
func Unresolved ¶ added in v0.1.1
func Unresolved() (malformed, missing int64)
Unresolved returns (malformed, missing) counts for marker ids that resolved to nothing.
`missing` is the alertable one. Non-zero means this proxy removed content, told the model it could have it back, and then could not produce it.
func WellFormedID ¶ added in v0.1.1
WellFormedID reports whether id has the shape of a marker id this proxy mints, i.e. whether an unresolved lookup for it is a context-guru defect rather than a model invention.
Deliberately conservative in the direction that matters: an id this returns false for is counted as the model's fault, so a shape check that is too NARROW hides our own defects. Hence the tested round-trip against the minters rather than a hand-maintained pattern.
Types ¶
type Anchor ¶ added in v0.5.0
type Anchor struct {
// ID is the marker id the agent expanded; its stash holds the original.
ID string `json:"id"`
// At is the client message index the restored copy is inserted BEFORE: the first message
// after the turn that expanded it. At == len(messages) appends.
At int `json:"at"`
// Fp fingerprints the client message at At-1, so a transcript that no longer has that
// message there (the agent's own compaction, /compact, an edited history) is recognised
// and the anchor is not used.
Fp string `json:"fp"`
}
Anchor is one restored original's fixed place in a session's transcript.
type Call ¶
Call is one model request to expand offloaded content: CallID identifies the tool call (for the continuation's tool_result), HashID is the store key.
func ResponseCalls ¶
func ResponseCalls(provider string, resp []byte, otherProxyTools ...string) (calls []Call, otherTools bool)
ResponseCalls parses a provider response for expand tool calls. otherTools is true if the model also called some OTHER tool — in that case the host cannot safely auto-continue (the client must resolve the other tools), so the loop bails and returns the response as-is. otherProxyTools are additional names the caller owns. otherTools means "a tool the CLIENT implements", which is what makes the response loop hand the turn over untouched — so a second proxy-injected tool counted as "other" caused the loop to bail and stream that proxy tool_use to the client. Variadic so the existing callers, which advertise only expand, are unchanged.
type CallSite ¶ added in v0.5.0
type CallSite struct {
ID string
// At is the index of the message holding the call.
At int
// Answer is what the transcript now carries as that call's result, after the repair.
Answer string
}
CallSite is one context_guru_expand call the CLIENT received and answered (the repair path, RepairToolResults): the assistant message holding the call is the turn that expanded, so the anchor sits right before it.