tooldefer

package
v0.6.6 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 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 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):

  1. it is not used in this thread so far;
  2. the user's last 3 sessions, in any project, declared it and used it in none;
  3. this project did not use it in its last 10 sessions (the project veto);
  4. 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);
  5. it weighs at least 200 tokens, weighed on the ORIGINAL request.

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

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 (a restart with no disk copy) the set is decided again with the same rule, from history that leaves out the current session, which gives the same answer unless another session of the user ended in between. Every tool a search in this transcript has loaded is then added, because the client echoes those loads (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

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

View Source
const (
	UserSessions    = 3
	ProjectSessions = 10
	MinTokens       = 200
)

The thresholds of the rule. See the package comment.

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

View Source
const FileName = "context-guru-tooldefer.db"

FileName is the file's name next to the dashboard database path.

View Source
const MaxSessions = 64

MaxSessions is how many sessions per tenant the history keeps.

View Source
const ProbeTTL = 24 * time.Hour

ProbeTTL is how long a verdict holds.

View Source
const PurposeProbe = "tooldefer.probe"

PurposeProbe is the dispatch purpose of a probe.

Variables

This section is empty.

Functions

func AnthropicModel

func AnthropicModel(model string) bool

AnthropicModel reports whether model names a Claude model: v1 defers on Claude models only.

func Decide

func Decide(h History, in Input) []string

Decide returns the tool names to defer, sorted. Empty when the rule defers nothing.

func DeclaredNames

func DeclaredNames(body []byte) map[string]bool

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

func DeferralCause(body []byte) bool

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 HasAssistantTurn

func HasAssistantTurn(body []byte) bool

HasAssistantTurn reports whether this request continues a thread (it is not the first one).

func Key

func Key(session, thread string) string

Key is the store key of one thread's record.

func Loaded

func Loaded(body []byte) map[string]bool

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

func LoadedWeight(body []byte, names []string) int

LoadedWeight is the weight, in the original request, of the named tools.

func MissingRef

func MissingRef(errBody []byte) string

MissingRef returns the tool name a provider 400 says a tool_reference names but `tools` lacks, or "" when the error is another one.

func NamesList

func NamesList(names []string) string

NamesList is the names list for a sorted set of names.

func NeverDefer

func NeverDefer(name string) bool

NeverDefer reports whether the fixed list, or Context Guru's own prefix, protects name.

func Nonce

func Nonce() string

Nonce is a fresh random hex string.

func NormProject

func NormProject(p string) string

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 OpenForPurge

func OpenForPurge(path string) (*sql.DB, error)

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 ProbeBody

func ProbeBody(model, nonce string) []byte

ProbeBody is the probe request for model, with nonce.

func Rebuild

func Rebuild(h History, in Input) []string

Rebuild is the set after a store miss: the rule decided again (the history leaves out this session), plus every tool our search has loaded in this transcript. A tool our search loaded was deferred by definition, so adding it back cannot move a tool the provider cached as loaded.

Known limit: a tool the model called directly while it was deferred, with no search (the API accepts that), reads as "used" and comes back loaded. So does a tool whose history moved because another session ended in between. Either rewrites the prefix once. The disk store, on with the dashboard, makes both cases rare: Rebuild runs only when the stored record is gone.

func RepairRefs

func RepairRefs(body []byte) (out []byte, added []string, ok bool)

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

func Rewrite(body []byte, set map[string]bool) (out []byte, names []string, ok bool)

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 Save

func Save(st store.Store, session, thread string, r Record)

Save writes a thread's record.

func SearchOff

func SearchOff(st store.Store, session string) bool

SearchOff reports whether st holds the tool search opt-out for session.

func SearchOffValue

func SearchOffValue(raw string) bool

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

func SearchesIn(msg []byte) (searches int, loaded []string)

SearchesIn reads one response message (an Anthropic message object): how many server-side searches ran, and which tools they loaded.

func SearchesInSSE

func SearchesInSSE(raw []byte) (searches int, loaded []string)

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

func SetSearchOff(st store.Store, session string, on bool)

SetSearchOff stores the opt-out for session (on), or removes it.

func StubTools

func StubTools(body []byte, names []string) (out []byte, added []string, ok bool)

StubTools appends a deferred stub for each of names to `tools`. ok=false on a shape it does not handle; out is then body.

Types

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

func (e Env) RecordStore() store.Store

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

type File struct {
	DB    *sql.DB
	Store *store.Memory
	// contains filtered or unexported fields
}

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.

func OpenFile

func OpenFile(path string, retention time.Duration) (*File, error)

OpenFile opens (or creates) the file at path. retention bounds how long a row lives after its last write (the session-state retention).

func (*File) Close

func (f *File) Close() error

Close flushes and closes the file.

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

func NewGate() *Gate

NewGate returns an empty Gate.

func (*Gate) Break

func (g *Gate) Break(tenant, model string)

Break turns deferral off for this tenant and model, and counts it.

func (*Gate) Broken

func (g *Gate) Broken(tenant, model string) bool

Broken reports whether a 400 turned deferral off for this tenant and model.

func (*Gate) DropTenant

func (g *Gate) DropTenant(tenant string)

DropTenant forgets everything held for tenant (a purge).

func (*Gate) NoteToolSearch

func (g *Gate) NoteToolSearch(tenant, session, raw string, rs store.Store, seen bool)

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.

func (*Gate) TakePending

func (g *Gate) TakePending(tenant, session string, rs store.Store) bool

TakePending reports whether tenant's session has a pending opt-out, and moves it into rs.

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
}

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. Safe for concurrent use.

func (*Ledger) Add

func (l *Ledger) Add(r Request, p modelinfo.Price)

Add folds one request in.

func (*Ledger) Snapshot

func (l *Ledger) Snapshot() Stats

Snapshot returns the totals.

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

func NewMem(db *sql.DB) *Mem

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

func (m *Mem) DropTenant(tenant string)

DropTenant forgets tenant's history in memory (a purge; the rows are the purge's to delete).

func (*Mem) Has

func (m *Mem) Has(tenant, session string) bool

Has reports whether the history has seen tenant's session.

func (*Mem) LoadVerdicts

func (m *Mem) LoadVerdicts(p *Prober)

LoadVerdicts seeds p with every kept verdict. Called once at start, off the request path.

func (*Mem) Observe

func (m *Mem) Observe(tenant, session, project string, body []byte, ts int64)

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

func (m *Mem) Open(flushEvery time.Duration, p *Prober) (stop func())

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

func (m *Mem) ProjectUsed(tenant, project, tool, exclude string, n int) bool

ProjectUsed is History.ProjectUsed.

func (*Mem) Ready

func (m *Mem) Ready() bool

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

func (m *Mem) SaveVerdict(k ProbeKey, v Verdict, at time.Time)

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

func (m *Mem) SeedTenant(tenant string) <-chan struct{}

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

func (m *Mem) UserSessions(tenant, exclude string, n int) []Session

UserSessions is History.UserSessions.

func (*Mem) WaitReady

func (m *Mem) WaitReady(d time.Duration) bool

WaitReady waits up to d for the load that Open started (the probe verdicts first, then the history). It reports whether the load finished. For a host's start-up only, never the request path: the first request after a start then reads the stored verdicts.

type Money

type Money struct {
	Gross float64 `json:"gross_usd"`
	Cost  float64 `json:"cost_usd"`
	Net   float64 `json:"net_usd"`
}

Money is one request's (or a total's) deferral figures in USD.

func Price

func Price(r Request, p modelinfo.Price) (Money, bool)

Price prices one request. ok=false when the model has no known price.

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
}

Outcome is what Apply did.

func Apply

func Apply(env Env, r Req) (o Outcome)

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.

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 NewProber

func NewProber() *Prober

NewProber returns an empty Prober.

func (*Prober) Ensure

func (p *Prober) Ensure(k ProbeKey, send func(ctx context.Context) (Verdict, error))

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

func (p *Prober) Forget(k ProbeKey)

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

func (p *Prober) Runs() (pass, fail int64)

Runs is how many probes finished with each verdict.

func (*Prober) Seed

func (p *Prober) Seed(k ProbeKey, v Verdict, at time.Time)

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

func (p *Prober) Stale(k ProbeKey) bool

Stale reports whether k's verdict is older than ProbeTTL. False when there is none.

func (*Prober) Verdict

func (p *Prober) Verdict(k ProbeKey) 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"`
}

Record is one thread's decision. Tool names only: metadata, so the disk store keeps it.

func Load

func Load(st store.Store, session, thread string) (Record, bool)

Load reads a thread's record. ok=false on a miss.

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
	// Keep is the account's keep list.
	Keep []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 {
	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.
	LoadedTokens int
	// Tier is how this request was billed.
	Tier Tier
}

Request is one request's deferral facts, in OUR tokenizer's units.

type Session

type Session struct {
	Declared map[string]bool
	Used     map[string]bool
}

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"`
}

Stats is the ledger as /stats reports it.

type Tier

type Tier int

Tier is how a request was billed for the bytes at the head of its prefix.

const (
	TierFresh Tier = iota
	TierRead
	TierWrite
	TierWrite1h
)

func TierOf

func TierOf(cacheRead, cacheWrite, cacheWrite1h int64) Tier

TierOf is the tier the head of the prefix was billed at, from the response usage. The same rule as the dashboard's declaration-filter saving: any cache read means the head was read.

type Verdict

type Verdict int

Verdict is a probe's result.

const (
	Unknown Verdict = iota // no probe has finished for this key
	Pass
	Fail
)

func ProbeVerdict

func ProbeVerdict(resp []byte, nonce string) Verdict

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 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 (Verdict) String

func (v Verdict) String() string

Jump to

Keyboard shortcuts

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