Repository navigation
fix(tools): pass agent context window and max_tokens to media tools via the claude_cli bridge and /v1/tools/invoke (#1649) - #1650
Conversation
…_cli bridge (#1649) Media tools (read_image/read_audio/read_video) refuse to run without the agent budget in context. The bridge middleware set the agent key and tool policy but not the budget, so every call from a claude_cli agent failed with an agent budget wiring error. Set both values from the agent row, using the loop's defaults when the columns are unset. Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
clark-cant
left a comment
There was a problem hiding this comment.
Review — fix(mcp): pass agent context window and max_tokens through the claude_cli bridge (#1649)
Summary: bridgeContextMiddleware now sets agent_context_window and agent_max_tokens on the tool context from the agent row, with the loop's own fallbacks when the columns are unset. That closes the AgentBudgetWiringError that made read_image / read_audio / read_video fail for every claude_cli agent.
Risk level: Low. 13 lines in one middleware, one test, no auth/HMAC change, no schema, no contract.
Verdict: approve on the code.
Mandatory gates
- Duplicate / prior implementation: clear.
agent_context_windowsearch returns only #1649 and this PR. The pattern is the established one: #1197 (agent key), #1094, #512, #799 all inject into the same middleware and all merged. Open PR #1105 touchesbridgeContextMiddlewaretoo, but for sender/role, and has been DIRTY since 2026-06-26 — no semantic overlap. - Project standards:
AGENTS.mdpresent. Go conventions followed (errorsuntouched, no ignored returns, no new imports needed —configwas already imported atserver.go:21). - Strategic necessity: clear value. This is the reported bug for a whole provider class, and it is a 13-line fix.
Verified at 5662d581 (worktree, no edits)
gofmt -lon both changed files: empty.go build ./internal/gatewayandgo build -tags sqliteonly ./internal/gateway: clean.go veton both tag variants: clean.go test ./internal/gateway: ok.- Red/green on the new test: checking
server.goback to5662d581^makesTestBridgeContextMiddleware_InjectsAgentBudgetfail withcontext window = 0, want 120000/max tokens = 0, want 4096and0, want 200000/0, want 8192; restoring the head makes it pass. The test pins exactly the pre-fix state, so it is not phantom coverage. - The defaulting is a true mirror of the loop:
resolver.go:243-246computescontextWindowthe same way,loop_types.go:477-483(effectiveMaxTokens) returnsconfig.DefaultMaxTokensat 0, andloop_context.go:67-69injects that same pair. Bridge tools therefore see the same budget the in-process tools see — which is the property that matters, since the guard is shared (usage_caps.go:54→context_guard.go:62-72). - No regression for paths that used to run: every consumer of these two keys hard-fails with
AgentBudgetWiringErrorwhen either is 0 (context_guard.go:65-72), andclampToolRequestMaxTokenslives after that guard, so nothing that previously succeeded can now be clamped by the newly non-zeromax_tokens. store.WithAgentContextWindow/WithAgentMaxTokensalready ignore values<= 0(store/context.go:151-186), so the guards here are belt-and-braces rather than load-bearing.
Findings
Important — the second affected surface is still broken, and Fixes #1649 would close the issue over it.
/v1/tools/invoke has the identical gap: tools_invoke.go:98-104 loads the agent row and injects only store.WithAgentID, so POST /v1/tools/invoke {"tool":"read_image"} still returns agent budget wiring error: missing agent_context_window,agent_max_tokens. AGENTS.md → "Cross-Surface Feature/Fix Parity" requires auditing every affected surface before a fix is marked complete, and the PR body already names this one. The body's honesty is appreciated, but the close keyword is the problem: once this merges, #1649 reads as fixed while an operator-visible path keeps the exact symptom in the title. Either extend this PR (the row is already in hand at tools_invoke.go:100, so it is the same six lines) or switch to Refs #1649 and file the follow-up now. I would extend it — the second call site is cheaper to fix than to remember.
Suggestion — default before the lookup, and log a failed lookup.
The budget injection sits inside if err == nil && ag != nil (server.go:443-444), so a store error or a nil row leaves both keys unset and the media tool fails with the wiring error again, with nothing in the log to distinguish it from the pre-fix behavior. internal/consolidation/agent_budget.go:17-40 already codifies the project's answer to this exact question: start at config.DefaultContextWindow / DefaultMaxTokens, slog.Warn when the row cannot be read, then overwrite from the row when it can. Moving the two initializations above the lookup and adding the warn would make the bridge match that precedent — worth it for the diagnostics even if the call is already degraded by the missing row.
Suggestion — the same defaulting now exists in six places.
resolver.go:243-246, loop_types.go:505, consolidation/agent_budget.go:25-26, http/agents.go:313, http/agents_import_agent.go:157, and now server.go:462-469. The body preempts this ("kept inline here to keep the diff small") and that is a defensible call for this PR. Recording it anyway because the next call site is the tools_invoke fix above, and internal/store already imports config (store/agent_store.go:10), so AgentData.EffectiveContextWindow() / EffectiveMaxTokens() costs no new dependency and gives every future call site one thing to call instead of a seventh copy. Not a request to change this diff.
Suggestion — two notes for the body/changelog.
Bridge-spawned subagents now inherit the calling agent's window: subagent_spawn.go:321 reads store.AgentContextWindowFromContext into OriginContextWindow, which previously arrived as 0 and fell through to NewLoop's config.DefaultContextWindow (loop_types.go:505). That is the correct direction, but it is a behavior change beyond the media tools and is worth one line in the PR body so it is not discovered later. A CHANGELOG.md entry would also match the repo's fix cadence (d70ef203 is a recent example), though nothing in AGENTS.md makes it mandatory.
CI / merge state
Zero check runs on 5662d581. CI run 41699471055 is completed / action_required, created 2026-11-03T19:02:18Z — the first-time-contributor workflow gate, same as every other external PR here. mergeable: true, mergeable_state: unstable, base dev at 22e71c80, so nothing to rebase.
No formal approval and no merge from me: approving another author's workflow run is a maintainer call, and the head carries no checks to review. Once a maintainer approves the run and CI is green, this is a merge-on-green PR barring the tools_invoke decision above.
…ge (#1649) Start from the default context window and max tokens, overwrite from the agent row, and warn when the row cannot be read. /v1/tools/invoke now injects the budget too. Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
|
Thanks for the careful review, @clark-cant. I pushed 86c8b98 with these changes:
I also updated the title and description to cover both surfaces. |
clark-cant
left a comment
There was a problem hiding this comment.
Review — fix(tools): pass agent context window and max_tokens to media tools via the claude_cli bridge and /v1/tools/invoke (#1649)
Summary: 86c8b986 closes the parity finding from the 19:09Z review. /v1/tools/invoke now injects the agent budget too, both surfaces start from config.DefaultContextWindow / DefaultMaxTokens before the row lookup, and a failed lookup logs a warning. The delta also adds TestToolsInvoke_InjectsAgentBudget, the subagent-inheritance note in the body, and a CHANGELOG entry.
Risk level: Low. 5 files, +168/−0, 2 commits. No auth/HMAC change, no schema, no contract change; the only behavior change is that a path which previously hard-failed now runs with the same defaults the agent loop uses.
Verdict: approve on the code.
Mandatory gates
- Duplicate / prior implementation: clear. Searches for
agent_context_windowandtools_invokereturn only this PR; no merged or open PR duplicates it. This is the chosen successor to #1649's triage, not a parallel implementation. - Project standards:
AGENTS.mdpresent. The shape now matchesinternal/consolidation/agent_budget.go:17-40exactly (defaults first, warn on lookup failure, overwrite from the row), which is the precedent the previous review asked for. - Strategic necessity: clear. This is the user-visible failure in #1649, on both surfaces, fixed in five files.
Verified at 86c8b986 (fresh clone, no edits)
gofmt -lon the four changed Go files: empty.go buildandgo veton./internal/gateway ./internal/http: clean;go build -tags sqliteonlyon the same two: clean.go test ./internal/gateway ./internal/http -count=1: ok 0.06s / 3.54s.- Red/green on the new
/v1/tools/invoketest: checkingtools_invoke.goback to5662d58makes all three cases fail withcontext window = 0, want 120000 / 200000andmax tokens = 0, want 4096 / 8192; the head passes. Real coverage. - Red/green on the new bridge case: checking
server.goback to5662d58makesmissing_row_falls_back_to_defaultsfail with0, want 200000/0, want 8192, confirming the default-before-lookup path is what the test pins. - Merge state:
MERGEABLE/UNSTABLE, basedevat22e71c80, 2 commits, 5 files, +168/−0.
Findings
No Critical, no Important.
Suggestion — the warn branch has no test. stubAgentKeyStore.GetByIDUnscoped returns (s.ag, nil), so the missing row case exercises ag == nil && err == nil, not the new else if err != nil branch. A stub variant returning sql.ErrNoRows would pin the diagnostic line. Relatedly, the CHANGELOG says "log a warning when the row cannot be read" — for the bridge that holds only on an error, because a nil row with a nil error is silent.
Suggestion — the no-agent path is now fail-open by design. tools_invoke.go sets the defaults before agentIDStr is resolved, so a request that resolves no agent at all now runs media tools at 200000/8192 where it previously failed with the wiring error. That is the intended trade (the guard bounds a request; it does not authenticate it) and the endpoint is operator-gated, but it is a behavior change worth one line in the body rather than only in the diff.
Suggestion — default injection is scoped differently on the two surfaces. tools_invoke sets it unconditionally; the bridge sets it only after uuid.Parse(agentIDStr) succeeds, so a bridge call whose signed agent id is not a UUID still returns the original wiring error. One placement rule would remove the asymmetry.
Note — the if ag.ContextWindow > 0 guards duplicate what store.WithAgentContextWindow already enforces (store/context.go:151,167 ignore <= 0). Harmless and self-documenting; no action.
CI / merge state
Zero check runs on 86c8b986. CI run 41702631834 is completed / action_required, created 2026-11-03T19:22:17Z — the first-time-contributor workflow gate. 0 approvals repo-wide, reviewDecision empty, mergeStateStatus: UNSTABLE. No merge from me: approving another author's workflow and merging remain maintainer calls.
Posted by /ck:review-pr at 2026-11-03T22:08Z
…se (#1649) Set the default context window and max tokens before parsing the signed agent id, so the bridge follows the same rule as /v1/tools/invoke. Add bridge cases for a failed lookup and a non-UUID agent id, and say in the CHANGELOG that the warning is logged on a lookup error. Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
|
Thanks @clark-cant for the careful review and for re-running the red/green checks. All three suggestions are done in fda4771: a bridge test case where the agent lookup returns |
clark-cant
left a comment
There was a problem hiding this comment.
Re-reviewed at fda47715 (delta vs 86c8b98: 3 files, +26/−11, one commit). Verdict: approve on the code.
All three suggestions from my 22:08Z review are addressed, and the non-UUID agent id case is the one that actually mattered — it was the last behavioural difference between the two surfaces:
- Defaults are now set before the agent-id parse (
internal/gateway/server.go:436-440), so a signed bridge request with a malformed id gets the default budget instead of reaching the media tools with0, matching/v1/tools/invoke:99-100. stubAgentKeyStoregained anerrfield, and the lookup-error path is now covered.- The CHANGELOG sentence now says "when the agent lookup returns an error", which is what the code does.
Verification at the head (fresh checkout of refs/pull/1650/head):
gofmt -lon both changed Go files: empty.go build+go vetclean on./internal/gateway ./internal/http, default and-tags sqliteonly.go test ./internal/gateway ./internal/http -count=1: ok (0.14s / 4.99s).- Red/green on the new case: reverting
server.goto86c8b98failsnon-UUID agent id keeps defaultswithcontext window = 0, want 200000/max tokens = 0, want 8192; the head passes. Note thelookup errorcase passes on the parent too (defaults were already set inside the uuid branch there), so it pins the warn-and-default contract rather than a new behaviour — fine to keep, just don't read it as the regression test for this commit.
Two non-blocking notes, no action needed for this PR:
- The
slog.Warnonly fires whenagentStore != nil; with a nil store the defaults apply silently. Same shape as/v1/tools/invoke, so parity holds — just worth knowing the silent path exists on both. - The surfaces still resolve the agent differently (
GetByIDUnscopedwith a UUID here,GetByKeywith a key there). That is inherent to what each caller has, not something this PR should change.
Not approving formally and not merging: check-runs for fda47715 still return total_count 0, CI run 41729441134 is completed / action_required (created 2026-11-03T22:17:10Z) under the first-time-contributor workflow gate, and the repo has zero approved PRs. Once a maintainer approves the workflow run and it goes green, this is mergeable as-is.
|
@clark-cant thanks for the approval. Is anything else needed before this can be merged? |
|
Thanks for checking in. To be precise about the state, since "approval" is doing two jobs here:
Nothing else is needed from you. What remains is a maintainer action on the two gates this account cannot clear:
Branch state is |
|
Conflict, not a code problem — one Heads-up: the branch went from Verified with Resolution: after
Then Why I am asking instead of doing it: the automation's token has read-only access to your fork, so it cannot push the resolution to Nothing else is outstanding on the code side — 5662d58, 86c8b98 and fda4771 all approve the diff with zero Critical and zero Important, and the last suggestion was addressed. What remains after the push is process-only: the first-time-contributor workflow run (41729441134, |
…get-context # Conflicts: # CHANGELOG.md
|
Merged dev in and kept all three CHANGELOG entries. Build and the gateway and http tests pass. |
clark-cant
left a comment
There was a problem hiding this comment.
Re-reviewed at fec996e0 (delta vs fda47715: one merge commit, parents fda47715 + 8a5a10b0). Verdict: approve.
The only content change is the CHANGELOG.md conflict resolution; the PR's own four files are byte-identical to the head I reviewed at 2026-11-04T01:06Z (git diff fda47715 pr1650-new -- internal is empty).
Verified on pr1650-new in a clean worktree:
git diff origin/dev...fec996e0is still 5 files, +180/−2 — the dev sync added the 1648/1661 code without touching this PR's diff beyond the changelog entry.CHANGELOG.mdresolution is ours-not-theirs and additive: 10 lines, 0 deletions, a single### Fixedbullet placed after the 1661 "Queued agent runs" entry and before 1627. Nothing fromdevwas dropped, no conflict markers anywhere.gofmt -lon the four changed Go files: empty.go build ./internal/gateway ./internal/httpandgo veton the same two: clean.go test ./internal/gateway ./internal/http -count=1: ok (0.07s / 4.32s).
CI on fec996e0: run 42146256236 — web pass (56s), release-versioning pass (6s), go still in progress. The workflow gate is cleared on this head, so this is now merge-on-green. Approving, and merging as soon as go reports.
Summary
Media tools (
read_image,read_audio,read_video) now work forclaude_cliagents (through the MCP bridge) and when called directly throughPOST /v1/tools/invoke. They failed on every call withagent budget wiring error: missing agent_context_window,agent_max_tokens.How it happens: a
claude_cliagent calls a media tool through/mcp/bridge, or an operator callsPOST /v1/tools/invoke {"tool":"read_image"}. Neither path puts the agent's context window or max_tokens into the tool context.agentBudgetFromContext(internal/tools/usage_caps.go:53) reads them, andGuardContextWindowWithMediaTokens(internal/usage/caps/context_guard.go) returnsAgentBudgetWiringErrorwhen either is 0. The in-process loop sets both (internal/agent/loop_context.go:68-69), which is why native providers work.Cause:
bridgeContextMiddleware(internal/gateway/server.go) andToolsInvokeHandler.ServeHTTP(internal/http/tools_invoke.go) inject the agent ID (and, on the bridge, key, policy and shell deny groups), but not the budget.Fix: in both places, start from
config.DefaultContextWindow/config.DefaultMaxTokensbefore the agent id is parsed or looked up, overwrite from the agent row when it has values above 0, andslog.Warnwhen the row cannot be read. This mirrorsinternal/consolidation/agent_budget.go. The guard itself is unchanged.Behavior change: subagents spawned from a bridge call now get the calling agent's context window (
subagent_spawn.go:321) instead of the default, because that value used to arrive as 0.Behavior change on
/v1/tools/invoke: a request that resolves no agent now runs media tools with the default budget instead of failing with the wiring error. The endpoint is operator-gated, and the guard bounds a request but does not authenticate it.Scope: the same defaulting also exists in
resolver.go,loop_types.go,consolidation/agent_budget.goandhttp/agents*.go. I did not merge these into one shared helper here, to keep the diff small. A CHANGELOG entry is added.Type
Target Branch
devChecklist
go build ./...passes (rango build -tags sqliteonly ./internal/gateway ./internal/httponly)go vet ./...passes (ran on./internal/gateway ./internal/http)go test -race ./...(rango test ./internal/gateway ./internal/http, without-race)$1, $2(no SQL changes)Test Plan
TestBridgeContextMiddleware_InjectsAgentBudget(internal/gateway/bridge_context_test.go): explicit values, unset columns, a missing agent row, a lookup error (sql.ErrNoRows, the warn branch), and a non-UUID agent id.TestToolsInvoke_InjectsAgentBudget(internal/http/tools_invoke_budget_test.go): explicit values, unset columns, and a failed lookup. It posts to the real handler with a probe tool that reads the budget from its context.context window = 0, want 120000,max tokens = 0, want 4096(explicit), and0, want 200000/0, want 8192for the other two cases.go test ./internal/gateway ./internal/httppasses.go vetandgo teston those two packages.-race, integration tests, a liveclaude_cliagent.Fixes #1649