Documentation
¶
Overview ¶
Package tooldefer defers the tool declarations a user does not use (#485).
A deferred tool stays in the request with `defer_loading: true`. The model sees only its name, in a names list, and loads its definition through the API's own search tool (tool_search_tool_bm25) when it needs it. Nothing is removed, so a wrong guess costs one search turn and never a cache rewrite.
The rule ¶
A tool is deferred when ALL of these hold (Decide):
- it is not used in this thread so far;
- the user's last 3 sessions, in any project, declared it and used it in none;
- this project did not use it in its last 10 sessions (the project veto);
- it is not on the never-defer list (Bash, Read, Edit, Write, Agent, Skill, ToolSearch, AskUserQuestion, Context Guru's own tools, a tool tool_choice forces, the account keep list);
- it weighs at least 200 tokens, weighed on the ORIGINAL request.
The 200 tokens are o200k tokens (our own tokenizer, tokens.Count), not Claude tokens: about 340 Claude tokens. The ledger scales its weights by tokens.BilledDeltaFactor; the rule does not, on purpose, so the set it defers stays the one #485 measured (#866, N6).
An MCP server is one unit: all of mcp__<server>__* is deferred together, when the user's last 3 sessions declared the server and used none of its tools, the project used none of them in its last 10 sessions, and the server's tools weigh at least 200 o200k tokens together. A load of any one of its tools counts as a use of the server.
Without 3 user sessions of history, nothing is deferred. A tool loaded through search counts as used, so the user's next sessions keep it loaded.
The always-defer list ¶
A tool on the account's always-defer list (toolfilter `always_defer`, #878; a tool name, or mcp__<server> for a whole server) skips rules 2 and 3, and the 3-session minimum: it reads no history. It still obeys rule 1, rule 4 (the keep list wins when a name is on both lists) and rule 5 (for a server: its total). The list reads no history, so Rebuild gives the same set.
Cache discipline ¶
`tools` hashes first, so a tool that moves between loaded and deferred rewrites the whole cached prefix. So the set is decided ONCE per thread, at its first request, and never changes within the thread. It is stored under a metadata key (tool names only), which the disk store keeps across a restart. On a miss mid-thread (the record evicted at the pin cap) the transcript proves part of the set: every tool our search loaded was deferred. The rule is run again, as at the thread's first request; when its set leaves out a tool the transcript proves, the history drifted, so the original is sent and nothing is saved (Rebuild).
The search tool goes into `tools` at the first request and stays. The names list goes into Claude Code's own deferred-tools block at messages[1] when it exists, else into a system message inserted at index 1, with the same bytes on every request.
Fail open: any parse problem returns the input unchanged.
Index ¶
- Constants
- func AddBack(st store.Store, session, thread string, names []string) []string
- func AddKnownDescHash(h string)
- func AnthropicModel(model string) bool
- func AppendTools(wire string, body, src []byte, names []string) ([]byte, bool)
- func AuthBetas(values []string) string
- func ClientNamesList(names []string) string
- func ClientProbeBody(model, nonce string) []byte
- func ClientToolNamesList(names []string) string
- func ClientWire(wire string) bool
- func Decide(h History, in Input) []string
- func DeclaredNames(body []byte) map[string]bool
- func DeferralCause(body []byte) bool
- func DescHash(body []byte) string
- func Explain(h History, tenant, name string, keep, always []string) (defer_ bool, reason string)
- func HasAssistantTurn(body []byte) bool
- func HasClientSearch(wire string, body []byte) bool
- func HasClientToolSearch(body []byte) bool
- func Key(session, thread string) string
- func KnownDescHash(h string) bool
- func LoadView(names []string) []byte
- func Loaded(body []byte) map[string]bool
- func LoadedWeight(body []byte, names []string) int
- func MissingRef(errBody []byte) string
- func NamesList(names []string) string
- func NativeLoads(body []byte) []string
- func NativeSearch(wire string, body []byte) bool
- func NeverDefer(name string) bool
- func Nonce() string
- func NormProject(p string) string
- func NoteCalls(st store.Store, session, thread string, calls []SearchCall)
- func OpenForPurge(path string) (*sql.DB, error)
- func ProbeBody(model, nonce string) []byte
- func ReadCalls(body []byte, deferred map[string]bool) (broke bool, direct []string)
- func Rebuild(h History, in Input) (set []string, ok bool)
- func RepairRefs(body []byte) (out []byte, added []string, ok bool)
- func Rewrite(body []byte, set map[string]bool) (out []byte, names []string, ok bool)
- func RewriteSearch(wire string, body []byte, rec SearchRecord) (out []byte, removed []string, ok bool)
- func Save(st store.Store, session, thread string, r Record)
- func SaveSearch(st store.Store, session, thread string, r SearchRecord)
- func SearchAnswer(names []string, deferred map[string]bool) string
- func SearchOff(st store.Store, session string) bool
- func SearchOffValue(raw string) bool
- func SearchesIn(msg []byte) (searches int, loaded []string)
- func SearchesInSSE(raw []byte) (searches int, loaded []string)
- func SetSearchOff(st store.Store, session string, on bool)
- func StubTools(body []byte, names []string) (out []byte, added []string, ok bool)
- func View(wire string, body []byte) []byte
- func WrongGuesses(deferred []string, original []byte, loaded []string) int
- type Augment
- type Env
- type File
- type Gate
- func (g *Gate) Break(tenant, model string)
- func (g *Gate) Broken(tenant, model string) bool
- func (g *Gate) ClientDisabled(tenant, hash string) bool
- func (g *Gate) DisableClient(tenant, hash, reason string) bool
- func (g *Gate) DropTenant(tenant string)
- func (g *Gate) NoteToolSearch(tenant, session, raw string, rs store.Store, seen bool)
- func (g *Gate) TakePending(tenant, session string, rs store.Store) bool
- type History
- type Input
- type Ledger
- type Mem
- func (m *Mem) DropTenant(tenant string)
- func (m *Mem) Has(tenant, session string) bool
- func (m *Mem) LoadVerdicts(p *Prober)
- func (m *Mem) Observe(tenant, session, project string, body []byte, ts int64)
- func (m *Mem) Open(flushEvery time.Duration, p *Prober) (stop func())
- func (m *Mem) ProjectUsed(tenant, project, tool, exclude string, n int) bool
- func (m *Mem) Ready() bool
- func (m *Mem) ReadyC() <-chan struct{}
- func (m *Mem) SaveVerdict(k ProbeKey, v Verdict, at time.Time)
- func (m *Mem) SeedTenant(tenant string) <-chan struct{}
- func (m *Mem) UserSessions(tenant, exclude string, n int) []Session
- func (m *Mem) WaitReady(d time.Duration) bool
- type Money
- type Outcome
- type ProbeKey
- type Prober
- func (p *Prober) Ensure(k ProbeKey, send func(ctx context.Context) (Verdict, error))
- func (p *Prober) Forget(k ProbeKey)
- func (p *Prober) Runs() (pass, fail int64)
- func (p *Prober) Seed(k ProbeKey, v Verdict, at time.Time)
- func (p *Prober) Stale(k ProbeKey) bool
- func (p *Prober) Verdict(k ProbeKey) Verdict
- type Record
- type Req
- type Request
- type SearchCall
- type SearchRead
- type SearchRecord
- type Session
- type Stats
- type Tier
- type Verdict
- func ClientProbeVerdict(resp []byte, nonce string) Verdict
- func ProbeVerdict(resp []byte, nonce string) Verdict
- func RunClientProbeBeta(ctx context.Context, d dispatch.Dispatcher, ref dispatch.Ref, ...) (Verdict, error)
- func RunProbe(ctx context.Context, d dispatch.Dispatcher, ref dispatch.Ref, ...) (Verdict, error)
- func RunProbeBeta(ctx context.Context, d dispatch.Dispatcher, ref dispatch.Ref, ...) (Verdict, error)
Constants ¶
const ( ReasonUnknownDescription = "unknown_description" ReasonBreak = "break" )
The reasons ClientDisabled is set, as logged and exported.
const ( SearchType = "tool_search_tool_bm25_20251119" SearchName = "tool_search_tool_bm25" )
The server-side search tool. The version is pinned: an unknown date is a 400.
const ( UserSessions = 3 ProjectSessions = 10 MinTokens = 200 )
The thresholds of the rule. See the package comment. MinTokens is in o200k tokens.
const ClientProbeRoute = "#client-search"
ClientProbeRoute is added to the probe key's route, so the client-search probe has its own verdict.
const ClientSearchName = "context_guru_tools"
ClientSearchName is our search tool.
const FailTTL = 15 * time.Minute
FailTTL is how long a Fail verdict holds before a re-probe. Short, because one bad answer (the model only wrote text, a gateway hiccup) must not keep deferral off for a day; a Pass holds ProbeTTL.
const FileName = "context-guru-tooldefer.db"
FileName is the file's name next to the dashboard database path.
const MaxSessions = 64
MaxSessions is how many sessions per tenant the history keeps, newest first, in any project.
const ProbeTTL = 24 * time.Hour
ProbeTTL is how long a verdict holds.
const PurposeProbe = "tooldefer.probe"
PurposeProbe is the dispatch purpose of a probe.
Variables ¶
This section is empty.
Functions ¶
func AddBack ¶ added in v0.6.7
AddBack adds names to the thread's Added list, keeping the order, and returns the names it added now: the deferred ones not added before. A name outside the set is ignored.
func AddKnownDescHash ¶ added in v0.6.7
func AddKnownDescHash(h string)
AddKnownDescHash marks a description hash as verified. For tests; production adds to the list above.
func AnthropicModel ¶
AnthropicModel reports whether model names a Claude model: v1 defers on Claude models only.
func AppendTools ¶ added in v0.6.7
AppendTools appends the declarations of names, taken from src (the body before our rewrite), to the end of body's tools, in the order given. This is what RewriteSearch does with the Added list, so the follow-up and the client's next request carry the same `tools`.
func AuthBetas ¶ added in v0.6.7
AuthBetas is the auth-related part of a client's anthropic-beta values: the oauth-* betas, comma separated, in the client's order. The other betas change what a request does, so the probe, which tests one behaviour, leaves them out.
func ClientNamesList ¶ added in v0.6.7
ClientNamesList is the names list for a sorted set of names.
func ClientProbeBody ¶ added in v0.6.7
ClientProbeBody is the probe request for client-search mode: a plain ToolSearch tool, a deferred tool with a unique name, and a finished search round whose result is a tool_reference to it. The model is asked to call the tool. No server-side search is declared.
func ClientToolNamesList ¶ added in v0.6.7
ClientToolNamesList is the names list for a sorted set of names, in client-search mode.
func ClientWire ¶ added in v0.6.7
ClientWire reports whether our search runs on this wire: Chat Completions or Responses.
func DeclaredNames ¶
DeclaredNames is every client tool the request declares: the `tools` array (a tool the client deferred included, Claude Code's placeholder and our own tools left out) and the names on Claude Code's deferred-tools list.
func DeferralCause ¶
DeferralCause reports whether a provider's 400/422 body names a cause deferral can produce: defer_loading, a tool reference, the search tool, "all tools deferred", or cache_control on a deferred tool. For the log only: the proof that deferral caused a refusal is the original request succeeding (the host's retry).
func DescHash ¶ added in v0.6.7
DescHash is a short hash of ToolSearch's description, which documents the query syntax: the key of the format check. "" when body has no ToolSearch.
func Explain ¶ added in v0.6.7
Explain says whether the history rule would defer name in tenant's next session, and why, for save-more tools (#869). name is a tool, or a whole MCP server as "mcp__<server>". It reads the same history and the same thresholds as Decide, but without a request: the project veto, a use in the thread, tool_choice and the 200-token floor are decided per request and are not checked here, so a "yes" means "the user rule holds", not "this thread defers it". A name on always (the always-defer list, #878) is a "yes" without history, unless keep or the never-defer list holds it.
func HasAssistantTurn ¶
HasAssistantTurn reports whether this request continues a thread (it is not the first one).
func HasClientSearch ¶ added in v0.6.7
HasClientSearch reports whether body declares our search tool: the host holds and reads the response exactly when it does.
func HasClientToolSearch ¶ added in v0.6.7
HasClientToolSearch reports whether body declares Claude Code's own search: a client tool, loaded.
func KnownDescHash ¶ added in v0.6.7
KnownDescHash reports whether the proxy has verified the select syntax of this description.
func LoadView ¶ added in v0.6.7
LoadView is a body that says "these tools were declared and used", for the history: a load through our search counts as a use, and the client's transcript never shows an in-band load.
func Loaded ¶
Loaded is every tool name a search result in the transcript has loaded: the server-side search's tool_search_tool_result blocks, and the tool_reference blocks of Claude Code's own search.
func LoadedWeight ¶
LoadedWeight is the weight, in the original request, of the named tools.
func MissingRef ¶
MissingRef returns the tool name a provider 400 says a tool_reference names but `tools` lacks, or "" when the error is another one.
func NativeLoads ¶ added in v0.6.7
NativeLoads is the tool names the native search loaded in this transcript: the tool_search_output items the client echoes in `input`. A load counts as a use (LoadView). A namespace result gives its own name and each tool in it.
func NativeSearch ¶ added in v0.6.7
NativeSearch reports whether a Responses request declares the client's or provider's own tool search (a `tool_search` tool, as Codex sends): then our search is never added (#876).
func NeverDefer ¶
NeverDefer reports whether the fixed list, or Context Guru's own prefix, protects name.
func NormProject ¶
NormProject maps a worktree or scratch path to the repository it belongs to, so the project veto does not split one repository into many projects.
func NoteCalls ¶ added in v0.6.7
func NoteCalls(st store.Store, session, thread string, calls []SearchCall)
NoteCalls keeps the searches the client received, by call id, so a later request can answer them even when it does not carry the call (repairSearchResults).
func OpenForPurge ¶
OpenForPurge opens an EXISTING file for a purge only: a plain connection, with no store.Disk writer and no write test, and it never creates the file (mode=rw). The caller closes it.
func ReadCalls ¶ added in v0.6.7
ReadCalls reads the proxy's deferred tools that the model called in the transcript. broke: a call's own tool_result is an error that says the tool is not loaded or does not exist. direct: calls that no search loaded and that did not fail that way. The API accepts a direct call, so it is a use, not a break. keep is the set of tools tool_choice forced on this request: their calls are never a break.
func Rebuild ¶
Rebuild is the set after a store miss mid-thread. The transcript proves part of the set: a tool our search loaded was deferred by definition. The rule is decided again as at the thread's first request: the history leaves out this session, and the loads (and the calls that followed them) do not count as uses. ok is false when that set leaves out a tool the transcript proves: the history drifted, the set is unknown, and the host sends the original request and saves nothing (#866, N4).
The history can drift: Observe adds a session at its first request, so a session that only STARTED in between changes UserSessions. A drifted set moves a tool inside the thread's cached prefix, and saved, it would stay wrong for the rest of the thread.
Known limits: a drift on a tool no search loaded leaves no trace in the transcript, so the check cannot see it. And a tool the model called directly while it was deferred, with no search (the API accepts that), reads as "used" and comes back loaded. Also, a tool Claude Code's own search loaded, with no call after it, is not a use here, so the rebuilt set can defer it where the first decision kept it loaded. Each rewrites the prefix once. The disk store, on with the dashboard, makes both rare: Rebuild runs only when the stored record is gone.
func RepairRefs ¶
RepairRefs returns body with a deferred stub for every tool a tool_reference in the transcript names and `tools` does not declare. ok=false means nothing to repair; out is then body.
func Rewrite ¶
Rewrite defers the tools in set that this request declares and loads, adds the search tool, and puts the names list at messages[1]. It returns the names it deferred, sorted. ok=false means nothing changed (nothing to defer, or a shape it does not handle); out is then body.
Guards, from the 400 errors the API returns:
- a server tool (any element with a `type`) and a tool the client already deferred are left alone;
- at least one client tool stays loaded, so a cache_control mark always has a home: if the set would defer every client tool, the last one in array order stays loaded;
- a deferred tool cannot carry cache_control: its mark moves to the nearest loaded tool before it that has no mark, so no mark is lost while one has a home;
- a tool `tool_choice` forces on THIS request stays loaded for this request (a forced deferred tool can draw a 400). The thread's set does not change; the names list still names it.
func RewriteSearch ¶ added in v0.6.7
func RewriteSearch(wire string, body []byte, rec SearchRecord) (out []byte, removed []string, ok bool)
RewriteSearch removes the deferred tools that are not added back, appends our search tool and then the added tools in load order, and puts the names list in place. It returns the names it removed, sorted. The client's other tools keep their order and their bytes. ok=false: out is body.
func SaveSearch ¶ added in v0.6.7
func SaveSearch(st store.Store, session, thread string, r SearchRecord)
SaveSearch writes a thread's SearchRecord.
func SearchAnswer ¶ added in v0.6.7
SearchAnswer is the result our search returns for names. It depends only on the thread's fixed set, so a repaired answer has the same bytes on every request.
func SearchOffValue ¶
SearchOffValue reports whether a raw ENABLE_TOOL_SEARCH value turns tool search off on purpose: false, 0, no or off, in any case. "auto", "auto:N", "true" and "" are not a decision.
func SearchesIn ¶
SearchesIn reads one response message (an Anthropic message object): how many server-side searches ran, and which tools they loaded.
func SearchesInSSE ¶
SearchesInSSE is SearchesIn for a raw event stream (or a window of one): it reads the content_block_start events of server_tool_use and tool_search_tool_result blocks.
func SetSearchOff ¶
SetSearchOff stores the opt-out for session (on), or removes it.
func StubTools ¶
StubTools appends a deferred stub for each of names to `tools`. ok=false on a shape it does not handle; out is then body.
func View ¶ added in v0.6.7
View is body written the Anthropic way, for the rule and the history: each function tool as an element with a top-level name (its own bytes, so its weight is about the same), every other tool with its type (the rule leaves those alone), tool_choice as {"type":"tool"}, and one message per transcript item with a tool_use block for each tool call. nil when body has no tools array.
func WrongGuesses ¶ added in v0.6.7
WrongGuesses is how many wrong guesses one response shows (#866, N8): tools that are in this request's deferred set (deferred, the names we sent with defer_loading), that a search in the response loaded (loaded), and that no earlier message of the request's transcript had loaded (original, the client's body). Each tool counts once, however many results load it.
A tool Claude Code deferred is not in deferred: not our guess. A tool loaded earlier in the thread was counted at its first load: a search again is not a new wrong guess. /stats and the dashboard both count with this function, so their numbers agree.
Types ¶
type Augment ¶ added in v0.6.7
type Augment struct {
Body []byte
// Loads is the deferred tools that results written now carry; Answered how many calls were new.
Loads []string
Answered int
}
Augment is what AugmentSearches did on one request.
func AugmentSearches ¶ added in v0.6.7
func AugmentSearches(rs store.Store, session, thread string, body []byte, deferred map[string]bool) (a Augment)
AugmentSearches adds, to the result of every ToolSearch call in body, a tool_reference for each deferred tool (deferred is the thread's set) that the call's exact select query names. rs, session and thread name the record that keeps the lists. Fail open: any problem returns body.
type Env ¶
type Env struct {
// Store is the session store. Records live there when it is durable (store.Durable).
Store store.Store
// Fallback holds the records when Store is not durable: tool deferral's own file (File.Store).
// nil means there is none.
Fallback store.Store
History History
Gate *Gate
Prober *Prober
}
Env is the state one host keeps for deferral. One per process (or per tenant, as the host likes); every field is safe for concurrent use.
func (Env) RecordStore ¶
RecordStore is where this Env keeps its records: a durable session store, else the durable fallback, else nil (nothing is deferred: a record that dies with the process would move tools inside live cached prefixes on the next start).
type File ¶
File is tool deferral's own on-disk state, for a proxy whose session store does not survive a restart (no dashboard database, the session state off, hosted mode). Without it, a restart loses every thread's record and moves deferred tools back into live cached prefixes: a full rewrite of every live conversation.
It holds, in one SQLite file:
- each thread's record and each session's tool search opt-out (store keys cg:tdf: and cg:tso:, tool names and a flag only), through a store.Memory with a metadata-only store.Disk;
- the tool history and the probe verdicts, when there is no dashboard database to hold them.
Metadata only: tool names, session ids, project paths, flags, times. No tool text.
type Gate ¶
type Gate struct {
// Counters, for /stats.
Retries atomic.Int64 // every 400/422 on a changed request answered with the original, any cause
TurnedOff atomic.Int64 // the Retries whose original succeeded, which turned deferral off (Break)
Deferred atomic.Int64 // requests that carried deferred tools
Decisions atomic.Int64 // threads decided
Rebuilds atomic.Int64 // threads whose set was rebuilt after a store miss
Unproven atomic.Int64 // store misses sent as the original: the rule deferred a tool the transcript does not prove
// Our own search (#825).
AddBacks atomic.Int64 // deferred tools our own search (#825) added back to `tools`
ClientLoads atomic.Int64 // deferred tools a ToolSearch answer loaded in client-search mode (#898)
DirectCalls atomic.Int64 // deferred tools called with no search having loaded them (#898)
MixedSearches atomic.Int64 // searches in the same response as a client tool call
// Client-search mode (#898): disables by reason. The production monitor reads these.
DisabledUnknown atomic.Int64 // reason unknown_description
DisabledBreak atomic.Int64 // reason break
// contains filtered or unexported fields
}
Gate holds the per-account off switches that are not configuration: the user's tool search opt-out while its session is not seen yet (from the plugin's session-start hook, on /tool-search; a seen session's flag lives in the record store), and the turn-off after a 400 on a request we changed. Safe for concurrent use.
func (*Gate) Break ¶
Break turns deferral off for this tenant and model, and counts it (TurnedOff only when it stored).
func (*Gate) ClientDisabled ¶ added in v0.6.7
ClientDisabled reports whether client-search mode is disabled for this tenant and ToolSearch description hash. The mark expires after gateTTL; clear it sooner by restarting the proxy.
func (*Gate) DisableClient ¶ added in v0.6.7
DisableClient disables client-search mode for this tenant and description hash, and counts it by reason. It counts a reason once per live mark, so a client that sends the same unknown description on every request is one event, not thousands. It reports whether it counted.
func (*Gate) DropTenant ¶
DropTenant forgets everything held for tenant (a purge).
func (*Gate) NoteToolSearch ¶
NoteToolSearch records the raw ENABLE_TOOL_SEARCH value a session's hook sent (SearchOffValue). For a session the proxy has seen (seen), the flag goes into the record store rs at once; for one it has not, it waits in this tenant's pending set until the session's first request. A value that is not off clears both.
type History ¶
type History interface {
// UserSessions returns the user's last n sessions (newest first, any project), leaving out
// the session `exclude`, each as the tool names it declared and used. Leaving out the current
// session is what makes a re-decision after a restart give the same set.
UserSessions(tenant, exclude string, n int) []Session
// ProjectUsed reports whether the project used tool in its last n sessions, leaving out
// `exclude`. tool may be a server unit ("mcp__<server>__"): any tool of that server counts.
ProjectUsed(tenant, project, tool, exclude string, n int) bool
}
History is the user's tool history, as the rule reads it. A nil History means "no history": nothing is deferred.
type Input ¶
type Input struct {
// Tenant is the user ("" on a single-tenant proxy, which has one user).
Tenant string
Project string
Body []byte
// Session is the current session: the history leaves it out.
Session string
// Keep is the account's keep list: never deferred.
Keep []string
// AlwaysDefer is the account's always-defer list: deferred without the history rule (#878).
AlwaysDefer []string
}
Input is everything Decide reads. The body is the ORIGINAL request, before any rewrite.
type Ledger ¶
type Ledger struct {
// contains filtered or unexported fields
}
Ledger adds requests up for /stats, in total and per account. Safe for concurrent use.
type Mem ¶
type Mem struct {
// SeedDB is the dashboard database to seed a tenant's history from (SeedTenant). nil: no seed.
SeedDB *sql.DB
// Retention bounds a row's age: the flush deletes sessions idle longer. 0: no age bound.
Retention time.Duration
// contains filtered or unexported fields
}
Mem is the in-memory history. Safe for concurrent use. The zero value is not usable; use NewMem.
func NewMem ¶
NewMem returns an empty history. db may be nil: the history then lives in memory only, and a restart starts it from zero (so nothing is deferred until 3 new sessions).
func (*Mem) DropTenant ¶
DropTenant forgets tenant's history in memory (a purge; the rows are the purge's to delete).
func (*Mem) LoadVerdicts ¶
LoadVerdicts seeds p with every kept verdict. Called once at start, off the request path.
func (*Mem) Observe ¶
Observe records one request: the tools it declares (from the ORIGINAL body, Claude Code's own deferred list included) and the tools its recent turns used or loaded through search. tenant may be "" (single-tenant). It never blocks on the database.
func (*Mem) Open ¶
Open makes the table, loads the whole history into memory and starts the background writer. It returns at once; the load runs in the background, and until it finishes Ready reports false (the rule then defers nothing). stop ends the writer after a last flush.
p, when not nil, is seeded with the kept probe verdicts first, in the same background load. Known window: a request that arrives in the first moments after a start, before the load ends, reads no verdict and no history. A NEW thread then decides "nothing" (safe), and a thread whose record was lost is sent undeferred once. The disk store keeps the record itself, so that second case needs a restart with the session-state database off.
func (*Mem) ProjectUsed ¶
ProjectUsed is History.ProjectUsed.
func (*Mem) Ready ¶
Ready reports whether the history is loaded. Before that, the rule must not decide: an empty history read as "no sessions" is right (defer nothing), but the set it stores would then be "nothing" for that thread forever. Deciding "nothing" is the safe direction, so callers may still decide; Ready exists for tests and metrics.
func (*Mem) ReadyC ¶ added in v0.6.7
func (m *Mem) ReadyC() <-chan struct{}
ReadyC is closed when the load that Open started has finished. For a host's start-up only.
func (*Mem) SaveVerdict ¶
SaveVerdict keeps one probe verdict (Unknown deletes it). Synchronous and short: it runs on a probe's background goroutine, never on the request path.
func (*Mem) SeedTenant ¶
SeedTenant copies tenant's own sessions from the dashboard's inventory tables into its history, once per process and only for this tenant, so a user who picks ultrahigh has their recent sessions at once rather than after 3 more. Called at the tenant's first deferral request; the copy runs in the background. Best effort: an older dashboard database simply seeds nothing. Sessions the history already holds win (they are newer).
The returned channel closes when the copy ends (at once when there is nothing to copy). Only a host's start-up waits on it.
func (*Mem) UserSessions ¶
UserSessions is History.UserSessions.
A session that is still running counts as history, on purpose: the newest n by last activity, ended or not. Its uses are read up to the moment of the decision, which is what the rule needs. Measured on the hosted database (2026-10-28 to 11-02, 452 sessions): at 391 of 415 decisions (94%) one of the last 3 sessions was still running. A replay with ended sessions only gave 22 wrong guesses against 24, at the same deferred volume (#866, N10). Do not "fix" this.
type Money ¶
type Money struct {
Gross float64 `json:"gross_usd"`
Cost float64 `json:"cost_usd"`
Net float64 `json:"net_usd"`
// SearchCost is the part of Cost that the request body does not show: the search calls' output, the
// second pass over the loaded definitions, and their write to the cache. The accountant prices a
// request from its bodies, and the names list is in them, so it sees the rest of Cost on its own
// (accountant R56). SearchCost is what a host must still subtract from the accountant's figure.
SearchCost float64 `json:"-"`
}
Money is one request's (or a total's) deferral figures in USD.
type Outcome ¶
type Outcome struct {
Body []byte
Changed bool
// Deferred is the names this request carries with defer_loading, sorted.
Deferred []string
// DeferredTokens is their weight in the original request, less the tools a search has already
// loaded in this transcript. ListTokens is the names list's weight. Our tokenizer's units.
DeferredTokens, ListTokens int
// Why says why nothing changed, for /stats and the log: "" when Changed.
Why string
// Decided is true on the request that made the thread's decision; Rebuilt when the decision
// came from Rebuild after a store miss.
Decided, Rebuilt bool
// NeedProbe asks the host to start a probe for Req.Probe (no verdict, or a stale one).
NeedProbe bool
// NeedClientProbe asks for a probe of Req.ClientProbe (ClientProbeBody).
NeedClientProbe bool
// Client is true when the thread runs in client-search mode. Loads is the deferred tools the
// answers written on this request loaded, and Answered how many calls got a new answer.
Client bool
Loads []string
Answered int
// ClientDisabled is the reason client-search mode was disabled on this request ("" if not), and
// DescHash the ToolSearch description hash it concerns. The host logs the pair.
ClientDisabled, DescHash string
// Direct is the deferred tools the transcript calls with no search having loaded them: they
// worked, so they are uses.
Direct []string
}
Outcome is what Apply did.
func Apply ¶
Apply defers the thread's set on one request. Fail open: on any problem Body is the input.
The off switches are read on every request: the account opt-out and a 400 turn-off for this tenant and model. Each one sends the original request. The user's ENABLE_TOOL_SEARCH opt-out blocks new decisions only. The probe verdict and the history only gate a NEW decision: once a thread has a stored set, the set is applied as stored, so a restart that loses the in-memory probe cache cannot move a tool.
func ApplySearch ¶ added in v0.6.7
ApplySearch runs our search on one Chat Completions or Responses request. The checks are those of Apply, less the probe (our search needs no provider feature) and with the model test turned round: Claude models use Apply's defer_loading path.
Before the rewrite it answers, on the request side, any call to our search the client received (a search together with another tool call, or a response the host could not hold), and adds those tools back. Fail open: on any problem Body is the input.
type ProbeKey ¶
type ProbeKey struct {
Upstream, Model, Route string
}
ProbeKey names one probe verdict.
type Prober ¶
type Prober struct {
// Go starts fn in the background. Tests replace it to run inline.
Go func(fn func())
// Persist, when set, is told every verdict, so it survives a restart (see Mem.SaveVerdict).
// A thread decided before a restart needs it: without a verdict a store miss mid-thread would
// send the thread undeferred and move every deferred tool back into the cached prefix.
Persist func(k ProbeKey, v Verdict, at time.Time)
// contains filtered or unexported fields
}
Prober runs and caches probes. Safe for concurrent use.
func (*Prober) Ensure ¶
Ensure starts a probe for k in the background when none is fresh and none is running. send is called once, off the request path.
func (*Prober) Forget ¶
Forget drops k's verdict, so the next request probes again. Called after a 4xx on a changed request.
It runs on the request path, before the retry of the original request, so it only clears the memory. The kept copy is removed on the background runner (Go): a database write here would make the client wait on exactly the path that exists to hide the 400.
func (*Prober) Seed ¶
Seed loads a verdict kept from before a restart. An older verdict than ProbeTTL still seeds: Ensure re-probes it in the background.
func (*Prober) Stale ¶
Stale reports whether k's verdict is older than ProbeTTL. False when there is none.
func (*Prober) Verdict ¶
Verdict returns the cached verdict for k, Unknown when no probe has finished (or Forget dropped it). A verdict older than ProbeTTL is still returned while Ensure re-probes: a gap in which every new thread read Unknown would leave those threads undeferred for their whole life.
type Record ¶
type Record struct {
// Deferred is the set decided at the thread's first request. Empty means "decided: nothing",
// which is a decision too and is stored so the thread is never re-decided.
Deferred []string `json:"d"`
// Client is true when the thread runs in client-search mode (#898): the thread had Claude Code's
// own ToolSearch at its first request, so it has no server-side search tool, and the proxy answers
// the client's search results (AugmentSearches). Decided once, with the set.
Client bool `json:"c,omitempty"`
// Answers is the names each ToolSearch call was answered with, by tool_use id: nil or empty means
// "the client's own result stands". Written the first time a call is seen and replayed from here,
// so the bytes of every later request are the same (also after a restart). Bounded by maxAnswers.
Answers map[string][]string `json:"a,omitempty"`
}
Record is one thread's decision. Tool names only: metadata, so the disk store keeps it.
type Req ¶
type Req struct {
Tenant, Session, Thread, Project, Model string
// Orig is the request as the client sent it: the rule and the weights read it.
Orig []byte
// Body is the request to rewrite (the pipeline's output). nil means Orig.
Body []byte
// Probe names the probe verdict that gates a NEW decision.
Probe ProbeKey
// ClientProbe names the verdict that gates client-search mode (#898); the zero key means the
// host has none, and the mode is off.
ClientProbe ProbeKey
// Keep is the account's keep list; AlwaysDefer its always-defer list (#878).
Keep, AlwaysDefer []string
// AccountOff is the account opt-out (toolfilter.defer: off).
AccountOff bool
}
Req is one request, as the host sees it.
type Request ¶
type Request struct {
// Tenant is the account ("" on a single-tenant proxy): the ledger keeps a total per account.
Tenant string
Model string
// DeferredTokens is the weight of the definitions deferred on this request, minus those of
// tools a search has already loaded in this transcript (those are paid inline again).
DeferredTokens int
// ListTokens is the names list's weight.
ListTokens int
// Searches is how many server-side searches this response ran.
Searches int
// SearchOutput is the output tokens of the search calls (provider units; from usage when known,
// else an estimate of 30 per search).
SearchOutput int64
// LoadedTokens is the weight of the definitions the searches in this response loaded: the
// second pass reads them uncached once, and the next request writes them to the cache once.
LoadedTokens int
// WrongGuesses is how many tools this request deferred that a search in its response then
// loaded. DroppedSearches is how many searches of this response have no result: the API does
// not run a search sent together with another tool call, and the model searches again.
WrongGuesses, DroppedSearches int
// Tier is how this request was billed.
Tier Tier
}
Request is one request's deferral facts, in OUR tokenizer's units.
type SearchCall ¶ added in v0.6.7
SearchCall is one call to our search tool in a response.
func SearchCalls ¶ added in v0.6.7
func SearchCalls(wire string, msg []byte, proxyTools ...string) (calls []SearchCall, other bool)
SearchCalls reads one response (a Chat Completions object or a Responses object): the calls to our search, and whether it called a client tool too. proxyTools are the host's other tools: a call to one of them is not a client call.
type SearchRead ¶ added in v0.6.7
type SearchRead struct {
// Searches is the calls to our search tool; Results the tool_search_tool_result blocks.
Searches, Results int
// Loaded is the tools the results loaded.
Loaded []string
}
SearchRead is what one response's server-side searches did.
func ReadSearches ¶ added in v0.6.7
func ReadSearches(msg []byte) (r SearchRead)
ReadSearches is SearchesIn with the result count.
func ReadSearchesSSE ¶ added in v0.6.7
func ReadSearchesSSE(raw []byte) (r SearchRead)
ReadSearchesSSE is SearchesInSSE with the result count.
func (SearchRead) Dropped ¶ added in v0.6.7
func (r SearchRead) Dropped() int
Dropped is how many searches have no result: the API does not run a search sent in the same response as another tool call, and the client drops the call (#866, N8).
type SearchRecord ¶ added in v0.6.7
type SearchRecord struct {
// Deferred is the set decided at the thread's first request. It never changes; the names list
// is built from it.
Deferred []string `json:"d"`
// Added is the deferred tools a search loaded, in the order they were loaded. They go at the end
// of `tools`, in this order, from then on.
Added []string `json:"a,omitempty"`
// Calls is the searches the client received (made together with a client tool call), by call
// id: the names each asked for. A chained Responses turn carries the client's answer to such a
// call but not the call, so the repair reads the names here. Bounded by maxCalls.
Calls map[string][]string `json:"c,omitempty"`
}
SearchRecord is one thread's decision for our search. Tool names only: metadata.
func LoadSearch ¶ added in v0.6.7
func LoadSearch(st store.Store, session, thread string) (SearchRecord, bool)
LoadSearch reads a thread's SearchRecord. ok=false on a miss.
type Session ¶
Session is one past session of the history: which tools it declared and which it used.
type Stats ¶
type Stats struct {
Money
Requests int64 `json:"requests"`
Searches int64 `json:"searches"`
DeferredTokens int64 `json:"deferred_tokens"`
Unpriced int64 `json:"unpriced_requests"`
WrongGuesses int64 `json:"wrong_guesses"`
DroppedSearches int64 `json:"dropped_searches"`
}
Stats is the ledger as /stats reports it.
type Verdict ¶
type Verdict int
Verdict is a probe's result.
func ClientProbeVerdict ¶ added in v0.6.7
ClientProbeVerdict reads a client-search probe response: Pass only when the model calls the tool the tool_reference loaded.
func ProbeVerdict ¶
ProbeVerdict reads a probe response: Pass only when a tool_search_tool_result loads the probe tool and a later tool_use calls it.
func RunClientProbeBeta ¶ added in v0.6.7
func RunClientProbeBeta(ctx context.Context, d dispatch.Dispatcher, ref dispatch.Ref, path, model, beta string) (Verdict, error)
RunClientProbeBeta is RunProbeBeta for client-search mode (#898): it checks that the API expands a tool_reference the proxy wrote, for a deferred tool, with no server-side search declared.
func RunProbe ¶
func RunProbe(ctx context.Context, d dispatch.Dispatcher, ref dispatch.Ref, path, model string) (Verdict, error)
RunProbe sends one probe through the host's Dispatcher. A transport error or a 5xx/429 is an error (no verdict, retried later); any other answer is a verdict.
func RunProbeBeta ¶ added in v0.6.7
func RunProbeBeta(ctx context.Context, d dispatch.Dispatcher, ref dispatch.Ref, path, model, beta string) (Verdict, error)
RunProbeBeta is RunProbe with an anthropic-beta header (none when beta is ""). A host passes the client's auth betas (AuthBetas): a subscription token on direct Anthropic needs the OAuth beta, and without it the probe gets a 401, which is no verdict, so deferral would stay off (#866, N12a).