Skip to content

fix(agents): keep every untrusted-content block closed and bound the MCP serving paths - #207205

Closed
obviyus wants to merge 3 commits into
mainfrom
core/result-bound-followup
Closed

obviyus wants to merge 3 commits into
mainfrom
core/result-bound-followup

Conversation

@obviyus

@obviyus obviyus commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Depends on #207101 (stacked on its head 2ad43647). Merge only after #207101, and only with the owner's OK: this touches the same untrusted-content boundary.

Problem

Two gaps left open by #207101's one tool-result bound (boundToolResult):

  1. Multi-block results. Only a result with exactly one text block that is one untrusted-content envelope had its body cut and its frame kept. With several text blocks, the truncator's per-block path falls back to a whole-prefix cut at small budgets, which drops an envelope block's end marker. Red at the 4,000-token minimum window, both for a header block beside a wrapped page and for two wrapped pages.
  2. Two MCP serving paths had no bound at all: the Gateway MCP loopback (src/gateway/mcp-http.handlers.ts, used by CLI backends) and the plugin tools MCP server (src/mcp/plugin-tools-handlers.ts).

Solution

  1. In boundToolResult (one owner), every text block that is exactly one envelope is unwrapped to its body; the frames are reserved in both budgets; after the cut each surviving body goes back inside its own whole frame. The body carries its frame on a module-private symbol key, which the truncator copies with the block. When the truncator keeps whole leading blocks and replaces the first omitted block with a notice, that notice is placed inside the omitted block's frame. If the summed frames do not fit beside the non-text blocks (hostile metadata), the text is cut as plain text, as in fix(agents): one tool-result bound on every route, untrusted-content wrapper intact #207101.
  2. Both MCP paths call boundToolResult(result, undefined, false) on results with a content array, before content normalization. Observers, receipts and isError still read the raw result. Plain strings and other JSON results keep their existing normalization.

Decision for the owner (MCP paths)

  • The MCP serving paths have no context window, so the bound uses its existing unknown-window default: 16k chars, with a size-only notice (no Gateway path; MCP clients read with their own tools). Before, the full result went to the client; clients such as CLI backends may apply their own, larger limits. This is a visible reduction for very large results through these paths. If that is not wanted, the alternative is to plumb the run's window into the loopback (a new parameter) or drop change 2.

Gaps (named, not fixed)

  • Agents API (from fix(agents): one tool-result bound on every route, untrusted-content wrapper intact #207101, not changed here): the adapter joins the bounded blocks with newlines and image placeholders, then cuts the joined string with a raw prefix slice at the cap. When the joining overhead pushes the string over the cap, that slice can cut the last characters of a closing marker (reproduced: a header and two wrapped pages that fit by one char before joining). Two fixes were tried and dropped: bounding the joined string again replaces the first notice with a false count ("67 chars omitted" where 217k were cut); dropping the final cap lets output exceed the cap by one char per block and 54 per image. A correct fix needs the owner pass to budget the adapter's serialization, which is a design choice for the owner; the tried patch is kept on a parked branch.

  • Frames are all-or-nothing: with many envelope blocks in one result (for example 12+ at a 4,000-token window, 25+ at 8,000), the summed frames do not fit and every block is cut as plain text. No known producer emits that many.

  • A notice placed inside an omitted block's frame sits in an untrusted region and its count covers following blocks too (same class as fix(agents): one tool-result bound on every route, untrusted-content wrapper intact #207101's residual).

  • MCP results whose content is a string, or that have no content array, are not bounded (unchanged).

Evidence

Red on #207101's head, green here:

Area Test
Bound header + wrapped page at 4,000 / 8,000 / 16,000 / 128,000-token windows, and two wrapped pages at 4,000 / 16,000 / 128,000: every envelope block keeps start and end with one id
Gateway MCP loopback oversized result: head + tail, size-only notice, no path; plain string / undefined / null / number results still succeed
Plugin tools MCP server oversized wrapped result: bounded, wrapper closed, no path

Consumer suites for #207101's routes (embedded, Codex, Copilot, Agents API, Tool Search) and the MCP server suites pass; prefix stability passes. Typecheck: core, core tests.

- 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.
@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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 28, 2026
@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. 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/result-bound-followup branch from 4e567f6 to 48cb75b Compare November 28, 2026 04:00
@obviyus
obviyus force-pushed the core/result-bound-followup branch from 48cb75b to d2017f7 Compare November 28, 2026 04:17
…MCP serving paths

- boundToolResult unwraps every text block that is exactly one envelope, reserves the frames, cuts bodies, and puts each surviving body (or the notice replacing it) back inside its own frame.
- Gateway MCP loopback and plugin tools MCP server results go through boundToolResult (size-only notice) before content normalization.
- A text block that is one envelope whose frame does not fit beside the other blocks is left out whole; one trusted notice with the true count follows the cut, outside every frame. Untrusted text never reaches the model unwrapped.
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]>
Base automatically changed from core/one-tool-result-bound to main November 28, 2026 07:28
@obviyus

obviyus commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #207101 (merged as e1599de). Its multi-block end-marker cases are covered there frame by frame, including several wrapped values inside one JSON block. The MCP serving-path bound is left out: those values are wrapped inside JSON the tools build, and that needs an owner at those tools.

@obviyus obviyus closed this Nov 28, 2026
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
…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 gateway Gateway runtime impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant