Documentation
¶
Overview ¶
Package apply is the one place the pipeline meets a raw wire request, shared by every host adapter (the bifrost proxy and the AuthBridge plugin). It extracts the messages array, runs the pipeline on it, and splices the result back into the original body — byte-lossless for every other field (headroom invariant I1). This is what makes "one implementation behind both integrations" concrete: hosts differ only in how they obtain the body, provider, and session id.
Provider normalization. Components operate on OpenAI-shaped tool outputs (role=="tool" messages with string content). The Anthropic Messages API instead carries tool outputs as `tool_result` content blocks INSIDE user messages — a shape bifrost's ChatContentBlock cannot even represent (it drops the payload on unmarshal). So for Anthropic requests we expand each tool_result block into a synthetic role=tool message the existing components already know how to shrink, run the pipeline, then splice each rewritten tool output back into its exact source block via sjson. Everything the pipeline did not touch stays byte-identical.
Index ¶
- Constants
- func Body(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func BodyFull(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func BodyWithModel(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func BodyWithModelWindow(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- type Breakpoints
- type Change
- type Opts
- type Result
- type Trace
Constants ¶
const ( TTLEphemeral5m = "ephemeral_5m" TTLEphemeral1h = "ephemeral_1h" )
TTL tier names, as the provider names them. These are the strings the dashboard stores and groups by, so they are the provider's own vocabulary rather than ours.
const TraceTextCap = 4000
TraceTextCap bounds Change.Before/After — the copy of the text that goes into a trace or a dashboard row. It is NOT a cap on the message: the pipeline rewrote the whole thing, and BeforeTokens/AfterTokens are counted on the FULL string, so a Change can legitimately report 2,658 tokens next to 4,000 bytes of text. clip() appends a visible "…[+N bytes]" so a reader is told, and the original is recoverable through the expand tool when the after-text carries a <<cg:HASH>> marker.
It is exported because it is the cap that actually binds. apply is an importable library — the bifrost plugin embeds it and has its own reason to bound trace size — so an embedder that stores these rows must be able to report the EFFECTIVE limit rather than assert its own, larger one. dash does exactly that for content_cap_bytes.
Variables ¶
This section is empty.
Functions ¶
func Body ¶
func Body(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool) ([]byte, bool)
Body runs the pipeline with no LLM clients available (deterministic components only). See BodyWithModel to supply model clients for LLM-based components.
func BodyFull ¶
func BodyFull(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool, models components.ModelSpec, window int, cacheMode string) ([]byte, bool)
BodyFull is BodyWithModelWindow plus the cache mode ("auto"|"on"|"off", default "auto") controlling cache-aware compaction. "auto" turns on cache-awareness when the backend is a prompt-caching provider or the request already carries cache_control breakpoints; "on" forces it; "off" restores the legacy compact-everything behavior (correct for confirmed non-caching backends).
func BodyWithModel ¶
func BodyWithModel(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool, models components.ModelSpec) ([]byte, bool)
BodyWithModel runs the pipeline over the request body's messages and returns the rewritten body. changed=false means "forward the original unchanged" (no messages array, unparseable, or a re-serialization problem) — always fail open. explicitSession is the host-supplied session id ("" -> content hash). models carries the LLM clients that NeedsModel components may call.
func BodyWithModelWindow ¶
func BodyWithModelWindow(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool, models components.ModelSpec, window int) ([]byte, bool)
BodyWithModelWindow is BodyWithModel plus the model's resolved context window (max input tokens, 0 = unknown) so fraction-based Trigger thresholds can scale with the model. Hosts that resolve the window (the proxy, via internal/modelinfo) call this; window=0 reproduces the pre-D3 behavior exactly.
Types ¶
type Breakpoints ¶ added in v0.1.1
type Breakpoints struct {
System int // system.#.cache_control / .cachePoint
Tools int // tools.#.cache_control / .cachePoint
Messages int // messages.#.cache_control (message level)
Blocks int // messages.#.content.#.cache_control / .cachePoint (content-block level)
}
Breakpoints is where a request's prompt-cache breakpoints actually sit, split by the location the provider hashes them at. The split is what makes the count diagnosable rather than merely a number: `tools` and `system` render AHEAD of `messages`, so a breakpoint's location decides how much of the prefix it protects, and a dashboard that reports only a total cannot tell a well-placed request from a badly-placed one with the same count.
func CountBreakpoints ¶ added in v0.1.1
func CountBreakpoints(body []byte) Breakpoints
CountBreakpoints counts every breakpoint the provider will see in this request, by location. Structural (a field, per gjson) for the same reason hasCacheBreakpoint is: a tool output whose text merely contains the string "cache_control" must not count.
A component cannot count these for itself. `system` and `tools` never reach it at all, and the `tool_result` blocks this package normalizes into synthetic role=tool messages lose their mark on the way in (see toolMessage) — so on real Claude Code traffic all three of the agent's own breakpoints were invisible to it (2 in `system`, 1 on a `tool_result` block), and it computed 3 free slots when 1 was free: 6 on the wire, and a 400 (issue #32).
ONE pass over the top-level object, not one gjson `#.field` query per location. The path form re-scanned the whole body seven times and squashed every matched array on the way, which made this ~22% of the rewrite path's CPU on real 600 KB Claude Code requests — and it runs twice per request (inbound count + the cap check). Walking the object once also means the location a mark was found AT is known for free, which is what the split below reports; the path form had to derive it from the query string.
func (Breakpoints) Total ¶ added in v0.1.1
func (b Breakpoints) Total() int
Total is the figure the provider's cap of four applies to.
type Change ¶ added in v0.1.1
type Change struct {
Path string `json:"path"`
BeforeTokens int `json:"before_tokens"`
AfterTokens int `json:"after_tokens"`
Before string `json:"before"`
After string `json:"after"`
// Components names which components rewrote this message, IN THE ORDER THEY
// TOUCHED IT. A LIST, not a single id, and that is not a hedge: several components
// routinely rewrite the same message in sequence (a reformatter then an offloader),
// and the before/after pair here is their cumulative result — a single field would
// have to name a winner and would be wrong for every other toucher.
//
// A REVERTED component is absent. The pipeline only records indices for a run that
// survived its guards (see components.runOne), so a component rolled back by an
// error, a panic, or the never-worse rule is never credited with the change.
Components []string `json:"components,omitempty"`
}
Change is one rewritten message, captured for the CONTEXT_GURU_DUMP trace and for the dashboard's before/after diff view, so a human can see exactly what context-guru did to the wire.
type Opts ¶ added in v0.1.1
type Opts struct {
Provider bschemas.ModelProvider
Body []byte
// Session is the host-supplied session id ("" => content hash).
Session string
// Tenant namespaces the session id in a hosted, multi-tenant deployment. Empty
// in single-tenant use, which leaves session keys byte-identical to before this
// field existed.
//
// It has to exist because the fallback session id is a content hash of the system
// prompt plus the first user message. Two people running the same agent on the
// same repository produce the SAME hash — so without a namespace they would share
// one session key, and therefore one sticky offload set and one cached-prefix
// boundary. That is a cross-tenant state collision arrived at by nobody doing
// anything wrong.
Tenant string
Bypass bool
Models components.ModelSpec
// Window is the model's resolved context window (max input tokens; 0 = unknown).
Window int
// CacheMode is "auto" (default) | "on" | "off" — see resolveCacheAware.
CacheMode string
// Now is the clock, injected so idle-time reasoning is testable. Zero means time.Now().
Now time.Time
// SelfRates are the per-token rates of the model a NeedsModel component would call via
// `model.source: incoming` — i.e. the request's own model. Supplied by the host, which is
// the only layer with a Pricer. Zero means unknown and the component falls back.
SelfRates components.TokenRates
// RatesFor resolves the operator's rate card for a NAMED model, so a component that
// compacts with a model other than the request's own can price its own calls from the
// same card the bill is computed from. nil means unavailable; the component falls back.
RatesFor func(model string) components.TokenRates
// Mode is the operating mode. Empty means components.ModeSync, so a caller that does
// not know about modes gets exactly today's behavior.
Mode components.Mode
// HeadTTL1h asks for the provider's one-hour cache tier on the HEAD breakpoints
// (`tools`, `system`) while the trailing message breakpoint stays at five minutes —
// the documented mixed-TTL shape. Off by default; see headttl.go for the measured reason,
// which is that Bedrock grants the tier for the Claude 4.5 family and silently downgrades
// it for the Opus 5 / Sonnet 5 models this service actually runs.
//
// NOTE for anyone reading the cold-cache logic: setting this makes bodyAsksExtendedTTL
// true, so cacheTTL returns 1h and cacheIsCold becomes correspondingly permissive. That is
// the right behaviour when the tier is granted and a deliberate over-estimate when it is
// not (the safe direction — believing a cache is warm only forgoes an optimisation). It
// cannot affect anything today because this is off, but it is the one way this field
// touches shared behaviour.
HeadTTL1h bool
// HeadTTLMinTokens is the size gate on HeadTTL1h, in estimated tokens. 0 disables the
// upgrade entirely rather than defaulting, so a host that forgets to resolve its
// configuration asks for nothing instead of asking on every request.
HeadTTLMinTokens int
// PrefixAsk, when set, lets a component put a question to the request's own model with the
// previous turn's SENT body as the cached prefix. See components.PrefixAsker. nil => a component
// that wants one gets none and decides for itself; today's behaviour for every caller that does
// not set it.
PrefixAsk components.PrefixAsker
// Tracker, when set, owns the per-session cached-prefix boundary. Supplying it also
// removes the concurrent-turn race in the legacy read-then-deferred-write of prevLen.
// nil => the legacy store-backed path, unchanged for library callers and /compact.
Tracker *modes.Tracker
}
Opts is BodyOpts' input: everything the positional BodyFull takes, plus the operating mode (#31) and the per-session boundary tracker.
A struct rather than more positional arguments: the parameter list was already at the limit of readability, and these fields are set by one host only.
type Result ¶ added in v0.1.1
type Result struct {
// Body is the body to forward. Always valid: on any trouble it is the input.
Body []byte
// Changed is false when Body is the untouched input.
Changed bool
Trace
}
Result is BodyOpts' output.
The embedded Trace carries everything observational: the resolved Session, the pipeline's Run report (which observe mode reads as its ONLY output, since the body is thrown away), the cache-awareness facts, and each rewritten message's before/after text for the dashboard. It is embedded rather than duplicated so there is exactly one Session and one Run in the codebase — two copies of the same value is how one of them goes stale.
func BodyOpts ¶ added in v0.1.1
BodyOpts is the full entry point: everything BodyFull takes plus the operating mode (#31), the per-session boundary tracker, and the observational Trace the dashboard's capture path reads. Hosts that support modes call this; BodyFull is the positional shim every other caller keeps using.
The rewrite is byte-identical whether or not anyone reads the trace: every trace field is filled from a value the rewrite already computed, and nothing branches on it.
type Trace ¶ added in v0.1.1
type Trace struct {
Session string
Bypassed bool
CacheAware bool
MaxCachedIdx int
// Messages is the normalized message count this request carried.
Messages int
// AttemptedTokens is the token count of the messages age/supersession
// offloaders were ALLOWED to touch (the uncached tail when cache-aware, the
// whole request otherwise). It is the honest denominator for
// "saved / attempted-to-compress"; TokensBefore−AttemptedTokens is the
// compaction our own cache-safety mechanism deliberately gave up.
AttemptedTokens int
// FrozenTokens is TokensBefore−AttemptedTokens: the cost of cache safety.
FrozenTokens int
// Breakpoints is where this request's prompt-cache breakpoints sat ON ARRIVAL,
// split by location. Observational, and free: the pipeline already counts them to
// respect the provider's cap of four.
Breakpoints Breakpoints
// CacheTTL is the prompt-cache lifetime tier this request asked for: "ephemeral_5m",
// "ephemeral_1h", or "" when the body carried no cache_control at all. See ttlTier.
CacheTTL string
// SplitTailHash identifies the VOLATILE half the split moved the breakpoint off. Compared
// against the same session's previous request to decide whether the snapshot moved, which
// is the turn on which the split is worth anything: with the block unsplit, a moved
// snapshot re-creates the whole thing. 0 when nothing split.
SplitTailHash uint64
// SplitStableTokens is the token count of the half the volatile-tail split moved the
// breakpoint onto — the tokens it moved out of the cache-creation tier. 0 when nothing
// split. It is the honest numerator for the prefix-cache saving: the alternative,
// crediting the request's whole cache_read, over-credits by whatever the agent's OTHER
// breakpoints were already matching — 7.5x in dollars on a measured session.
SplitStableTokens int
// FilteredDeclTokens is what the declaration filter stopped carrying on this request:
// the token weight of the `tools` elements it removed under the account's opt-in list.
// 0 when nothing was configured, nothing matched, or the prose gate refused.
//
// It is the ONLY honest numerator for this feature's saving, and it is written from the
// filter itself rather than derived from the inventory: the inventory records what the
// CLIENT declared (it reads the pristine body), so a figure computed from it would keep
// reporting a saving for a request the filter had declined to touch.
FilteredDeclTokens int
// FilteredDecls is how many declarations went, for the component's own report.
FilteredDecls int
// HeadTTL1h says this request asked for the provider's ONE-HOUR cache tier on its head
// breakpoints (`tools`, `system`) while leaving the trailing message breakpoint at five
// minutes. False on every request unless the account opted in.
HeadTTL1h bool
// HeadTTLTokens is the size of the prefix that 1h entry covers — the numerator of the
// head share f, on which the whole mixed-TTL economics is linear. Measured rather than
// assumed, because f was the one input R4's simulation could not read off the database
// and had to parameterise.
HeadTTLTokens int
// Run is the pipeline's aggregate report (nil when the pipeline never ran).
Run *components.RunReport
// Changes lists each rewritten message's before/after text (clipped).
Changes []Change
}
Trace is the per-request record of what BodyFull actually did: the resolved session, the pipeline's own run report (per-component accounting), the before/after text of every rewritten message, and the cache-awareness facts that decided which messages were even eligible. It is the dashboard's capture input — the same material CONTEXT_GURU_DUMP writes to a file, handed to a caller instead. Purely observational: nothing on it affects the rewrite.