components

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 16 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 components defines context-guru's component model: the abstract API every context-engineering operation implements, the per-component report used for metrics, the runtime context handed to each component, and the pipeline that stacks them in configured order.

The API is split by lossiness (design D3, after headroom's Rust traits) so reversibility is type-enforced:

  • Reformat: lossless repack (re-encode, skeletonize, add cache_control). No information leaves the wire, so nothing needs stashing.
  • Offload: drops bytes and MUST return a non-optional cache_key proving it stashed the original in the Store — you cannot compile an Offload that silently loses data.

The pipeline is fail-open (any error/panic reverts that component), applies a never-worse guard (a component that grows the request is reverted), and emits one Report per component.

Index

Constants

View Source
const (
	FieldBool    = "bool"
	FieldInt     = "int"
	FieldFloat   = "float"
	FieldEnum    = "enum"
	FieldString  = "string"
	FieldStrings = "strings"
)

Field types.

Variables

View Source
var ErrNoPrefix = errNoPrefix{}

ErrNoPrefix is what Ask returns on the FIRST turn of a session: nothing has been forwarded yet, so there is no cached prefix to append to.

Declared here rather than in the host so a component can tell it apart from a transport failure without string matching. The distinction is worth a sentinel because the two mean opposite things to an operator: "there was nothing to read yet", which every session does once and which needs no attention, against "the read failed", which does.

Functions

func AllFields added in v0.1.1

func AllFields() map[string][]Field

AllFields returns every registered component's declared fields.

func ConfigProto added in v0.1.1

func ConfigProto(name string) (any, bool)

ConfigProto returns the zero-value config struct a component declared with its fields. For the parity test; nothing in the run path needs it.

func Decode added in v0.1.1

func Decode(raw []byte, dst any) error

Decode unmarshals a component's raw config block STRICTLY: an unknown key is an error rather than silence.

Non-strict was the default and it made the settings form untrustworthy in the one way that matters — `min_tokns: 5000` on any component parsed fine, changed nothing, and reported nothing. config.LoadBytes has rejected typos at the top level since day one; per-component blocks are where the numbers that cost money live.

func Names

func Names() []string

Names lists every registered component name, sorted.

func Register

func Register(name string, c Constructor)

Register makes a component available by name. Called from each component's init(); double-registration or an empty name panics at boot (the database/sql pattern AuthBridge also uses).

func RegisterFields added in v0.1.1

func RegisterFields(name string, config any, f []Field)

RegisterFields declares a component's configurable keys, from the same init() that registers the component. config is a ZERO VALUE of the component's config struct: the anti-drift test reflects over its yaml tags and fails when the declared keys and the struct's keys disagree, which is the only thing that catches "a component gained a knob and nobody told the form".

Types

type Budgeter added in v0.1.1

type Budgeter interface {
	WithMaxTokens(n int) Model
}

Budgeter is an optional interface on a Model: the same endpoint, the same credential and the same model id, with a larger REPLY budget.

It exists because a truncated reply is the worst outcome available — full price, zero result — and it is indistinguishable from a model declining to act. MEASURED (`659e7a6`): the batched adjudication arm had 24 of 34 replies unparseable, and the cause was the client's default output budget, not the prompt. A verdict array over a dozen items, each carrying an obligation label and a verbatim quote, is simply long; a request model running adaptive thinking spends part of the budget before emitting any text at all. The array was cut mid-flight, the parse failed, and the caller changed nothing — misread as "the model declined" for three iterations.

Why an interface rather than raising cheapmodel.DefaultMaxTokens: the budget a caller needs is a property of what it ASKS FOR, not of the endpoint. A one-tool-output compaction reply and a twelve-verdict array are different lengths, and raising the shared default would move both.

Output tokens bill as generated, not as budgeted, so a raised ceiling costs nothing until used. Optional, and callers must fall back to the client as-is: a Model implementation that does not support it still works, it just keeps its own budget.

type Component

type Component interface {
	Name() string
	Enabled(*Ctx) bool
}

Component is the common surface: identity + a per-request enable check.

func New

func New(name string, raw []byte) (Component, error)

New builds a single component by name with its raw config block.

type Configurable

type Configurable interface {
	Configure(raw []byte) error
}

Configurable receives its typed config block from the registry/loader.

type Constructor

type Constructor func(raw []byte) (Component, error)

Constructor builds a component instance. It receives the raw config block for its name (may be nil), so a component can be configured purely from YAML with no core change. Returning an error aborts pipeline construction.

type Ctx

type Ctx struct {
	Ctx     context.Context
	Session string
	Store   store.Store
	Model   ModelSpec
	// Bypass short-circuits the whole pipeline (x-context-guru-bypass header).
	Bypass bool
	// CtxWindow is the model's max input tokens for THIS request, resolved by the
	// host (dynamically, via internal/modelinfo). 0 = unknown, in which case
	// fraction-based Trigger thresholds are ignored and only absolutes apply. Stored
	// as a resolved int so Trigger stays a pure, network-free, unit-testable function.
	CtxWindow int
	// CacheAware is true when this request goes to a prompt-caching backend and the
	// pipeline should avoid mutating already-cached content. When true, supersession/
	// age-based offloaders (failed_run, mask, collapse) must restrict their
	// mutations to the uncached tail (message index > MaxCachedIdx) so they don't
	// invalidate the provider's KV cache at a full→collapsed transition. Deterministic
	// tail/in-place offloaders (dedup, cmdfilter, extract) are already byte-stable on
	// the unchanged prefix and ignore this. False = legacy compact-everything.
	CacheAware bool
	// ColdCache is true when this session has been idle longer than the provider's prompt
	// cache TTL, so the cached prefix CacheAware exists to protect is certainly gone.
	//
	// It is INFORMATION, not a global lifting of the tail gate: the gate stays where it is
	// and each component opts in. mask, failed_run and collapse opt in BY DEFAULT since
	// 2026-08 (their replacements are pure functions of (content, config), which is what
	// makes a decision taken at depth re-derivable on every later warm turn); readlifecycle
	// and skeleton do not, because theirs are not. `cold_cache: false` restores the gate per
	// component. See coldCacheDefault in components/offload for the measurement that flipped
	// it — 90.8% of the context was being frozen on turns whose cache had already expired.
	//
	// False means "warm, or unknown". A new session, an evicted tracker entry and the first
	// turn after a restart all read false: acting on a fabricated idle time would invalidate
	// a live cache, which costs a full cache-write of the suffix at 1.25x the fresh rate.
	ColdCache bool
	// ModelName is the id of the model this request targets, so a component that reuses it
	// (model.source: incoming, the default for the LLM components) can say WHICH model it
	// called instead of recording an empty string.
	ModelName string
	// SelfRates are the per-token rates for the model a component would call itself — the
	// incoming model's, since that is what `source: incoming` uses. Zero when unknown.
	SelfRates TokenRates
	// RatesFor resolves the operator's rate card for ANY model id, not just the incoming
	// one. nil, or a zero return, means "not on the card" and the component must fall back.
	//
	// It exists because a component that names its own cheap model (`model.model:
	// claude-haiku-4-5`) could not price it: SelfRates covers the request's model and nothing
	// reached the host's price table, so the economic gate spent against the built-in haiku
	// LIST rates while the dashboard priced the same call from the operator's card. MEASURED
	// on this deployment: `cheap_model_price_unconfigured` was recorded on 1,770 of 1,770
	// requests, so every allow/suppress decision in the window was made against the wrong
	// card, and the same 93 calls were booked at $0.7946 in extraction_calls.cost_usd against
	// $0.6039 in requests.cg_llm_cost_usd — 32% apart, for one set of calls. Two numbers for
	// one invoice is not a rounding difference; it is a component and a dashboard disagreeing
	// about whether a configuration pays.
	RatesFor func(model string) TokenRates
	// IdleMs is how long this session was idle before this request, in milliseconds; 0 when
	// there is no previous turn on record. Carried alongside ColdCache so a component can
	// demand MORE idle time than the provider TTL implies, and so the figure can be
	// reported rather than re-derived.
	IdleMs int64
	// MaxCachedIdx is the highest req.Input index considered already committed to the
	// provider cache (the messages present on the previous turn of this session).
	// -1 = unknown/first turn/cache off ⇒ no tail restriction. Only meaningful when
	// CacheAware is true.
	MaxCachedIdx int
	// PrefixAsk, when non-nil, lets a component put a question to the request's own model with the
	// previous turn's SENT body as the prefix, so the provider reads its prompt cache instead of
	// being re-sent the transcript. See PrefixAsker for why that body and not the incoming one.
	PrefixAsk PrefixAsker
	// CacheTTLMs is how long this request's prompt cache is assumed to live, in milliseconds, as
	// DERIVED from the request rather than assumed: for the Anthropic family the body declares it
	// (a bare `ephemeral` mark is 5 minutes, an explicit `ttl: "1h"` is an hour), widened to the
	// longest lifetime this prefix has ever asked for. 0 when unknown.
	//
	// Carried alongside IdleMs and ColdCache so a component can reason about where in the cache's
	// LIFETIME this turn falls, not merely whether the entry is already gone. extract_llm_sweep
	// needs exactly that: a prefix ask must read a cache that still EXISTS, while rewriting deep
	// history wants one that is nearly worthless — which is a window before expiry, not after it.
	CacheTTLMs int64
	// FilterStats receives cmdfilter's per-filter ledger (which command families pay
	// off, and which output shapes matched nothing). nil = not recording.
	//
	// Read it through Stats(), never directly: in observe mode nothing is forwarded, so
	// recording into an enforced-namespace field would report savings that never happened.
	FilterStats FilterStatsSink
	// ExistingBreakpoints is how many prompt-cache breakpoints the RAW request already
	// carries, counted across `system`, `tools` and `messages` — which is what the
	// provider's cap of four applies to. A component that spends breakpoint slots must
	// budget against this number rather than what it can see in Input, for two reasons
	// measured on real Claude Code traffic: 2 of its 3 breakpoints live in the
	// top-level `system` array, which components never see at all, and the third sits
	// on a `tool_result` block whose mark the host's own normalize step drops. Both
	// were invisible, so the budget came out as 3 free slots when only 1 was free —
	// enough to put 6 on the wire and take a 400 (issue #32). The host fills it from
	// the raw body; 0 means "unknown, fall back to what you can see".
	ExistingBreakpoints int
	// Mode is the operating mode this request runs under. Components that behave
	// differently off the request path read this rather than inferring anything.
	Mode Mode
	// SystemSplit says the host already split a volatile tail out of the top-level
	// `system` array for this request. Only `cachesplit` reads it, and only to report
	// itself honestly: the split is body-level work that happens in the host (components
	// never see the system array), so without this the marker component reported Skipped
	// on the very requests where the mechanism had just run — and everything downstream
	// derives "did it do anything" from that.
	SystemSplit bool
	// ToolSchema says the host already stripped JSON-Schema annotation keywords from
	// the top-level `tools` array for this request. Only `toolschema` reads it, and
	// only to report itself honestly — same arrangement, same reason, as SystemSplit.
	ToolSchema bool
	// FilteredDecls is how many tool/MCP declarations the host dropped from `tools` on
	// this request under the account's opt-in removal list. Set for the same reason
	// ToolSchema is: `tools` is a top-level field no component can see, so toolfilter
	// would otherwise report itself as skipped on every request where it just acted.
	FilteredDecls int
}

Ctx is the per-request runtime handed to every component.

func (*Ctx) Stats added in v0.1.1

func (c *Ctx) Stats() FilterStatsSink

Stats returns the per-filter ledger sink, or nil in observe mode.

Observe computes what compaction WOULD have done and forwards the request untouched, so every enforced-namespace metric must stay zero: a figure that cannot be told apart from a real saving is worse than no figure, because it silently inflates the product's own headline. The savings totals are already namespaced (potential_* / projected_*), but the filter ledger is not — an observe-only run was reporting real-looking `cmdfilter_families` and `cmdfilter_filters` entries with no mode label and no hypothetical counterpart.

Gating here rather than at the call site is deliberate. A component author reaching for c.FilterStats has no reason to think about modes, and the next sink added to Ctx would reproduce the bug; an accessor makes the safe path the only convenient one.

Two enforced fields are deliberately NOT suppressed in observe mode, because they are real rather than hypothetical: cg_added_ms_avg (a true measurement of the enforced path, which correctly reads ~0) and context-guru's own model spend (observe measures off-path, and that costs real money). Those are labelled instead — see metrics.Snapshot's observe notices.

func (*Ctx) TailOnly

func (c *Ctx) TailOnly(i int) bool

TailOnly reports whether a supersession/age-based offloader may mutate the message at index i without risking the provider's cached prefix. When cache-awareness is off or the boundary is unknown, every index is fair game (legacy behavior).

func (*Ctx) TailOnlyCold added in v0.1.1

func (c *Ctx) TailOnlyCold(i int, optIn bool) bool

TailOnlyCold is TailOnly with the depth restriction lifted on a turn whose prompt cache is provably gone (ColdCache), for a component that opted in.

The opt-in is per component. It defaults ON for the three whose replacement is a pure function of (content, config) — mask, failed_run, collapse — and OFF for the two whose is not. When ColdCache is right there is no prefix to disturb, so acting at depth is free by construction; when it is WRONG the component flips content the provider is still holding and forces a cache-write of the whole suffix at 1.25x the fresh rate, where a missed cold turn only forgoes a saving. That asymmetry is why the DETECTION is conservative rather than why the default is off: see cacheIsCold, sessionTTL and the alias clock in apply/apply.go, and docs/design.md.

Only safe for a component whose replacement is a pure function of (content, config) — the same property repairLostFreeze requires — because the decision it makes at depth is frozen and replayed on every later (warm) turn.

type Emitter

type Emitter interface {
	Component(Report)
	Run(RunReport)
}

Emitter receives one Report per component and one RunReport per request. Defined here (not in metrics) so the pipeline has no dependency on any concrete telemetry backend; metrics provides the implementations.

type Field added in v0.1.1

type Field struct {
	// Key is the DOTTED path of the key inside the component's block —
	// `cold_cache.min_tokens`, `model.source` — so a nested block needs no nesting here.
	Key string `json:"key"`
	// Type is one of the Field* constants below. It tells the form what control to draw
	// and the server what a posted value must decode to.
	Type string `json:"type"`
	// Default is what an ABSENT key means to the component, i.e. what the form should show
	// greyed as the fallback. It is NOT the recommended prefill — that is a policy layer
	// (see config.RecommendedExtractLLM), and conflating the two is how a form ends up
	// writing its own opinion over an operator's deliberate value. nil = the type's zero.
	Default any `json:"default,omitempty"`
	// Options is the permitted set for Type == FieldEnum, in display order.
	Options []string `json:"options,omitempty"`
	// Hint is one line of prose for the field, taken from the doc comment already written
	// on the config struct.
	Hint string `json:"hint,omitempty"`
	// Secret marks a credential: the form must never echo a stored value back, and the
	// control is write-only.
	Secret bool `json:"secret,omitempty"`
	// Min is the smallest accepted number. It carries real semantics: 0 on a CAP means
	// "unlimited" and is a legitimate choice, while a size threshold with Min 1 rejects 0
	// because 0 there is not a setting, it is a removed brake.
	Min int `json:"min,omitempty"`
}

Field describes ONE configurable key of one component, for the settings form. It is form metadata only: nothing in the run path reads it, and a component's constructor behaves identically whether or not its fields are declared.

It exists because the settings page used to hand-list the keys it knew about, in Go and again in JavaScript, and nothing could notice an omission: the form exposed 18 keys of ~100, one component of fifteen, and the keys it did expose had already drifted from the values the engine accepts (a stored `strategy: deterministic` was not recognised and got REWRITTEN to `code`, silently turning an LLM-free configuration into one that makes model calls). Declaring the keys beside the config struct they describe, and deriving the form from that, makes the omission a compile-or-test failure instead of a silent one.

func Fields added in v0.1.1

func Fields(name string) []Field

Fields returns a component's declared fields, in declaration order.

func TriggerFields added in v0.1.1

func TriggerFields(prefix string) []Field

TriggerFields declares Trigger's keys for the settings form, under prefix (normally "trigger"). It lives beside the struct so a new threshold cannot be added without the form learning about it — the fields parity test compares these keys against the struct's yaml tags.

type FilterStatsSink added in v0.1.1

type FilterStatsSink interface {
	// FilterAct notes one applied filter: its family (builds/tests/iac/pkg/net/...),
	// its name, the content key (so a compaction re-sent verbatim next turn is counted
	// once), and the tokens saved.
	FilterAct(family, filter, contentKey string, saved int)
	// FilterMiss notes a selector that matched no filter — the ledger that says which
	// filter is worth writing next (after rtk's parse_failures table).
	FilterMiss(selector string)
}

FilterStatsSink records cmdfilter's per-filter/per-family ledger. metrics.Aggregator implements it; the pipeline depends only on this interface. Implementations must be safe for concurrent use.

type Mode added in v0.1.1

type Mode string

Mode is context-guru's operating mode for one request. The host sets it explicitly (proxy Options / config `mode:`); it is NEVER inferred.

ModeSync    — compact inline; the caller waits and the compacted request is sent.
              The default, byte-identical to pre-mode behavior.
ModeObserve — the pipeline runs on a copy whose output is discarded. The agent
              receives the untouched original; results land in a strictly separate
              (hypothetical) metric namespace.

An async mode — deferring compaction off the request path — is designed and implemented on a separate branch (#31/#35), held back because its measured benefit collapsed once the expensive component stopped running on caching backends. Mode is a closed set here so an unknown value fails loudly rather than silently meaning sync.

const (
	ModeSync    Mode = "sync"
	ModeObserve Mode = "observe"
)

The operating modes. See Mode.

func ParseMode added in v0.1.1

func ParseMode(s string) (Mode, error)

ParseMode validates a configured mode string; empty means sync.

type Model

type Model interface {
	Complete(ctx context.Context, prompt string) (string, error)
}

Model is the minimal LLM surface a component may call: one prompt in, text out. internal/cheapmodel's Anthropic and OpenAI clients implement it.

type ModelCall added in v0.1.1

type ModelCall struct {
	Component string
	Model     string
	Strategy  string
	// Aggressiveness is the compaction target asked for, so a level's real effect on this
	// workload can be read off recorded calls instead of inferred.
	Aggressiveness string
	// Cold marks a call made during a cold-cache sweep, whose economics differ by ~12.5x.
	Cold bool
	// Escalated marks a call that fell back to the agent's own model because the transcript
	// did not fit the extraction model's window.
	Escalated       bool
	CandidateTokens int
	SavedTokens     int
	LatencyMs       float64
	// Token usage of the CALL itself, split by tier, and its cost priced with the extraction
	// model's rates rather than the agent's.
	PromptTokens     int64
	CompletionTokens int64
	CacheRead        int64
	CacheWrite       int64
	CostUSD          float64
	Accepted         bool
	// GateReason is what the economic gate concluded, including when it was overridden — the
	// counterfactual an operator needs to see after choosing to override it.
	GateReason string
	// Rejection says why a call produced nothing: no usable reply, a result that was not
	// smaller, or one the acceptance check refused. Empty on success. Without it every
	// failure looked identical, and they have opposite fixes.
	Rejection string
	Summary   string
	Before    string
	After     string
}

ModelCall is one LLM call a component made, with what it cost and what it bought.

It exists because "this component spent money" was previously a single dollar figure per REQUEST, priced at the agent model's rate, with no record of how many calls made it up, which candidate each looked at, whether it was accepted, or what the gate thought. For the one component that can be net-negative, that is the difference between an operator being able to answer "was that worth it?" and having to guess.

Before/After hold the candidate's text either side of the call. They are transcript content, so whether they are ever PERSISTED is decided downstream by the same per-account capture consent that governs the diff view — this struct only carries them.

type ModelSpec

type ModelSpec struct {
	Incoming Model
	Static   Model
}

ModelSpec carries the LLM clients a NeedsModel component may use, resolved per request by the host adapter. Incoming is the proxied request's own model + credentials (nil when unavailable, e.g. the AuthBridge host); Static is a configured cheap model (nil when none is configured). A component selects one by its own `model.source` config via For.

func (ModelSpec) For

func (m ModelSpec) For(source string) Model

func (ModelSpec) ForModel added in v0.1.1

func (m ModelSpec) ForModel(source, id string) Model

For returns the client the component's configured source asks for: "config" -> the static cheap model; anything else ("incoming"/unset) -> the incoming model, falling back to the static one when there is no incoming client. Returns nil when nothing is available, and the caller must degrade gracefully. ForModel is For plus an optional model-id override: when id is set and the selected client can be re-pointed, the returned client talks to id instead of its own model. An id the client cannot honour is ignored rather than fatal — the component still runs, on the model it would have used anyway, and the caller sees that in the recorded model name.

func (ModelSpec) ForModelSource added in v0.1.1

func (m ModelSpec) ForModelSource(source, id string) (Model, string)

ForModelSource is ForModel plus the source actually used — see ForSource.

func (ModelSpec) ForSource added in v0.1.1

func (m ModelSpec) ForSource(source string) (c Model, used string)

ForSource is For, plus the source that was ACTUALLY used. It exists because the fallback below is silent and the substitution is not cosmetic: `source: incoming` means "spend on the model and credential the caller is already paying for", and falling back to the static one spends a DIFFERENT credential on a DIFFERENT model. A component that cannot tell the difference cannot report it, and an operator reading `model.source: incoming` in their config has no way to learn that none of their calls went there.

Cost a real investigation: a local run's extraction calls failed authentication, and because the fallback is invisible there was no way to tell whether the caller's credential or the operator's static one was being presented. Callers should record `used` (extract_llm gates on it) rather than assume the configured source is the one that ran.

type NeedsModel

type NeedsModel interface {
	NeedsModel() bool
}

NeedsModel is implemented by components that call an LLM (extract's code/rlm strategies, summarize). A component that needs a model but finds none available (Ctx.Model.For returns nil) MUST degrade gracefully — fall back to a deterministic path or no-op — never fail the request.

type NopEmitter

type NopEmitter struct{}

NopEmitter discards all telemetry. Default when none is configured.

func (NopEmitter) Component

func (NopEmitter) Component(Report)

func (NopEmitter) Run

func (NopEmitter) Run(RunReport)

type Offload

type Offload interface {
	Component
	Offload(req *schemas.BifrostChatRequest, rep *Report, c *Ctx) (cacheKeys []string, err error)
}

Offload is a lossy-but-reversible component: it drops bytes from the wire and returns the cache_keys under which it stashed the originals (via c.Store) — one per offloaded item. If it shrinks the request but returns no keys, the pipeline treats it as a failed offload and reverts (you cannot silently lose data) — UNLESS it set rep.Irreversible, the deliberate lossy drop a non-`full` marker_mode makes (summary/off: no stash, no restoration). Returning no keys AND leaving the request unchanged is a legitimate no-op (set rep.Skipped). Examples: collapse, dedup, cmdfilter, extract, smartcrush.

type Pipeline

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

Pipeline runs an ordered list of components over a request. Order is set by config (the pipeline: name-list); this type just executes it. Each component is isolated: a panic or error reverts only that component, and a component that fails to shrink the request is reverted too (never-worse guard, after rtk). The original request is always a valid fallback — fail open, always.

func NewPipeline

func NewPipeline(comps []Component, e Emitter) *Pipeline

NewPipeline builds a pipeline from already-constructed components in order.

func (*Pipeline) Find added in v0.1.1

func (p *Pipeline) Find(name string) Component

Find returns the configured component with this name, or nil. It is Has for the case where the host needs the component's CONFIGURATION and not just its presence — toolfilter carries the account's removal list, and a body-level transform in apply cannot read it off a boolean. Callers type-assert to the narrow interface they need.

func (*Pipeline) Has added in v0.1.1

func (p *Pipeline) Has(name string) bool

Has reports whether a component with this name is configured in the pipeline. Hosts use it to gate body-level work that belongs to a component's concern but cannot be done inside it — e.g. cacheinject's cache-prefix repair, which must touch the top-level `system` array that components never see.

func (*Pipeline) HasOffload added in v0.1.1

func (p *Pipeline) HasOffload() bool

HasOffload reports whether any component in this pipeline is an Offload — i.e. whether a request through it can produce a `<<cg:HASH>>` marker at all.

Asked by the host to decide whether advertising `context_guru_expand` is meaningful. A pipeline with no Offload mints no markers, so every expand call a model makes against it MUST fail: there is nothing in the Store to resolve. Advertising it there costs a wasted round trip and a step of the user's turn to learn that.

A type assertion, deliberately, rather than a list of component names: a name list is a second copy of "which components are lossy" that drifts the moment somebody adds one, and the interface is the definition. `components.Offload` cannot be implemented by accident — it requires returning cache keys that prove the original was stashed.

func (*Pipeline) RecordDiscards added in v0.1.1

func (p *Pipeline) RecordDiscards(rr *RunReport, discarded map[int]int)

RecordDiscards emits one follow-up Report per component whose changes the writeback layer threw away, so a silently-suppressed component is visible in telemetry instead of looking like a working one. discarded maps req.Input index -> number of discarded changes at that index; hosts call this after the splice.

One discarded message is charged to exactly ONE component: the LAST one that changed that index. Several components can touch the same message, but the writeback layer discards the final cumulative state, so that component's change is the one actually thrown away — charging every earlier toucher too would make this counter a false-positive generator, and its whole point is to be trustworthy enough to catch a #32-class bug.

func (*Pipeline) Run

func (p *Pipeline) Run(req *schemas.BifrostChatRequest, c *Ctx) *RunReport

Run applies every enabled component to req in place and returns the aggregate report. req is mutated; on any per-component failure that component's changes are rolled back, so the returned request is never worse than the input.

type PrefixAsker added in v0.1.1

type PrefixAsker interface {
	Ask(ctx context.Context, session, ask string) (reply string, usage PrefixUsage, err error)
}

PrefixAsker completes `ask` as a trailing user message appended to the EXACT body this session sent upstream on the PREVIOUS turn.

WHY THE PREVIOUS TURN'S SENT BODY AND NOT THE INCOMING ONE. The provider's prompt cache was populated by what context-guru emitted, which is the COMPACTED form. The incoming body is uncompacted, so it diverges from the cached bytes at the first thing any component removed, and everything after that point is a miss. Appending to the bytes actually sent is the only construction that reliably reads the cache — measured at 19,595 read against 0 created.

THE CONSEQUENCE, stated here rather than left to be rediscovered: the ask sees the transcript as of the PREVIOUS turn, so the newest tool output is invisible to it. That is acceptable for the judgement this serves — the missing part is tail content, which has had no turns in which to be superseded and would be kept anyway — and it has the side benefit of keeping a large model call off the agent's critical path.

nil when the host cannot support it: no stashed body for this session yet, the first turn, a non-Anthropic route, or the feature switched off. A caller must decide for itself what nil means; see extract_llm_sweep, which DECLINES rather than falling back, because the fallback is the cost the mechanism exists to avoid.

type PrefixUsage added in v0.1.1

type PrefixUsage struct {
	CacheRead  int
	CacheWrite int
	Fresh      int
	Output     int
	// ViaTool records that the answer arrived as a tool_use for the proxy's own structured-answer
	// tool rather than as reply TEXT. Reported for the same reason CacheRead is: a caller that
	// declares a verdict tool in order to get a schema-shaped answer cannot otherwise tell whether it
	// got one. A sweep whose tool is never used and a sweep that works look IDENTICAL in every other
	// counter -- both return parsed verdicts and real savings -- because the prose parser accepts
	// both. Measured: a review of PR #137 found 0 of 5 live asks using the declared tool while every
	// verdict arrived through the text path, and no counter in this repo could show that.
	ViaTool bool
}

PrefixUsage reports what one PrefixAsk cost, straight from the provider's usage block. It exists because the whole point of a prefix ask is the cache READ, and a cache read that silently is not happening looks identical to one that is — except on the bill.

RETURNED rather than merely recorded, and that is the load-bearing part of this type. A caller whose entire justification is the cache read has to be able to gate on whether the read happened, which a metrics counter cannot support.

type Reformat

type Reformat interface {
	Component
	Reformat(req *schemas.BifrostChatRequest, rep *Report, c *Ctx) error
}

Reformat is a lossless component: it repacks the request denser in place and loses no information. Examples: format re-encode, code skeleton, cache_control injection.

type Remodeler added in v0.1.1

type Remodeler interface {
	AsModel(id string) Model
}

Remodeler is an optional interface on a Model: the same endpoint and the same credential, pointed at a DIFFERENT model id. It exists for one measured reason.

The incoming-source client is the proxied request's own model, which for a coding agent is a frontier model. Compaction on a frontier model cannot pay: measured on a real Claude Code session through the hosted service, a cold-cache sweep cut the provider bill by $0.63 and spent $1.25 of opus doing it — net MINUS $0.62. The same work on a cheap model is roughly an order of magnitude less on the call side, which is the difference between a component that pays and one that does not.

The static ("config") source cannot supply that cheap model on a multi-tenant deployment, because there the operator will not spend its own credential on a tenant's traffic. So the remaining honest option is the tenant's OWN credential and upstream with a cheaper model id on it, which is exactly what this returns.

type Report

type Report struct {
	Component    string
	Kind         string // "reformat" | "offload"
	TokensBefore int
	TokensAfter  int
	DurationMs   float64
	// CacheKeys are this run's content-derived dedup keys. An Offload sets them itself,
	// one per stashed original (they double as the store keys the expand loop resolves). A
	// Reformat stashes nothing, so the PIPELINE fills them from the pre-fold text of each
	// message it rewrote — without that, every Reformat took metrics' keyless fallback and
	// reported SavedUnique == Saved by construction (overcount_ratio 1.0 for
	// format/textclean/toon/searchfold, against a measured token replay of 10x-95x).
	CacheKeys    []string
	Skipped      bool // component ran but chose not to act
	Reverted     bool // pipeline reverted it (error/panic/never-worse)
	Irreversible bool // Offload dropped content on purpose without stashing (marker_mode summary/off)
	Err          error
	// ChangedIdx are the req.Input indices this component modified, filled by the
	// pipeline. The writeback layer uses them to attribute a discarded change back to
	// the component that made it (see Pipeline.RecordDiscards).
	ChangedIdx []int
	// Discarded counts changes this component made that the WRITEBACK layer then threw
	// away (bifrost could not round-trip the message, so splicing would have dropped
	// provider fields). A report carrying Discarded > 0 is a follow-up attribution, not
	// a fresh run — emitters must not count it as one. A component that mutates and is
	// then silently discarded looked identical to one that works, which is how issue
	// #32 survived two benchmark studies.
	Discarded int
	// Mode is the operating mode the run happened under, stamped by the pipeline from
	// Ctx.Mode. Emitters MUST branch on it: an observe-mode report is a HYPOTHETICAL and
	// may never be summed into enforced savings.
	Mode Mode
	// Gates counts, per named gate, how many CANDIDATES this component turned away — either
	// declined outright or resolved without a fresh decision (extract_llm's reapplied_*).
	// "acted: 0" is the one number a diagnosis can't use — it cannot tell a component
	// with nothing to do from one whose guard is misfiring, which is how eight components
	// sat at zero on a whole workload without anyone being able to say which case each
	// was in. Filled by the component via Gate(); rolled up into /stats per component.
	Gates map[string]int
	// Events counts, per named event, things this component DID rather than declined — a cache
	// hit replayed, a candidate reached at depth, an output removed, an inventory offered.
	//
	// Separate from Gates because they were one map and the name lied. Everything in Gates is
	// exported as `cg_component_gate_declines_total`, so `reapplied_same_session` (a cache HIT)
	// and `sweep_dropped` (a removal that WORKED) were being counted as declines: anyone summing
	// that series to gauge whether the pipeline was doing anything got the wrong SIGN, because the
	// more a component succeeded the higher its "declines" climbed. Splitting the map rather than
	// classifying names in the exporter puts the judgement at the call site, where the author knows
	// which one it is, instead of in a lookup table that goes stale the next time a gate is added.
	//
	// A name must not appear in both maps for one component: that would mean the component cannot
	// say whether the thing succeeded or was refused, and TestGatesAndEventsAreDisjoint pins it.
	// Filled via Event()/EventN(); rolled up into /stats beside Gates.
	Events map[string]int
	// Calls records each LLM call this component made on this request. Empty for every
	// deterministic component; one entry per model call for the two that make them.
	//
	// Assigned SERIALLY by the component, never appended to from a goroutine: a Report is
	// copied by value all over this codebase (emitters take one), so it cannot carry a lock.
	// extract_llm fans out into a pre-sized slice and assigns the result once, which is the
	// same shape its projected-output collection already uses.
	Calls []ModelCall
	// Replays counts changes this component made by REPLAYING a decision it had already taken
	// and frozen — the same bytes it emitted on an earlier turn, spliced again with no model
	// call and no new spend.
	//
	// It exists because /stats could not tell a replay from an act (#176). `acted` is
	// `Saved() > 0`, and a replay saves tokens, so a component whose every activation was a
	// free replay of work done days ago reported `acted: 239` — indistinguishable from 239
	// paid extractions. MEASURED (iteration 023, arm B): 239 acts, 2,291 replays, and the
	// component's own record showing zero surviving candidates, i.e. not one fresh call. The
	// two readings have opposite consequences ("this component is expensive, turn it off"
	// against "this component is amortizing, leave it on"), so they cannot share a counter.
	//
	// Set via Replay(), which also files the descriptive Event, so the count and the histogram
	// cannot drift apart.
	Replays int
}

Report is the per-component result, modelled after lean-ctx's ToolOutput token accounting and headroom's record_pipeline_run inputs. The pipeline fills TokensBefore/After/DurationMs; the component fills CacheKey and may set Skipped. It feeds every Emitter.

func (*Report) Event added in v0.1.1

func (r *Report) Event(name string)

Event records that the component DID the named thing once — a replay served, a candidate reached at depth, an output removed. The counterpart to Gate, and the distinction is the whole reason both exist: a decline and a success exported under one metric name called "declines" produced a series whose value rose as the component worked better. See Report.Events.

Same stability rule as Gate: the names are read off /stats and scraped by label.

func (*Report) EventN added in v0.1.1

func (r *Report) EventN(name string, n int)

EventN records n at once, for an event whose subject is a COUNT rather than a single candidate — how many were offered, how many were removed. GateN's rationale applies unchanged.

func (*Report) Gate added in v0.1.1

func (r *Report) Gate(name string)

Gate records that one candidate was declined by the named gate. Names are the component's own vocabulary (e.g. "min_size", "no_filter_match", "marker_no_win"); keep them stable, they are read off /stats.

func (*Report) GateN added in v0.1.1

func (r *Report) GateN(name string, n int)

GateN records n at once, for a gate whose subject is a COUNT rather than a single candidate.

It exists because a per-candidate loop cannot express "this many were OFFERED". The distinction is not cosmetic: a live batched-adjudication arm reported 2.80 verdicts per call and that was read as the batch size, when it counted what the model chose to ANSWER rather than what it was SHOWN. The truncation counter was firing on 43 of 162 calls at the same time, which is arithmetically impossible for batches of 2.8 — the resolution being that the model silently omitted labels. Without a way to count the offer, "the batch is starved" and "the model answered for a third of the batch" are the same number, and the first reading cost three iterations.

func (*Report) Replay added in v0.1.1

func (r *Report) Replay(name string)

Replay records that one change on this request came from replaying an already-frozen decision, under the descriptive event name the component uses for it.

It files BOTH the Event and Report.Replays deliberately, in one call: the Events histogram is the operator-facing vocabulary ("reapplied_same_session" vs "reapplied_cross_session") and Replays is the machine-readable "this cost nothing" that /stats needs to keep replays out of `acted`. Two separate calls at each site is how one of them gets forgotten when a third replay path is added — which is precisely how the free path came to be counted as paid work.

func (Report) Saved

func (r Report) Saved() int

Saved returns non-negative tokens saved by this component.

type RunReport

type RunReport struct {
	Session      string
	TokensBefore int
	TokensAfter  int
	DurationMs   float64
	Components   []Report
	// Mode is the operating mode this run happened under (see Report.Mode).
	Mode Mode
}

RunReport aggregates a whole pipeline run for one request.

func (RunReport) Saved

func (rr RunReport) Saved() int

Saved returns the net tokens saved across the run.

type TokenRates added in v0.1.1

type TokenRates struct {
	Input      float64
	Output     float64
	CacheRead  float64
	CacheWrite float64
}

TokenRates are per-token USD rates for the model a component would call ITSELF, so a component that spends money can price its own calls correctly.

It exists because the alternative was a constant. extract_llm priced every call it made at claude-haiku rates, while the shipped default routes extraction to the AGENT's model — so a call on a sonnet-class model was recorded, and judged by the economic gate, at roughly a third of what it actually cost. MEASURED on a real session: a call recorded at $0.0276 had really cost about $0.083.

Zero means unknown, and a caller must then fall back rather than treat a call as free.

func (TokenRates) Cost added in v0.1.1

func (r TokenRates) Cost(fresh, output, cacheWrite, cacheRead int64) float64

Cost prices one call's four token tiers.

func (TokenRates) Zero added in v0.1.1

func (r TokenRates) Zero() bool

Zero reports whether no rate is known.

type Trigger

type Trigger struct {
	MinRequestTokens int `yaml:"min_request_tokens"` // whole request must be at least this many tokens
	MinMessages      int `yaml:"min_messages"`       // …and carry at least this many messages (≈ steps)
	MinOutputTokens  int `yaml:"min_output_tokens"`  // per-item floor: only offload an output at least this big

	// Context-window fractions (0 = unset) make triggers general across models:
	// each is resolved against Ctx.CtxWindow (the model's max input tokens, obtained
	// dynamically). When the window is unknown (0) fractions are ignored and only the
	// absolute thresholds apply — fully backward compatible.
	MinRequestFrac float64 `yaml:"min_request_frac"` // fire when request >= frac*window (e.g. 0.6)
	MinOutputFrac  float64 `yaml:"min_output_frac"`  // per-item: only offload an output >= frac*window
	HugeOutputFrac float64 `yaml:"huge_output_frac"` // HARD per-item trigger: a single output >= frac*window
}

Trigger is the shared, configurable gate that decides whether an expensive (LLM-based) component should ACT on a request — so summarize/extract run only when it's worth an LLM call, not on every turn. It is embedded in a component's config as `trigger:` and works for any agent/benchmark/use-case because the thresholds are pure request shape (tokens and message count), not task-specific.

A zero field is "no constraint", so the zero Trigger fires always (backward compatible with configs that don't set it). Request-level thresholds (MinRequestTokens, MinMessages) are checked by Fires; the per-item MinOutputTokens floor is checked by the component against each candidate (e.g. extract, per tool output).

func (Trigger) Fires

func (t Trigger) Fires(req *schemas.BifrostChatRequest, window int) bool

Fires reports whether the request-level thresholds are met, given the resolved model context window (0 = unknown). The effective request-token threshold is the MAX of the absolute MinRequestTokens and the fraction MinRequestFrac*window; the message-count threshold is unchanged. Thresholds are ANDed; a zero threshold imposes no constraint. Does not consider the per-item floors (OutputFloor/IsHuge).

func (Trigger) IsHuge

func (t Trigger) IsHuge(outputTokens, window int) bool

IsHuge reports whether a single tool output is large enough (>= HugeOutputFrac*window) to be a "huge tool call" hard trigger — worth acting on regardless of the request-level Fires gate. Returns false when the window is unknown or HugeOutputFrac is unset.

func (Trigger) OutputFloor

func (t Trigger) OutputFloor(window, legacyDefault int) int

OutputFloor is the per-item minimum size an Offload should act on: the absolute MinOutputTokens if set, else MinOutputFrac*window, else legacyDefault (the component's pre-trigger min_tokens default). Lets a component keep firing sensibly whether configured absolutely, as a fraction, or not at all.

Directories

Path Synopsis
Package all blank-imports every built-in component so their init() registrations run.
Package all blank-imports every built-in component so their init() registrations run.
Package dsl is a declarative, user-extensible text-filter engine, adapted from rtk's TOML filter DSL (design D11).
Package dsl is a declarative, user-extensible text-filter engine, adapted from rtk's TOML filter DSL (design D11).
Package offload holds the lossy-but-reversible components (they drop bytes and stash the original for the expand tool loop).
Package offload holds the lossy-but-reversible components (they drop bytes and stash the original for the expand tool loop).
Package reformat holds the lossless components (they repack the request denser or add caching hints without losing information).
Package reformat holds the lossless components (they repack the request denser or add caching hints without losing information).

Jump to

Keyboard shortcuts

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