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 ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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).
Types ¶
type Configurable ¶
Configurable receives its typed config block from the registry/loader.
type Constructor ¶
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
// 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
}
Ctx is the per-request runtime handed to every component.
type Emitter ¶
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 Model ¶
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 ModelSpec ¶
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 ¶
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.
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 ¶
NewPipeline builds a pipeline from already-constructed components in order.
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 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 Report ¶
type Report struct {
Component string
Kind string // "reformat" | "offload"
TokensBefore int
TokensAfter int
DurationMs float64
CacheKeys []string // set by Offload components (one per stashed original)
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
}
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.
type RunReport ¶
type RunReport struct {
Session string
TokensBefore int
TokensAfter int
DurationMs float64
Components []Report
}
RunReport aggregates a whole pipeline run for one request.
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 ¶
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 ¶
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). |