Documentation
¶
Overview ¶
Package inband is the in-band loop: the host answers a call to one of our own tools (expand, adjudicate, tool search) itself, so the client never sees the call.
Known no-op: Responses over a WebSocket. Some clients send Responses over a WebSocket. Codex does (codex-rs/codex-api/src/endpoint/responses_websocket.rs, openai/codex f64f003). A WebSocket connection does not go through the HTTP host. On that path nothing in this package runs: no tool is injected, nothing is offloaded, and no call is expanded. This is safe, because nothing lossy happens there. A marker needs an offload, and an offload needs the HTTP host. The client works as it would without Context Guru.
Through the proxy, the case does not arise for Codex: the proxy answers a WebSocket upgrade on the Responses route with 426 (see Handler.Mux in proxy). Codex then falls back to HTTPS (codex-rs/core/src/client.rs, the UPGRADE_REQUIRED arms, f64f003). Only 426 makes it fall back at once. OpenCode falls back to HTTP after any failed WebSocket connect, and keeps HTTP until restart or a session move (packages/core/src/session/model-transport.ts, sst/opencode 2.4.1). Both clients send the full history over HTTP. The no-op applies when a client reaches the provider by a route that has no HTTP host.
Index ¶
- Constants
- func RepairExpandErrors(wire string, body []byte, st store.Store, sessionOf func(body []byte) string, ...) ([]byte, int)
- func RepairOnMissingRef(resp *http.Response, body []byte) (fixed []byte, ok bool)
- func RetryRefused(resp *http.Response, err error, body []byte, r Refused) (_ *http.Response, _ error, _ []byte, retried bool)
- func StatelessResponses(body []byte) bool
- type Refused
- type Result
- type SSESplicer
- func (sp *SSESplicer) Blocks() int
- func (sp *SSESplicer) FirstByte() time.Time
- func (sp *SSESplicer) HandBack(withheld []byte)
- func (sp *SSESplicer) Opened() bool
- func (sp *SSESplicer) Pass(body io.Reader, proxyTool string, moreProxyTools ...string) (whole, withheld []byte, called []string)
- func (sp *SSESplicer) Round(resp *http.Response)
- func (sp *SSESplicer) Terminate(withheld []byte)
- type Search
- type Sinks
- type Turn
Constants ¶
const MaxExpandRounds = 3
MaxExpandRounds caps the continuation loop (headroom's default).
Variables ¶
This section is empty.
Functions ¶
func RepairExpandErrors ¶
func RepairExpandErrors(wire string, body []byte, st store.Store, sessionOf func(body []byte) string, s Sinks) ([]byte, int)
RepairExpandErrors resolves every expand tool_result the CLIENT had to answer itself, so `No such tool available: context_guru_expand` never reaches the model. It is the request half of interception: the loop withholds the call from the client wherever it can, and this covers what it structurally cannot — a batched client tool, the round cap, an event stream that will not reconstruct, a non-Anthropic stream, a bypassed turn carrying older markers. See expand.RepairToolResults.
Restored content is marked kept-verbatim: an offloader that re-compacted it would trigger the same expand call again next turn. That mark is also what keeps the accounting honest — the tokens are charged to the dashboard row once, on the turn the original first comes back, because the client keeps its own copy of the error and the repair therefore runs again on every later turn. Nothing is charged to the process-wide bounce counter, which counts expand CALLS, and ten repairs of one stale error are one call.
func RepairOnMissingRef ¶
RepairOnMissingRef reads a refused response. When it is a 400 that names a tool_reference to a tool body does not declare, it closes resp and returns body with a deferred stub for that tool. Otherwise resp is left readable, with the same bytes, and ok is false. The decision is tooldefer.RepairFromError's; this keeps the HTTP response.
func RetryRefused ¶
func RetryRefused(resp *http.Response, err error, body []byte, r Refused) (_ *http.Response, _ error, _ []byte, retried bool)
RetryRefused sends the request without deferral, once, when the provider refused it with 400 or 422: the client must never see that 400 (Claude Code would turn its own search off for the session). It returns retried=false, and leaves resp as it is, when the response is not such a refusal. When retried, body is what went upstream last, and the host must drop deferral for the rest of the request.
func StatelessResponses ¶
StatelessResponses reports whether a Responses request never relies on the server keeping the response: store is false and the body holds no server-held history (schema.ServerHeldHistory: previous_response_id, conversation, item_reference). Codex over HTTP sends exactly this. A missing store field means the API default, which is true.
Types ¶
type Refused ¶
type Refused struct {
// Orig is the request before deferral.
Orig []byte
// Search: the original declares our search, so the repair below does not apply (it reads
// Anthropic shapes, not our search's OpenAI wires).
Search bool
// Do sends one request upstream.
Do func(body []byte) (*http.Response, error)
// Book records the refusal: the refused status, the provider's error body, and whether the
// original was accepted.
Book func(status int, errBody []byte, originalOK bool)
}
Refused is a round-0 request that tool deferral changed and the provider refused.
type Result ¶
type Result struct {
// Next is the follow-up request. Nil when Bail is true.
Next []byte
// Bail: the loop cannot answer. The host hands the upstream response over unchanged.
Bail bool
// Our search (#825).
Searches int // calls to our search in the round
SearchLoaded []string // tools added back now
SearchClient bool // the turn also holds a client tool call
// Expand. Reached is true once the round held a call to answer: the host logs then.
Reached bool
Calls int // expand calls
Resolved int // of those, resolved from the store
// Strays is the number of adjudication calls answered in band. Set only when Next is set.
Strays int
}
Result is what the loop decided, with the counts the host logs and books. The counts are set on every path, also on a bail, because the side effects they describe already happened.
type SSESplicer ¶
type SSESplicer struct {
// contains filtered or unexported fields
}
SSESplicer joins the rounds of an expand continuation into ONE client event stream.
Round 1's events are forwarded as they arrive and forwarding stops at the expand call. The continuation's blocks are then written into the same open response, renumbered to follow the blocks already sent and with their message_start dropped, because a client sees one message per turn. If the loop cannot answer after all, handBack writes the withheld events through the same transform — which, for a round whose blocks were not renumbered, is byte-for-byte the stream as it arrived: exactly the old pass-through.
func NewChatSSESplicer ¶
func NewChatSSESplicer(w http.ResponseWriter, copyHeaders func(dst, src http.Header)) *SSESplicer
NewChatSSESplicer is the splicer for a Chat Completions stream.
func NewResponsesSSESplicer ¶
func NewResponsesSSESplicer(w http.ResponseWriter, copyHeaders func(dst, src http.Header)) *SSESplicer
NewResponsesSSESplicer is the splicer for an OpenAI Responses stream.
func NewSSESplicer ¶
func NewSSESplicer(w http.ResponseWriter, copyHeaders func(dst, src http.Header)) *SSESplicer
copyHeaders is the host's header copy for the first round's response headers. The host owns it because it decides which headers may reach its client. Nil means "copy no headers".
func (*SSESplicer) Blocks ¶
func (sp *SSESplicer) Blocks() int
Blocks is the number of content blocks the client holds.
func (*SSESplicer) FirstByte ¶
func (sp *SSESplicer) FirstByte() time.Time
FirstByte is when the client got its first byte (zero before any).
func (*SSESplicer) HandBack ¶
func (sp *SSESplicer) HandBack(withheld []byte)
handBack sends events the splice withheld — the fail-open path, and the one that hands a client the model's own expand call when nothing else can be done with it.
func (*SSESplicer) Opened ¶
func (sp *SSESplicer) Opened() bool
opened reports whether the client holds any of the model's answer: a content block on Anthropic, text, reasoning or a tool call on Chat Completions. A round whose proxy call came before any of it made the client wait for the whole continuation.
func (*SSESplicer) Pass ¶
func (sp *SSESplicer) Pass(body io.Reader, proxyTool string, moreProxyTools ...string) (whole, withheld []byte, called []string)
pass forwards this round's events until the one that calls the expand tool, and returns the round's whole event stream — forwarded and withheld together — because the continuation loop reconstructs the assistant turn from all of it. withheld is the deciding event and everything after it: the caller either answers it or hands it back. called is WHICH proxy tools the round named, in order of first appearance and deduplicated: the caller counts a leaked tool_use by tool (#174), which a bare `found` could not tell it.
Past sseRetainMaxBytes it returns whole=nil: the turn can no longer be rebuilt, so nothing can be intercepted, and everything is forwarded as it arrives. called still reports which proxy tools the response named, because the client then receives those calls and the caller has to count them.
ONE REQUIRED NAME plus a variadic tail, rather than a bare `proxyTools ...string`. A bare variadic compiles with NO names at all, and an empty withhold set silently disables this entire defence: startsProxyToolCall can never match, called stays empty, cut stays -1, and every proxy-injected tool_use streams straight to the client while the call site reads as though it were protected. The two-argument signature this grew out of made that unrepresentable; this keeps that property while still taking a set.
func (*SSESplicer) Round ¶
func (sp *SSESplicer) Round(resp *http.Response)
round starts an upstream round. Its blocks are numbered from the end of what the client already holds, and only the first round's headers and status are sent — by the time a continuation answers, the response is long open.
func (*SSESplicer) Terminate ¶
func (sp *SSESplicer) Terminate(withheld []byte)
terminate closes the client's turn if nothing has. A continuation round is not obliged to carry a message_stop — it can come back empty, truncated, or in another dialect — and the round whose terminator the splice withheld is the only other place one exists. Without this the client is left with a half-open message, which is worse than the leaked tool_use it replaced: on main those rounds cannot arise at all.
type Search ¶
type Search struct {
// Orig is the request before deferral. Loaded tools are added back from it.
Orig []byte
// Load adds the named tools back to the thread and says which were deferred (set) and which
// went in now (now).
Load func(names []string) (set map[string]bool, now []string)
// Mixed keeps the searches the client receives together with its own tool call.
Mixed func(calls []tooldefer.SearchCall)
}
Search is the host's side of our own tool search (#825) for one answer.
type Sinks ¶
type Sinks struct {
// Bounce counts an expand call process-wide (offload had to come back).
Bounce func(tokens int)
// NoteExpand books the restored tokens on the request's dashboard row.
NoteExpand func(tokens int)
// NoteSweepExpand charges a restored sweep marker to the sweep (#404 point 7).
NoteSweepExpand func(tokens int, note offload.SweepExpandNote)
}
Sinks are the host's accounting hooks for an expand. Any nil hook is skipped.
type Turn ¶
type Turn struct {
Wire string
// Body is the request that produced this round. The follow-up extends it.
Body []byte
// Msg is the round's assistant message (an event stream is aggregated first).
Msg []byte
Store store.Store
Session string
ThreadID string
// Anchor, when non-nil, is where this turn's expands are restored on later turns
// (expand.fixed_restore, #407).
Anchor *expand.Anchor
// InBandBreakpoint moves the client's last message breakpoint onto the follow-up (#784).
InBandBreakpoint bool
// Search is nil unless the request declares our search and deferral ran.
Search *Search
Sinks Sinks
}
Turn is one upstream round the loop must answer.