{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package llm\n\nPackage llm is the metered model-execution gateway: the ONE path every model call goes through. Calling a model directly via provider.Complete/Stream is banned (a guard test enforces it) — instead callers hold a \\*Runner and pass a Purpose, so token/cost accounting (and, later, latency, route metadata, cost guardrails, and learning metrics) is automatic and impossible to bypass.\n\nArchitecture: provider (wire) → Runner (meters every call) → Ledger (one shared record) → /cost, /route, guardrails, learning. One Runner per top-level session; sub-agents share it, so their spend lands in the same Ledger with no manual rollup.\n\n## Functions\n\n```go\nfunc CacheUtilization(in, cacheRead, cacheWrite int) float64\n```\nCacheUtilization computes CacheRead / (In + CacheRead + CacheWrite) as a percentage (0-100), returning 0 when total input is zero.\n\n```go\nfunc IsTerminal(err error) bool\n```\nterminalForFallback reports errors the fallback chain must never touch — they carry their own recovery policy elsewhere. IsTerminal reports whether an error will fail identically no matter which model receives it — billing and auth state, or a request WE malformed.\n\nCallers outside the fallback walk need this too. A delegated worker that dies on a terminal error is not a retryable tool failure: handing \"agent failed\" back to the model invites it to try again, and it did — a Gemini thought-signature 400 was retried roughly 150 times over 12 minutes, because nothing in the loop could tell \"this tool had a bad day\" from \"this will never work\".\n\n```go\nfunc SetSameModelRetryDelays(d ...time.Duration) (restore func())\n```\nSetSameModelRetryDelays replaces the same-model retry schedule and returns a func restoring it. For tests outside this package; production never calls it.\n\n## Types\n\n```go\ntype BackendStat struct {\n\tCalls      int\n\tIn, Out    int\n\tCacheRead  int\n\tCacheWrite int\n\tUSD        float64 // actual total at the served model's rate card\n\tLatencyMS  int64   // summed wall-clock; divide by Calls for the mean\n\tReasons    map[string]int\n\t// per-component USD (so /cost can PROVE where the money went — input vs\n\t// cache-write vs cache-read vs output — instead of hand-waving).\n\tInUSD, OutUSD, CacheReadUSD, CacheWriteUSD float64\n}\n```\nBackendStat aggregates per serving backend (cheap | anthropic | openai | …) — where the tokens actually ran and what they cost. USD is the real token bill at the served model's rates: every backend is token-billed (the cheap lane + frontier APIs; the self-hosted/GPU-hours and counterfactual-savings era is gone).\n\n```go\nfunc (b BackendStat) CacheUtilization() float64\n```\nCacheUtilization returns the percentage (0-100) of TotalInput served from cache.\n\n```go\nfunc (b BackendStat) TotalInput() int\n```\nTotalInput returns the total input tokens for this backend: uncached + cache reads + cache writes.\n\n```go\ntype Ledger struct {\n\t// contains filtered or unexported fields\n}\n```\nLedger is the single, concurrency-safe record of all model usage for a run. Shared across a session and its sub-agents.\n\n```go\nfunc (l *Ledger) ByBackend() map[string]BackendStat\n```\nByBackend returns a snapshot of per-backend usage — who actually served the session's calls, at what latency, and what the per-token bill would have been (for /cost backends and the GPU-economics decision).\n\n```go\nfunc (l *Ledger) ByPurpose() map[Purpose]Stat\n```\nByPurpose returns a snapshot of per-purpose usage (for /cost --by-purpose, /route, and learning).\n\n```go\nfunc (l *Ledger) Total() Stat\n```\nTotal returns the aggregate usage + cost across every metered call.\n\n```go\ntype ModelRunner interface {\n\tComplete(ctx context.Context, p Purpose, req wire.Request) (wire.Response, error)\n\tStream(ctx context.Context, p Purpose, req wire.Request, h wire.StreamHandler) (wire.Response, error)\n\tLedger() *Ledger\n}\n```\nModelRunner is the ONLY interface a model consumer should depend on. Every call carries a Purpose and is metered. (Consumers take this, never provider.ModelProvider.)\n\n```go\ntype Purpose string\n```\nPurpose labels WHY a model call was made, so cost/latency can be attributed per kind of work (and a future router can learn which purposes Haiku handles well).\n\n```go\nconst (\n\tMainLoop   Purpose = \"main_loop\"  // the executive turn loop\n\tReflect    Purpose = \"reflect\"    // plan-mode reflection gate\n\tReview     Purpose = \"review\"     // cross-model plan critic (a 2nd cheap model reviews the draft)\n\tSynth      Purpose = \"synth\"      // plan synthesis\n\tExplore    Purpose = \"explore\"    // read-only scout sub-agent\n\tAgent      Purpose = \"agent\"      // first-class delegated sub-agent (agent tool: any tier, read-only or mutating)\n\tClassify   Purpose = \"classify\"   // cheap routing/safety classifier\n\tPredict    Purpose = \"predict\"    // next-step prediction\n\tLearn      Purpose = \"learn\"      // claim/knowledge extraction\n\tCompact    Purpose = \"compact\"    // context compaction\n\tShrinkwrap Purpose = \"shrinkwrap\" // one-time MEMCODE.md instruction compression (own concern, not compaction)\n\tOther      Purpose = \"other\"      // unlabelled — still counted\n)\n```\n\n```go\ntype Runner struct {\n\t// contains filtered or unexported fields\n}\n```\nRunner is the metered model-policy gateway over a provider.ModelProvider. Since the all-policy-client-side migration it is also THE routing authority: every call's concrete model is selected here (lane.go semantic ladder + resolve.go physical resolution over the /v1/models control plane), and failed calls recover here (recover.go fallback walk). The backend — gateway, Ollama, anything OpenAI-compatible — just serves what this picks.\n\n```go\nfunc NewRunner(prov provider.ModelProvider) *Runner\n```\nNewRunner wraps a provider with a fresh ledger. Construct ONE at the top level (the cmd boundary) and thread it everywhere — sub-agents share it.\n\n```go\nfunc (r *Runner) Complete(ctx context.Context, p Purpose, req wire.Request) (wire.Response, error)\n```\nComplete runs a non-streamed call — selection, the recovery walk, and metering (usage, cost, latency, backend).\n\n```go\nfunc (r *Runner) Fork() *Runner\n```\nFork returns a NEW Runner that shares this one's Ledger, selection state, and provider connection but is otherwise its own object. Sub-agents Fork the parent's runner instead of sharing the pointer — so what's shared across the main loop and its scouts is passive (the Ledger, the control-plane snapshot), never an executor with per-context state. The pin is inherited: /model pins the whole session, sub-agents included.\n\n```go\nfunc (r *Runner) ForkWithModel(label string) *Runner\n```\nForkWithModel returns a fork that serves ONE explicitly chosen model instead of the session's pin, for a user-directed one-shot like \"review this plan with another model\".\n\nThe override lives on the returned Runner and dies with it: the session pin, the workspace store, and the user store are all untouched. That containment is the point — an ephemeral override is the one seam through which per-request model switching could grow back, so it exists in exactly one function and leaves no trace.\n\n```go\nfunc (r *Runner) InvalidateModels()\n```\nInvalidateModels drops the control-plane snapshot so the next call refetches — call after /login, /apikeys mutations, or anything else that changes the org's keys/credits/roles. (Billing-class errors invalidate automatically.)\n\n```go\nfunc (r *Runner) Ledger() *Ledger\n```\nLedger exposes the shared usage record.\n\n```go\nfunc (r *Runner) Provider() provider.ModelProvider\n```\nProvider returns the wrapped provider — ONLY for capability assertions that aren't model calls (e.g. provider.WebSearcher / WebFetcher detection, doctor checks). Never use it to call Complete/Stream directly; that bypasses metering.\n\n```go\nfunc (r *Runner) SetPin(label string)\n```\nSetPin ties this Runner to the session's model — the label every real request serves on. The pin resolver settles it once at session start; nothing else changes it mid-session except an explicit /model.\n\n```go\nfunc (r *Runner) SetRetryNotify(fn func(attempt int, err error, delay time.Duration))\n```\nSetRetryNotify registers the callback runWithRecovery calls before each same-model retry.\n\n```go\nfunc (r *Runner) SetSession(id string)\n```\nSetSession ties this Runner to a Session id so every call carries it on the wire (X-Memcode-Session). Called when the owning Session gets its id; forks set their own.\n\n```go\nfunc (r *Runner) Stream(ctx context.Context, p Purpose, req wire.Request, h wire.StreamHandler) (wire.Response, error)\n```\nStream runs a streamed call (live deltas via h) with the same selection + recovery; the emitted-output guard stops the fallback walk the moment any delta reached the user. Falls back to Complete if the provider can't stream.\n\n```go\ntype Stat struct {\n\tCalls                          int\n\tIn, Out, CacheRead, CacheWrite int\n\tUSD                            float64\n}\n```\nStat is an aggregate of usage + estimated cost (total or per-purpose).\n\n```go\nfunc (s Stat) CacheUtilization() float64\n```\nCacheUtilization returns the percentage (0-100) of TotalInput served from cache.\n\n```go\nfunc (s Stat) TotalInput() int\n```\nTotalInput returns the total input tokens seen by the model across all disjoint categories: uncached input + cache reads + cache writes.\n\n","path":"github.com/memcode-ai/memcode/internal/llm","name":"llm","synopsis":"Package llm is the metered model-execution gateway: the ONE path every model call goes through.","isRedistributable":true}
