Documentation
¶
Overview ¶
Package proxy is the context-guru HTTP proxy: it runs the component pipeline on inbound chat requests, then forwards them to the configured upstream provider. It is the eval-containers gateway (exposes /openai + /anthropic on one port) and the standalone LLM-proxy integration.
It reuses bifrost's ChatMessage type but not its transport: the transport can't inject an in-process Go plugin, so we drive the request path directly. Message rewriting is byte-lossless (headroom invariant I1) — only the `messages` array is re-serialized; every other field of the original body is preserved verbatim via sjson.
Index ¶
- Constants
- func AuthHeader(p bschemas.ModelProvider, key, scheme string) http.Header
- func CallerAuthScheme(r *http.Request) string
- func CallerKey(r *http.Request) string
- func CampaignArmEnforceable(arm string) bool
- func CampaignCellOutcome(cell dash.KVCacheSuggestion, honorsHeadTTL1h func(tenantID string) bool) (activatable bool, skipReason string)
- func HeadTTL1hHonored(model string) bool
- func IsPasswordRoute(method, path string) bool
- func MailConfigured() (bool, string)
- func PasswordRoutePatterns() []string
- func PrefixStashOversized() int64
- func RegisterMode() string
- func ResetUsageShapeRecordForTest()
- func TokenFromRequest(r *http.Request) string
- func UsageGaps() (unparsed, unreadable int64)
- type AuthMode
- type BuiltConfig
- type CachePolicy
- type CheapModelConfig
- type ConfigBuilder
- type Dispatcher
- func (d *Dispatcher) Do(ctx context.Context, req dispatch.Request) (dispatch.Response, error)
- func (d *Dispatcher) Pin(base string, auth http.Header) dispatch.Ref
- func (d *Dispatcher) Price(ctx context.Context, endpoint, model string, promptTokens int64) (dispatch.Price, bool)
- func (d *Dispatcher) Release(ref dispatch.Ref)
- type Handler
- func (h *Handler) API() *dash.API
- func (h *Handler) Close()
- func (h *Handler) DashAdaptConfig() dash.AdaptCompactionConfigFunc
- func (h *Handler) DashAuth() dash.Authenticator
- func (h *Handler) DashToolFilter() func(string) dash.ToolFilterState
- func (h *Handler) DashWhoami() func(*http.Request) any
- func (h *Handler) KeepAlivePingStates(tenantID string, allTenants bool, session string) map[string]dash.PingState
- func (h *Handler) KeepAlivePlans(tenantID string, allTenants bool, session string) map[string]dash.KeepAlivePlan
- func (h *Handler) MountControl(m *http.ServeMux)
- func (h *Handler) Mux() *http.ServeMux
- func (h *Handler) PendingPings() int
- type KeepAliveStats
- type Limiter
- func (l *Limiter) Acquire(tenantID string) (release func(), err error)
- func (l *Limiter) AcquireCheapModel(done <-chan struct{}) (release func(), ok bool)
- func (l *Limiter) AcquireSpare(tenantID string, reserveFrac float64) (release func(), err error)
- func (l *Limiter) AllowAction(key, what string, perHour int) error
- type Limits
- type LiveFacts
- type ObserveOptions
- type Options
- type SavingsScope
- type SavingsStats
- type SpendChecker
- type StatusError
- type Tenancy
- type TenantMetricRow
- type TenantMetricsSource
- type TenantSource
- type Upstream
- type Usage
Constants ¶
const DefaultMaxTenancies = 256
DefaultMaxTenancies bounds how many tenants hold live pipelines and stores at once. Each is a few hundred KB of state plus its store's entry cap, so this is a memory bound; a box serving more than this many CONCURRENTLY active users wants the number raised, not the cache removed.
const DefaultMaxUSDPerPing = keepalive.DefaultMaxUSDPerPing
DefaultMaxUSDPerPing mirrors keepalive's; pinned to config's by TestTheProxysPingCeilingDefaultMatchesTheConfigLoaders.
const IncomingRefTTL = 2 * time.Hour
IncomingRefTTL is how long an incoming-model ref (the caller's own endpoint and credential, resolved per request for a NeedsModel component) is kept after its last use. A detached call (cache_aware_summarizer's own background summary, a keep-alive substitute) can still be running after its triggering request returned, so the ref is not dropped at request end — but a request that spawns no such call must not hold the caller's credential forever either.
const ManualHoldHeader = "x-context-guru-ping"
ManualHoldHeader is how a client opts a request in to being held for the Ping button. Claude Code sends it from ANTHROPIC_CUSTOM_HEADERS (the plugin writes it into settings env); it is an x-context-guru-* header, so copyHeaders never forwards it upstream.
const TokenHeader = "x-context-guru-token"
TokenHeader is where a caller presents its context-guru token. A DEDICATED header, because the Authorization / x-api-key slot now carries the caller's OWN provider credential, which is what gets forwarded upstream — the whole point of not billing every user's traffic to one server-held key.
copyHeaders already strips every x-context-guru-* header before forwarding, so this name is safe by construction: it cannot reach an upstream.
Variables ¶
This section is empty.
Functions ¶
func AuthHeader ¶ added in v0.5.3
func AuthHeader(p bschemas.ModelProvider, key, scheme string) http.Header
AuthHeader is the header a provider credential goes in, in the exact shape incomingModel and cmd/ tools present it: x-api-key (or bearer, for an Anthropic gateway that wants one) for Anthropic, Authorization: Bearer for OpenAI.
func CallerAuthScheme ¶ added in v0.1.1
CallerAuthScheme reports HOW the caller presented the credential CallerKey returns, so a component that reuses it presents it the same way. "bearer" when it arrived in Authorization; "" — the Anthropic client's x-api-key default — for the api-key slots.
Without this the credential was reused in the wrong slot. A caller authenticating with `Authorization: Bearer <token>` (which is what Claude Code does when it is given ANTHROPIC_AUTH_TOKEN rather than ANTHROPIC_API_KEY) had its token re-sent as `x-api-key` on every extraction call, and a gateway that authenticates with bearer tokens answered 401 to all of them. `model.source: incoming` is the DEFAULT, so for that whole class of caller extract_llm could never make a single successful call — silently, because the failure was reported as "no usable program or reply".
It returns the scheme of the SAME header CallerKey picks, so the two cannot disagree.
func CallerKey ¶ added in v0.1.1
CallerKey returns the caller's OWN provider credential — the first auth slot that holds something which is not one of our tokens. "" means the caller presented no credential of their own.
func CampaignArmEnforceable ¶ added in v0.5.3
CampaignArmEnforceable reports whether a campaign can enforce arm on live traffic at all. A cell can still be skipped for its own reasons (too few requests, unpriced rows, a 1h-tier arm on a model that does not honor it) — CampaignCellOutcome answers that.
func CampaignCellOutcome ¶ added in v0.5.3
func CampaignCellOutcome(cell dash.KVCacheSuggestion, honorsHeadTTL1h func(tenantID string) bool) (activatable bool, skipReason string)
CampaignCellOutcome is what creating a campaign would do with one uploaded suggest cell: activate it (or keep it on a baseline arm), or record it with skipReason. honorsHeadTTL1h reports whether a tenant's traffic honors the 1h cache tier. It is the SAME decision ctlCreateCampaign makes, so an offline tool that builds an upload file can report it without a second copy of the rules.
func HeadTTL1hHonored ¶ added in v0.5.3
HeadTTL1hHonored reports whether model is measured to honor the 1h cache tier on this deployment — the set a campaign checks before it activates a 1h-tier arm.
func IsPasswordRoute ¶ added in v0.2.0
IsPasswordRoute reports whether a request's method and path address one of the routes PasswordRoutePatterns names.
Provided because the patterns are not all literal: "POST /api/tenants/{id}/password-reset" carries a tenant id, so a host matching on strings alone has to reimplement that wildcard — and a host that reimplements it slightly differently has a hole exactly where it thinks it has a wall. Matching lives here, next to the list it matches.
PASS r.URL.EscapedPath(), NOT r.URL.Path. This matters and is not a style preference: http.ServeMux routes on the ESCAPED path, so "%2F" inside a segment stays part of that segment and the {id} wildcard matches it. r.URL.Path is DECODED, where the same "%2F" has become a literal "/" and looks like two segments. Matching the decoded form therefore answers false for a request the mux routes to the handler:
POST /api/tenants/a%2Fb/password-reset
mux → matches {id}, handler RUNS
IsPasswordRoute(r.URL.Path) → false ← the hole
IsPasswordRoute(r.URL.EscapedPath()) → true
Callers are defended against the mistake rather than merely warned about it: a path containing a percent-encoded slash is treated as ONE segment here too, so passing the decoded path still errs towards reporting a password route rather than away from it.
method is compared case-sensitively — HTTP methods are upper-case by definition, and ServeMux does not fold them either.
func MailConfigured ¶ added in v0.1.1
MailConfigured reports whether this deployment has any way to send a code, for the startup banner — so an operator learns at boot that registration cannot complete, rather than from a user's bug report.
func PasswordRoutePatterns ¶ added in v0.2.0
func PasswordRoutePatterns() []string
PasswordRoutePatterns names every control-plane route that belongs to the PASSWORD flow: the routes that present, set or reset a password, and the account creation and verification steps that flow depends on.
"Password flow" rather than "authenticates with a password", because two entries are broader than the narrower phrasing would suggest and a host trusting this list should know which: ctlRegister takes a password and returns ErrBadPassword, ctlVerify mints the session that completes the emailed half, and POST /api/login has a token branch taken BEFORE any password work, so withdrawing it also removes a bare-token dashboard sign-in. For an external-IdP deployment that is the intent — the IdP is the only way in — but it is not only about passwords.
WHY THIS IS EXPORTED. A deployment that authenticates through an external identity provider — SSO, OIDC, an enterprise gateway — has no passwords, and these routes must then be absent rather than merely unused. Present-but-unused is not equivalent: POST /api/register and POST /api/password-reset are ctlPublic, so an unauthenticated caller can reach them and create or take over an account whose identity the IdP is supposed to be the only source of.
Such a host previously had no way to know WHICH patterns to withdraw. It had to hardcode the list, which then silently rots the moment a route is added here — the failure being a route the host believes it withdrew and did not. Asking core is what keeps the two in step.
The patterns are returned in http.ServeMux form ("METHOD /path", with a "{id}" wildcard where one exists), so a caller can compare them against its own mux registrations directly.
This function only REPORTS. Core mounts these routes exactly as before, so no existing deployment changes behaviour; withdrawal is the host's decision and the host's code.
func PrefixStashOversized ¶ added in v0.6.0
func PrefixStashOversized() int64
PrefixStashOversized returns sentStashOversized for /stats.
func RegisterMode ¶ added in v0.1.1
func RegisterMode() string
RegisterMode is registerMode, exported for the startup banner.
The banner used to switch on os.Getenv("CG_REGISTER") directly, which meant CG_REGISTER=Open (or " open", or "OPEN") logged "self-registration is off" while this file happily accepted registrations — a log line that disagrees with the enforcement is worse than none. One resolver, both callers.
func ResetUsageShapeRecordForTest ¶ added in v0.2.0
func ResetUsageShapeRecordForTest()
ResetUsageShapeRecordForTest forgets the shapes recorded so far. For TESTS only: the record is the diagnostic this whole change exists to produce, so a test has to be able to observe it, and the per-process bound makes that a one-shot for the entire binary otherwise.
func TokenFromRequest ¶ added in v0.1.1
TokenFromRequest extracts the caller's context-guru token. The dedicated header first; failing that, an auth slot — but ONLY a value shaped like one of our tokens, so a provider key is never mistaken for a token and sent to the registry.
It does not validate beyond the shape: the registry decides what a valid token is.
func UsageGaps ¶ added in v0.2.0
func UsageGaps() (unparsed, unreadable int64)
UsageGaps returns how many responses carried usage this proxy could not read (an unrecognised dialect) and how many carried bytes it could not parse at all. Non-zero on either means fresh_input_tokens / cache_read_tokens / cache_write_tokens are 0 for some route or provider while everything else about the request looks healthy.
RESPONSES, not requests, and the distinction matters when reading them against traffic: one request can drive several upstream rounds through the expand continuation loop, so a single unaccounted request can move these more than once. The 4,015-of-4,015 figure this was filed against is a per-REQUEST count, so it is not directly comparable.
Types ¶
type AuthMode ¶ added in v0.2.0
type AuthMode string
AuthMode selects how a human authenticates to the control plane.
const ( // AuthPassword is the default and today's behaviour: email, password and a mailed code. The // zero value, so a deployment that never sets CG_AUTH is unaffected by this existing. AuthPassword AuthMode = "password" // AuthExternal means an external identity provider is the ONLY way in, and the password // routes are not mounted at all. The provider is the host's business: core only needs to know // that passwords are not in use. AuthExternal AuthMode = "external" )
func ReadAuthMode ¶ added in v0.2.0
ReadAuthMode reads CG_AUTH.
Empty or unset → AuthPassword, so an existing deployment is untouched.
AN UNRECOGNISED VALUE IS AN ERROR, deliberately, and this is the whole point of reading it through a function rather than comparing a string at the call site. A typo'd security-relevant setting must never fail towards LESS secure: CG_AUTH=oauth2 silently leaving the password door open is exactly the outcome this refuses. The caller is expected to treat the error as fatal.
func (AuthMode) DisablesPasswordRoutes ¶ added in v0.2.0
DisablesPasswordRoutes reports whether the password door is withdrawn.
A method rather than an equality test at each call site: there are several, and "== something" repeated is how one of them comes to compare against the wrong thing.
type BuiltConfig ¶ added in v0.1.1
type BuiltConfig struct {
Pipe *components.Pipeline
Store store.Store
Mode components.Mode
Preset string
// Cache is the document's `cache:` block, resolved. Host-level prompt-cache policy the
// pipeline cannot express, because it acts between requests rather than during one.
Cache CachePolicy
}
BuiltConfig is what one configuration document expands to.
type CachePolicy ¶ added in v0.1.1
CachePolicy is keepalive.Policy, kept under its old name for the config builder and tests.
type CheapModelConfig ¶ added in v0.5.3
type CheapModelConfig struct {
Provider string // anthropic (default) | openai
BaseURL string // default: the provider's public API
APIKey string
Auth string // anthropic only: "" | x-api-key (default) | bearer
Model string
MaxTokens int
}
CheapModelConfig is the operator's own "config"-source cheap model: a dedicated endpoint and credential, pinned once at startup rather than resolved per request.
type ConfigBuilder ¶ added in v0.1.1
type ConfigBuilder func(doc []byte, e components.Emitter) (BuiltConfig, error)
ConfigBuilder expands a tenant's configuration document into a runnable pipeline and state store. Supplied by the host rather than called directly, so this package stays decoupled from `config` — the same arrangement Options. PipelineFor already uses, and the reason the bifrost adapter can reuse all of this without dragging the file loader in.
type Dispatcher ¶ added in v0.5.3
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher is cmd/context-guru-proxy's dispatch.Dispatcher: every call a core package makes — keep-alive pings, cheap-model completions — leaves the proxy here. It holds, per Ref, the upstream and the credential, MASKED; the core holds only the Ref.
Lock order: hold and Release may run under the keeper's lock and take d.mu; Do takes only d.mu. Nothing here calls back into the core.
func NewDispatcher ¶ added in v0.5.3
func NewDispatcher(c *http.Client) *Dispatcher
NewDispatcher returns an empty Dispatcher sending on a copy of c (nil: a default upstream transport) that never follows a redirect.
func (*Dispatcher) Do ¶ added in v0.5.3
Do sends one request. It copies the held material under its own lock, so a Release racing an in-flight call zeroizes the held copy and never the one this request is using.
Bounded by the caller's ctx: a core call has no client waiting and must never hold a connection for the ten minutes the request path's header timeout allows.
func (*Dispatcher) Pin ¶ added in v0.5.3
Pin holds base and auth for the life of the proxy and returns their Ref — the operator's configured cheap model, or a cmd/ tool's single target.
func (*Dispatcher) Release ¶ added in v0.5.3
func (d *Dispatcher) Release(ref dispatch.Ref)
Release zeroizes and forgets what a Ref held. Safe on an unknown Ref.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler serves the proxy + management routes.
func New ¶
func New(pipe *components.Pipeline, st store.Store, agg *metrics.Aggregator, opts Options) *Handler
New builds the proxy handler. agg may be nil (no /stats rollups).
func (*Handler) API ¶ added in v0.1.1
API exposes the dashboard's HTTP surface so the host can attach an authenticator. nil when the dashboard is off.
func (*Handler) Close ¶ added in v0.1.1
func (h *Handler) Close()
Close shuts down the off-path worker pool and waits briefly for its goroutines to exit, so a host that builds and discards handlers (tests, a reload) leaks none. Safe on a sync-mode handler and safe to call twice.
func (*Handler) DashAdaptConfig ¶ added in v0.5.2
func (h *Handler) DashAdaptConfig() dash.AdaptCompactionConfigFunc
DashAdaptConfig is the dashboard's read hook for the adapt report: the caller's EFFECTIVE configuration (on a single-tenant proxy, including an applied override) and the service default.
func (*Handler) DashAuth ¶ added in v0.1.1
func (h *Handler) DashAuth() dash.Authenticator
DashAuth returns the authenticator to hand dash.API.SetAuth, so the dashboard's read routes and these write routes agree on who the caller is. One resolver, so there is no way for the two halves to disagree about identity.
func (*Handler) DashToolFilter ¶ added in v0.1.1
func (h *Handler) DashToolFilter() func(string) dash.ToolFilterState
DashToolFilter is the dashboard's READ hook for an account's removal list: the inventory page needs to draw a switch per declaration, and dash holds no tenant configuration of its own. Wired in cmd/context-guru-proxy beside the capture hook.
func (*Handler) DashWhoami ¶ added in v0.1.1
DashWhoami returns the body for /api/whoami: whether this is a hosted deployment and, if the caller is signed in, everything the UI needs to render itself — so the mode probe and the first data fetch are one round trip rather than two.
func (*Handler) KeepAlivePingStates ¶ added in v0.5.4
func (h *Handler) KeepAlivePingStates(tenantID string, allTenants bool, session string) map[string]dash.PingState
KeepAlivePingStates is the keeper's per-thread ping state for one session (dash.API.SetPingStates): whether a manual ping can work, and when not, why. nil when there is no keeper.
func (*Handler) KeepAlivePlans ¶ added in v0.5.1
func (h *Handler) KeepAlivePlans(tenantID string, allTenants bool, session string) map[string]dash.KeepAlivePlan
KeepAlivePlans is the keeper's ping plan for one session's threads, keyed by thread id, for the status line's "held warm until" (dash.API.SetKeepAlivePlans). Only an entry that will still be pinged has a plan (keepalive.Keeper.Plans). allTenants matches the session in any tenant, for a single-tenant or service-wide scope.
func (*Handler) MountControl ¶ added in v0.1.1
MountControl registers the control-plane routes. Called only in hosted mode; without a tenant registry there are no accounts to manage.
func (*Handler) PendingPings ¶ added in v0.1.1
PendingPings reports how many tracked sessions still have a ping scheduled ahead of them.
This exists for the idle-exit watchdog, and it exists because the keep-alive INVERTS the ordinary meaning of "idle": pinging is what the proxy does precisely while no client traffic is arriving. A watchdog counting only requests would therefore kill the process in exactly the window the feature was built for — the quiet gap after `end_turn`, where 83.7% of the recoverable dollars sit. So "no requests recently" is not sufficient to exit; "and nothing is waiting to be pinged" is the other half.
The conditions are `due`'s minus the timing term: an entry that is stopped, or has spent its MaxPings, or whose policy is off will never be pinged again and must not hold the process open.
One caveat, because "a live entry is by construction one we intend to ping" is very nearly true and not exactly: `sweep` also drops entries whose `pingable()` has since gone false, and it only looks once `now >= startedAt + Idle`. Inside that window this counts an entry that will never actually be pinged, which resets the activity clock and delays the exit by up to one `Idle`. Bounded by the entry's own retire timer at `(MaxPings+1) * Idle`, and immaterial against a 24h threshold — but the honest statement is "outside that window", not "by construction".
Erring toward counting is the right direction anyway: over-counting delays an exit by minutes, while under-counting kills the process during the quiet gap the keep-alive exists to work in.
type KeepAliveStats ¶ added in v0.1.1
KeepAliveStats is keepalive.Stats, kept under its old name so /stats JSON and callers are unchanged.
type Limiter ¶ added in v0.1.1
type Limiter struct {
// contains filtered or unexported fields
}
Limiter enforces per-tenant rate and concurrency limits.
func NewLimiter ¶ added in v0.1.1
NewLimiter builds a limiter. A nil result is a working no-op, so callers never have to nil-check at the call site.
func (*Limiter) Acquire ¶ added in v0.1.1
Acquire checks the rate limit and takes a concurrency slot. The returned release function must always be called; it is a no-op when nothing was taken, so `defer release()` is correct even on the error path.
func (*Limiter) AcquireCheapModel ¶ added in v0.1.1
AcquireCheapModel takes a slot on the process-wide compaction-model semaphore, blocking until one is free or the caller's deadline passes. Blocking rather than refusing, because the alternative to waiting here is not compacting — and a request that skips compaction is correct, just more expensive. Returns false if the wait was abandoned, in which case the caller must proceed without compaction.
func (*Limiter) AcquireSpare ¶ added in v0.1.1
AcquireSpare is Acquire for traffic that is OURS rather than the agent's: it succeeds only out of the tenant's slack, leaving reserveFrac of both bounds untouched.
The idle keep-alive needs this. A ping is a real request against the tenant's rate and concurrency budget, and the requirement is that it never crowd out a request an agent is waiting on. Refusing rather than queueing is half of that — a queued ping sits in front of real traffic — but with a fixed-window counter refusing at the limit is not enough either: a ping that takes the last request of the minute has already displaced whatever arrives next. So a ping is only allowed while the tenant is comfortably inside its bounds, and is simply skipped otherwise. Skipping costs one idle span's refresh; displacing costs an agent a 429 it did not earn.
reserveFrac <= 0 makes this identical to Acquire.
func (*Limiter) AllowAction ¶ added in v0.1.1
AllowAction rate-limits a deliberate act — arming a keep-alive override is the one caller — on a per-hour fixed window, and returns an error naming when the caller may retry.
Separate from Acquire because it is a different kind of limit on a different thing. Acquire bounds request THROUGHPUT per minute and hands back a concurrency slot; this bounds how often somebody may authorize a spend, has no concurrency half, and takes nothing that has to be released. Sharing the per-minute window would have made "30 arms an hour" unexpressible and would have charged a settings click against an agent's request budget.
A fixed window for the same reason Acquire uses one: the refusal can say exactly when the window resets, which a leaky bucket cannot. It is also its own map, so an arm cannot evict a live tenantLimiter holding an in-flight semaphore.
type Limits ¶ added in v0.1.1
type Limits struct {
// RequestsPerMinute bounds one tenant's request rate. 0 = unlimited.
RequestsPerMinute int
// Concurrent bounds one tenant's in-flight requests. 0 = unlimited.
Concurrent int
// CheapModelConcurrent bounds cheap-model (compaction) calls across the WHOLE
// process. Not per tenant: the point is to stop one tenant's extract_llm traffic
// from making every other tenant's agent wait on a shared, rate-limited backend.
// 0 = unlimited.
CheapModelConcurrent int
}
Limits configures the per-tenant bounds. Zero values disable a bound rather than defaulting to something small — a limit nobody asked for that silently throttles an agent is worse than no limit, because it presents as the tool being slow.
type LiveFacts ¶ added in v0.5.1
type LiveFacts struct {
Messages, Tools, SystemBlocks, MaxTokens int
Effort, Thinking, CacheTTL, Agent string
Stream bool
TTFBMs float64
// Arrival is this request's identity in a learned campaign's tracker (nil when no campaign applies). It travels with the request, not with its thread,
// because requests overlap on a thread.
Arrival *predictive.Arrival
}
LiveFacts are the request-side inputs of a learned keep-alive campaign, taken from the same places the dashboard row is filled from, so a campaign sees at serve time the values it was trained on.
type ObserveOptions ¶ added in v0.1.1
type ObserveOptions struct {
// MaxQueue bounds the off-path measurement queue; a full queue DROPS (counted) rather
// than blocking the request path. 0 = modes.DefaultMaxQueue.
MaxQueue int `yaml:"max_queue"`
// Workers is the number of drain goroutines. 0 = modes.DefaultWorkers (1), which keeps
// one measurement's cheap-model call in flight per process.
Workers int `yaml:"workers"`
}
ObserveOptions tunes observe mode: one option per real decision.
type Options ¶
type Options struct {
OpenAIUpstream string // e.g. https://api.openai.com
AnthropicUpstream string
// BobUpstream, when set, enables the Bob (BobShell) gateway: Bob's
// OpenAI-dialect model calls (POST /inference/v1/chat/completions) are reduced
// and forwarded here, and every other path Bob calls (control-plane:
// /admin/v1/profile, /inference/v1/model/info, …) is proxied through verbatim
// so the CLI boots and authenticates. Point Bob's CUSTOM_BASE_URL at this proxy.
BobUpstream string // e.g. https://api.example.com
OpenAIKey string // when set, REPLACES the caller's Authorization: Bearer
AnthropicKey string // when set, REPLACES the caller's x-api-key
// ForceModel, when set, overwrites the request's "model" field. eval-containers
// uses this to pin every call to EVAL_MODEL regardless of what the agent asked for.
ForceModel string
Client *http.Client
// UpstreamHeaderTimeout bounds how long an upstream may take to send its first byte
// (0 = defaultUpstreamHeaderTimeout). Deliberately NOT a whole-request timeout — see
// upstreamTransport for the 502s that cost.
UpstreamHeaderTimeout time.Duration
// StreamSilenceTimeout bounds how long a STREAMING upstream request may go without a single
// response byte after being written before it is resent once on a new connection
// (0 = streamSilenceTimeout). See upstreamsilence.go for the gateway behaviour it handles.
StreamSilenceTimeout time.Duration
// CheapModel is the static "config"-source LLM for NeedsModel components (nil = none): the
// operator's own endpoint and credential, pinned once at New. The "incoming"-source client
// is built per request from the route's upstream + the gateway's real key.
CheapModel *CheapModelConfig
// Windows resolves a model's context window (max input tokens) so fraction-based
// Trigger thresholds scale with the model. nil => window unknown (0), fractions
// ignored, absolutes apply. Built in main from internal/modelinfo.
Windows interface {
Window(ctx context.Context, model string) (int, bool)
}
// InjectExpand controls advertising the context_guru_expand tool on outgoing
// requests so Offload markers are actually recoverable (expand.InjectAuto |
// InjectAlways | InjectNever). Empty defaults to auto.
//
// `auto` injects when the request already declares tools, the store persists, and THE
// PIPELINE CONTAINS AT LEAST ONE OFFLOAD. It does NOT depend on the request carrying a
// marker — that would make the tools array vary turn to turn, and every variation is a
// whole-prefix cache miss (see the note on expand.InjectAuto).
//
// This comment used to claim a marker condition that expand.Inject explicitly disclaims,
// and the pipeline condition was missing entirely. The consequence was live: a
// cachesplit-only pipeline forwarded `context_guru_expand` to the provider, a model that
// saw marker-shaped text in a file called it, and the call could only ever fail because
// nothing in that pipeline mints a marker to resolve.
//
// `always` still injects unconditionally — an operator asking for it by name gets it.
InjectExpand string
// CacheMode controls cache-aware compaction ("auto"|"on"|"off"; empty=auto).
// auto/on keep offloaders from mutating already-cached content on prompt-caching
// backends; off restores legacy compact-everything (for confirmed non-caching backends).
CacheMode string
// RestartGrace switches the restart grace on (nil, the default) or off. The tracker's
// records die with the process; the provider's cache entries do not, so a live thread's
// first request after a restart must not be rewritten (#496). The grace's LENGTH is not
// set here: each request carries its own cache lifetime, and apply passes it to the
// tracker. An explicit false turns the rule off — what an eval that sends whole
// transcripts to a fresh proxy wants, so it measures compaction, not the grace.
// Startup setting, not a live knob.
RestartGrace *bool
// Prices resolves a model's per-token rates so the dashboard can price each
// request AT WRITE TIME (so history does not reprice when a rate changes). nil =
// no pricing, and every captured row is marked partially accounted rather than
// being priced as free. Built in main from internal/modelinfo.
Prices modelinfo.Pricer
// Preset labels captured rows with the configuration in effect, so the dashboard
// can filter and compare by preset.
Preset string
// Dashboard, when non-nil, enables the persistent observability layer: each
// request is captured off the hot path into a durable store and the dashboard UI
// + API are mounted. nil = the proxy behaves exactly as before.
Dashboard *dash.Recorder
// PipelineFor builds a pipeline for a per-request override on /compact
// (?preset=… or x-context-guru-pipeline: a,b,c). nil = overrides ignored, the
// handler always uses the configured pipeline. Supplied by main (which holds
// the config + emitter) so proxy stays decoupled from the config package.
PipelineFor func(preset string, names []string) (*components.Pipeline, error)
// Mode is the operating mode (#31): components.ModeSync (default, and byte-identical
// to pre-mode behavior) or ModeObserve. Empty = sync. Explicit by design — never
// inferred from the rest of the configuration.
Mode components.Mode
// Observe tunes observe mode's off-path measurement. Ignored in sync mode.
Observe ObserveOptions
// Tenants, when non-nil, makes this a HOSTED multi-tenant proxy: every chat
// request must carry a token that resolves to a tenant, and that tenant's
// configuration — not Options — decides the pipeline, the state store, the
// operating mode and which upstream the traffic goes to. nil keeps the
// single-tenant behaviour byte-identical to before tenancy existed.
Tenants *TenantSource
// Cache is the single-tenant host's prompt-cache policy (the idle keep-alive and the
// mixed-TTL head). In hosted mode each tenant's own `cache:` block is used instead.
Cache CachePolicy
// AuthMode selects how a human authenticates to the control plane. The zero value is
// AuthPassword, which is today's behaviour, so an existing deployment is unaffected by this
// field existing. AuthExternal withdraws the password routes entirely — see authmode.go for
// why present-but-unused is not equivalent to absent.
AuthMode AuthMode
// Upstreams is the operator's allow-list, by name, consulted only in hosted
// mode. A tenant selects a NAME; it can never supply a URL.
Upstreams map[string]Upstream
// Limits bounds what one tenant can consume of the shared box: request rate,
// in-flight concurrency, and (process-wide) concurrent compaction-model calls.
// Zero values disable each bound. Ignored in single-tenant mode, where there is
// nobody to protect anyone from.
Limits Limits
// Spend reports a tenant's month-to-date cost, for DISPLAY on the settings page.
// nil = no figure shown. There is no cap: every tenant spends their own provider
// credential, so there is no shared budget to guard.
Spend SpendChecker
// PresetNames and ComponentNames are what the settings page may offer. Supplied by
// the host because the registries live in `config` and `components`, and this
// package stays decoupled from both.
PresetNames []string
ComponentNames []string
// MetricsToken, when set, lets a remote Prometheus scrape /metrics with a bearer
// token. Empty means loopback only in hosted mode.
MetricsToken string
// TenantMetrics supplies per-tenant rollups for /metrics. nil = process-wide
// series only.
TenantMetrics TenantMetricsSource
// Version is reported as a label on cg_build_info.
Version string
// StatsTrusted reports whether a request may read /stats, which is a
// PROCESS-WIDE aggregate across every tenant. In hosted mode this must be
// restricted (loopback or a manager); nil means loopback only. Ignored in
// single-tenant mode, where /stats stays open as it always was — the benchmark
// harnesses in deploy/harbor read it.
StatsTrusted func(*http.Request) bool
// Single-tenant /api/adapt/* apply (adaptapply.go): BaseConfig is the configuration document
// the proxy was started with (its config file, or `preset: X`), BuildConfig rebuilds a
// pipeline from a document, and AdaptOverride is the file an applied configuration is kept
// in so a restart keeps it ("" keeps it in memory only).
BaseConfig string
BuildConfig ConfigBuilder
AdaptOverride string
}
Options configures upstreams and credential injection. Each upstream is a base URL the matching route forwards to (the incoming path is appended).
Credentials: by DEFAULT the caller's own auth header is forwarded unchanged, so each user's traffic is billed to their own provider account. Setting a key here replaces it — the eval-containers gateway model, where the agent holds only a placeholder and the real provider key lives in the gateway env. That is an explicit single-tenant/local fallback, never the hosted default.
type SavingsScope ¶ added in v0.2.0
type SavingsScope struct {
CostUSD float64 `json:"cost_usd"`
BaselineCostUSD float64 `json:"baseline_cost_usd"`
CGLLMCostUSD float64 `json:"cg_llm_cost_usd"`
NetSavedUSD float64 `json:"net_saved_usd"`
CachesplitSavedUSD float64 `json:"cachesplit_saved_usd"`
KeepAlivePingUSD float64 `json:"keepalive_ping_usd"`
KeepAliveSavedUSD float64 `json:"keepalive_saved_usd"`
KeepAliveNetUSD float64 `json:"keepalive_net_usd"`
TotalSavedUSD float64 `json:"total_saved_usd"`
}
SavingsScope is one dash.SavingsTotals, reshaped for /stats' JSON wire — same fields, same meaning, so a caller reading dash's own doc comments understands this shape too.
type SavingsStats ¶ added in v0.2.0
type SavingsStats struct {
// Current is the session that most recently sent a real (non-ping) request through
// this proxy. Absent (not zeroed) until the first real request arrives.
Current *SavingsScope `json:"current,omitempty"`
// Live sums every session the keep-alive keeper currently considers active.
Live *SavingsScope `json:"live,omitempty"`
// All is process-wide, all time, all sessions — Overview()'s own figure, minus the
// columns /stats does not need.
All *SavingsScope `json:"all,omitempty"`
}
SavingsStats is /stats' savings block: the same combined figure the dashboard shows, in three scopes, computed through dash.DB.SavingsTotals directly rather than through dash.API — this proxy already holds the DB (h.rec), and for a single local user's data the query is cheap enough to run synchronously.
type SpendChecker ¶ added in v0.1.1
type SpendChecker interface {
// MonthToDateUSD returns what this tenant has spent since the start of the
// current calendar month.
MonthToDateUSD(tenantID string) (float64, error)
}
SpendChecker reports a tenant's month-to-date cost, for display. Not a cap: each tenant spends their own provider credential, so there is no shared budget to guard.
type StatusError ¶ added in v0.1.1
StatusError is implemented by resolution errors that name their own HTTP status.
type Tenancy ¶ added in v0.1.1
type Tenancy struct {
// ID is the tenant this request belongs to; "" in single-tenant mode, which is
// also what lands in the dashboard's tenant_id column for pre-tenancy rows.
ID string
// Label and Manager are for the dashboard and the /stats gate, not the hot path.
Label string
Manager bool
// Preset labels captured rows so the dashboard can compare configurations.
Preset string
// Pipe is this tenant's compaction pipeline.
Pipe *components.Pipeline
// Store holds this tenant's offloaded originals and frozen decisions. Per tenant,
// for the eviction reason in this file's header comment.
Store store.Store
// Shadow is observe mode's disjoint store for this tenant. See Handler.shadow.
Shadow store.Store
// Mode is this tenant's operating mode (sync or observe).
Mode components.Mode
// CaptureContent is this tenant's consent to storing transcript text.
CaptureContent bool
// Upstream names, by dialect, into Options.Upstreams.
UpAnthropic, UpOpenAI, UpBob string
// Cache is this tenant's host-level prompt-cache policy: the idle keep-alive and the
// mixed-TTL head. Zero means both off, which is the default for every account.
Cache CachePolicy
}
Tenancy is everything the request path needs to know about the authenticated caller. Built once per request (cached per tenant), and NEVER mutated after it is published — readers on the request path (captureContentFor, newCapture, upstreamFor) take no lock, so a refresh publishes a new pointer instead of writing through the old one. See tenancy().
type TenantMetricRow ¶ added in v0.1.1
type TenantMetricRow struct {
TenantID string
Label string
Requests int64
TokensBefore int64
TokensAfter int64
SavedUnique int64
CacheRead int64
CacheWrite int64
FreshInput int64
OutputTokens int64
CostUSD float64
BaselineUSD float64
CGLLMCostUSD float64
CacheSavedUSD float64
CachesplitSavedUSD float64
CachesplitHistoricalUSD float64
KeepAliveNetUSD float64
DeclFilterUSD float64
CGLatencyMs float64
UpstreamMs float64
Sessions int64
ArchivedCount int64
ArchivedBytes int64
}
TenantMetricRow is one tenant's rollup. Deliberately flat: every field becomes one Prometheus series, and a nested shape would just have to be flattened here anyway.
type TenantMetricsSource ¶ added in v0.1.1
type TenantMetricsSource interface {
// TenantMetrics returns one row per tenant that has traffic in the window.
TenantMetrics(since int64) ([]TenantMetricRow, error)
}
TenantMetricsSource supplies per-tenant rollups for the exporter.
type TenantSource ¶ added in v0.1.1
type TenantSource struct {
// contains filtered or unexported fields
}
TenantSource turns an authenticated token into a Tenancy, caching the built pipeline and state store per tenant.
The cache is not a speed optimisation. A tenant's Store accumulates the frozen compaction decisions that make savings COMPOUND across turns; rebuilding it per request would throw that away every time and reduce the service to single-turn-only compaction. Which also means eviction is not free, so the LRU is bounded by tenant count and logs what it drops.
func NewTenantSource ¶ added in v0.1.1
func NewTenantSource(reg *tenant.Registry, e components.Emitter, b ConfigBuilder, maxTenancies int) *TenantSource
NewTenantSource builds a resolver over a control-plane registry. maxTenancies <= 0 uses DefaultMaxTenancies.
func (*TenantSource) ForTenant ¶ added in v0.1.1
func (s *TenantSource) ForTenant(t *tenant.Tenant) (*Tenancy, error)
ForTenant returns the tenancy for an already-authenticated tenant, for callers that authenticated some other way (a dashboard cookie).
func (*TenantSource) Forget ¶ added in v0.1.1
func (s *TenantSource) Forget(tenantID string)
Forget drops a tenant's cached pipeline and state store. Called when an account is DELETED: their tokens are gone, so nothing can authenticate as them again, but this cache is keyed by tenant id and holds a live Store — every offloaded original and frozen compaction decision that account accumulated. Without this it sits in memory until 255 other tenants push it out, and a re-registered id would inherit it.
func (*TenantSource) ObserveNamespaces ¶ added in v0.6.4
func (s *TenantSource) ObserveNamespaces(fn func(tenantID string))
ObserveNamespaces calls fn for every tenant whose CURRENT pipeline runs observe mode. The restart grace's lookup (#766) uses it to answer "no lookup" for exactly those tenants: observe rows carry no session id, so the recorder knows none of their threads and a miss would read every warm thread as new — the one answer worse than not asking. Only tenants that have RESOLVED at least once are here, which is no gap: a request resolves its tenancy before its pipeline runs, so by the time a thread's key is asked about, its tenant is in the cache. A tenant that switches modes rebuilds on its next request, and this walk reads the rebuilt entry.
func (*TenantSource) Resolve ¶ added in v0.1.1
func (s *TenantSource) Resolve(r *http.Request) (*Tenancy, error)
Resolve authenticates a request and returns its tenancy.
Two ways in, in order of preference. A context-guru token (TokenHeader) is the normal one. Failing that, the caller's own provider key is looked up by its sha256 — the path for an agent that can set no header we do not already occupy (Bob), and only for a digest a tenant has explicitly bound. Neither one falls open.
type Usage ¶ added in v0.1.1
type Usage struct {
// Live is the request-side facts a learned keep-alive campaign reads at response end (predictive.go). nil on paths that do not set it.
Live *LiveFacts
FreshInput int64
CacheRead int64
CacheWrite int64
Output int64
// CacheWrite1h is the part of CacheWrite the provider billed at the ONE-HOUR write
// tier, from `usage.cache_creation.ephemeral_1h_input_tokens`. Zero on every response
// that wrote only 5-minute entries, which on this deployment is all of them.
//
// It is here for two reasons, and both are about not being lied to. A 1h write costs
// 2.0x base input where a 5m write costs 1.25x, so pricing a 1h write as a 5m one
// understates that request by 0.75x of its whole written prefix. And it is the ONLY
// signal that a requested `ttl: "1h"` was HONOURED. A provider that does not support the
// tier for that model downgrades it silently: a normal 200 with a normal-looking
// `cache_creation_input_tokens` and nothing to distinguish it from a granted 1h entry.
// Measured live on this gateway: aws/claude-haiku-4-5 returned 36,251 of 36,574 written
// tokens at the 1h tier, aws/claude-sonnet-5 returned 0 of 48,212. Absent-or-zero here,
// with a 1h breakpoint on the wire, means the request was downgraded.
CacheWrite1h int64
// StopReason is the provider's terminal reason for this response, normalized across
// dialects (see responseStopReason). It rides on Usage because it comes off the same
// buffered/sniffed response bytes and reaches the dashboard by the same path — a
// second out-of-band channel for one string would be a second thing to keep in sync.
//
// It is filled even when the token tiers are absent, because the two facts are
// independent: an OpenAI response without `stream_options` reports no usage at all and
// still reports finish_reason, and "we could not price this, and it stopped because it
// hit max_tokens" is exactly the pair worth having.
StopReason string
// ToolUseNames is every tool_use (Anthropic) / function call (OpenAI chat, Responses)
// block name this response carried, in the order they appeared — read off the same
// bytes StopReason comes from (see responseToolUseNames), for issue #424's
// waitcause.ClassifyWaitingFor: a response that calls a tool is a thread about to wait
// on ITS OWN tool call, not on a human or a background task, and the LAST name here is
// what the dashboard keeps for it. nil when the response carried none, or when it was
// never buffered/sniffed far enough to see one (a long streamed response's tool_use
// block can fall outside the sniffer's bounded head window — see newSniffer — in which
// case this is best-effort, not exhaustive, and the row reads a weaker signal
// (background/teammate/human from open state) rather than own_tool, never a guess).
ToolUseNames []string
}
Usage is one response's provider-billed token tiers. ok=false means the provider told us nothing, in which case a caller must report the request as partially accounted rather than pricing it as free.
Source Files
¶
- adaptapply.go
- adaptcache.go
- adaptctl.go
- adaptreplay.go
- adapttoolsctl.go
- agentcompaction.go
- authmode.go
- campaign.go
- campaignauto.go
- campaignbuild.go
- clientsignal.go
- control.go
- counttokens.go
- credmask.go
- dashcapture.go
- dispatcher.go
- feedback.go
- keepalive.go
- keepalivectl.go
- keepaliveoverride.go
- keepalivestrategy.go
- lifecycle.go
- limits.go
- mail.go
- manualping.go
- modes.go
- passwordroutes.go
- predictive.go
- prefixask.go
- promexport.go
- proxy.go
- savings.go
- ssepeek.go
- tenancy.go
- thread.go
- toolfilterctl.go
- upstreamsilence.go
- usage.go