Skip to content

fix(hooks): raise the hook body limit to 1 MiB and log rejected bodies - #200514

Merged
obviyus merged 2 commits into
openclaw:mainfrom
garrytan:fix/hook-mapping-body-limit
Nov 17, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
garrytan:fix/hook-mapping-body-limit

Conversation

@garrytan

@garrytan garrytan commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Related: #111382, #120278, #130002

What Problem This Solves

Every custom hook path had a fixed 256 KiB body limit. A meeting-notes webhook (Circleback) carrying the full transcript of a 3 h 16 min meeting sent 332,553 bytes. The gateway answered 413 payload too large on all nine retries, so the meeting never reached the agent. The rejection was not logged anywhere, so the operator could not see that a delivery was lost.

256 KiB was the smallest limit among the gateway's authenticated endpoints: generic webhooks allow 1 MiB, tools invoke 2 MiB and chat completions 20 MiB.

Fix

  • The default hook body limit is now 1 MiB, the shared webhook default (DEFAULT_WEBHOOK_MAX_BODY_BYTES). The Gmail-path allowance is unchanged; its floor rises from 256 KiB to 1 MiB.
  • An authenticated hook request whose body is rejected (413, 408 or 400) now logs hook request rejected for <path>: status=<code> bodyLimitBytes=<limit>. No body content is logged, because parse errors can quote it.
  • No new config key. The first revision of this PR added a per-mapping hooks.mappings[].maxBodyBytes, up to 32 MiB. It is replaced by the default, which keeps hooks.maxBodyBytes retired as refactor(config): config-surface reduction tranche 2 — purge tuning knobs behind built-in defaults #111382 intended.

Why 1 MiB and not more: the Codex runtime accepts at most 1 MiB of text per turn (MAX_USER_INPUT_TEXT_CHARS in codex-rs). A larger body that is templated into an agent message is cut from the front before the model sees it, which removes the mapping's instruction. On the first revision, an 8 MiB accepted body made the agent ignore the hook and do unrelated tool work, and the run still reported status=ok. A visible 413 is better than that. Stopping the Codex runtime from cutting the current request is separate follow-up work.

User Impact

Hook senders whose payloads are between 256 KiB and 1 MiB now work with no config change. That is about 10 hours of meeting transcript at the rate above. Bodies over 1 MiB still get 413, and the gateway log now names the path and the limit. Auth still runs before the body is read.

Evidence

Real gateway from source, real agent turns (openai/gpt-5.4-mini, Codex runtime). Bodies are synthetic but use Circleback's documented JSON shape (transcript segments with speaker, text and timestamp), with a codeword in the last segment. The mapping asks the agent to return it.

build body result
main 332,553 B 413, nothing logged
this PR 332,553 B 200; agent returns the codeword (94k input tokens)
this PR 1,000,000 B 200; agent returns the codeword (231k input tokens); no truncation in the Codex rollout
this PR 2,097,152 B 413; hook request rejected for /hooks/circleback: status=413 bodyLimitBytes=1048576
this PR, other path 332,553 B 200 (wake)

First revision (per-mapping limit of 8 MiB), same setup:

body result
2 MiB accepted; Codex input cut to the last 1,048,576 chars ([truncated 1049630 chars from older context])
8 MiB accepted; instruction lost, agent ran unrelated tool calls, hook logged status=ok

Memory (accepted bodies, 10–20 concurrent): about 1.7× the concurrent body bytes. 20 × 2 MiB added about 60 MB of RSS.

Tests: two request-handler tests in src/gateway/server/hooks.wake-admission.test.ts. One accepts a 332,553-byte body; the other checks that a rejected body logs its path and limit without its content. Both fail on main and pass here. The hook suites pass (125 tests in 6 files), as do tsgo:core, oxlint, oxfmt, config:docs:check and git diff --check.

Thanks @garrytan for the report and the detailed proof.

…s stop getting 413

Every custom hook path is capped at 256 KiB, and the cap cannot be raised:
hooks.maxBodyBytes was retired in openclaw#111382, and the per-path allowance the
runtime already carries (HookMappingResolved.maxBodyBytes, folded by
resolveHookBodyLimitsByPath) is only ever set for gmail-path mappings.
Senders whose payloads outgrow 256 KiB, such as a meeting-notes webhook
carrying a three-hour transcript, get a permanent 413.

Accept hooks.mappings[].maxBodyBytes (positive integer, at most 32 MiB, the
same ceiling as the derived gmail allowance) and pass it through to the
existing per-path bound. Other paths keep the 256 KiB default, the body is
still read only after token auth, and a gmail-path mapping takes the larger
of its own value and the derived allowance.
@clawsweeper

clawsweeper Bot commented Nov 17, 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 docs Improvements or additions to documentation gateway Gateway runtime size: XS labels Nov 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

Adds an optional per-mapping body-size allowance, capped at 32 MiB, through the existing per-path limit mechanism.

Example: An authenticated sender posts a 332,553-byte JSON body to /hooks/circleback.

  • Before: The Gateway returns 413 because the path is limited to 262,144 bytes.
  • After: With maxBodyBytes set to 8388608 on that path's mapping, the Gateway accepts the request while other paths retain their existing limits.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong behavior and upgrade evidence support a focused patch; overall readiness remains capped by the unresolved configuration-direction choice.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor's redacted Linux built-Gateway output at 7408585 exercises real HTTP admission, configured boundaries, other-path rejection, and missing-token rejection; the added same-state 2026.11.4 upgrade transcript resolves the prior compatibility-proof gap.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A long meeting transcript exceeds the generic webhook body limit and is rejected on every retry.
Reason: The implementation has concrete value, but adding a public numeric control revisits an intentional configuration-surface decision.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR addresses a demonstrated payload-size limitation with a focused, correct implementation; the new configuration option needs an owner decision.

Priority: P2
Reviewed head: 7408585bae380ca5c515d5851b969d45093834fb
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should hooks.mappings[].maxBodyBytes become a supported operator control after the deliberate retirement of the global hook body-size knob?
  • Recommendation: Approve the bounded per-path option: Accept this focused extension for senders with larger payloads while preserving existing defaults and the 32 MiB ceiling.
  • Why: The concrete oversized webhook establishes user value, but neither the current discussion nor reviews records owner approval for this new configuration surface.

Before merge

  • Await maintainer action - A maintainer must approve the held GitHub Actions workflows for the reviewed head so the required CI can run.

Findings

None.

Agent review details

How this fits together

Gateway HTTP hooks authenticate incoming requests, enforce the configured path's body limit, parse JSON, and map accepted payloads into wake events or agent runs.

flowchart TD
  A[Webhook sender] --> B[Hook token authentication]
  C[Validated hook mappings] --> D[Resolved per-path limits]
  B --> E[Bounded JSON body reader]
  D --> E
  E --> F[Mapping and dispatch]
Loading

Technical review

Best possible solution:

Retain the existing path-limit owner and bounded implementation if the hook owner approves the new per-mapping configuration contract.

Do we have a high-confidence way to reproduce the issue?

Current source establishes the fixed generic-path limit, and the contributor supplies stable-release HTTP output showing 332,553-byte requests rejected with 413; this review executed no target code.

Is this the best way to solve the issue?

The patch is the smallest complete implementation of the proposed option: validate the field, carry it into existing resolution, and preserve Gmail's derived minimum.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e58cd2228d8f.

Provenance checked

  • Per-path body allowance and Gmail minimum changes intended behavior with a stated reason (03f3334: Derive Gmail's allowance from its batch producer contract while keeping other paths at the default and bounding memory use.)
  • Public hook body-size configuration changes intended behavior with a stated reason (783a5d2: Retire numeric tuning controls whose built-in defaults were intended to suffice; the PR explains why a real custom sender needs a per-path exception.)
  • Mapping normalization keeps the original intent (aeb5455: Centralize configured webhook mapping resolution before matching and dispatch.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +10, Tests +28, Docs +3, Generated 0. Total +41 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 12 2 +10
Tests 1 28 0 +28
Docs 1 4 1 +3
Config 0 0 0 0
Generated 2 3 3 0
Other 0 0 0 0
Total 8 47 6 +41

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
New configuration surface 1 optional field hooks.mappings[].maxBodyBytes accepts positive integers through 33554432; existing configurations retain their limits.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: ⏳ waiting on maintainer.

Label justifications:

  • P2: Oversized custom webhook payloads are repeatedly rejected, with impact limited to affected integrations.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-17T09:23:42.850Z sha 7408585 :: needs real behavior proof before merge. :: none

Reviewed November 17, 2026, 4:55 AM ET / 09:55 UTC (Revision 2).

@garrytan

Copy link
Copy Markdown
Contributor Author

I added the requested proof: an in-place upgrade from 2026.11.4 to this head. It reuses the same state dir and config, keeps the existing session and state, and changes nothing about hook behaviour or the hooks block until the key is set. The new key then works on the upgraded install. Downgrading is covered as an accepted edge case. The redacted transcript is in the PR body's Evidence section. The code is unchanged at 7408585.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 17, 2026
Replace the per-mapping maxBodyBytes key with a 1 MiB default, the shared
webhook bound and the Codex turn text cap. Log the path and bound when an
authenticated hook body is rejected.

Co-authored-by: obviyus <[email protected]>
@obviyus obviyus changed the title fix(hooks): custom hook paths reject every body over 256 KiB with 413, with no way to raise it fix(hooks): raise the hook body limit to 1 MiB and log rejected bodies Nov 17, 2026
@obviyus
obviyus merged commit df82bcf into openclaw:main Nov 17, 2026
124 of 126 checks passed
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks @garrytan, this was a great report, and the upgrade transcript made it easy to check.

Landed as df82bcf, with one change to the approach. Instead of a per-mapping maxBodyBytes, the default hook body limit is now 1 MiB, the gateway's shared webhook default. Your 332,553-byte Circleback payload now goes through with no config change. A rejected body also logs hook request rejected for <path>: status=… bodyLimitBytes=… now, so a lost delivery shows up in the gateway log.

Why we stopped at 1 MiB: while testing larger limits, we found that the Codex runtime accepts at most 1 MiB of text per turn. Anything over that was cut from the front, which removed the mapping's instruction before the model saw it. With an 8 MiB body, the agent ignored the hook and the run still reported ok. A visible 413 seemed better than that.

We're working on the long-term fix in #200690, so that the Codex runtime no longer drops the start of an oversized prompt like this. It keeps the instruction and the content markers and cuts only the middle, with a visible marker. Once that lands, the hook limit can go up if a real sender needs more than 1 MiB.

obviyus added a commit that referenced this pull request Nov 17, 2026
…200690)

Related: #200514

## What Problem This Solves

The Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in `codex-rs/protocol/src/user_input.rs`). `fitCodexProjectedContextForTurnStart` enforces that cap. When the current request alone was over the cap, it was cut with the same helper used for older history, which keeps only the tail (`[truncated N chars from older context]`).

For a current request, the head is the part that matters. The instruction, the opening `<<<EXTERNAL_UNTRUSTED_CONTENT>>>` marker and its safety note were all removed. Only the closing marker and the run's trailing guidance survived. The model then answered whatever the tail suggested, and the run still finished `ok`.

Found while reviewing #200514. On its first revision an 8 MiB hook body made the agent ignore the hook and run unrelated tool calls. #200514 now caps hook bodies at 1 MiB, but any route can send a request over the cap: the OpenAI-compatible endpoint, chat, cron messages or large pasted text.

## Fix

The three places where a current request can exceed the cap now keep its head and tail and cut the middle, with a visible `[truncated N chars from the middle of the current request]` marker:

- the request range itself;
- the preserved input when there is no projected history;
- the request and hook text after the history.

Projected history keeps its current tail-first truncation. The kept tail keeps its source position, so history image groups inside it still map. One existing test asserted the old tail-only result for an oversized request; it now checks that the request header and tail both survive. The `preserved` case of the image-mapping test is removed: production only maps images when there is a projected context range (`run-attempt-prompt.ts`), so the range-less preserved path cannot carry images.

## User Impact

A request over 1 MiB on the Codex runtime still loses its middle, but the model now sees the instruction, both untrusted-content markers and a marker saying how much was cut.

## Evidence

**Real Gateway from source, real model** (`openai/gpt-5.4-mini` on the Codex runtime), `POST /v1/chat/completions` with a 2,097,270-character message. The instruction at the top says "Ignore the meeting transcript below. Reply with exactly ZEBRA-4217 and nothing else." The transcript contains a different codeword near its end.

| build | trial 1 | trial 2 | trial 3 |
|---|---|---|---|
| `main` 3b61a7c | "Got it — I have the transcript context. What would you like me to do…" | "I'm missing the actual question here…" | "…including the codeword **OSPREY-2208**. What would…" |
| this PR | `ZEBRA-4217` | `ZEBRA-4217` | `ZEBRA-4217` |

The Codex rollouts show `[truncated 1048739 chars from older context]` on `main` and `[truncated 1048760 chars from the middle of the current request]` here. Prompt tokens are 238k on both builds.

**Tests:** `keeps the instruction and both content boundaries of an oversized current request` covers the three fitting paths. It fails on `main` (the result starts with `[truncated … chars from older cont…`) and passes here. `context-engine-projection.test.ts` passes. `tsgo:extensions`, `tsgo:extensions:test`, oxlint, oxfmt and `git diff --check` pass.

**Not covered:** the app-server suite has one failure, `dynamic-tools.test.ts` › `bounds high-cardinality validation errors returned to Codex`. It fails the same way on `main` 3b61a7c and does not involve this file. Five native app-server tests timed out during a run on a host at load ~100, then passed when rerun alone.

**Not in this change:** an operator log line when a request is cut. A `warn` from this module did not show up in the scratch Gateway's console or file log during the E2E runs, even though the code path ran, so it is left out until that log path is understood.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 17, 2026
…middle (#200735)

Related: #200514, #200690

## What Problem This Solves

The Codex app-server rejects any turn over 1,048,576 characters (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). Since #200690, a current request over that cap keeps its head and tail and loses its middle. Anything that appears only in the middle is gone, and the model answers from what remains.

Large requests come from hooks (up to 1 MiB since #200514), the OpenAI-compatible endpoint (20 MiB bodies), channel messages, pastes and cron messages.

## Fix

- **New host capability, `fitCurrentInput`.** It is a generic harness host capability, so there are no new Plugin SDK exports. The Codex attempt calls it right after its connection is ready, with the Codex turn cap and the connection's own `prepareInputAttachments`.
- **Over the cap, and the run may read files on this host:** the full request is saved as an inbound attachment (`current-request.txt`). The model sees the request's head and tail, which keep the instruction and both untrusted-content markers. It also sees a marker saying the visible part is incomplete and that it should search the attachment before answering, plus the attachment path.
- **Placement is the connection's decision.** It already refuses local paths for a sandbox, remote execution, non-stdio transport, a remote workspace root, restricted tools or a non-full permission mode, and prefers a registered remote attachment binding.
- **Otherwise:** only the middle is cut, as in #200690.
- **Transcript:** keeps the original (`transcriptPrompt`). There is no change to stored turns, schema or retention; the file follows the operator's existing inbound attachment retention.
- **Visible outcome:** each case logs `current input oversize: chars=… budget=… action=attached|cut`.

**Scope, after local review.** Earlier revisions also estimated a token budget from the model window and fitted requests for the built-in runtime. A chars-per-token estimate cannot prove token overflow. Fitting below the hard cap could drop content that fit, and the built-in runtime has its own token-aware overflow handling. This version acts only past a runtime's hard per-turn text cap, so nothing that worked inline changes.

## User Impact

On the Codex runtime, a request over 1 MiB stays usable: the agent can search the full text instead of guessing from its start and end. Requests within the cap and the built-in runtime behave as before.

## Evidence

Real Gateways from source with real models on the Codex runtime, `POST /v1/chat/completions`.

**1. 3 MB request.** A 2,948,079-character meeting transcript. The instruction is at the top ("Kenji Sato states the budget codeword. Reply with ONLY that codeword"). The codeword `HERON-5150` appears once, at the 49.9% offset.

| model | `main` 9aed362 | this PR, final head |
|---|---|---|
| gpt-5.4 | `Fire`, `Fire`, `ClawRouter` (0/3) | `HERON-5150` ×3 (3/3) |
| gpt-5.4-mini | `armed`, `Fire`, `Fire` (0/3) | `HERON-5150` 1/3 (`armed`, `done`) on an earlier head with the same staging path |

- The log shows `current input oversize: chars=2948079 budget=1048576 action=attached`.
- The Codex rollout shows the agent opening `…/media/inbound/current-request---….txt`, parsing it, and printing the matching segment.

**2. 2 MiB request whose instruction is only at the top** ("reply exactly ZEBRA-4217"), gpt-5.4-mini, final head: `ZEBRA-4217`, `action=attached`.

**Tests:**

- `src/agents/harness/current-input-budget.test.ts` covers three cases:
  - unchanged within the cap;
  - attached: the saved file holds the full original, and the instruction and both markers stay inline;
  - cut-only when staging returns nothing.
- Passing: `src/agents/harness/` and every `extensions/codex/src/app-server/run-attempt*.test.ts` (11 shards), `tsgo:core`, `tsgo:extensions`, `check:test-types`, `plugin-sdk:surface:check`, oxlint, oxfmt and `git diff --check`.

**Not covered / accepted:**

- gpt-5.4-mini is unreliable at finding a middle-only fact through the attachment (1/3). The docs say so.
- Requests over the 5 MB inbound media cap fall back to the cut.
- Each retry of the same oversized turn saves its own copy.
- The Codex-side head/tail cut from #200690 stays as the guard for prompt decoration that still exceeds the cap.
- The built-in runtime's handling of an oversized single message stays a separate, token-aware follow-up.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
openclaw#200514)

Related: openclaw#111382, openclaw#120278, openclaw#130002

## What Problem This Solves

Every custom hook path had a fixed 256 KiB body limit. A meeting-notes webhook (Circleback) carrying the full transcript of a 3 h 16 min meeting sent 332,553 bytes. The gateway answered `413 payload too large` on all nine retries, so the meeting never reached the agent. The rejection was not logged anywhere, so the operator could not see that a delivery was lost.

256 KiB was the smallest limit among the gateway's authenticated endpoints: generic webhooks allow 1 MiB, tools invoke 2 MiB and chat completions 20 MiB.

## Fix

- The default hook body limit is now 1 MiB, the shared webhook default (`DEFAULT_WEBHOOK_MAX_BODY_BYTES`). The Gmail-path allowance is unchanged; its floor rises from 256 KiB to 1 MiB.
- An authenticated hook request whose body is rejected (`413`, `408` or `400`) now logs `hook request rejected for <path>: status=<code> bodyLimitBytes=<limit>`. No body content is logged, because parse errors can quote it.
- No new config key. The first revision of this PR added a per-mapping `hooks.mappings[].maxBodyBytes`, up to 32 MiB. It is replaced by the default, which keeps `hooks.maxBodyBytes` retired as openclaw#111382 intended.

Why 1 MiB and not more: the Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). A larger body that is templated into an agent message is cut from the front before the model sees it, which removes the mapping's instruction. On the first revision, an 8 MiB accepted body made the agent ignore the hook and do unrelated tool work, and the run still reported `status=ok`. A visible 413 is better than that. Stopping the Codex runtime from cutting the current request is separate follow-up work.

## User Impact

Hook senders whose payloads are between 256 KiB and 1 MiB now work with no config change. That is about 10 hours of meeting transcript at the rate above. Bodies over 1 MiB still get 413, and the gateway log now names the path and the limit. Auth still runs before the body is read.

## Evidence

**Real gateway from source, real agent turns** (`openai/gpt-5.4-mini`, Codex runtime). Bodies are synthetic but use Circleback's documented JSON shape (`transcript` segments with speaker, text and timestamp), with a codeword in the last segment. The mapping asks the agent to return it.

| build | body | result |
|---|---:|---|
| `main` | 332,553 B | 413, nothing logged |
| this PR | 332,553 B | 200; agent returns the codeword (94k input tokens) |
| this PR | 1,000,000 B | 200; agent returns the codeword (231k input tokens); no truncation in the Codex rollout |
| this PR | 2,097,152 B | 413; `hook request rejected for /hooks/circleback: status=413 bodyLimitBytes=1048576` |
| this PR, other path | 332,553 B | 200 (wake) |

**First revision (per-mapping limit of 8 MiB), same setup:**

| body | result |
|---|---|
| 2 MiB | accepted; Codex input cut to the last 1,048,576 chars (`[truncated 1049630 chars from older context]`) |
| 8 MiB | accepted; instruction lost, agent ran unrelated tool calls, hook logged `status=ok` |

**Memory** (accepted bodies, 10–20 concurrent): about 1.7× the concurrent body bytes. 20 × 2 MiB added about 60 MB of RSS.

**Tests:** two request-handler tests in `src/gateway/server/hooks.wake-admission.test.ts`. One accepts a 332,553-byte body; the other checks that a rejected body logs its path and limit without its content. Both fail on `main` and pass here. The hook suites pass (125 tests in 6 files), as do `tsgo:core`, oxlint, oxfmt, `config:docs:check` and `git diff --check`.

Thanks @garrytan for the report and the detailed proof.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…penclaw#200690)

Related: openclaw#200514

## What Problem This Solves

The Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in `codex-rs/protocol/src/user_input.rs`). `fitCodexProjectedContextForTurnStart` enforces that cap. When the current request alone was over the cap, it was cut with the same helper used for older history, which keeps only the tail (`[truncated N chars from older context]`).

For a current request, the head is the part that matters. The instruction, the opening `<<<EXTERNAL_UNTRUSTED_CONTENT>>>` marker and its safety note were all removed. Only the closing marker and the run's trailing guidance survived. The model then answered whatever the tail suggested, and the run still finished `ok`.

Found while reviewing openclaw#200514. On its first revision an 8 MiB hook body made the agent ignore the hook and run unrelated tool calls. openclaw#200514 now caps hook bodies at 1 MiB, but any route can send a request over the cap: the OpenAI-compatible endpoint, chat, cron messages or large pasted text.

## Fix

The three places where a current request can exceed the cap now keep its head and tail and cut the middle, with a visible `[truncated N chars from the middle of the current request]` marker:

- the request range itself;
- the preserved input when there is no projected history;
- the request and hook text after the history.

Projected history keeps its current tail-first truncation. The kept tail keeps its source position, so history image groups inside it still map. One existing test asserted the old tail-only result for an oversized request; it now checks that the request header and tail both survive. The `preserved` case of the image-mapping test is removed: production only maps images when there is a projected context range (`run-attempt-prompt.ts`), so the range-less preserved path cannot carry images.

## User Impact

A request over 1 MiB on the Codex runtime still loses its middle, but the model now sees the instruction, both untrusted-content markers and a marker saying how much was cut.

## Evidence

**Real Gateway from source, real model** (`openai/gpt-5.4-mini` on the Codex runtime), `POST /v1/chat/completions` with a 2,097,270-character message. The instruction at the top says "Ignore the meeting transcript below. Reply with exactly ZEBRA-4217 and nothing else." The transcript contains a different codeword near its end.

| build | trial 1 | trial 2 | trial 3 |
|---|---|---|---|
| `main` 7ae74c4 | "Got it — I have the transcript context. What would you like me to do…" | "I'm missing the actual question here…" | "…including the codeword **OSPREY-2208**. What would…" |
| this PR | `ZEBRA-4217` | `ZEBRA-4217` | `ZEBRA-4217` |

The Codex rollouts show `[truncated 1048739 chars from older context]` on `main` and `[truncated 1048760 chars from the middle of the current request]` here. Prompt tokens are 238k on both builds.

**Tests:** `keeps the instruction and both content boundaries of an oversized current request` covers the three fitting paths. It fails on `main` (the result starts with `[truncated … chars from older cont…`) and passes here. `context-engine-projection.test.ts` passes. `tsgo:extensions`, `tsgo:extensions:test`, oxlint, oxfmt and `git diff --check` pass.

**Not covered:** the app-server suite has one failure, `dynamic-tools.test.ts` › `bounds high-cardinality validation errors returned to Codex`. It fails the same way on `main` 7ae74c4 and does not involve this file. Five native app-server tests timed out during a run on a host at load ~100, then passed when rerun alone.

**Not in this change:** an operator log line when a request is cut. A `warn` from this module did not show up in the scratch Gateway's console or file log during the E2E runs, even though the code path ran, so it is left out until that log path is understood.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…middle (openclaw#200735)

Related: openclaw#200514, openclaw#200690

## What Problem This Solves

The Codex app-server rejects any turn over 1,048,576 characters (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). Since openclaw#200690, a current request over that cap keeps its head and tail and loses its middle. Anything that appears only in the middle is gone, and the model answers from what remains.

Large requests come from hooks (up to 1 MiB since openclaw#200514), the OpenAI-compatible endpoint (20 MiB bodies), channel messages, pastes and cron messages.

## Fix

- **New host capability, `fitCurrentInput`.** It is a generic harness host capability, so there are no new Plugin SDK exports. The Codex attempt calls it right after its connection is ready, with the Codex turn cap and the connection's own `prepareInputAttachments`.
- **Over the cap, and the run may read files on this host:** the full request is saved as an inbound attachment (`current-request.txt`). The model sees the request's head and tail, which keep the instruction and both untrusted-content markers. It also sees a marker saying the visible part is incomplete and that it should search the attachment before answering, plus the attachment path.
- **Placement is the connection's decision.** It already refuses local paths for a sandbox, remote execution, non-stdio transport, a remote workspace root, restricted tools or a non-full permission mode, and prefers a registered remote attachment binding.
- **Otherwise:** only the middle is cut, as in openclaw#200690.
- **Transcript:** keeps the original (`transcriptPrompt`). There is no change to stored turns, schema or retention; the file follows the operator's existing inbound attachment retention.
- **Visible outcome:** each case logs `current input oversize: chars=… budget=… action=attached|cut`.

**Scope, after local review.** Earlier revisions also estimated a token budget from the model window and fitted requests for the built-in runtime. A chars-per-token estimate cannot prove token overflow. Fitting below the hard cap could drop content that fit, and the built-in runtime has its own token-aware overflow handling. This version acts only past a runtime's hard per-turn text cap, so nothing that worked inline changes.

## User Impact

On the Codex runtime, a request over 1 MiB stays usable: the agent can search the full text instead of guessing from its start and end. Requests within the cap and the built-in runtime behave as before.

## Evidence

Real Gateways from source with real models on the Codex runtime, `POST /v1/chat/completions`.

**1. 3 MB request.** A 2,948,079-character meeting transcript. The instruction is at the top ("Kenji Sato states the budget codeword. Reply with ONLY that codeword"). The codeword `HERON-5150` appears once, at the 49.9% offset.

| model | `main` 709b566 | this PR, final head |
|---|---|---|
| gpt-5.4 | `Fire`, `Fire`, `ClawRouter` (0/3) | `HERON-5150` ×3 (3/3) |
| gpt-5.4-mini | `armed`, `Fire`, `Fire` (0/3) | `HERON-5150` 1/3 (`armed`, `done`) on an earlier head with the same staging path |

- The log shows `current input oversize: chars=2948079 budget=1048576 action=attached`.
- The Codex rollout shows the agent opening `…/media/inbound/current-request---….txt`, parsing it, and printing the matching segment.

**2. 2 MiB request whose instruction is only at the top** ("reply exactly ZEBRA-4217"), gpt-5.4-mini, final head: `ZEBRA-4217`, `action=attached`.

**Tests:**

- `src/agents/harness/current-input-budget.test.ts` covers three cases:
  - unchanged within the cap;
  - attached: the saved file holds the full original, and the instruction and both markers stay inline;
  - cut-only when staging returns nothing.
- Passing: `src/agents/harness/` and every `extensions/codex/src/app-server/run-attempt*.test.ts` (11 shards), `tsgo:core`, `tsgo:extensions`, `check:test-types`, `plugin-sdk:surface:check`, oxlint, oxfmt and `git diff --check`.

**Not covered / accepted:**

- gpt-5.4-mini is unreliable at finding a middle-only fact through the attachment (1/3). The docs say so.
- Requests over the 5 MB inbound media cap fall back to the cut.
- Each retry of the same oversized turn saves its own copy.
- The Codex-side head/tail cut from openclaw#200690 stays as the guard for prompt decoration that still exceeds the cap.
- The built-in runtime's handling of an oversized single message stays a separate, token-aware follow-up.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
#200514)

Backport the shared authenticated webhook body limit and content-free rejection diagnostics. Keep authentication before body reads and the existing Gmail-derived allowance.

(cherry picked from commit df82bcf)

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
…200690)

Related: #200514

## What Problem This Solves

The Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in `codex-rs/protocol/src/user_input.rs`). `fitCodexProjectedContextForTurnStart` enforces that cap. When the current request alone was over the cap, it was cut with the same helper used for older history, which keeps only the tail (`[truncated N chars from older context]`).

For a current request, the head is the part that matters. The instruction, the opening `<<<EXTERNAL_UNTRUSTED_CONTENT>>>` marker and its safety note were all removed. Only the closing marker and the run's trailing guidance survived. The model then answered whatever the tail suggested, and the run still finished `ok`.

Found while reviewing #200514. On its first revision an 8 MiB hook body made the agent ignore the hook and run unrelated tool calls. #200514 now caps hook bodies at 1 MiB, but any route can send a request over the cap: the OpenAI-compatible endpoint, chat, cron messages or large pasted text.

## Fix

The three places where a current request can exceed the cap now keep its head and tail and cut the middle, with a visible `[truncated N chars from the middle of the current request]` marker:

- the request range itself;
- the preserved input when there is no projected history;
- the request and hook text after the history.

Projected history keeps its current tail-first truncation. The kept tail keeps its source position, so history image groups inside it still map. One existing test asserted the old tail-only result for an oversized request; it now checks that the request header and tail both survive. The `preserved` case of the image-mapping test is removed: production only maps images when there is a projected context range (`run-attempt-prompt.ts`), so the range-less preserved path cannot carry images.

## User Impact

A request over 1 MiB on the Codex runtime still loses its middle, but the model now sees the instruction, both untrusted-content markers and a marker saying how much was cut.

## Evidence

**Real Gateway from source, real model** (`openai/gpt-5.4-mini` on the Codex runtime), `POST /v1/chat/completions` with a 2,097,270-character message. The instruction at the top says "Ignore the meeting transcript below. Reply with exactly ZEBRA-4217 and nothing else." The transcript contains a different codeword near its end.

| build | trial 1 | trial 2 | trial 3 |
|---|---|---|---|
| `main` 3b61a7c | "Got it — I have the transcript context. What would you like me to do…" | "I'm missing the actual question here…" | "…including the codeword **OSPREY-2208**. What would…" |
| this PR | `ZEBRA-4217` | `ZEBRA-4217` | `ZEBRA-4217` |

The Codex rollouts show `[truncated 1048739 chars from older context]` on `main` and `[truncated 1048760 chars from the middle of the current request]` here. Prompt tokens are 238k on both builds.

**Tests:** `keeps the instruction and both content boundaries of an oversized current request` covers the three fitting paths. It fails on `main` (the result starts with `[truncated … chars from older cont…`) and passes here. `context-engine-projection.test.ts` passes. `tsgo:extensions`, `tsgo:extensions:test`, oxlint, oxfmt and `git diff --check` pass.

**Not covered:** the app-server suite has one failure, `dynamic-tools.test.ts` › `bounds high-cardinality validation errors returned to Codex`. It fails the same way on `main` 3b61a7c and does not involve this file. Five native app-server tests timed out during a run on a host at load ~100, then passed when rerun alone.

**Not in this change:** an operator log line when a request is cut. A `warn` from this module did not show up in the scratch Gateway's console or file log during the E2E runs, even though the code path ran, so it is left out until that log path is understood.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 64e2ad2)

Backport-proof: source regressions fail 4/31 on c317a25, preserving head and both boundaries is required.
Co-authored-by: vincentkoc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
…middle (#200735)

Related: #200514, #200690

## What Problem This Solves

The Codex app-server rejects any turn over 1,048,576 characters (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). Since #200690, a current request over that cap keeps its head and tail and loses its middle. Anything that appears only in the middle is gone, and the model answers from what remains.

Large requests come from hooks (up to 1 MiB since #200514), the OpenAI-compatible endpoint (20 MiB bodies), channel messages, pastes and cron messages.

## Fix

- **New host capability, `fitCurrentInput`.** It is a generic harness host capability, so there are no new Plugin SDK exports. The Codex attempt calls it right after its connection is ready, with the Codex turn cap and the connection's own `prepareInputAttachments`.
- **Over the cap, and the run may read files on this host:** the full request is saved as an inbound attachment (`current-request.txt`). The model sees the request's head and tail, which keep the instruction and both untrusted-content markers. It also sees a marker saying the visible part is incomplete and that it should search the attachment before answering, plus the attachment path.
- **Placement is the connection's decision.** It already refuses local paths for a sandbox, remote execution, non-stdio transport, a remote workspace root, restricted tools or a non-full permission mode, and prefers a registered remote attachment binding.
- **Otherwise:** only the middle is cut, as in #200690.
- **Transcript:** keeps the original (`transcriptPrompt`). There is no change to stored turns, schema or retention; the file follows the operator's existing inbound attachment retention.
- **Visible outcome:** each case logs `current input oversize: chars=… budget=… action=attached|cut`.

**Scope, after local review.** Earlier revisions also estimated a token budget from the model window and fitted requests for the built-in runtime. A chars-per-token estimate cannot prove token overflow. Fitting below the hard cap could drop content that fit, and the built-in runtime has its own token-aware overflow handling. This version acts only past a runtime's hard per-turn text cap, so nothing that worked inline changes.

## User Impact

On the Codex runtime, a request over 1 MiB stays usable: the agent can search the full text instead of guessing from its start and end. Requests within the cap and the built-in runtime behave as before.

## Evidence

Real Gateways from source with real models on the Codex runtime, `POST /v1/chat/completions`.

**1. 3 MB request.** A 2,948,079-character meeting transcript. The instruction is at the top ("Kenji Sato states the budget codeword. Reply with ONLY that codeword"). The codeword `HERON-5150` appears once, at the 49.9% offset.

| model | `main` 9aed362 | this PR, final head |
|---|---|---|
| gpt-5.4 | `Fire`, `Fire`, `ClawRouter` (0/3) | `HERON-5150` ×3 (3/3) |
| gpt-5.4-mini | `armed`, `Fire`, `Fire` (0/3) | `HERON-5150` 1/3 (`armed`, `done`) on an earlier head with the same staging path |

- The log shows `current input oversize: chars=2948079 budget=1048576 action=attached`.
- The Codex rollout shows the agent opening `…/media/inbound/current-request---….txt`, parsing it, and printing the matching segment.

**2. 2 MiB request whose instruction is only at the top** ("reply exactly ZEBRA-4217"), gpt-5.4-mini, final head: `ZEBRA-4217`, `action=attached`.

**Tests:**

- `src/agents/harness/current-input-budget.test.ts` covers three cases:
  - unchanged within the cap;
  - attached: the saved file holds the full original, and the instruction and both markers stay inline;
  - cut-only when staging returns nothing.
- Passing: `src/agents/harness/` and every `extensions/codex/src/app-server/run-attempt*.test.ts` (11 shards), `tsgo:core`, `tsgo:extensions`, `check:test-types`, `plugin-sdk:surface:check`, oxlint, oxfmt and `git diff --check`.

**Not covered / accepted:**

- gpt-5.4-mini is unreliable at finding a middle-only fact through the attachment (1/3). The docs say so.
- Requests over the 5 MB inbound media cap fall back to the cut.
- Each retry of the same oversized turn saves its own copy.
- The Codex-side head/tail cut from #200690 stays as the guard for prompt decoration that still exceeds the cap.
- The built-in runtime's handling of an oversized single message stays a separate, token-aware follow-up.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 52e8079)

Backport-proof: added a production-host Codex turn/start regression with registered workspace attachment owner; red on a8f3bfad459c because complete-request attachment guidance is absent. Existing placement and live binding owner retained.
Co-authored-by: vincentkoc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
#200514)

Related: #111382, #120278, #130002

## What Problem This Solves

Every custom hook path had a fixed 256 KiB body limit. A meeting-notes webhook (Circleback) carrying the full transcript of a 3 h 16 min meeting sent 332,553 bytes. The gateway answered `413 payload too large` on all nine retries, so the meeting never reached the agent. The rejection was not logged anywhere, so the operator could not see that a delivery was lost.

256 KiB was the smallest limit among the gateway's authenticated endpoints: generic webhooks allow 1 MiB, tools invoke 2 MiB and chat completions 20 MiB.

## Fix

- The default hook body limit is now 1 MiB, the shared webhook default (`DEFAULT_WEBHOOK_MAX_BODY_BYTES`). The Gmail-path allowance is unchanged; its floor rises from 256 KiB to 1 MiB.
- An authenticated hook request whose body is rejected (`413`, `408` or `400`) now logs `hook request rejected for <path>: status=<code> bodyLimitBytes=<limit>`. No body content is logged, because parse errors can quote it.
- No new config key. The first revision of this PR added a per-mapping `hooks.mappings[].maxBodyBytes`, up to 32 MiB. It is replaced by the default, which keeps `hooks.maxBodyBytes` retired as #111382 intended.

Why 1 MiB and not more: the Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). A larger body that is templated into an agent message is cut from the front before the model sees it, which removes the mapping's instruction. On the first revision, an 8 MiB accepted body made the agent ignore the hook and do unrelated tool work, and the run still reported `status=ok`. A visible 413 is better than that. Stopping the Codex runtime from cutting the current request is separate follow-up work.

## User Impact

Hook senders whose payloads are between 256 KiB and 1 MiB now work with no config change. That is about 10 hours of meeting transcript at the rate above. Bodies over 1 MiB still get 413, and the gateway log now names the path and the limit. Auth still runs before the body is read.

## Evidence

**Real gateway from source, real agent turns** (`openai/gpt-5.4-mini`, Codex runtime). Bodies are synthetic but use Circleback's documented JSON shape (`transcript` segments with speaker, text and timestamp), with a codeword in the last segment. The mapping asks the agent to return it.

| build | body | result |
|---|---:|---|
| `main` | 332,553 B | 413, nothing logged |
| this PR | 332,553 B | 200; agent returns the codeword (94k input tokens) |
| this PR | 1,000,000 B | 200; agent returns the codeword (231k input tokens); no truncation in the Codex rollout |
| this PR | 2,097,152 B | 413; `hook request rejected for /hooks/circleback: status=413 bodyLimitBytes=1048576` |
| this PR, other path | 332,553 B | 200 (wake) |

**First revision (per-mapping limit of 8 MiB), same setup:**

| body | result |
|---|---|
| 2 MiB | accepted; Codex input cut to the last 1,048,576 chars (`[truncated 1049630 chars from older context]`) |
| 8 MiB | accepted; instruction lost, agent ran unrelated tool calls, hook logged `status=ok` |

**Memory** (accepted bodies, 10–20 concurrent): about 1.7× the concurrent body bytes. 20 × 2 MiB added about 60 MB of RSS.

**Tests:** two request-handler tests in `src/gateway/server/hooks.wake-admission.test.ts`. One accepts a 332,553-byte body; the other checks that a rejected body logs its path and limit without its content. Both fail on `main` and pass here. The hook suites pass (125 tests in 6 files), as do `tsgo:core`, oxlint, oxfmt, `config:docs:check` and `git diff --check`.

Thanks @garrytan for the report and the detailed proof.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit df82bcf)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 57caad23e2defdf33bdf6735fb165eadb08b73e9)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…200690)

Related: #200514

## What Problem This Solves

The Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in `codex-rs/protocol/src/user_input.rs`). `fitCodexProjectedContextForTurnStart` enforces that cap. When the current request alone was over the cap, it was cut with the same helper used for older history, which keeps only the tail (`[truncated N chars from older context]`).

For a current request, the head is the part that matters. The instruction, the opening `<<<EXTERNAL_UNTRUSTED_CONTENT>>>` marker and its safety note were all removed. Only the closing marker and the run's trailing guidance survived. The model then answered whatever the tail suggested, and the run still finished `ok`.

Found while reviewing #200514. On its first revision an 8 MiB hook body made the agent ignore the hook and run unrelated tool calls. #200514 now caps hook bodies at 1 MiB, but any route can send a request over the cap: the OpenAI-compatible endpoint, chat, cron messages or large pasted text.

## Fix

The three places where a current request can exceed the cap now keep its head and tail and cut the middle, with a visible `[truncated N chars from the middle of the current request]` marker:

- the request range itself;
- the preserved input when there is no projected history;
- the request and hook text after the history.

Projected history keeps its current tail-first truncation. The kept tail keeps its source position, so history image groups inside it still map. One existing test asserted the old tail-only result for an oversized request; it now checks that the request header and tail both survive. The `preserved` case of the image-mapping test is removed: production only maps images when there is a projected context range (`run-attempt-prompt.ts`), so the range-less preserved path cannot carry images.

## User Impact

A request over 1 MiB on the Codex runtime still loses its middle, but the model now sees the instruction, both untrusted-content markers and a marker saying how much was cut.

## Evidence

**Real Gateway from source, real model** (`openai/gpt-5.4-mini` on the Codex runtime), `POST /v1/chat/completions` with a 2,097,270-character message. The instruction at the top says "Ignore the meeting transcript below. Reply with exactly ZEBRA-4217 and nothing else." The transcript contains a different codeword near its end.

| build | trial 1 | trial 2 | trial 3 |
|---|---|---|---|
| `main` 3b61a7c | "Got it — I have the transcript context. What would you like me to do…" | "I'm missing the actual question here…" | "…including the codeword **OSPREY-2208**. What would…" |
| this PR | `ZEBRA-4217` | `ZEBRA-4217` | `ZEBRA-4217` |

The Codex rollouts show `[truncated 1048739 chars from older context]` on `main` and `[truncated 1048760 chars from the middle of the current request]` here. Prompt tokens are 238k on both builds.

**Tests:** `keeps the instruction and both content boundaries of an oversized current request` covers the three fitting paths. It fails on `main` (the result starts with `[truncated … chars from older cont…`) and passes here. `context-engine-projection.test.ts` passes. `tsgo:extensions`, `tsgo:extensions:test`, oxlint, oxfmt and `git diff --check` pass.

**Not covered:** the app-server suite has one failure, `dynamic-tools.test.ts` › `bounds high-cardinality validation errors returned to Codex`. It fails the same way on `main` 3b61a7c and does not involve this file. Five native app-server tests timed out during a run on a host at load ~100, then passed when rerun alone.

**Not in this change:** an operator log line when a request is cut. A `warn` from this module did not show up in the scratch Gateway's console or file log during the E2E runs, even though the code path ran, so it is left out until that log path is understood.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 64e2ad2)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 7cadb580a88e6fb6be8af64483dc4f8ef9cbc174)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…middle (#200735)

Related: #200514, #200690

## What Problem This Solves

The Codex app-server rejects any turn over 1,048,576 characters (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). Since #200690, a current request over that cap keeps its head and tail and loses its middle. Anything that appears only in the middle is gone, and the model answers from what remains.

Large requests come from hooks (up to 1 MiB since #200514), the OpenAI-compatible endpoint (20 MiB bodies), channel messages, pastes and cron messages.

## Fix

- **New host capability, `fitCurrentInput`.** It is a generic harness host capability, so there are no new Plugin SDK exports. The Codex attempt calls it right after its connection is ready, with the Codex turn cap and the connection's own `prepareInputAttachments`.
- **Over the cap, and the run may read files on this host:** the full request is saved as an inbound attachment (`current-request.txt`). The model sees the request's head and tail, which keep the instruction and both untrusted-content markers. It also sees a marker saying the visible part is incomplete and that it should search the attachment before answering, plus the attachment path.
- **Placement is the connection's decision.** It already refuses local paths for a sandbox, remote execution, non-stdio transport, a remote workspace root, restricted tools or a non-full permission mode, and prefers a registered remote attachment binding.
- **Otherwise:** only the middle is cut, as in #200690.
- **Transcript:** keeps the original (`transcriptPrompt`). There is no change to stored turns, schema or retention; the file follows the operator's existing inbound attachment retention.
- **Visible outcome:** each case logs `current input oversize: chars=… budget=… action=attached|cut`.

**Scope, after local review.** Earlier revisions also estimated a token budget from the model window and fitted requests for the built-in runtime. A chars-per-token estimate cannot prove token overflow. Fitting below the hard cap could drop content that fit, and the built-in runtime has its own token-aware overflow handling. This version acts only past a runtime's hard per-turn text cap, so nothing that worked inline changes.

## User Impact

On the Codex runtime, a request over 1 MiB stays usable: the agent can search the full text instead of guessing from its start and end. Requests within the cap and the built-in runtime behave as before.

## Evidence

Real Gateways from source with real models on the Codex runtime, `POST /v1/chat/completions`.

**1. 3 MB request.** A 2,948,079-character meeting transcript. The instruction is at the top ("Kenji Sato states the budget codeword. Reply with ONLY that codeword"). The codeword `HERON-5150` appears once, at the 49.9% offset.

| model | `main` 9aed362 | this PR, final head |
|---|---|---|
| gpt-5.4 | `Fire`, `Fire`, `ClawRouter` (0/3) | `HERON-5150` ×3 (3/3) |
| gpt-5.4-mini | `armed`, `Fire`, `Fire` (0/3) | `HERON-5150` 1/3 (`armed`, `done`) on an earlier head with the same staging path |

- The log shows `current input oversize: chars=2948079 budget=1048576 action=attached`.
- The Codex rollout shows the agent opening `…/media/inbound/current-request---….txt`, parsing it, and printing the matching segment.

**2. 2 MiB request whose instruction is only at the top** ("reply exactly ZEBRA-4217"), gpt-5.4-mini, final head: `ZEBRA-4217`, `action=attached`.

**Tests:**

- `src/agents/harness/current-input-budget.test.ts` covers three cases:
  - unchanged within the cap;
  - attached: the saved file holds the full original, and the instruction and both markers stay inline;
  - cut-only when staging returns nothing.
- Passing: `src/agents/harness/` and every `extensions/codex/src/app-server/run-attempt*.test.ts` (11 shards), `tsgo:core`, `tsgo:extensions`, `check:test-types`, `plugin-sdk:surface:check`, oxlint, oxfmt and `git diff --check`.

**Not covered / accepted:**

- gpt-5.4-mini is unreliable at finding a middle-only fact through the attachment (1/3). The docs say so.
- Requests over the 5 MB inbound media cap fall back to the cut.
- Each retry of the same oversized turn saves its own copy.
- The Codex-side head/tail cut from #200690 stays as the guard for prompt decoration that still exceeds the cap.
- The built-in runtime's handling of an oversized single message stays a separate, token-aware follow-up.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 52e8079)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 4f7dcc1980d999588febf5f02aa05c4d5a1e30eb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants