proxy

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: Apache-2.0 Imports: 48 Imported by: 1 module, 0 packages

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

View Source
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.

View Source
const DefaultMaxUSDPerPing = 0.25

DefaultMaxUSDPerPing mirrors config.DefaultKeepAliveMaxUSDPerPing, which this package may not import (proxy does not depend on the configuration loader). They are pinned equal by TestTheProxysPingCeilingDefaultMatchesTheConfigLoaders.

View Source
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 CallerAuthScheme added in v0.1.1

func CallerAuthScheme(r *http.Request) string

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

func CallerKey(r *http.Request) string

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 IsPasswordRoute added in v0.2.0

func IsPasswordRoute(method, path string) bool

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

func MailConfigured() (bool, string)

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

func TokenFromRequest(r *http.Request) string

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

func ReadAuthMode() (AuthMode, error)

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

func (m AuthMode) DisablesPasswordRoutes() bool

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

type CachePolicy struct {
	// KeepAlive turns the mechanism on for this tenant. Off by default.
	KeepAlive bool
	// Idle is X: how long a session must be idle before the first ping, measured from the
	// previous request's START per the provider's documented lifetime rule. Zero disables.
	Idle time.Duration
	// MaxPings is K: the most pings one idle span may send. Zero disables.
	MaxPings int
	// MaxUSDPerPing refuses a ping whose projected cost exceeds this. PER PING, because ping
	// cost is bimodal (p50 $0.0004, p99 $0.2275, max $0.3780) while a per-SESSION budget
	// truncates exactly the long large-prefix sessions holding the value — capping the
	// window's pings per session at 20 drops the net from +$164 to $92.34.
	//
	// Read it through Ceiling(), never directly: zero here means UNCONFIGURED, and for a spend
	// guard that has to resolve to the default rather than to infinity.
	MaxUSDPerPing float64
	// MinPrefixTokens is the billed-prefix floor (the previous request's cache_read +
	// cache_write) a session must reach before it is pinged. With the first-request skip this
	// sends 8.7x fewer pings for 3.3% less money.
	MinPrefixTokens int
	// HeadTTL1h asks for the one-hour tier on the head breakpoints; HeadTTLMinTokens gates
	// it on request size. Passed through to apply.Opts — see apply/headttl.go.
	HeadTTL1h        bool
	HeadTTLMinTokens int
	// PredictorID optionally names a registered predictor (see predictorFor and
	// knownPredictorIDs in keepalivestrategy.go) that pingable() must also clear before a
	// ping fires. "" (every account today, and every strategy created before this field
	// existed) means no predictor gate at all — unchanged behaviour.
	PredictorID string
	// PredictorThreshold is the minimum probability PredictorID must return. Ignored
	// while PredictorID is "".
	PredictorThreshold float64
}

CachePolicy is one tenant's resolved cache policy — the host-level half of the cache story, which no component can reach.

A plain struct in this package rather than config.CacheConfig, for the reason ConfigBuilder exists: proxy does not depend on the configuration loader, so a library host or the bifrost adapter can set this directly.

func (CachePolicy) Ceiling added in v0.1.1

func (p CachePolicy) Ceiling() float64

Ceiling is the per-ping cost guard that is actually ENFORCED.

The whole of this method is the sentinel. `MaxUSDPerPing == 0` means "nobody configured one", and the shipped code read that as "no cap": `MaxUSDPerPing <= 0 || cost <= cap`. On an account whose keep-alive is OFF the config builder hands the request path a zero CachePolicy, and enabling one session by hand is precisely the use case a per-session override exists for — so the one path where the guard was written to matter was the one path that ran without it, while the arm response cheerfully reported a ceiling of $0.00.

Zero in a money guard resolves to the DEFAULT. A caller that genuinely wants no ceiling has to say so with a negative value, which is a thing somebody has to type on purpose.

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

func (h *Handler) API() *dash.API

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

func (h *Handler) DashWhoami() func(*http.Request) any

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) MountControl added in v0.1.1

func (h *Handler) MountControl(m *http.ServeMux)

MountControl registers the control-plane routes. Called only in hosted mode; without a tenant registry there are no accounts to manage.

func (*Handler) Mux

func (h *Handler) Mux() *http.ServeMux

Mux wires the routes: chat proxying + health/stats/expand management.

func (*Handler) PendingPings added in v0.1.1

func (h *Handler) PendingPings() int

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

type KeepAliveStats struct {
	Live     int     `json:"live_sessions"`
	Pings    int64   `json:"pings"`
	Skipped  int64   `json:"skipped"`
	Failed   int64   `json:"failed"`
	Wrote    int64   `json:"wrote_instead_of_read"`
	SpentUSD float64 `json:"spend_usd"`
}

KeepAliveStats is the keeper's own ledger, for /stats. Every field is a way the mechanism can be worthless, which is the point of publishing them together: pings with no conversions is a policy that spends and gains nothing, and `wrote` above zero is a bug.

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

func NewLimiter(l Limits) *Limiter

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

func (l *Limiter) Acquire(tenantID string) (release func(), err error)

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

func (l *Limiter) AcquireCheapModel(done <-chan struct{}) (release func(), ok bool)

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

func (l *Limiter) AcquireSpare(tenantID string, reserveFrac float64) (release func(), err error)

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

func (l *Limiter) AllowAction(key, what string, perHour int) error

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 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.us-east.bob.ibm.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
	// CheapModel is the static "config"-source LLM client for NeedsModel
	// components (nil = none). The "incoming"-source client is built per request
	// from the route's upstream + the gateway's real key.
	CheapModel components.Model
	// 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
	// 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
}

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

type StatusError interface {
	error
	HTTPStatus() int
}

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) 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 Upstream added in v0.1.1

type Upstream struct {
	Dialect string
	BaseURL string
	KeyEnv  string
	Header  string
}

Upstream is one resolved entry of the server's allow-list.

type Usage added in v0.1.1

type Usage struct {
	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
}

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.

Jump to

Keyboard shortcuts

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