Repository navigation
fix: send the desktop and GitHub tools only after a chat first uses them - #204805
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. What this changesThis PR loads desktop and GitHub tools on first use, preserves them in the session tool pin, and moves GitHub procedures into action results. Example: A new unsandboxed vision chat uses Tool Search but has not requested desktop or GitHub work.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains Keep open: this maintainer-authored optimization remains useful, and the revised head addresses all four prior findings without a remaining discrete code defect. Reviewed head: Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe agent tool surface converts available tools into provider declarations and discoverable catalog entries; the embedded resolver executes deferred direct calls, while transcript checkpoints preserve the session's tool definitions. flowchart TD
A[Chat request] --> B[Tool surface catalog]
B --> C[Model discovery]
C --> D[Deferred direct resolver]
D --> E[Desktop or GitHub execution]
D --> F[Session tool checkpoint]
F --> G[Later provider requests]
Technical reviewBest possible solution: Retain the existing resolver and checkpoint ownership, preserve direct execution contracts, and complete live first-use and existing-session upgrade validation. Do we have a high-confidence way to reproduce the issue? Current-main source confirms both tools retain direct-only placement and therefore bypass catalog deferral; the supplied measurement exercises real construction and compaction, but no product run was performed during this read-only review. Is this the best way to solve the issue? The implementation preserves the reasons for direct execution while using the existing deferred resolver and session pin, and the guidance extraction removes substantial repeated prompt text without changing Gateway authorization. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against bf4c7d3e98a6. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +267, Tests +424, Docs +32, Other +140. Total +863 across 37 files. Added test files: 3. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 24, 2026, 9:30 PM ET / November 25, 2026, 02:30 UTC (Revision 2). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
257d203 to
00b539e
Compare
With Tool Search or Code Mode active, both tools were marked direct-only and sent on every request whether or not the session ever used them (about 13k characters per request together). Add an on-demand catalog mode: the tool starts deferred with a short catalog entry, loads on its first direct call by name in the embedded runner, and the session tool pin then keeps it direct for the rest of the prompt series, across restarts. Catalog bridges refuse it, so screenshots and the prepare handoff still run only through a direct call. Harnesses that cannot load a tool on use keep it direct. Replace the github_publish manual with a short summary plus one line per action, and return each procedure in the result where it applies.
- Add uniquely named on-demand catalog entries to the live stream tool set, so the unknown-tool guard no longer refuses repeated computer calls before the definition is sent. - Put github_publish result guidance in details as well as text: Code Mode returns only details to the model. - Mark on-demand rows in the deferred-tool directory and exempt them from the dispatch_action guidance in tools and directory modes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
prepare_pr details now carry next for Code Mode, so the workspace fixture validates the Gateway schema on the payload without it.
…ults and prompt directories
…ance into Code Mode values Tool result details stay equal to the Gateway protocol payload, which the gateway schema checks require. Code Mode's value projection now copies a string `next` from the result text, so github_publish guidance still reaches exec guest code.
Models do not call a tool that is missing from their tool list, so loading computer and github_publish only on a first call by name never happened. tool_describe and a refused dispatch_action now load the tool: the agent loop sends its definition with the next request in the same run, and the session pin keeps it on later turns. The session's next-turn step keeps tools a run loaded for itself, which also keeps a resolved deferred tool for the rest of the run.
A tool execution context that outlives its call must not keep the run's history or agent alive. Clear loadTool alongside pendingInput when updates close.
The embedded runner's continuation resends the session's tool list after each tool batch, which dropped an on-demand tool loaded mid-run, so the model could not call it until the next turn. The agent loop now keeps tools a run loaded for itself whenever a continuation or next-turn snapshot replaces the tool list. Resolved deferred tools keep their previous behavior.
3942f40 to
0a82b8c
Compare
…hem (openclaw#204805) Computer use and github_publish were sent with every request whenever Tool Search or Code Mode was on (about 13k characters per request), even in chats that never use them. - New catalogMode "on-demand": both tools start in the Tool Search / Code Mode catalog. Looking one up (tool_describe, or a refused dispatch_action) loads it for the rest of the run, and the session tool pin keeps it on later turns. /new, /reset, compaction and a model change defer it again. - The agent loop keeps tools a run loaded for itself when a continuation resends the session's tool list. - github_publish's description drops from about 6.1k to under 800 characters; each action's result carries the guidance it used to hold, in a `next` field. - Copilot, Codex, cloud workers and headless catalogs keep both tools direct.
…ir own exemption (#206801) With Tool Search on (the default), `agents_wait` and `subagents` are deferred, so the model can reach them only through `dispatch_action`. The tool repeat guard reads the `repeatable` declaration of the called tool, which is `dispatch_action`, not its target. A model that polls its children with the same `agents_wait` call gets a "stop repeating" note at call 3. At call 20 the turn ends with `tool_repeat_limit`, even though these tools exist to be polled. `isDirectVisibleCatalogTool` (the Tool Search owner of "which trusted tools stay in the provider tool list") now keeps OpenClaw tools that declare `repeatable` visible, unless they are on-demand. The model calls them by name, and the guard reads their own declaration. They stay searchable as before. - The guard, `dispatch_action` and the worker wire are unchanged. A dispatcher-side fix would need either a new `repeatable` shape in the worker tool protocol schema or a function that cannot cross the worker wire, so the visibility owner takes this. - Code Mode is unchanged. Its catalog also requires the tool in `directToolNames`, so guest scripts keep calling `agents_wait` as before. - On-demand tools (`computer`, `github_publish`) stay deferred. - Cost: `agents_wait` (638 B) and `subagents` (638 B) of tool schema join the tool list when those tools are enabled. That is +1,276 B, stable across turns. | Check | Tier | Base (`55f3ed64`) | Head | |---|---|---|---| | Tool Search `tools` and `directory` modes send `agents_wait` and `subagents`, and keep a plain tool deferred (`tool-search.repeatable.test.ts`) | vitest-source | **fails**: both deferred | passes | | 25 identical `agents_wait` polls through the real agent loop and guard | vitest-source | **fails**: the tool is not in the list; the only route is `dispatch_action` | passes: 25 run, no note, the turn ends normally | | Main's only route measured: 25 identical `agents_wait` calls through `dispatch_action` | vitest-source | note at call 3, 19 run, turn ends with `tool_repeat_limit` at call 20 | not the route any more | | A non-repeatable target repeated through `dispatch_action` still stops at call 20 with `tool_repeat_limit` | vitest-source | passes | passes | | Prompt-prefix stability, Tool Search on-demand/agent-loop/discovery/directory/catalog suites, system-prompt inventory and cache-prefix suites | vitest-source | | 13 files, 124 tests pass | A model that still routes a polling tool through `dispatch_action` is counted as `dispatch_action` calls. The tool is now in its tool list, so the dispatcher is not its route. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit afd8195) Release adaptation: Use an existing trusted OpenClaw catalog predicate to keep repeatable tools model-visible. Stable does not have on-demand catalog tooling, so omit that exclusion and retain the stable directory wording. Keep Code Mode, dispatch_action and the repeat guard unchanged. Follow-ups: No later pinned-main production changes touch this owner; #204805 is an upstream-only prerequisite for the omitted exclusion, not required by the stable predicate. Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: sallyom <[email protected]> (cherry picked from commit 3f00a51) Companion audit: #204847 participant-limit propagation, #205572 worker exec settings, #204805 deferred tools, #206762 tool-description perf, and #206537 prompt manifest redesign touch neighboring owners but are not prerequisites for stable worker spawn guidance. Release adaptation: Render the dedicated-worker hint only for worker placement; preserve stable local workflow text and keep both render sites on one delegation section binding, and let the worker hint suppress the duplicate full-surface messaging hint. Co-authored-by: RomneyDa <[email protected]>
Summary
High Level TLDR
With Tool Search or Code Mode on (the default for OpenClaw's own runtime and for most frontier models), two heavy tools were still sent on every model request whether or not the chat ever used them:
computer(desktop control) andgithub_publish. Together they were about 13k characters of tool definitions per request, and most ofgithub_publish's size was a long procedural manual in its description.This PR makes both tools load when the model looks them up, then stay direct: they start in the Tool Search / Code Mode catalog with a short entry. When the model describes one (or tries to reach it through
dispatch_action), the next request in the same turn carries its definition, so the model calls it as a normal direct tool, and the session keeps it for the rest of the conversation (across Gateway restarts). It also cutsgithub_publish's description from about 6.1k to under 800 characters and moves each procedure into the result of the action where the model needs it.User impact: a default unsandboxed session with Tool Search sends about 13k fewer characters (roughly 3.3k tokens) of tool definitions on every request until it actually uses one of these tools. Screenshots, the PR-preparation turn handoff and all Gateway checks behave as before.
Root Cause
shouldCatalogToolinsrc/agents/tool-search-catalog.tskeeps anycatalogMode: "direct-only"tool out of the catalog, so it is sent on every request in every catalog mode.computer(src/agents/tools/computer-tool.ts) is direct-only because catalog bridges serialize nested results as JSON and drop the screenshot image block. It is built whenever the model has vision and a computer transport exists, whether or not anything is paired.github_publish(src/agents/tools/github-publish-tool.ts) is direct-only on unsandboxed sessions and sandboxed sessions that adopt a managed workspace, becauseprepare_pr/publishwithworkspacePathyield the turn and a Code Modeexeccannot carry that handoff. That marking was added by feat: prepare existing PRs from ordinary chats #178756 ("feat: prepare existing PRs from ordinary chats"); this PR keeps its handoff requirement and only changes when the definition is sent. Publication availability is set on essentially every non-detached Gateway turn (attempt-gateway-tools.ts), so every unsandboxed agent paid for it.describeGitHubPublishToolwas a full manual (per-action workflows, requestId recovery, guest and maintainer eligibility, automations continuation, the re-review comment, landing policy): 6,129 of the tool's 7,161 definition characters.Both reasons for direct-only are about how a call runs (result shape, turn handoff), not about whether the definition must be sent before the tool is ever used.
What Changed
catalogMode: "on-demand"(generic; onlycomputerand the yieldinggithub_publishlisting use it in this PR):onDemanddescriptor fact; search, describe and directory entries carrycall: "loads as a top-level tool once looked up; call it by name, not through dispatch_action or exec", and directory rows are marked[loads on lookup].dispatch_actionand Code Mode guest calls never run it: they load it and refuse with a message saying it is now a top-level tool to call by name (ToolSearchRuntime.callEntry), so screenshot results and turn handoffs only ever run through a direct call.tool_describe(and a refuseddispatch_action) call the runner'scatalogRef.loadOnDemandTool, which hydrates the entry, adds it to the run's context through a new agent-coreloadToolhook on the tool execution context, so the next provider request in the same run sends it, and pins it for the session. A live test of the first version showed why this is needed: models do not call a tool that is missing from their tool list, so loading only on a call by name never fired.directorymode) also hydrates an on-demand entry when the model calls it by name intools,directoryand Code Mode. The call is a normal direct tool call.createSessionPrepareNextTurnWithContextreset the tool list to the session's tools on a run's first continuation, which dropped a tool loaded during the first tool batch. It now keeps tools the run loaded for itself (marked byappendRunContextTool). This also keeps a resolved deferred tool for the rest of the run instead of re-resolving it on every call.promoteSessionTool) and checkpointed with the existingopenclaw.system-prompttranscript entry. On the next attempt the restored pin's names mark those on-demand tools direct before compaction (promotedToolNames), folded into the existinginstallToolListingPincatalog rebuild. No new state store./new,/reset, compaction and a model change start a new prompt series, so the tool is deferred again until its next use. Compaction was chosen as a reset point because it already rebuilds the provider cache and is where context is reclaimed.loadsOnDemandTools. Copilot, Codex app-server, cloud workers and headless catalogs cannot load a tool on its first direct call, so they keep on-demand tools direct exactly as today (Codex and Copilot catalogs treaton-demandlikedirect-only; the worker wire format maps it todirect-only). The flag is not part of the public plugin SDK parameters.github_publishdescription: a short summary plus one line per offered action (793 chars unsandboxed, 572 without publication, 252 observation-only). The moved guidance now arrives in anextfield of each action's result (github-publish-guidance.ts), in both the text anddetails, because Code Mode guests receive onlydetails; the Gateway payload's own fields are unchanged:headCommitasexpectedHeadCommitwith the observed title/body, keep attribution and footer; edit write: read again after an uncertain response;@clawsweeper re-reviewwas posted, read comments before retrying;Eligibility, write access and the busy refusals stay enforced and explained by the Gateway's existing checks and messages; nothing the Gateway enforces changed.
Scope Boundary
openclaw(security),sessions_yield,view_image,structured_output,session_projectand the delegate tool staydirect-only.messagetool schema work is a separate change and is not touched here.Before / After
Real core tool construction (
createOpenClawCodingToolswith GitHub publication available, vision model) plus the real embedded surface runtime (createAgentHarnessToolSurfaceRuntimeCore(...).compactTools), default unsandboxed session, no plugins, isolated temp state dir. Sizes are JSON characters of{ name, description, parameters }of the provider-visible tools; tokens are chars / 4. Same script and environment on both revisions; sizes were identical across 5 samples per arm.328a438toolsmode, always-sent tool charsgithub_publishdefinition charsgithub_publishdescription, unsandboxed / no publication / observation-onlycomputerdefinition charsThe compaction step costs about 0.05 ms more per attempt because the catalog now holds two more large schemas. It runs once per attempt preparation; it is not whole-turn latency.
Prompt cache: the provider tool list changes once, on the request right after the lookup (same turn), by appending the definition after the existing tools; the session pin carries the same order into later turns, so the list then stays byte-identical for the rest of the series. Anthropic
defer_loadingtool references were not used: OpenClaw's Anthropic transport has no support for them, and adding it is a provider-transport feature beyond this change.Measurement commands and environment
Linux x64, Node v24.22.1, one host, no Gateway,
OPENCLAW_STATE_DIRforced to a fresh temp directory by the script.Verification
Regression tests (each fails on origin/main behavior; checked by reverting both tools to
direct-onlyand by disabling the restore step):src/agents/tool-search.on-demand.test.ts: intools,directoryand Code Mode, a default run's direct surface excludescomputerandgithub_publishand the catalog holds both; a promoted tool is direct and out of the catalog; a runner without the opt-in and a headless catalog keep them direct;tool_searchshows the call hint;dispatch_actionand Code Mode guest calls refuse; thetoolsanddirectoryprompt directories mark on-demand rows[call directly]and exempt them from thedispatch_actionrule, and the Code Mode index marks them[top-level call only; not from exec].attempt-deferred-tool-resolver.test.ts: through the real agent loop, in Tool Searchtoolsmode and Code Mode, a direct call by name loads the deferred tool, the screenshot image block survives in the tool result, and promotion is recorded.attempt-session-runtime-prepare.on-demand.test.ts(shares its SQLite session fixture with the existing history-boundary test throughattempt-session-runtime-prepare.test-support.ts): real SQLite-backed session manager plus real tool construction, catalog and attempt preparation, both Tool Search and Code Mode. Turn 1 does not sendgithub_publish; after its first direct call it is sent on the next turn and after another restart, and compaction (Tool Search case) or/reset(Code Mode case) defers it again. The transport receives its name as a deferred tool, and 11 consecutive calls to it before its definition is sent pass the stream's unknown-tool guard (threshold 10) instead of being rewritten into a refusal on the 11th.github-publish-tool.handoff.test.ts: theprepare_pr/workspacePathturn handoff runs through the promoted direct tool in Code Mode.github-publish-tool.test.ts: description length bounds, and the old description's key guidance (requestId retention and no resubmission, read before edit, re-review wording, landing rules) arrives in the matching action results, with text anddetailscarrying the samenextand the Gateway payload's fields intact.code-mode.github-publish.test.ts: the realgithub_publishtool (managed-worktree sandbox) called from Code Mode guest code returns the receipt with itsrequestIdand the publishnextguidance in the guest value.src/gateway/github-pr-workspace-preparation.test-support.ts: theprepare_prresult still matches the Gateway result schema oncenextis set aside.tool-search.on-demand.test.ts(load on lookup):tool_describeand a refuseddispatch_actioncall the runner's loader and the refusal names the direct call;tool_searchalone does not load.agent-session-loop-next-turn.test.ts: through a real session, a tool loaded during the first tool batch is sent with the next request. It fails on the old next-turn step and on an agent loop without theloadToolhook.Test-line budget: +449 net test lines against the 400 allowance, with a 49-line record in
config/test-lines-allocations/204805-on-demand-tool-loading.txt. Before the allocation the suite was consolidated: table-driven Tool Search / directory / Code Mode / no-opt-in cases, one SQLite session fixture shared with the existing history-boundary test, one table ofgithub_publishresult guidance, reset coverage folded into the SQLite restart test instead of a separate prompt-state case, and a droppedsession-tool-listingcase that duplicated it. The remaining 27 lines are the three review regressions (11-call stream guard, real-tool Code Mode guidance, prompt-directory marker); cutting them would remove coverage for those fixes.pnpm check:baseline-ratchetspasses.Broader runs: 168 affected test files (Tool Search, Code Mode, prompt state, attempt preparation and streaming, system prompt, computer, github_publish and PR workspace preparation, registration, Copilot tool bridge, Codex dynamic tools, worker computer surfaces): 167 files passed. The one failing file,
src/agents/system-prompt-params.test.ts, fails three repository-discovery cases only because this host's test temp directory sits inside an unrelated git checkout, so "no repository" discovery finds that checkout; this PR does not touch that code.pnpm check:changedpassed with the dead-export scan skipped; that scan fails identically on origin/main on unused exports inextensions/beam, which this PR does not touch.Review:
$autoreview(Codex, branch mode against origin/main, P0–P1): scoped-clean, no findings, on the first version. The load-on-lookup follow-up (fix: load on-demand tools when the model looks them up) was self-reviewed;pnpm check:changedpassed on it (dead-export scan skipped for the same unrelatedextensions/beamfailure), and the 48 affected test files (808 tests) pass.Real behavior proof
Live run on a real Gateway (this PR applied to current main, Tool Search
toolsmode, Opus 5.5 on the direct Anthropic API route, fresh session): asked to inspect this PR read-only with the GitHub tool, the model calledtool_describeforgithub_publish, received the short description withcall: "loads as a top-level tool once looked up; ...", then calledgithub_publishdirectly in the next request of the same run ({action: "inspect_pr", pullRequestUrl: ...}). The Gateway returned the PR's state, author, base and head (head commit matched this branch) plusnext: "This read binds nothing and grants no later authority.", and the model answered correctly. Nothing was written to GitHub.Two earlier live runs found the two gaps this PR now closes: the first version loaded the tool only on a call by name, which models do not make for an undeclared tool (the model ran
tool_describe, trieddispatch_action, was refused, and gave up); the second loaded it on lookup, but the embedded runner's continuation resent the session's tool list and dropped it until the next turn.fix: load on-demand tools when the model looks them upandfix: keep a looked-up tool for the rest of the runfix those, each with a regression test that fails on the previous code.Upgrade: the same Gateway was updated in place from v2026.11.9 (and from earlier revisions of this PR) to current main with this PR. Existing sessions kept working after the restart; sessions pinned before the change keep both tools direct until their next reset, so their provider tool list does not change on upgrade.
The closest feasible path without a live Gateway or model: the real attempt preparation with a real SQLite session transcript (
attempt-session-runtime-prepare.on-demand.test.ts), and the real agent loop with the real deferred-tool resolver (attempt-deferred-tool-resolver.test.ts), shown above. Sizes come from the real tool factories and the real surface runtime.What was not tested
toolsmode, the model rantool_describeforgithub_publish, would not call the undeclared tool by name, trieddispatch_action, was refused, and gave up. That is the gap the load-on-lookup follow-up closes. A live retest of the final version passed (see Real behavior proof).