offload

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 33 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 offload holds the lossy-but-reversible components (they drop bytes and stash the original for the expand tool loop). Each registers itself via init(); a binary blank-imports components/all to pull them in.

Index

Constants

View Source
const (
	// GateAlreadyMarked: this content already carries an offload marker, so reducing again would
	// double-compact and can orphan the earlier stash. Benign — nothing flips.
	GateAlreadyMarked = "already_marked"
	// GateKeptVerbatim: the agent expanded this content, so it must not be re-compacted (that
	// would bounce it straight into another expand). The turn this first appears is the turn the
	// message reverts to its full form inside the cached prefix — see ExpandPrefixFlips.
	GateKeptVerbatim = "kept_verbatim_after_expand"
)

The two gate labels skipReduce distinguishes, named constants because eleven offloaders raise them and a typo in one would silently split a counter in two.

View Source
const (
	// EventFreshSummary marks a turn that PAID for a summary: a model call was made, a
	// checkpoint was written, and the transcript was restructured around new bytes. It is the
	// t0 of a compaction episode.
	EventFreshSummary = "fresh_summary"
	// The three replay names — a turn that re-emitted an existing checkpoint for free. Each
	// says WHY the replay happened, which is the operator-facing distinction: the trigger
	// permitted this turn and the tail had not grown (reused), the trigger declined it
	// (gated), or the store's rewind reserve refused a new stash (reserve exhausted).
	EventReusedCheckpoint                   = "reused_checkpoint"
	EventGatedReplayedCheckpoint            = "gated_replayed_checkpoint"
	EventReserveExhaustedReplayedCheckpoint = "reserve_exhausted_replayed_checkpoint"
	// EventSummaryStarted marks a turn that COMMISSIONED a summary without waiting for it. The
	// spend is committed here; the summary lands (or does not) on its own, and EventFreshSummary
	// is filed by the goroutine that commits it. Two names because a started-and-lost call is a
	// real outcome that must not read as a delivered summary.
	EventSummaryStarted = "summary_started"
	// EventAwaitedCheckpoint marks a turn that WAITED for a summary an earlier turn started and
	// then spliced it. Distinct from EventReusedCheckpoint because this one cost latency: it is
	// the turn that paid for the async design, and the pair (awaited, summary_wait_timeout) is
	// what says whether the wait cap is set anywhere near right.
	EventAwaitedCheckpoint = "awaited_checkpoint"
)

The four names summarize files on Report.Events. Promoted to constants because a SECOND package now keys on them: the dashboard's compaction-episode walk (dash/compactepisode.go) identifies a fresh summary as an act carrying EventFreshSummary and a replay as one carrying any of the other three. A renamed string here would leave that walk matching nothing and reporting zero episodes — a silent zero, which is the failure mode this repo has already paid for twice (see Report.Replays on #176).

Variables

View Source
var AllowEnvModelKey = true

AllowEnvModelKey permits an api_key-less `model:` block to fall back to this process's provider credential (OPENAI_API_KEY / ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN). True for single-tenant use, where the config and the environment belong to the same person.

A hosted host sets it FALSE: there, the config document is written by a tenant and the environment holds the operator's credential, so the fallback would let any tenant bill their compaction to the operator — the one thing per-caller credentials exist to prevent. A block with no key then builds no client, and the component degrades (fail open).

View Source
var ErrSummaryDidNotLand = errors.New("no summary landed within the deadline")

ErrSummaryDidNotLand is what a test helper returns when a summary never arrived, so a failure message can say that rather than reporting a confusing downstream symptom.

Functions

func AgentDietCallTimeout added in v0.1.1

func AgentDietCallTimeout() time.Duration

AgentDietCallTimeout exposes the resolved per-call budget, so /stats can report it beside the counters (a timeout count means nothing without the budget it hit).

func AgentDietErrors added in v0.1.1

func AgentDietErrors() int64

AgentDietErrors returns non-timeout reflection failures (transport, HTTP status, unparseable reply, cancelled parent request).

func AgentDietTimeouts added in v0.1.1

func AgentDietTimeouts() int64

AgentDietTimeouts returns the reflection calls abandoned on the per-call deadline. Non-zero means CONTEXT_GURU_AGENTDIET_TIMEOUT is too small for the server's load, and this arm's savings are an undercount rather than a measurement.

func AsyncSummaryStats added in v0.2.0

func AsyncSummaryStats() (started, committed, waitedMs, waitTimeouts, refused, unresolved, panics int64)

AsyncSummaryStats reports the async path's counters for /stats.

func CacheAwareAsyncStats added in v0.2.0

func CacheAwareAsyncStats() (started, committed, refused, panics int64)

CacheAwareAsyncStats returns (started, committed, refused, panics). The PAIR is the signal: started without committed is a summary that was paid for and lost, which no other counter here would reveal. Refused is the global bound shedding compaction under load rather than queueing a call nobody is waiting for.

func CacheAwareSummarizerCallTimeout added in v0.2.0

func CacheAwareSummarizerCallTimeout() time.Duration

func CacheAwareSummarizerCalls added in v0.2.0

func CacheAwareSummarizerCalls() int64

func CacheAwareSummarizerDeclined added in v0.2.0

func CacheAwareSummarizerDeclined() int64

CacheAwareSummarizerDeclined counts turns that reached the model step and stopped because no components.MessagesModel was available. That is the ONLY reason it counts — a role the backend rejects returns an error and lands in Errors, not here. Non-zero means this arm is not measuring cache-reuse compaction; it is measuring `off`.

func CacheAwareSummarizerEmpty added in v0.2.0

func CacheAwareSummarizerEmpty() int64

CacheAwareSummarizerEmpty counts calls that were PAID FOR and returned nothing usable. It is the signature of the silent failure the profile registry guards against: an instruction the template dropped or hoisted, so the model answered the conversation instead of the request.

func CacheAwareSummarizerErrors added in v0.2.0

func CacheAwareSummarizerErrors() int64

func CacheAwareSummarizerProfileFallbacks added in v0.2.0

func CacheAwareSummarizerProfileFallbacks() int64

CacheAwareSummarizerProfileFallbacks counts turns that fell back to the embedded registry because profiles_path was unreadable or unparseable.

func CacheAwareSummarizerRefusedStash added in v0.2.0

func CacheAwareSummarizerRefusedStash() int64

CacheAwareSummarizerRefusedStash counts summaries abandoned because the store would not accept the span. The splice is skipped rather than completed, because a marker promising a span the store never took is a lossy Offload advertising reversibility it does not have.

func CacheAwareSummarizerTimeouts added in v0.2.0

func CacheAwareSummarizerTimeouts() int64

func CacheAwareSummarizerTooLarge added in v0.2.0

func CacheAwareSummarizerTooLarge() int64

CacheAwareSummarizerTooLarge counts turns declined because the outbound request would have exceeded max_request_tokens. Non-zero means this session outgrew the method rather than that anything failed.

func CacheAwareSummarizerUnverifiedSystem added in v0.2.0

func CacheAwareSummarizerUnverifiedSystem() int64

CacheAwareSummarizerUnverifiedSystem counts turns declined because instruction_role was pinned to `system` for a model no registry profile marks as accepting a trailing system message. Non-zero means the arm is configured for a silent failure and is refusing to take it.

func ExpandPrefixFlips added in v0.2.0

func ExpandPrefixFlips() int64

ExpandPrefixFlips returns how many times a replay declined because the agent had expanded content that WAS compacted before. Non-zero means expansion is re-writing cached prefixes; see expandFlips for why it is per turn per message rather than per distinct content.

func FrozenStats added in v0.1.1

func FrozenStats() (hits, misses int64)

FrozenStats returns the cumulative freeze-replay hits and misses since process start. Exported for the host's /stats, which pairs them with the store's drop/repair counts.

func KeptVerbatim added in v0.1.1

func KeptVerbatim(st store.Store, original string) bool

KeptVerbatim reports whether this content has already been marked. The expand repair reads it to charge a restored original to the dashboard ONCE: the client keeps its own copy of the error, so the same repair runs on every later turn, and counting each one drives the headline savings arbitrarily negative (ExpandTokens is subtracted from a unique-counted total, so the units do not even match).

func LLMCallTimeout added in v0.1.1

func LLMCallTimeout() time.Duration

LLMCallTimeout exposes the resolved per-call budget so /stats can report the configuration next to the counters (a timeout count is meaningless without it).

func LLMErrors added in v0.1.1

func LLMErrors() int64

LLMErrors returns non-timeout failures of extract_llm model calls (transport, HTTP status, unparseable body, or a cancelled parent request).

func LLMTimeouts added in v0.1.1

func LLMTimeouts() int64

LLMTimeouts returns the number of extract_llm calls abandoned on the per-call deadline. Non-zero means CONTEXT_GURU_LLM_TIMEOUT is too small for the current server load, and any token-savings number from this arm is an UNDERCOUNT of what the pipeline would have done on an unloaded server.

func LLMTruncated added in v0.1.1

func LLMTruncated() int64

LLMTruncated returns the number of extraction replies cut off at the output cap.

func MarkKeptVerbatim

func MarkKeptVerbatim(st store.Store, original string)

MarkKeptVerbatim records that this original content was expanded and must not be re-compacted (keyed by content hash, session-independent). Exported for the proxy's expand loop, which has the restored original but not the offload Ctx.

func MaxConcurrentSummaries added in v0.2.0

func MaxConcurrentSummaries() int64

MaxConcurrentSummaries is the global bound, reported beside the counts for the reason llm_call_timeout_ms travels with its timeout total: a refusal count is meaningless without the ceiling it was measured against.

func OwnsKey

func OwnsKey(st store.Store, session, key string) bool

OwnsKey reports whether session stashed key. Exported for the proxy's GET /expand handler to scope retrieval to the caller's session (prevents cross-session/tenant disclosure of offloaded originals). Returns false when either is empty.

func StashMissing added in v0.1.1

func StashMissing() int64

StashMissing returns how many marker replays found no payload behind them. Non-zero means markers ARE on the wire that the store cannot resolve — unlike StashRefusals, this is a broken promise, and the leading indicator for expand_unresolved_missing.

func StashRefusals added in v0.1.1

func StashRefusals() int64

StashRefusals returns how many removals were declined because the store's rewind reserve was full. Non-zero means max_entries is too small for what this configuration removes; the removals did not happen, so nothing became irreversible.

func SummarizeCallTimeout added in v0.1.1

func SummarizeCallTimeout() time.Duration

SummarizeCallTimeout exposes the resolved budget so /stats can report the configuration next to the counters (a timeout count is meaningless without it).

func SummarizeErrors added in v0.1.1

func SummarizeErrors() int64

SummarizeErrors returns non-timeout failures of summarize model calls (transport, HTTP status, empty/unparseable body, or a cancelled parent request).

func SummarizeTimeouts added in v0.1.1

func SummarizeTimeouts() int64

SummarizeTimeouts returns the number of summarize calls abandoned on the per-request deadline. Non-zero means CONTEXT_GURU_SUMMARIZE_TIMEOUT is too small for the current server load, and this arm compacted less than the method would on an idle server.

func WaitForAllSummariesForTest added in v0.2.0

func WaitForAllSummariesForTest(within time.Duration) bool

WaitForAllSummariesForTest drains every in-flight summary, whatever session it belongs to.

For tests that drive the pipeline through apply rather than calling the component directly: apply DERIVES a session id from the transcript when the caller supplies none (session.Scoped over the system prompt and first user message), so such a test cannot name the session it just created and cannot wait on it by name.

It polls, unlike WaitForSummaryForTest, because "no summaries are running" is a property of the whole registry rather than of one channel. The interval is short and the deadline is the caller's, so a passing test is bounded by the work rather than by the poll.

func WaitForSummaryForTest added in v0.2.0

func WaitForSummaryForTest(session string, within time.Duration) bool

WaitForSummaryForTest blocks until the session's in-flight summary has landed, or the deadline passes. It reports whether one landed.

EXPORTED AND TEST-ONLY, and it is deliberately not a `_test.go` file: components/all's tests drive summarize through the registry from another package, and they need the same drain. The alternative was every caller sleeping, which is how a suite becomes both slow and flaky.

It waits on the SAME channel a real turn waits on (summaryFlight.done), so a test that passes here is exercising the production synchronisation rather than a sleep that happens to be long enough on the machine that ran it.

Types

type AgentDiet added in v0.1.1

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

AgentDiet is a baseline reproduction of the trajectory-reduction method from "Reducing Cost of LLM Agents with Trajectory Reduction" (Xiao, Gao, Peng, Xiong; FSE 2026, arXiv:2509.23586), which the paper calls AgentDiet. It is offered as a COMPARABLE BASELINE next to context-guru's own reducers, so the published method can be A/B'd against `extract_llm` / `summarize` on the same traffic.

The method, and what makes it different from extract_llm:

  1. Its unit is the STEP — one assistant message plus the tool results answering it — not one tool output. A step is reduced as a whole.
  2. A FIXED AGE, not a size or an economic estimate, chooses the target: when the agent has completed step s, only step s-a is eligible (`delay_steps`, a=2). The most recent a steps are never touched, so a bad reduction can never corrupt what the agent is working on right now — the paper's protection against a malfunctioning reflection model.
  3. The reflection model gets a SLIDING WINDOW of surrounding steps as context (`context_steps`, b=1 ⇒ steps [s-a-b … s]), serialized as XML. This is the part extract_llm structurally cannot do: seeing neighbouring steps is what lets the model recognise content as *redundant* (already stated nearby) or *expired* (mattered only to a finished sub-goal) rather than merely verbose.
  4. Two thresholds bound the spend. A step shorter than `min_step_tokens` (θ=500) is not worth a call at all; and a reduction that comes back is APPLIED only if it clears `min_saved_tokens` OR `max_keep_ratio`, so a marginal rewrite does not pay a cache-write for nothing.
  5. A reduction is made ONCE and then frozen: later turns replay the same bytes (freeze/reapplyFrozen), so the request prefix stays stable and reductions accumulate across the session exactly as they do in the paper, where the agent's own trajectory is edited in place.

Deviations from the paper, all forced by the wire and documented in docs/components/agentdiet.md:

  • The paper's reflection module REPLACES the whole step with one assistant message. context-guru rewrites messages in place (only `summarize` changes the message count, and it must run alone for that reason), so the reduction is written into the step's tool-result messages — where 63% of trajectory tokens live, by the paper's own accounting (30.4K of 48.4K).
  • Tool-call ARGUMENTS are not reduced. On Anthropic traffic bifrost's schema does not model `tool_use` blocks at all, so their name and input are not visible to any component here; the assistant message is not even Rewritable. That forgoes the paper's str_replace_editor redundancy case (~25% of trajectory tokens) and is the main reason to expect a smaller reduction here than the paper's 39.9%–59.7%.
  • The reflection prompt is written from the paper's description (its four parts: job, format, the three waste categories, anti-loss guidelines) rather than copied from the authors' artifact.

Defaults are the paper's tuned values (a=2, b=1, θ=500). `min_saved_tokens` (400) and `max_keep_ratio` (0.8) come from the authors' artifact, whose apply-gate is `saved >= 400 || keep < 0.8` — Algorithm 1 in the paper states this more simply as `l_orig - l_reduced > θ`. The artifact's form is used because it is what produced the published numbers; setting `min_saved_tokens` to θ and `max_keep_ratio` to 0 reproduces the paper's stated gate exactly.

func (*AgentDiet) Enabled added in v0.1.1

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

func (*AgentDiet) Name added in v0.1.1

func (*AgentDiet) Name() string

func (*AgentDiet) NeedsModel added in v0.1.1

func (*AgentDiet) NeedsModel() bool

NeedsModel reports that this component calls an LLM. With no model available it degrades to replaying whatever it already froze — never an error.

func (*AgentDiet) Offload added in v0.1.1

type CacheAwareSummarizer added in v0.2.0

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

CacheAwareSummarizer summarizes by APPENDING the instruction to the conversation instead of rebuilding the prompt, so the summarization call can reuse a prefix the backend already has rather than paying fresh prefill for tokens it has already seen.

`summarize` builds a fresh prompt — a preamble plus the rendered transcript as one user message — which shares no prefix with the conversation it describes, so that call is a cache miss on every token. This one sends [the conversation, verbatim and in order] + [one appended instruction]. It is the shape prompt-caching guidance prescribes for a fork: reuse the parent's prefix and append only what the fork adds.

⛔ HOW FAR THE REUSE ACTUALLY GOES, because the naive reading of the paragraph above is wrong after the first compaction. The prefix that would be hit is one the BACKEND has seen, and the backend only ever receives what this proxy forwards. The agent keeps sending its own full uncompacted history, but from the first triggering turn onward the backend has received COMPACTED requests — so there is no full-history prefix upstream to match, and the shared prefix is roughly the pinned head. Two consequences worth measuring rather than assuming: the saving is largest on the first compaction and smaller afterwards, and sending the full growing history as a side call can evict the compacted prefix the forwarded request needs. Judge this component on the backend's own telemetry (vllm:prefix_cache_hits_total, or usage.cache_read_input_tokens, which the OpenAI client records) — never on a savings percentage.

⛔ IT NEEDS A components.MessagesModel AND DECLINES WITHOUT ONE. A plain Model flattens the conversation to one string, which is exactly the prefix-destroying shape this exists to avoid, so a client without the capability makes the component skip. A silent fallback would report this method's latency while paying the old method's cost. Because a declining arm compacts nothing and is byte-identical to `off` on every other metric, the decline is COUNTED: read CacheAwareSummarizerDeclined before believing any delta from this arm.

Span selection, kept-verbatim repair and orphan repair all come from summarize_pairing.go — the same functions `summarize` uses, not a second implementation. A tool exchange is atomic and both boundaries must respect that; a private copy of the invariant would be a second place for it to drift, and the drift would surface as an exception-rate difference blamed on the method under test.

func (CacheAwareSummarizer) Enabled added in v0.2.0

func (*CacheAwareSummarizer) InstructionRole added in v0.2.0

func (s *CacheAwareSummarizer) InstructionRole() string

InstructionRole exposes the resolved role so /stats and a probe can report which channel this arm actually used; with `auto` it cannot be read off the config alone.

func (CacheAwareSummarizer) Name added in v0.2.0

func (*CacheAwareSummarizer) NeedsModel added in v0.2.0

func (*CacheAwareSummarizer) NeedsModel() bool

func (*CacheAwareSummarizer) Offload added in v0.2.0

Offload rewrites the transcript to [head, summary, tail]. The summary comes from a model call built as [the whole conversation] + [instruction], and is REUSED across turns until the tail grows past resummarize_tokens — without that reuse the forwarded prefix would change every turn and this component would invalidate the cache it exists to protect.

type Cmdfilter

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

Cmdfilter shrinks tool-output messages with declarative DSL filters. It is an Offload: it stashes the original before filtering so the expand tool can recover it. Filters match on the tool output's first few non-empty lines AND, when the transcript pairs the result with its call (schema.ToolCalls), on a leading `$ <command>` line — so a filter can key on the command that produced the output the way rtk's do, not only on the output's shape.

func (*Cmdfilter) Enabled

func (f *Cmdfilter) Enabled(*components.Ctx) bool

func (Cmdfilter) Name

func (Cmdfilter) Name() string

func (*Cmdfilter) Offload

type Collapse

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

Collapse is the content-agnostic fallback for an oversized tool output that no more specific component handled: it keeps a head + tail window, stashes the full original, and leaves an expand marker. Runs late in the pipeline (after cmdfilter/format), and skips anything already carrying a marker so it never double-collapses.

The window is cut by LINES when that actually shrinks the output, and by CHARACTERS when it does not. The character path is not a nicety. Being the last-resort catch-all, collapse declining a payload means nothing caps it, and the line-only version declined every output of head_lines+tail_lines lines or fewer — which includes the single most common shape of an enormous tool result: a database or HTTP API response serialised as ONE line of JSON. Measured on a live 128k-band arm: 16 upstream 400s ("prompt is too long") in 3,347 requests on outgoing bodies of 2.6 MB to 14.8 MB, and 17 of 75 runs errored. Nothing else caught them either — extract acted 0 times (no_obvious_noise 16,891, it only strips KNOWN noise patterns), cmdfilter 0 (no_filter_match, only known command families), toon 21 (not_uniform_object_array 233,501), dedup 774 (exact duplicates only), extract_llm declines by design when the output exceeds the compaction model's own window (over_model_context), and summarize protects keep_last, which is exactly where a FRESH oversized output sits. linecap's per-line cap does not rescue this shape either: its neverTruncate allow-list exempts any line matching `^\S+:\d+`, and a one-line JSON body (`{"items":[{"id":1,...`) matches that by accident.

The choice between the two windows is made on BYTES, not on the line count: an output with more than head_lines+tail_lines lines whose kept head or tail is itself multi-megabyte takes the CHARACTER window too. Gating on the line count alone left the motivating shape alive above 40 lines — measured at 4,195,111 B in, 4,194,922 B out, and worse than declining, because dropping the small filler lines in the middle counts as acting and stamps a marker, which then makes linecap decline (already_marked) and forwards 1.57 M tokens. linecap could not have capped it even without the marker: its neverTruncate allow-list exempts any line matching `^\S+:\d+`, which one-line JSON matches by accident (issue #151), so the mitigation this comment used to name is void rather than conditional.

ponytail: []rune(content) on the character path copies the whole output — ~59 MB for the 14.8 MB payloads that motivated this component — once per oversized message per turn, on top of the strings.Split above it. Fine at the measured rate (16 bodies in 3,347 requests) but it is the obvious thing to make streaming if that rate rises.

func (Collapse) Enabled

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

func (Collapse) Name

func (Collapse) Name() string

func (*Collapse) Offload

func (cl *Collapse) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Coref added in v0.2.0

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

Coref is co-reference-aware compaction: at a threshold crossing it cuts the tool outputs that later turns never carried anything forward from, in ONE batched pass. Design and derivation: docs/proposals/coref-compaction.md.

It differs from every other offloader here in one deliberate way, and the whole shape of the component follows from it: it MUTATES THE CACHED PREFIX on purpose. Age-based offloaders refuse to (Ctx.TailOnly) because breaking the prefix hash at index i cache-WRITES the suffix, at 11.5x a cache-read. So:

  • The cut is BATCHED. One rewrite has to serve every cut in the pass, because a single early cut can never repay its own rewrite on tokens: at 5k cut from 20% depth of a 150k transcript the break-even is T > 276 turns. Batched, 60k of the same transcript needs T > 23, which a long session actually reaches. Hence min_batch_frac, and hence "rare and certain" rather than "per output per turn".
  • The spend is BUDGETED and reported, not incidental (rewrite_budget). A component that spends cache-writes on purpose has to be answerable for how many.
  • The decision is LATCHED and replayed, never re-derived. See the freeze note in Offload; this is the constraint that rules out repairLostFreeze.

The default cut set is `unreferenced` only — outputs no later turn exactly reuses anything from. That is the honest ceiling of a zero-LLM implementation and needs no calibrated threshold. `closed` (the case-A large cut: referenced once or twice, long ago) is off by default because its two thresholds are the OUTPUT of the measurement pass in deploy/harbor/coref.py, which has not yet run on real traffic; shipping a guessed closed_dist would be shipping the one number the proposal says must be measured. Turn it on with cut_closed once there are numbers.

func (Coref) Enabled added in v0.2.0

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

func (Coref) Name added in v0.2.0

func (Coref) Name() string

func (*Coref) Offload added in v0.2.0

func (cf *Coref) Offload(req *bschemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Dedup

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

Dedup replaces a tool output that is byte-identical to an earlier one in the same request with a short pointer + expand marker, stashing the original. Exact-match only in v1; near-duplicate (similarity threshold) is deferred.

func (Dedup) Enabled

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

func (Dedup) Name

func (Dedup) Name() string

func (*Dedup) Offload

func (d *Dedup) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Extract

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

Extract is the DETERMINISTIC (no-LLM) tool-output reducer. It runs every request (cheap) and is deliberately CONSERVATIVE: it removes only OBVIOUS, provably redundant noise (exactly repeated lines/blocks, runs of blank lines, progress bars/spinners) via collapseObviousNoise, keeping every unique informative line verbatim. This guarantees it can never hide content the agent needs and force it to redo work. Relevance-aware, aggressive trimming (regex rewrites, summaries) is the job of the separate `extract_llm` component — configure them together (`[extract, extract_llm]`) so the cheap pass runs every step and the LLM pass only every few steps.

It is byte-stable on unchanged content (deterministic per-message), so it is cache-safe and needs no cache-boundary restriction. The full original is stashed under a marker (reversible via the expand tool).

func (Extract) Enabled

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

func (Extract) Name

func (Extract) Name() string

func (*Extract) Offload

func (e *Extract) Offload(req *bschemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type ExtractLLM

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

ExtractLLM is the relevance-aware, LLM-driven tool-output reducer. A cheap model writes a small Starlark program that trims ONE tool output down to what the agent needs next (it may delete OR rewrite via regex, preserving ids/paths/errors verbatim, and may emit a one-line SUMMARY that goes into the marker). The program runs in a sandbox (no imports/IO, step+time limited) and the result must pass a sanity check (non-empty, strictly smaller, keep-ids present); on any miss the item is left verbatim. The full original is always stashed (reversible via expand).

It is the EXPENSIVE pass, so it is throttled (per-session cadence + per-request cap) and — in cache-aware mode — only rewrites tool outputs in the uncached tail that are still medium/large AFTER the deterministic components ran. Prior compactions are reused byte-for-byte from state so the request prefix stays stable.

func (*ExtractLLM) Enabled

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

func (*ExtractLLM) Name

func (*ExtractLLM) Name() string

func (*ExtractLLM) Offload

type ExtractSweep added in v0.1.1

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

ExtractSweep is the SWEEP ADJUDICATOR: it asks the request's OWN model, over the transcript that model already has in its prompt cache, which tool outputs are spent — and removes those, leaving a shape descriptor plus a recoverable marker. It never rewrites anything and it never copies output content into a prompt.

WHY IT IS A SEPARATE COMPONENT FROM extract_llm. The two situations want different operations. On a warm turn extract_llm works the uncached tail: the output is recent, the agent may still want most of it, and a smaller version of it is more useful than none of it. The sweep works DEEP HISTORY, where rewriting is the wrong operation on either branch of the only question that matters — deep history is either still load-bearing, in which case rewriting corrupts content the model has already reasoned about, or it is spent, in which case the answer is to remove it.

WHY IT ASKS THE REQUEST'S MODEL OVER THE CACHE, in one call, shipping an inventory:

Need is relevance MINUS what has already been captured elsewhere, and that second term lives in
the LATER TURNS. A judgement shown only the candidate cannot see them.
Verbatim quoting — the only signal that says whether the model is inventing — degraded to 20.8%
on the cheap model at bulk batch sizes, against 0 of 59 on the request model.
Appending a trailing user message to a byte-identical prefix read 19,595 tokens from cache and
created 0, so the whole transcript is affordable exactly once: as a cache read.

See internal/extract/adjudicate.go for the full evidence and components.PrefixAsker for the construction.

WHAT IT NEVER DOES. It selects no compaction strategy, produces no rewritten text, and there is no reply field a model could return content through. `strategy`, `rewrite`, `aggressiveness` and `max_chars` are therefore not merely defaulted differently here, they are meaningless, and writing one is a config error rather than a silently ignored key (see newExtractSweep).

func (*ExtractSweep) Enabled added in v0.1.1

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

func (*ExtractSweep) Name added in v0.1.1

func (*ExtractSweep) Name() string

func (*ExtractSweep) Offload added in v0.1.1

type FailedRun

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

FailedRun collapses earlier test/build runs that a later run supersedes: only the most recent run-like tool output is kept in full; earlier ones become a pointer + stash. This is the "provable-reason" collapse — a superseded run is safely recoverable via expand if the agent still needs it.

func (FailedRun) Enabled

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

func (FailedRun) Name

func (FailedRun) Name() string

func (*FailedRun) Offload

func (fr *FailedRun) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Linecap added in v0.1.1

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

Linecap applies the two COMMAND-AGNOSTIC output rules, in one pass over each tool message: scattered duplicate-line collapse, then a per-line character cap.

Why generic rather than more cmdfilter filters. cmdfilter ships 939 lines of per-command filters and production has matched exactly two of them (`ssh`, `uv-sync`; `no_filter_match` 164,865). Sixteen further rtk command signatures — pytest, apt, npm, pip, go test, cargo, tsc, eslint, mypy, ruff, docker, kubectl, make, gcc, git log, ps — were replayed against 9,763 real messages and every one matched ZERO. These two rules need no command signature, which is exactly why they fire where the signatures do not: on the same corpus they remove 1.75M tokens, 20.3% of everything shipped.

It is an Offload, not a Reformat: both rules drop bytes. Under the default marker_mode the original is stashed and a <<cg:HASH>> marker names it, so the agent can call the expand tool and get the whole output back.

Cache safety needs no depth gate. The rewrite is a pure function of the message's own text, so a message re-sent next turn rewrites to the same bytes and no cached position is re-anchored — the same argument format, textclean, searchfold and cmdfilter rely on.

func (*Linecap) Enabled added in v0.1.1

func (lc *Linecap) Enabled(*components.Ctx) bool

func (Linecap) Name added in v0.1.1

func (Linecap) Name() string

func (*Linecap) Offload added in v0.1.1

func (lc *Linecap) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Mask

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

Mask hides older tool outputs beyond a keep-recent window (after CE-Manager's context garbage collection): the newest KeepRecent tool results stay verbatim, older ones are replaced with a short marker + stash. Age-based, complementary to the content-based offloaders.

func (Mask) Enabled

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

func (Mask) Name

func (Mask) Name() string

func (*Mask) Offload

func (m *Mask) Offload(req *bschemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type ReadLifecycle added in v0.1.1

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

ReadLifecycle offloads a file Read whose body no longer describes the file, judged from the transcript itself (after headroom's read_lifecycle.py). Two classes, and only these two:

  • STALE — an Edit/Write/MultiEdit/NotebookEdit on the same path appears LATER in the transcript. What sits in context is then FACTUALLY WRONG, so removing it is a correctness argument before it is a token argument: the model is otherwise reasoning about line numbers and content that no longer exist.
  • SUPERSEDED — the same path is Read again later with the SAME range, so the later Read is authoritative and the earlier body is redundant.

A FRESH Read — no later edit, no later re-read — is never touched. That is the safety property the component stands on: it removes only what the transcript itself proves is out of date, and the marker says only what is true (the file was modified / was read again), never "identical to", which a re-indent would already falsify.

Deliberately conservative, in three places that each cost measurable savings:

  • Supersession keys on (path, offset, limit), not path alone. Claude Code Reads ranges; a later Read of lines 500-600 does not supersede an earlier read of the whole file, and calling it superseded would delete content nothing replaced. Containment (a later full read covering an earlier partial one) is NOT modelled — measured at 867 tokens on the whole corpus on this box, which does not pay for the reasoning.
  • An Edit anywhere in the file staleizes every prior Read of it, including a Read of a different range: an edit shifts the line numbers the Read printed, so the rest of the body is wrong even where the text is not.
  • Bash commands count as edits only under `bash_edits`, off by default, and only for the narrow write forms listed in bashEditPaths. A false positive here deletes CORRECT context, which is the one failure this component must not have.

Cache safety. The classification is MONOTONE: it is a function of strictly later events, and events only ever accumulate, so a Read goes fresh → stale/superseded exactly once and never flaps back. The replacement text is a pure function of (content, class, path, config) — the marker key is sha256(content) — so it is byte-identical every time it is re-derived, from any process, with no map iteration on the path that produces it. That is what makes the freeze/reapply machinery this component shares with mask and failed_run correct here: a NEW offload happens only in the uncached tail (or at depth on a provably cold turn, `cold_cache`), and once frozen it is REPLAYED on every later turn regardless of depth, so the forwarded prefix is byte-stable. Determinism, not "only touch the delta", is the argument — see TestFrozenPrefixIsByteStable and TestDeterministicAcrossProcesses. atDepth (config `stale_at_depth`) is the one knob that can make this component pay on a WARM turn, and it is off by default because it costs a cache-write to buy one.

The measured reason it exists: with the tail gate on, a real SWE-bench session declined 1,125 stale-Read candidates as `cached_prefix` and removed ZERO tokens — structurally, not accidentally. A Read only becomes stale when a LATER Edit appears, and by that turn the Read is already in the provider's cached prefix, so the gate can essentially never let this component act warm.

Lifting it costs one re-anchor: rewriting the Read at index i forces a cache-write of everything after i, once, at the turn the Read goes stale. That is cheap exactly when the Read is near the tail at that moment — which the Read→Edit loop makes the common case — and the freeze then replays the decision on every later turn, so the body is gone for the rest of the session. See TestStaleAtDepthAmortizes for the measured distance, and the doc for the dollars.

func (ReadLifecycle) Enabled added in v0.1.1

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

func (ReadLifecycle) Name added in v0.1.1

func (ReadLifecycle) Name() string

func (*ReadLifecycle) Offload added in v0.1.1

type SmartCrush

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

SmartCrush is headroom's statistical JSON-array compressor, in essence: keep a first-K/last-K anchor window plus any item that carries an error signal, drop the rest, and stash the full original. Schema-preserving (kept items are verbatim originals). v1 uses fixed anchors; headroom's Kneedle adaptive-K is a documented refinement.

func (SmartCrush) Enabled

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

func (SmartCrush) Name

func (SmartCrush) Name() string

func (*SmartCrush) Offload

type Summarize

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

Summarize compresses the middle of a long trajectory into one LLM-written summary (ported from CE-Manager's ReSum-style summarizer). It restructures the message list to [msg0, <summary system message>, last-K messages], replacing everything in between. It is an Offload: the replaced span is stashed under a <<cg:HASH>> marker (carried in the summary message) so the expand tool can restore it. NeedsModel — it no-ops when no model is available.

This is the one component that changes the message count; apply.Body rebuilds the body preserving the retained messages' original bytes.

func (Summarize) Enabled

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

func (Summarize) Name

func (Summarize) Name() string

func (*Summarize) NeedsModel

func (*Summarize) NeedsModel() bool

func (*Summarize) Offload

Jump to

Keyboard shortcuts

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