Repository navigation
fix(agents): large tool results lose their last lines and cannot be recovered - #206880
Merged
Merged
Conversation
…ecovered Bound every executed tool result once, before its first send: keep head and tail, put the notice at the cut, and spill the full text to an owner-only file the model can page with read. Delete the "rerun with narrower args" notice and the keyword heuristic that decided whether the tail survived. Co-authored-by: Ayaan Zaidi <[email protected]>
Contributor
|
🦞👀 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. |
Reserve the notice for the largest count it can show, so head and tail never overflow the budget and fall back to a head-only cut. Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Gate head and tail on the caller's minimum again, and drop a generated declaration config that a killed build left in the tree. Co-authored-by: Ayaan Zaidi <[email protected]>
Collaborator
Author
|
Rejected review findings:
|
Collaborator
Author
|
Maintainer override: |
obviyus
added a commit
that referenced
this pull request
Nov 27, 2026
…under workspace-only read (#206972) ## What Problem This Solves #206880 saves the full output of a large tool result to a private file and tells the model `Full output: <path> (page it with read offset/limit)`. exec and web_fetch already did the same for their own output. In host sessions with workspace-only file access (`tools.fs.workspaceOnly`, or guarded/read-only permission modes), `read` refuses that path: the file sits in the OS temp directory, outside the workspace. The model is told where the omitted output is but cannot open it, and falls back to rerunning the tool. Review of #206880 flagged this in both rounds. The owner approved this follow-up with a fixed scope: `read` may open the session's own spill files, and nothing broader. ## Fix The private spill writer (`sessions/tools/private-temp-file.ts`) owns the allowlist: - `writePrivateTempFile` and `openPrivateTempFileStream` take an optional `owner` (`{ agentId, sessionKey }`). After the exclusive create, the writer records the file's realpath under that owner. Registration happens only there. A path taken from a tool result (`details.spill.path`, `fullOutputPath`) is never trusted, so a plugin cannot name an arbitrary file. - `resolveOwnSpillFile(owner, path)` admits a path only when its realpath was recorded for that same owner, and it is a regular file owned by this uid. - The list is process memory with caps: newest 64 paths per owner, 256 owners. A restart or eviction makes old paths unreadable again, and `read` then refuses them visibly. The owner is computed once per embedded attempt, with the same expression tool construction already uses for its session key. The same value goes to the #206880 bound step, exec's output file, web_fetch's spill, and the `read` guard. web_fetch's result cache is scoped by owner, so a cached result never points one session at another session's file. The `read` guard (`wrapToolWorkspaceRootGuardWithOptions`) gets `ownFile`. On an admitted path it skips only the root-containment check, and every other read step still runs. Only `read` receives it; `ls`, `write`, `edit` and `apply_patch` keep the plain workspace guard. Sandboxed sessions are unchanged: their spills are already staged inside the workspace. Two existing helpers moved verbatim into sibling modules so the touched files stay under their line caps: `assertSandboxPathWithinAnyRoot` → `agent-tools.workspace-roots.ts`, `sanitizeWebFetchUrl` → `web-fetch-utils.ts`. One exec auto-review state block moved to `bash-tools.exec-auto-review-state.ts`. Accepted edge cases (named, not coded): - After a restart or cap eviction, older spill paths are refused again. - A subagent cannot read its parent's spill files. - A same-uid local process could swap the file between the check and the open. It can already read everything. ## User impact - Gateway and one-shot users on the embedded runtime with workspace-only file access can now page the full output that a large tool result points to, instead of rerunning the tool. - No new config, no schema change, no new retention rule. The spill location and lifetime stay those of #206880: the OS temp directory, 0600, OS cleanup. ## Evidence End to end, through `openclaw agent --local` on a cheap OpenAI model, in an isolated state dir and HOME, with `tools.fs.workspaceOnly: true`. The model runs `head -c 4000000 /dev/urandom | base64 -b 76 | head -n 50000` (random lines, so line 30000 cannot be guessed) and is asked for line 30000: - Merge base `59e5c7309581`: the 64 KB exec result keeps head and tail and names the full-output file. `read` on that file fails with `Path escapes sandbox root (<workspace>): <tmp>/openclaw-exec-<id>.log`, and the model replies UNKNOWN. - This PR: the same `read` (offset 30000, limit 3) succeeds. The reply equals line 30000 of the spill file on disk. `src/agents/sessions/tools/private-temp-file.test.ts`, through the production `createCoreCodingTools` workspace-only `read`: - A session reads its own spill outside the workspace with offset/limit. Without an owner record, the same production `read` refuses the path with the workspace-containment error (the "fresh owner" and "plugin path" cases below), which is what main does for every spill path. - Denied: - a file at a plugin-chosen path; - an unissued file with a spill-like name; - another session's spill (same agent); - the same session key under another agent; - a fresh owner; - an admitted path replaced by a symlink or a directory; - a neighbour file reached through an alias; - `write`, `edit`, `ls` and `apply_patch` on an admitted spill; - a missing file, and a file owned by another uid. - Allowed: `..` and `/private/var` aliases of exactly the issued file. - Caps: the newest 64 paths per owner and 256 owners are kept. Also: exec and web_fetch register their own files (`bash-tools.exec-approval-output.test.ts`, `web-fetch.provider-fallback.test.ts`), and the attempt's bound step passes the owner (`attempt-context-guards.test.ts`). The design was reviewed adversarially before coding; the rejected alternatives were session-tagged file names (they admit a name pattern) and a per-session directory root (it admits any file in the directory). Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus
added a commit
that referenced
this pull request
Nov 27, 2026
…spill shape (#206984) ## What Problem This Solves A tool result can point to a file holding its full output. Two shapes record that pointer: - web_fetch and the record-time bound (#206880) use `details.spill { path, chars?, truncated? }`; - exec uses flat `details.fullOutputPath` plus `details.spillTruncated`. So every reader handles both shapes: - `getToolResultSpillDetails` (history elision and the bound's producer-spill reuse) falls back to the flat fields. It also reads a `spilledChars` field that nothing writes. - The persisted-details allowlists keep both shapes (6 extra keys). - The tokenjuice plugin checks exec's flat field to leave spilled results alone. ## Fix Exec records `details.spill { path, truncated? }`, the one shape. Exec has bytes, not chars, so it does not set `chars`. The flat fields and every reader of them are removed: - the flat fallback, and the never-written `spilledChars`, in `getToolResultSpillDetails`; - `fullOutputPath`, `spilledChars` and `spillTruncated` in both persistence allowlists; - tokenjuice now checks `details.spill`. Accepted edge case: no migration. Exec results recorded before this change keep their text footer (`Full output: <path>`), but history elision no longer finds their pointer in `details`. The owner approved this. Spill files live in the OS temp directory anyway, so old pointers rarely outlive the session. Not touched: `fullOutputPath` on the session `BashResult`/`BashToolDetails` types and the agent-core bash-execution message. Those are a different, extension-facing contract, and exec never writes them. ## User impact None visible. The exec result text is unchanged. Model-visible behavior is the same: elision and the bound reuse exec's file as before, through the shared shape. ## Evidence - `session-tool-result-guard.test.ts`: an exec output file cut at its limit records `spill: { path, truncated: true }`. - `tool-result-truncation.test.ts`: history elision with an exec-shaped spill keeps its pointer. - `runtime.integration.test.ts` (tokenjuice): a spilled exec result is left to the host. - `tool-result-bounds.test.ts` (owner, unchanged) and `session-tool-result-guard.tool-result-persist-hook.test.ts` (fallback keeps `spill`) still pass. - `bash-tools.exec-approval-output.test.ts`: a real exec spill path, read through workspace-only `read` (#206972), comes from `details.spill.path`. Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot
pushed a commit
that referenced
this pull request
Nov 28, 2026
…ecovered (#206880) ## What Problem This Solves When a tool returns more text than its context budget, OpenClaw keeps only the start, discards the rest, and tells the model to "rerun with narrower args". The end of the output, where commands print errors, totals and exit status, is lost unless a keyword list happens to match it. MCP and plugin tools have no other copy, so the model cannot get the cut text back. Production signal (a production deployment, 2.76 days of Gateway logs): - 102 `[tool-result-truncation] Truncated N tool result(s) for prompt history (maxChars=64000 …)` lines, up to 96 results in one session. - 310 context-overflow diagnostics in the same window, driven by long sessions full of tool output. Reproduced on main (`ab296c23d2c4`) through the real record path (`guardSessionManager`, 200k-token window). The fixture is a 180,015-character plain log, the same for exec, read, web_fetch, an MCP result and a plugin result: | | main | this PR | |---|---|---| | Characters the model sees | 63,973 | 63,961 | | Last line kept | no | yes | | Full output recoverable | no (dropped) | yes, 180,015 chars in a file | | Notice | `[... 116116 more characters truncated; rerun with narrower args if needed]` | `[... 116221 chars omitted. Full output: <path> (page it with read offset/limit)]` | ## Fix The bound has one owner, at record time: - `boundToolResult` (`src/agents/embedded-agent-runner/tool-result-bound.ts`) runs once at the end of `afterToolCall` (`run/attempt-setup.ts`), after tool-result hooks and before the result is first sent. It applies to every executed tool: core, MCP and plugin. - It keeps the head and the tail and puts the notice at the cut. The full text goes to an owner-only file through the existing `writePrivateTempFile` (tmpdir, 0600; staged in the workspace for sandboxed sessions), the same rule as `exec` and `web_fetch` output files. A tool that already saved its own file (`exec`, `web_fetch`) keeps that file, and the notice names it. - The budget comes from the transcript guard's registry, so the existing synchronous cap leaves a bounded result byte for byte. Prefix stability holds, because a recorded result never changes after it is recorded. - If the file write fails, the result passes on unchanged, and the existing transcript cap bounds it with head, tail and the character count. Deleted: - `context-truncation-notice.ts`: the "rerun with narrower args" notice and its `sessions_send` variant. - `hasImportantTail`, a keyword regex that decided whether the tail survived, and the head-only branch it guarded. Head+tail is now unconditional for any window over 4,000 characters. Smaller windows keep a whole prefix, so short records are not split. Fixed on the way (exposed by the shorter notice): - The aggregate planner sized notices with a count of 1, so a notice carrying a real count could be cut. That dropped the spill path from a disclosed `Full output:` pointer. It now sizes the notice for the largest count it can show. - A multi-block result made only of short records keeps whole leading records with one notice (#201795) instead of cutting every record. ## User impact - Gateway and one-shot (`agent --local`) users on the embedded runtime. Both run `installEmbeddedAttemptContextGuards` (`src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:515`). - A large tool result keeps its last lines (errors, totals, exit status), and the model can read the omitted middle from the named file instead of rerunning the tool. - No config change. Results within budget are unchanged. - Not covered: the Codex app-server and Claude CLI runtimes, which do not run this loop. ## Evidence - `src/agents/tool-result-bounds.test.ts`: one case per tool family through the real guard registry: - exec (`buildExecForegroundResult`), MCP (`projectMcpCallToolResult`) and plugin: head, tail, spill file with the full text, and the recorded bytes equal to the bound bytes (fixed point); - web_fetch reuses its own spill file; - read reaches the middle of a 180k one-line spill page by page, and no page needs a second spill; - a failed spill write falls back to head, tail and the count, with no path. - `run/attempt-context-guards.test.ts`: the installed `afterToolCall` bounds the result an earlier hook returned and restores the previous hook on removal. - Touched suites pass (8 files), and `agent-tools.prefix-stability` passes. All core test typecheck shards pass. - The prompt-cache prefix-stability journeys fail the same way on the merge base `ab296c23d2c4`, so these failures are not from this change: - They expect a summary marker ("compacted into the following summary") that #205584 replaced. - Google also counts 2 compactions in its overflow run where the test expects 1 (`expected 2 to be 1`, reproduced on the base). - The breaks they report are the allowed compactions; no tool-result bytes change after they are recorded. - On main, the same contract test fails 5 of 5 families (63,973 of 180,015 characters kept, tail lost, no file). - **End to end, real model.** Isolated `openclaw agent --local` (scratch HOME, state and config), `openai/gpt-5.4-mini` on the embedded runtime. The agent runs `seq 1 60000 | sed 's/$/ padding padding padding/'` through `exec`, calls no other tool, and replies with the last line of the output: - main `ab296c23d2c4`: `UNKNOWN` (the recorded result kept only the head of exec's retained window); - this PR: `60000 padding padding padding`. The notice points at exec's own output file; no second file is written. - Review fixes, each with a test that is red on the earlier head: - a notice that gains a digit no longer pushes head+tail over the cap; - the separator newlines are reserved at the caller's weight (the context guard counts 2 per char), so a dense single-line result keeps its tail. - Workspace-only host sessions cannot open tmpdir paths with `read`; exec and web_fetch spill paths are in the same position on main. Letting `read` open this session's own spill paths is the follow-up PR. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 5c3c123)
github-actions Bot
pushed a commit
to Desicool/openclaw
that referenced
this pull request
Nov 28, 2026
…ecovered (openclaw#206880) ## What Problem This Solves When a tool returns more text than its context budget, OpenClaw keeps only the start, discards the rest, and tells the model to "rerun with narrower args". The end of the output, where commands print errors, totals and exit status, is lost unless a keyword list happens to match it. MCP and plugin tools have no other copy, so the model cannot get the cut text back. Production signal (a production deployment, 2.76 days of Gateway logs): - 102 `[tool-result-truncation] Truncated N tool result(s) for prompt history (maxChars=64000 …)` lines, up to 96 results in one session. - 310 context-overflow diagnostics in the same window, driven by long sessions full of tool output. Reproduced on main (`856cbaecaad8`) through the real record path (`guardSessionManager`, 200k-token window). The fixture is a 180,015-character plain log, the same for exec, read, web_fetch, an MCP result and a plugin result: | | main | this PR | |---|---|---| | Characters the model sees | 63,973 | 63,961 | | Last line kept | no | yes | | Full output recoverable | no (dropped) | yes, 180,015 chars in a file | | Notice | `[... 116116 more characters truncated; rerun with narrower args if needed]` | `[... 116221 chars omitted. Full output: <path> (page it with read offset/limit)]` | ## Fix The bound has one owner, at record time: - `boundToolResult` (`src/agents/embedded-agent-runner/tool-result-bound.ts`) runs once at the end of `afterToolCall` (`run/attempt-setup.ts`), after tool-result hooks and before the result is first sent. It applies to every executed tool: core, MCP and plugin. - It keeps the head and the tail and puts the notice at the cut. The full text goes to an owner-only file through the existing `writePrivateTempFile` (tmpdir, 0600; staged in the workspace for sandboxed sessions), the same rule as `exec` and `web_fetch` output files. A tool that already saved its own file (`exec`, `web_fetch`) keeps that file, and the notice names it. - The budget comes from the transcript guard's registry, so the existing synchronous cap leaves a bounded result byte for byte. Prefix stability holds, because a recorded result never changes after it is recorded. - If the file write fails, the result passes on unchanged, and the existing transcript cap bounds it with head, tail and the character count. Deleted: - `context-truncation-notice.ts`: the "rerun with narrower args" notice and its `sessions_send` variant. - `hasImportantTail`, a keyword regex that decided whether the tail survived, and the head-only branch it guarded. Head+tail is now unconditional for any window over 4,000 characters. Smaller windows keep a whole prefix, so short records are not split. Fixed on the way (exposed by the shorter notice): - The aggregate planner sized notices with a count of 1, so a notice carrying a real count could be cut. That dropped the spill path from a disclosed `Full output:` pointer. It now sizes the notice for the largest count it can show. - A multi-block result made only of short records keeps whole leading records with one notice (openclaw#201795) instead of cutting every record. ## User impact - Gateway and one-shot (`agent --local`) users on the embedded runtime. Both run `installEmbeddedAttemptContextGuards` (`src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:515`). - A large tool result keeps its last lines (errors, totals, exit status), and the model can read the omitted middle from the named file instead of rerunning the tool. - No config change. Results within budget are unchanged. - Not covered: the Codex app-server and Claude CLI runtimes, which do not run this loop. ## Evidence - `src/agents/tool-result-bounds.test.ts`: one case per tool family through the real guard registry: - exec (`buildExecForegroundResult`), MCP (`projectMcpCallToolResult`) and plugin: head, tail, spill file with the full text, and the recorded bytes equal to the bound bytes (fixed point); - web_fetch reuses its own spill file; - read reaches the middle of a 180k one-line spill page by page, and no page needs a second spill; - a failed spill write falls back to head, tail and the count, with no path. - `run/attempt-context-guards.test.ts`: the installed `afterToolCall` bounds the result an earlier hook returned and restores the previous hook on removal. - Touched suites pass (8 files), and `agent-tools.prefix-stability` passes. All core test typecheck shards pass. - The prompt-cache prefix-stability journeys fail the same way on the merge base `856cbaecaad8`, so these failures are not from this change: - They expect a summary marker ("compacted into the following summary") that openclaw#205584 replaced. - Google also counts 2 compactions in its overflow run where the test expects 1 (`expected 2 to be 1`, reproduced on the base). - The breaks they report are the allowed compactions; no tool-result bytes change after they are recorded. - On main, the same contract test fails 5 of 5 families (63,973 of 180,015 characters kept, tail lost, no file). - **End to end, real model.** Isolated `openclaw agent --local` (scratch HOME, state and config), `openai/gpt-5.4-mini` on the embedded runtime. The agent runs `seq 1 60000 | sed 's/$/ padding padding padding/'` through `exec`, calls no other tool, and replies with the last line of the output: - main `856cbaecaad8`: `UNKNOWN` (the recorded result kept only the head of exec's retained window); - this PR: `60000 padding padding padding`. The notice points at exec's own output file; no second file is written. - Review fixes, each with a test that is red on the earlier head: - a notice that gains a digit no longer pushes head+tail over the cap; - the separator newlines are reserved at the caller's weight (the context guard counts 2 per char), so a dense single-line result keeps its tail. - Workspace-only host sessions cannot open tmpdir paths with `read`; exec and web_fetch spill paths are in the same position on main. Letting `read` open this session's own spill paths is the follow-up PR. Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot
pushed a commit
to Desicool/openclaw
that referenced
this pull request
Nov 28, 2026
…under workspace-only read (openclaw#206972) ## What Problem This Solves openclaw#206880 saves the full output of a large tool result to a private file and tells the model `Full output: <path> (page it with read offset/limit)`. exec and web_fetch already did the same for their own output. In host sessions with workspace-only file access (`tools.fs.workspaceOnly`, or guarded/read-only permission modes), `read` refuses that path: the file sits in the OS temp directory, outside the workspace. The model is told where the omitted output is but cannot open it, and falls back to rerunning the tool. Review of openclaw#206880 flagged this in both rounds. The owner approved this follow-up with a fixed scope: `read` may open the session's own spill files, and nothing broader. ## Fix The private spill writer (`sessions/tools/private-temp-file.ts`) owns the allowlist: - `writePrivateTempFile` and `openPrivateTempFileStream` take an optional `owner` (`{ agentId, sessionKey }`). After the exclusive create, the writer records the file's realpath under that owner. Registration happens only there. A path taken from a tool result (`details.spill.path`, `fullOutputPath`) is never trusted, so a plugin cannot name an arbitrary file. - `resolveOwnSpillFile(owner, path)` admits a path only when its realpath was recorded for that same owner, and it is a regular file owned by this uid. - The list is process memory with caps: newest 64 paths per owner, 256 owners. A restart or eviction makes old paths unreadable again, and `read` then refuses them visibly. The owner is computed once per embedded attempt, with the same expression tool construction already uses for its session key. The same value goes to the openclaw#206880 bound step, exec's output file, web_fetch's spill, and the `read` guard. web_fetch's result cache is scoped by owner, so a cached result never points one session at another session's file. The `read` guard (`wrapToolWorkspaceRootGuardWithOptions`) gets `ownFile`. On an admitted path it skips only the root-containment check, and every other read step still runs. Only `read` receives it; `ls`, `write`, `edit` and `apply_patch` keep the plain workspace guard. Sandboxed sessions are unchanged: their spills are already staged inside the workspace. Two existing helpers moved verbatim into sibling modules so the touched files stay under their line caps: `assertSandboxPathWithinAnyRoot` → `agent-tools.workspace-roots.ts`, `sanitizeWebFetchUrl` → `web-fetch-utils.ts`. One exec auto-review state block moved to `bash-tools.exec-auto-review-state.ts`. Accepted edge cases (named, not coded): - After a restart or cap eviction, older spill paths are refused again. - A subagent cannot read its parent's spill files. - A same-uid local process could swap the file between the check and the open. It can already read everything. ## User impact - Gateway and one-shot users on the embedded runtime with workspace-only file access can now page the full output that a large tool result points to, instead of rerunning the tool. - No new config, no schema change, no new retention rule. The spill location and lifetime stay those of openclaw#206880: the OS temp directory, 0600, OS cleanup. ## Evidence End to end, through `openclaw agent --local` on a cheap OpenAI model, in an isolated state dir and HOME, with `tools.fs.workspaceOnly: true`. The model runs `head -c 4000000 /dev/urandom | base64 -b 76 | head -n 50000` (random lines, so line 30000 cannot be guessed) and is asked for line 30000: - Merge base `8744e6101f66`: the 64 KB exec result keeps head and tail and names the full-output file. `read` on that file fails with `Path escapes sandbox root (<workspace>): <tmp>/openclaw-exec-<id>.log`, and the model replies UNKNOWN. - This PR: the same `read` (offset 30000, limit 3) succeeds. The reply equals line 30000 of the spill file on disk. `src/agents/sessions/tools/private-temp-file.test.ts`, through the production `createCoreCodingTools` workspace-only `read`: - A session reads its own spill outside the workspace with offset/limit. Without an owner record, the same production `read` refuses the path with the workspace-containment error (the "fresh owner" and "plugin path" cases below), which is what main does for every spill path. - Denied: - a file at a plugin-chosen path; - an unissued file with a spill-like name; - another session's spill (same agent); - the same session key under another agent; - a fresh owner; - an admitted path replaced by a symlink or a directory; - a neighbour file reached through an alias; - `write`, `edit`, `ls` and `apply_patch` on an admitted spill; - a missing file, and a file owned by another uid. - Allowed: `..` and `/private/var` aliases of exactly the issued file. - Caps: the newest 64 paths per owner and 256 owners are kept. Also: exec and web_fetch register their own files (`bash-tools.exec-approval-output.test.ts`, `web-fetch.provider-fallback.test.ts`), and the attempt's bound step passes the owner (`attempt-context-guards.test.ts`). The design was reviewed adversarially before coding; the rejected alternatives were session-tagged file names (they admit a name pattern) and a per-session directory root (it admits any file in the directory). Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot
pushed a commit
to Desicool/openclaw
that referenced
this pull request
Nov 28, 2026
…spill shape (openclaw#206984) ## What Problem This Solves A tool result can point to a file holding its full output. Two shapes record that pointer: - web_fetch and the record-time bound (openclaw#206880) use `details.spill { path, chars?, truncated? }`; - exec uses flat `details.fullOutputPath` plus `details.spillTruncated`. So every reader handles both shapes: - `getToolResultSpillDetails` (history elision and the bound's producer-spill reuse) falls back to the flat fields. It also reads a `spilledChars` field that nothing writes. - The persisted-details allowlists keep both shapes (6 extra keys). - The tokenjuice plugin checks exec's flat field to leave spilled results alone. ## Fix Exec records `details.spill { path, truncated? }`, the one shape. Exec has bytes, not chars, so it does not set `chars`. The flat fields and every reader of them are removed: - the flat fallback, and the never-written `spilledChars`, in `getToolResultSpillDetails`; - `fullOutputPath`, `spilledChars` and `spillTruncated` in both persistence allowlists; - tokenjuice now checks `details.spill`. Accepted edge case: no migration. Exec results recorded before this change keep their text footer (`Full output: <path>`), but history elision no longer finds their pointer in `details`. The owner approved this. Spill files live in the OS temp directory anyway, so old pointers rarely outlive the session. Not touched: `fullOutputPath` on the session `BashResult`/`BashToolDetails` types and the agent-core bash-execution message. Those are a different, extension-facing contract, and exec never writes them. ## User impact None visible. The exec result text is unchanged. Model-visible behavior is the same: elision and the bound reuse exec's file as before, through the shared shape. ## Evidence - `session-tool-result-guard.test.ts`: an exec output file cut at its limit records `spill: { path, truncated: true }`. - `tool-result-truncation.test.ts`: history elision with an exec-shaped spill keeps its pointer. - `runtime.integration.test.ts` (tokenjuice): a spilled exec result is left to the host. - `tool-result-bounds.test.ts` (owner, unchanged) and `session-tool-result-guard.tool-result-persist-hook.test.ts` (fallback keeps `spill`) still pass. - `bash-tools.exec-approval-output.test.ts`: a real exec spill path, read through workspace-only `read` (openclaw#206972), comes from `details.spill.path`. Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus
added a commit
that referenced
this pull request
Nov 28, 2026
…wrapper intact (#207101) ## Problem A tool result that is too big for the model is cut differently on each route, and on two of them the cut is unsafe or loses data: - **Codex app-server dynamic tools** kept a prefix only and appended "rerun with narrower args". When the result was untrusted network content, the cut removed the wrapper's end marker, so the rest of the turn ran with an open untrusted-content region. Production (one team deployment, 7 days): 719 cut results in 102 sessions, **292 of them with the wrapper left open** (`github_read` 227, code-mode `exec` 59, `sessions_history` 7, `wait` 1). - **Agents API** cut a prefix with no notice and no file. - **Copilot** forwarded results with no bound at all (no production Copilot sessions in the window; found by reading the code). - **Embedded** (#206880) bounded at the per-result cap, which is looser than the context guard's budget below 32k-token windows and with images. The guard then cut again with no file path. ## Solution One bound, `boundToolResult`, for every route that executes OpenClaw tools: - **Budget:** the strictest one the result meets later: the per-result cap, then the context guard's weighted share with images and other blocks reserved first. A bounded result is a fixed point of both the transcript cap and the context guard, so the saved-file path survives. Unknown window: the 16k default. - **Cut:** head and tail (the existing truncator); the full text goes to an owner-only file (`writePrivateTempFile`). The notice is harness-neutral: `[... N chars omitted. Full output: <path>]`. A route whose model cannot open a Gateway file gets the same cut with a size-only notice: the Codex app-server (its native file tools run under its own sandbox policy, local or remote) and the Agents API (file tools run in the hosted VM). A path is named only where OpenClaw's own `read` opens it (embedded, Copilot). If the budget cannot hold the whole path, the notice names the size only. - **Untrusted content fails closed, per frame:** a frame is one `wrapExternalContent` region (warning, start marker and metadata header, body, end marker with the same id), found inside any text block, raw or JSON-escaped, so several wrapped values in one JSON block (`web_search`) count one by one (`findExternalContentFrames`, next to the writer). Frames and the text between them are kept whole, in order, while they fit; the first piece that does not fit keeps its ends and loses only body (head and tail); everything after it is left out. One trusted notice, `[... N chars omitted. Full output: <path>]`, follows the cut outside every frame, with the true count. A frame whose ends cannot fit (forged or hostile metadata, an image taking a small window's share) is left out whole: untrusted text never reaches the model outside a frame. When images alone exceed the context share, the bound reserves what the embedded context guard will keep (the images that fit plus its image-omission notice, one shared formatter), so the guard drops images without cutting the framed text again. Results with no frames keep the head-and-tail cut. - **Where:** `runAgentHarnessToolInvocation` after result middleware (Codex dynamic tools, Agents API); the Copilot bridge calls it directly (`boundAgentHarnessToolResult`, private harness SDK subpath); embedded keeps its `afterToolCall` call site. Copilot registers the file to the run's owner (the sandbox workspace for sandboxed runs), so its own `read` can open it. Codex `skills_read` stays whole-or-error: its check now uses the same budget as the bound, so a skill that passes is never cut later (an attempt budget smaller than the model window used to let a 12k skill pass and then be cut while reported as a success). Deleted: the Codex prefix-only cut and its "rerun" notice, the Agents API silent prefix cut. **Agents API serialization:** the adapter joins the bounded blocks with newlines and a 54-char placeholder per image into one function-output string, then applies its own cap. The bound reserves exactly what that serialization adds (`resultBound.reservedChars`, computed from the adapter's one `serializeFunctionOutput`), so the single cut leaves room for it and the adapter's cap never cuts a bounded result. The bound never adds a block (its notice goes into a text block it keeps; it only removes others), so the reserve computed before the cut covers the output. One cut, so the omitted count in the notice is true. Not in this PR: Tool Search's whole-result omission (3 unrecoverable omissions in 7 days in production) stays. Removing it is safe only where the model can read the saved file; on Codex and Agents API a partial page would show a continuation cursor with no way to read the omitted records. It returns once those routes can read the file. ## Security boundary This changes how untrusted content is cut on every route. Before: the Codex route dropped end markers (292 open wrappers in 7 days), and on the other routes several frames in one result could lose markers or leave untrusted text outside a frame. After: every frame the finder matches is either whole, or cut in its body with both ends kept, or left out; the omission notice is ours and sits outside every frame. Residuals, named, not fixed here: - A forged frame (raw tool output that copies the marker format) whose metadata is oversized is left out whole, and so is everything after it. Accepted: fail closed is the rule, and the saved file (where the reader can open it) still holds everything. - A start marker with no matching end marker is plain text and gets the plain cut; markers in another encoding (`\u003c`, HTML entities) are not found. The writers produce neither. - A cut JSON block is no longer valid JSON; its frames stay whole. - A spill file read back with `read` has no wrapper (same as the `web_fetch` precedent). - The two MCP serving paths stay unbounded: there, wrapped values sit inside JSON the tools build, and that needs an owner at the tools that wrap them. ## Follow-ups (not in this PR) - A recovery hint for size-only routes (Codex, Agents API), which only report the size today. - One fit predicate for `skills_read` and the bound, with the default budget inside `resolveToolResultBudget`. - Move the bound out of `embedded-agent-runner/` under one name. - Check the bound is not above Codex's own tool-output limit for dynamic tools. - Spill provenance so `read` wraps a spilled untrusted result; a spill size cap with a truthful notice; a retention rule. - Stage the spill file into the executor's filesystem for Codex and the Agents API; Tool Search's omission can go after that. - A per-turn aggregate budget on the Codex, Agents API and Copilot routes. - Carry provenance on the block (wrap after the cut) instead of finding frames in text. - The two unbounded MCP serving paths, once the tools that wrap JSON values own their bound. - A truthful notice when a tiny budget (reserve close to the cap) shortens the notice itself. ## Gaps - Two MCP serving paths (`mcp-http.handlers.ts`, `src/mcp/plugin-tools-handlers.ts`) have no tool-result bound; out of scope. - Agents API: if image placeholders alone exceed the per-result budget (hundreds of images in one result), the text budget clamps to zero and the adapter's cap cuts the placeholders. - Codex and Agents API results are cut with a size-only notice; the omitted middle is not recoverable there (it was not before either). Staging the file into the executor's filesystem is a follow-up. - CJK text is over-cut when the context budget binds. - Images: when images alone exceed the context share, the bound does not drop them; the embedded context guard does (as on `main`). On Codex and Copilot such images pass as on `main`, where no route budgeted images. Moving image omission into the bound is a separate change. ## Evidence Red on `main`, green here (same tests): | Route | Test | |---|---| | Codex | `skills_read` with a 16k-token attempt budget and a complete 12k skill: refused whole, not cut; a wrapped network result at 128k through the dynamic-tool bridge: one closed frame with head and tail, a size-only notice and no Gateway path; mixed text + image within the shared budget. The small-window and image cases live in the bound's fail-closed suite below, which every route calls | | Copilot | oversized result bounded before the SDK, file equals the full text | | Agents API | an image block before one oversized wrapped page: output starts with the image placeholder, keeps the warning, start and end markers with one id, and the notice's omitted count equals exactly the chars cut (at the previous head the output ended `<<<END_EXTE`); a header plus two wrapped pages that fit the 32k budget by one char before the joining newlines: all four markers kept, output within the cap | | All routes (`tool-result-bound.multi-block.test.ts`, 14 of these red on the previous head) | one helper checks every case: no untrusted text or filler outside a whole frame, every start marker closed with its id, exactly one notice outside frames with count = original − kept, and the real context guard, run after the bound, passes every text block unchanged. Cases: header + page at 4k/8k/16k/128k; two pages at 4k/16k/128k (second left out whole); 14 pages at 4k/8k; 200 small pages at 128k keep whole bodies; one JSON block with 5 wrapped values at 4k/8k, cut mid-way; image beside a page at 4k/8k/16k (a browser snapshot's shape; red one commit earlier, where the guard re-cut the frame after dropping the image); spill on: the notice names the file and the file holds the full text | | Embedded | a forged envelope with a 200k metadata header is left out whole with the notice; 16k-token window: the bound's output passes the context guard unchanged and keeps its path; spill write failure keeps head + tail with a size-only notice | Consumer suites pass; tests that pinned the Codex prefix cut were rewritten to the bound's contract. A producer's own spill path is also withheld from size-only routes. `agent-tools.prefix-stability` passes. Typecheck: core, core tests, extensions, extension tests. Supersedes #207205: its multi-block end-marker cases are covered here frame by frame; its MCP-path bounding is left out (see Security boundary). Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot
pushed a commit
to Desicool/openclaw
that referenced
this pull request
Nov 29, 2026
…wrapper intact (openclaw#207101) ## Problem A tool result that is too big for the model is cut differently on each route, and on two of them the cut is unsafe or loses data: - **Codex app-server dynamic tools** kept a prefix only and appended "rerun with narrower args". When the result was untrusted network content, the cut removed the wrapper's end marker, so the rest of the turn ran with an open untrusted-content region. Production (one team deployment, 7 days): 719 cut results in 102 sessions, **292 of them with the wrapper left open** (`github_read` 227, code-mode `exec` 59, `sessions_history` 7, `wait` 1). - **Agents API** cut a prefix with no notice and no file. - **Copilot** forwarded results with no bound at all (no production Copilot sessions in the window; found by reading the code). - **Embedded** (openclaw#206880) bounded at the per-result cap, which is looser than the context guard's budget below 32k-token windows and with images. The guard then cut again with no file path. ## Solution One bound, `boundToolResult`, for every route that executes OpenClaw tools: - **Budget:** the strictest one the result meets later: the per-result cap, then the context guard's weighted share with images and other blocks reserved first. A bounded result is a fixed point of both the transcript cap and the context guard, so the saved-file path survives. Unknown window: the 16k default. - **Cut:** head and tail (the existing truncator); the full text goes to an owner-only file (`writePrivateTempFile`). The notice is harness-neutral: `[... N chars omitted. Full output: <path>]`. A route whose model cannot open a Gateway file gets the same cut with a size-only notice: the Codex app-server (its native file tools run under its own sandbox policy, local or remote) and the Agents API (file tools run in the hosted VM). A path is named only where OpenClaw's own `read` opens it (embedded, Copilot). If the budget cannot hold the whole path, the notice names the size only. - **Untrusted content fails closed, per frame:** a frame is one `wrapExternalContent` region (warning, start marker and metadata header, body, end marker with the same id), found inside any text block, raw or JSON-escaped, so several wrapped values in one JSON block (`web_search`) count one by one (`findExternalContentFrames`, next to the writer). Frames and the text between them are kept whole, in order, while they fit; the first piece that does not fit keeps its ends and loses only body (head and tail); everything after it is left out. One trusted notice, `[... N chars omitted. Full output: <path>]`, follows the cut outside every frame, with the true count. A frame whose ends cannot fit (forged or hostile metadata, an image taking a small window's share) is left out whole: untrusted text never reaches the model outside a frame. When images alone exceed the context share, the bound reserves what the embedded context guard will keep (the images that fit plus its image-omission notice, one shared formatter), so the guard drops images without cutting the framed text again. Results with no frames keep the head-and-tail cut. - **Where:** `runAgentHarnessToolInvocation` after result middleware (Codex dynamic tools, Agents API); the Copilot bridge calls it directly (`boundAgentHarnessToolResult`, private harness SDK subpath); embedded keeps its `afterToolCall` call site. Copilot registers the file to the run's owner (the sandbox workspace for sandboxed runs), so its own `read` can open it. Codex `skills_read` stays whole-or-error: its check now uses the same budget as the bound, so a skill that passes is never cut later (an attempt budget smaller than the model window used to let a 12k skill pass and then be cut while reported as a success). Deleted: the Codex prefix-only cut and its "rerun" notice, the Agents API silent prefix cut. **Agents API serialization:** the adapter joins the bounded blocks with newlines and a 54-char placeholder per image into one function-output string, then applies its own cap. The bound reserves exactly what that serialization adds (`resultBound.reservedChars`, computed from the adapter's one `serializeFunctionOutput`), so the single cut leaves room for it and the adapter's cap never cuts a bounded result. The bound never adds a block (its notice goes into a text block it keeps; it only removes others), so the reserve computed before the cut covers the output. One cut, so the omitted count in the notice is true. Not in this PR: Tool Search's whole-result omission (3 unrecoverable omissions in 7 days in production) stays. Removing it is safe only where the model can read the saved file; on Codex and Agents API a partial page would show a continuation cursor with no way to read the omitted records. It returns once those routes can read the file. ## Security boundary This changes how untrusted content is cut on every route. Before: the Codex route dropped end markers (292 open wrappers in 7 days), and on the other routes several frames in one result could lose markers or leave untrusted text outside a frame. After: every frame the finder matches is either whole, or cut in its body with both ends kept, or left out; the omission notice is ours and sits outside every frame. Residuals, named, not fixed here: - A forged frame (raw tool output that copies the marker format) whose metadata is oversized is left out whole, and so is everything after it. Accepted: fail closed is the rule, and the saved file (where the reader can open it) still holds everything. - A start marker with no matching end marker is plain text and gets the plain cut; markers in another encoding (`\u003c`, HTML entities) are not found. The writers produce neither. - A cut JSON block is no longer valid JSON; its frames stay whole. - A spill file read back with `read` has no wrapper (same as the `web_fetch` precedent). - The two MCP serving paths stay unbounded: there, wrapped values sit inside JSON the tools build, and that needs an owner at the tools that wrap them. ## Follow-ups (not in this PR) - A recovery hint for size-only routes (Codex, Agents API), which only report the size today. - One fit predicate for `skills_read` and the bound, with the default budget inside `resolveToolResultBudget`. - Move the bound out of `embedded-agent-runner/` under one name. - Check the bound is not above Codex's own tool-output limit for dynamic tools. - Spill provenance so `read` wraps a spilled untrusted result; a spill size cap with a truthful notice; a retention rule. - Stage the spill file into the executor's filesystem for Codex and the Agents API; Tool Search's omission can go after that. - A per-turn aggregate budget on the Codex, Agents API and Copilot routes. - Carry provenance on the block (wrap after the cut) instead of finding frames in text. - The two unbounded MCP serving paths, once the tools that wrap JSON values own their bound. - A truthful notice when a tiny budget (reserve close to the cap) shortens the notice itself. ## Gaps - Two MCP serving paths (`mcp-http.handlers.ts`, `src/mcp/plugin-tools-handlers.ts`) have no tool-result bound; out of scope. - Agents API: if image placeholders alone exceed the per-result budget (hundreds of images in one result), the text budget clamps to zero and the adapter's cap cuts the placeholders. - Codex and Agents API results are cut with a size-only notice; the omitted middle is not recoverable there (it was not before either). Staging the file into the executor's filesystem is a follow-up. - CJK text is over-cut when the context budget binds. - Images: when images alone exceed the context share, the bound does not drop them; the embedded context guard does (as on `main`). On Codex and Copilot such images pass as on `main`, where no route budgeted images. Moving image omission into the bound is a separate change. ## Evidence Red on `main`, green here (same tests): | Route | Test | |---|---| | Codex | `skills_read` with a 16k-token attempt budget and a complete 12k skill: refused whole, not cut; a wrapped network result at 128k through the dynamic-tool bridge: one closed frame with head and tail, a size-only notice and no Gateway path; mixed text + image within the shared budget. The small-window and image cases live in the bound's fail-closed suite below, which every route calls | | Copilot | oversized result bounded before the SDK, file equals the full text | | Agents API | an image block before one oversized wrapped page: output starts with the image placeholder, keeps the warning, start and end markers with one id, and the notice's omitted count equals exactly the chars cut (at the previous head the output ended `<<<END_EXTE`); a header plus two wrapped pages that fit the 32k budget by one char before the joining newlines: all four markers kept, output within the cap | | All routes (`tool-result-bound.multi-block.test.ts`, 14 of these red on the previous head) | one helper checks every case: no untrusted text or filler outside a whole frame, every start marker closed with its id, exactly one notice outside frames with count = original − kept, and the real context guard, run after the bound, passes every text block unchanged. Cases: header + page at 4k/8k/16k/128k; two pages at 4k/16k/128k (second left out whole); 14 pages at 4k/8k; 200 small pages at 128k keep whole bodies; one JSON block with 5 wrapped values at 4k/8k, cut mid-way; image beside a page at 4k/8k/16k (a browser snapshot's shape; red one commit earlier, where the guard re-cut the frame after dropping the image); spill on: the notice names the file and the file holds the full text | | Embedded | a forged envelope with a 200k metadata header is left out whole with the notice; 16k-token window: the bound's output passes the context guard unchanged and keeps its path; spill write failure keeps head + tail with a size-only notice | Consumer suites pass; tests that pinned the Codex prefix cut were rewritten to the bound's contract. A producer's own spill path is also withheld from size-only routes. `agent-tools.prefix-stability` passes. Typecheck: core, core tests, extensions, extension tests. Supersedes openclaw#207205: its multi-block end-marker cases are covered here frame by frame; its MCP-path bounding is left out (see Security boundary). Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot
pushed a commit
that referenced
this pull request
Nov 30, 2026
Co-authored-by: hannesrudolph <[email protected]> (cherry picked from commit 1108290) Follow-ups: 5c3c123 fix(agents): large tool results lose their last lines and cannot be recovered (#206880) [not selected for this narrow backport]; 8b36e34 test(codex): build expected summaries from the agent-core summary constants (#207004) [not selected for this narrow backport] Release adaptation: Use the stable structured-summary path consistently without adding the warm transport absent from stable; retain the settled-approval tests, not main-only warm transport tests. Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot
pushed a commit
that referenced
this pull request
Nov 30, 2026
…wrapper intact (#207101) ## Problem A tool result that is too big for the model is cut differently on each route, and on two of them the cut is unsafe or loses data: - **Codex app-server dynamic tools** kept a prefix only and appended "rerun with narrower args". When the result was untrusted network content, the cut removed the wrapper's end marker, so the rest of the turn ran with an open untrusted-content region. Production (one team deployment, 7 days): 719 cut results in 102 sessions, **292 of them with the wrapper left open** (`github_read` 227, code-mode `exec` 59, `sessions_history` 7, `wait` 1). - **Agents API** cut a prefix with no notice and no file. - **Copilot** forwarded results with no bound at all (no production Copilot sessions in the window; found by reading the code). - **Embedded** (#206880) bounded at the per-result cap, which is looser than the context guard's budget below 32k-token windows and with images. The guard then cut again with no file path. ## Solution One bound, `boundToolResult`, for every route that executes OpenClaw tools: - **Budget:** the strictest one the result meets later: the per-result cap, then the context guard's weighted share with images and other blocks reserved first. A bounded result is a fixed point of both the transcript cap and the context guard, so the saved-file path survives. Unknown window: the 16k default. - **Cut:** head and tail (the existing truncator); the full text goes to an owner-only file (`writePrivateTempFile`). The notice is harness-neutral: `[... N chars omitted. Full output: <path>]`. A route whose model cannot open a Gateway file gets the same cut with a size-only notice: the Codex app-server (its native file tools run under its own sandbox policy, local or remote) and the Agents API (file tools run in the hosted VM). A path is named only where OpenClaw's own `read` opens it (embedded, Copilot). If the budget cannot hold the whole path, the notice names the size only. - **Untrusted content fails closed, per frame:** a frame is one `wrapExternalContent` region (warning, start marker and metadata header, body, end marker with the same id), found inside any text block, raw or JSON-escaped, so several wrapped values in one JSON block (`web_search`) count one by one (`findExternalContentFrames`, next to the writer). Frames and the text between them are kept whole, in order, while they fit; the first piece that does not fit keeps its ends and loses only body (head and tail); everything after it is left out. One trusted notice, `[... N chars omitted. Full output: <path>]`, follows the cut outside every frame, with the true count. A frame whose ends cannot fit (forged or hostile metadata, an image taking a small window's share) is left out whole: untrusted text never reaches the model outside a frame. When images alone exceed the context share, the bound reserves what the embedded context guard will keep (the images that fit plus its image-omission notice, one shared formatter), so the guard drops images without cutting the framed text again. Results with no frames keep the head-and-tail cut. - **Where:** `runAgentHarnessToolInvocation` after result middleware (Codex dynamic tools, Agents API); the Copilot bridge calls it directly (`boundAgentHarnessToolResult`, private harness SDK subpath); embedded keeps its `afterToolCall` call site. Copilot registers the file to the run's owner (the sandbox workspace for sandboxed runs), so its own `read` can open it. Codex `skills_read` stays whole-or-error: its check now uses the same budget as the bound, so a skill that passes is never cut later (an attempt budget smaller than the model window used to let a 12k skill pass and then be cut while reported as a success). Deleted: the Codex prefix-only cut and its "rerun" notice, the Agents API silent prefix cut. **Agents API serialization:** the adapter joins the bounded blocks with newlines and a 54-char placeholder per image into one function-output string, then applies its own cap. The bound reserves exactly what that serialization adds (`resultBound.reservedChars`, computed from the adapter's one `serializeFunctionOutput`), so the single cut leaves room for it and the adapter's cap never cuts a bounded result. The bound never adds a block (its notice goes into a text block it keeps; it only removes others), so the reserve computed before the cut covers the output. One cut, so the omitted count in the notice is true. Not in this PR: Tool Search's whole-result omission (3 unrecoverable omissions in 7 days in production) stays. Removing it is safe only where the model can read the saved file; on Codex and Agents API a partial page would show a continuation cursor with no way to read the omitted records. It returns once those routes can read the file. ## Security boundary This changes how untrusted content is cut on every route. Before: the Codex route dropped end markers (292 open wrappers in 7 days), and on the other routes several frames in one result could lose markers or leave untrusted text outside a frame. After: every frame the finder matches is either whole, or cut in its body with both ends kept, or left out; the omission notice is ours and sits outside every frame. Residuals, named, not fixed here: - A forged frame (raw tool output that copies the marker format) whose metadata is oversized is left out whole, and so is everything after it. Accepted: fail closed is the rule, and the saved file (where the reader can open it) still holds everything. - A start marker with no matching end marker is plain text and gets the plain cut; markers in another encoding (`\u003c`, HTML entities) are not found. The writers produce neither. - A cut JSON block is no longer valid JSON; its frames stay whole. - A spill file read back with `read` has no wrapper (same as the `web_fetch` precedent). - The two MCP serving paths stay unbounded: there, wrapped values sit inside JSON the tools build, and that needs an owner at the tools that wrap them. ## Follow-ups (not in this PR) - A recovery hint for size-only routes (Codex, Agents API), which only report the size today. - One fit predicate for `skills_read` and the bound, with the default budget inside `resolveToolResultBudget`. - Move the bound out of `embedded-agent-runner/` under one name. - Check the bound is not above Codex's own tool-output limit for dynamic tools. - Spill provenance so `read` wraps a spilled untrusted result; a spill size cap with a truthful notice; a retention rule. - Stage the spill file into the executor's filesystem for Codex and the Agents API; Tool Search's omission can go after that. - A per-turn aggregate budget on the Codex, Agents API and Copilot routes. - Carry provenance on the block (wrap after the cut) instead of finding frames in text. - The two unbounded MCP serving paths, once the tools that wrap JSON values own their bound. - A truthful notice when a tiny budget (reserve close to the cap) shortens the notice itself. ## Gaps - Two MCP serving paths (`mcp-http.handlers.ts`, `src/mcp/plugin-tools-handlers.ts`) have no tool-result bound; out of scope. - Agents API: if image placeholders alone exceed the per-result budget (hundreds of images in one result), the text budget clamps to zero and the adapter's cap cuts the placeholders. - Codex and Agents API results are cut with a size-only notice; the omitted middle is not recoverable there (it was not before either). Staging the file into the executor's filesystem is a follow-up. - CJK text is over-cut when the context budget binds. - Images: when images alone exceed the context share, the bound does not drop them; the embedded context guard does (as on `main`). On Codex and Copilot such images pass as on `main`, where no route budgeted images. Moving image omission into the bound is a separate change. ## Evidence Red on `main`, green here (same tests): | Route | Test | |---|---| | Codex | `skills_read` with a 16k-token attempt budget and a complete 12k skill: refused whole, not cut; a wrapped network result at 128k through the dynamic-tool bridge: one closed frame with head and tail, a size-only notice and no Gateway path; mixed text + image within the shared budget. The small-window and image cases live in the bound's fail-closed suite below, which every route calls | | Copilot | oversized result bounded before the SDK, file equals the full text | | Agents API | an image block before one oversized wrapped page: output starts with the image placeholder, keeps the warning, start and end markers with one id, and the notice's omitted count equals exactly the chars cut (at the previous head the output ended `<<<END_EXTE`); a header plus two wrapped pages that fit the 32k budget by one char before the joining newlines: all four markers kept, output within the cap | | All routes (`tool-result-bound.multi-block.test.ts`, 14 of these red on the previous head) | one helper checks every case: no untrusted text or filler outside a whole frame, every start marker closed with its id, exactly one notice outside frames with count = original − kept, and the real context guard, run after the bound, passes every text block unchanged. Cases: header + page at 4k/8k/16k/128k; two pages at 4k/16k/128k (second left out whole); 14 pages at 4k/8k; 200 small pages at 128k keep whole bodies; one JSON block with 5 wrapped values at 4k/8k, cut mid-way; image beside a page at 4k/8k/16k (a browser snapshot's shape; red one commit earlier, where the guard re-cut the frame after dropping the image); spill on: the notice names the file and the file holds the full text | | Embedded | a forged envelope with a 200k metadata header is left out whole with the notice; 16k-token window: the bound's output passes the context guard unchanged and keeps its path; spill write failure keeps head + tail with a size-only notice | Consumer suites pass; tests that pinned the Codex prefix cut were rewritten to the bound's contract. A producer's own spill path is also withheld from size-only routes. `agent-tools.prefix-stability` passes. Typecheck: core, core tests, extensions, extension tests. Supersedes #207205: its multi-block end-marker cases are covered here frame by frame; its MCP-path bounding is left out (see Security boundary). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit e1599de) Release adaptation: Use the stable result truncator for embedded context and size caps; preserve paired untrusted-content markers under a single weighted budget. Bound the actual serialized Agents API and Copilot text without changing binary/image handling, tool receipts, existing spill access, or native Codex. Companion audit: PR #207101; pinned scan passed. The selected donor already covers the framed result cases from superseded #207205; leave native Codex and MCP-path changes out. All three baseline assertions failed at the expected tail/budget boundaries; the negative proof was reused after normalizing ANSI output. Co-authored-by: RomneyDa <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What Problem This Solves
When a tool returns more text than its context budget, OpenClaw keeps only the start, discards the rest, and tells the model to "rerun with narrower args". The end of the output, where commands print errors, totals and exit status, is lost unless a keyword list happens to match it. MCP and plugin tools have no other copy, so the model cannot get the cut text back.
Production signal (a production deployment, 2.76 days of Gateway logs):
[tool-result-truncation] Truncated N tool result(s) for prompt history (maxChars=64000 …)lines, up to 96 results in one session.Reproduced on main (
ab296c23d2c4) through the real record path (guardSessionManager, 200k-token window). The fixture is a 180,015-character plain log, the same for exec, read, web_fetch, an MCP result and a plugin result:[... 116116 more characters truncated; rerun with narrower args if needed][... 116221 chars omitted. Full output: <path> (page it with read offset/limit)]Fix
The bound has one owner, at record time:
boundToolResult(src/agents/embedded-agent-runner/tool-result-bound.ts) runs once at the end ofafterToolCall(run/attempt-setup.ts), after tool-result hooks and before the result is first sent. It applies to every executed tool: core, MCP and plugin.writePrivateTempFile(tmpdir, 0600; staged in the workspace for sandboxed sessions), the same rule asexecandweb_fetchoutput files. A tool that already saved its own file (exec,web_fetch) keeps that file, and the notice names it.Deleted:
context-truncation-notice.ts: the "rerun with narrower args" notice and itssessions_sendvariant.hasImportantTail, a keyword regex that decided whether the tail survived, and the head-only branch it guarded. Head+tail is now unconditional for any window over 4,000 characters. Smaller windows keep a whole prefix, so short records are not split.Fixed on the way (exposed by the shorter notice):
Full output:pointer. It now sizes the notice for the largest count it can show.User impact
agent --local) users on the embedded runtime. Both runinstallEmbeddedAttemptContextGuards(src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:515).Evidence
src/agents/tool-result-bounds.test.ts: one case per tool family through the real guard registry:buildExecForegroundResult), MCP (projectMcpCallToolResult) and plugin: head, tail, spill file with the full text, and the recorded bytes equal to the bound bytes (fixed point);run/attempt-context-guards.test.ts: the installedafterToolCallbounds the result an earlier hook returned and restores the previous hook on removal.agent-tools.prefix-stabilitypasses. All core test typecheck shards pass.ab296c23d2c4, so these failures are not from this change:expected 2 to be 1, reproduced on the base).openclaw agent --local(scratch HOME, state and config),openai/gpt-5.4-minion the embedded runtime. The agent runsseq 1 60000 | sed 's/$/ padding padding padding/'throughexec, calls no other tool, and replies with the last line of the output:ab296c23d2c4:UNKNOWN(the recorded result kept only the head of exec's retained window);60000 padding padding padding. The notice points at exec's own output file; no second file is written.read; exec and web_fetch spill paths are in the same position on main. Lettingreadopen this session's own spill paths is the follow-up PR.