components

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: Apache-2.0 Imports: 9 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

This section is empty.

Variables

This section is empty.

Functions

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).

Types

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
	// 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.

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).

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 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 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

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

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

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.

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
}

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 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