Skip to content

fix(agents): one tool-result bound on every route, untrusted-content wrapper intact - #207101

Merged
obviyus merged 11 commits into
mainfrom
core/one-tool-result-bound
Nov 28, 2026
Merged

obviyus merged 11 commits into
mainfrom
core/one-tool-result-bound

Conversation

@obviyus

@obviyus obviyus commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

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 (fix(agents): large tool results lose their last lines and cannot be recovered #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).

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 642f43db6f02f76d04af3ceacf77f10ae4505f1c
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/security/external-content.ts: Controls product security checks or trust decisions. Check whether the change weakens detection, protection, or remediation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. labels Nov 28, 2026
@obviyus
obviyus force-pushed the core/one-tool-result-bound branch from 8571c9d to 7ae7340 Compare November 28, 2026 01:53
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 28, 2026
@obviyus
obviyus force-pushed the core/one-tool-result-bound branch 5 times, most recently from aedf187 to 47e7298 Compare November 28, 2026 02:53
- boundToolResult bounds at the strictest budget (per-result cap and the context guard's weighted share incl. images), keeps head and tail, saves the full text; size-only notice when the reader cannot open the file.
- Applied in runAgentHarnessToolInvocation (Codex dynamic tools, Agents API) and the Copilot bridge; embedded keeps its afterToolCall call site.
- Deleted: Codex prefix-only cut (left the untrusted-content wrapper open), Agents API silent prefix cut, Tool Search whole-result omission.
- Image-then-envelope and header-plus-two-pages cases through buildAgentsApiToolSurface; the
  second case is W3's parked reproduction. Both fail on 2ad4364.
…ders in the one bound

- One predicate defines both the serialization and its reserve; the adapter's cap never cuts
  a bounded result, and the notice keeps the true omitted count.
…result bound

- Frames (each marker pair, raw or JSON-escaped) are kept whole while they fit; the first that
  does not keeps its ends and loses only body; the rest are left out with one trusted notice
  (true count, saved-file path) outside every frame. Linear frame finder next to the writer.
- reservedChars lowers the one budget object every check uses.
… frames

- When images alone exceed the share, the guard keeps what fits and adds its notice; the bound
  reserves both, so the guard never re-cuts a framed result. One notice formatter, shared.
- The fail-closed helper now runs the real context guard after the bound.
- Codex small-window and image cases and the two-page case are covered by the bound's
  fail-closed suite, which also runs the context guard; keeps the test-lines budget.
@obviyus

obviyus commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: landing at 642f43d with these checks red on causes from main, not this PR (this PR changes no ui/, apps/ or scripts/ file):

@obviyus
obviyus merged commit e1599de into main Nov 28, 2026
123 of 128 checks passed
@obviyus
obviyus deleted the core/one-tool-result-bound branch November 28, 2026 07:28
vincentkoc added a commit that referenced this pull request Nov 28, 2026
* commit '262f14aab89ca286633992760fa45aeeded998f9': (207 commits)
  fix(ui): remove redundant type argument from Board browser test (#207352)
  test(channels): distinguish status and batch fixtures (#207232)
  fix(ui): type the Board drop test mock as void (#207348)
  fix(ui): break the Skill Workshop import cycle (#207345)
  test(channels): expose label guard regressions (#207195)
  fix: explain when a previous automation run keeps the agent from starting (#207180)
  refactor(test): consolidate loader proof and repair rollback coverage (#207152)
  fix(agents): one tool-result bound on every route, untrusted-content wrapper intact (#207101)
  test(plugins): verify staged SDK named exports (#207170)
  fix(ui): truncate empty Compose hints on narrow screens (#207301)
  fix: keep unsent Cmd+K Compose drafts when reopened (#207307)
  fix: explain chat update errors when a session changes (#206419)
  fix(ios): keep consecutive commands on one line in chat (#207242)
  fix(ios): keep connection messages from flashing when chat reopens (#207233)
  fix(ios): give Sessions groups more breathing room (#207221)
  fix(ui): show chat completions as activity rows (#201891)
  fix(ui): make empty composer hints look distinct from drafts (#207295)
  fix: explain why chat won’t attach an empty file (#206402)
  fix(agents): show Doctor's restore-first warning before deleting a held store (#207290)
  test(channels): fix join failure proof and trim probe fixture (#207264)
  ...
vincentkoc added a commit that referenced this pull request Nov 28, 2026
* commit '262f14aab89ca286633992760fa45aeeded998f9': (207 commits)
  fix(ui): remove redundant type argument from Board browser test (#207352)
  test(channels): distinguish status and batch fixtures (#207232)
  fix(ui): type the Board drop test mock as void (#207348)
  fix(ui): break the Skill Workshop import cycle (#207345)
  test(channels): expose label guard regressions (#207195)
  fix: explain when a previous automation run keeps the agent from starting (#207180)
  refactor(test): consolidate loader proof and repair rollback coverage (#207152)
  fix(agents): one tool-result bound on every route, untrusted-content wrapper intact (#207101)
  test(plugins): verify staged SDK named exports (#207170)
  fix(ui): truncate empty Compose hints on narrow screens (#207301)
  fix: keep unsent Cmd+K Compose drafts when reopened (#207307)
  fix: explain chat update errors when a session changes (#206419)
  fix(ios): keep consecutive commands on one line in chat (#207242)
  fix(ios): keep connection messages from flashing when chat reopens (#207233)
  fix(ios): give Sessions groups more breathing room (#207221)
  fix(ui): show chat completions as activity rows (#201891)
  fix(ui): make empty composer hints look distinct from drafts (#207295)
  fix: explain why chat won’t attach an empty file (#206402)
  fix(agents): show Doctor's restore-first warning before deleting a held store (#207290)
  test(channels): fix join failure proof and trim probe fixture (#207264)
  ...
vincentkoc added a commit that referenced this pull request Nov 28, 2026
* commit '262f14aab89ca286633992760fa45aeeded998f9': (207 commits)
  fix(ui): remove redundant type argument from Board browser test (#207352)
  test(channels): distinguish status and batch fixtures (#207232)
  fix(ui): type the Board drop test mock as void (#207348)
  fix(ui): break the Skill Workshop import cycle (#207345)
  test(channels): expose label guard regressions (#207195)
  fix: explain when a previous automation run keeps the agent from starting (#207180)
  refactor(test): consolidate loader proof and repair rollback coverage (#207152)
  fix(agents): one tool-result bound on every route, untrusted-content wrapper intact (#207101)
  test(plugins): verify staged SDK named exports (#207170)
  fix(ui): truncate empty Compose hints on narrow screens (#207301)
  fix: keep unsent Cmd+K Compose drafts when reopened (#207307)
  fix: explain chat update errors when a session changes (#206419)
  fix(ios): keep consecutive commands on one line in chat (#207242)
  fix(ios): keep connection messages from flashing when chat reopens (#207233)
  fix(ios): give Sessions groups more breathing room (#207221)
  fix(ui): show chat completions as activity rows (#201891)
  fix(ui): make empty composer hints look distinct from drafts (#207295)
  fix: explain why chat won’t attach an empty file (#206402)
  fix(agents): show Doctor's restore-first warning before deleting a held store (#207290)
  test(channels): fix join failure proof and trim probe fixture (#207264)
  ...
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: daniel-lxs <[email protected]>
(cherry picked from commit 71b9c69)

Follow-ups: The separate 39bdddd replay persistence row was blocked; do not import warm-prompt compaction. e1599de fix(agents): one tool-result bound on every route, untrusted-content wrapper intact (#207101) [not selected for this narrow backport]

Release adaptation: Apply suppression guard to stable in-place replay. Stable has no compacted-turn replay helper, so preserve its pre-persisted-user-turn module unchanged.

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. docs Improvements or additions to documentation extensions: agentsapi extensions: codex extensions: copilot impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. P2 Normal backlog priority with limited blast radius. security-sensitive-changed size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant