Skip to content

fix(agents): apply per-agent contextTokens cap to embedded run context budget - #120343

Merged
steipete merged 2 commits into
openclaw:mainfrom
harjothkhara:fix/embedded-per-agent-context-cap
Aug 9, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
harjothkhara:fix/embedded-per-agent-context-cap

Conversation

@harjothkhara

@harjothkhara harjothkhara commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Embedded runs ignored the selected agent's contextTokens ceiling. The run instead fell back to agents.defaults.contextTokens, so prompt prechecks, compaction, and session metadata could disagree with the per-agent limit the operator configured.

Why This Change Was Made

The selected session agent is now resolved before OpenClaw-owned model policy and its configured ceiling is applied to the prepared attempt budget. That prepared budget is then carried into the effective model, normal and compaction session safeguard extensions, and result metadata instead of re-resolving mutable policy at each consumer.

Standalone queued/direct compaction resolves the canonical session agent when no prepared attempt exists. Caller budgets remain ceilings within the configured agent cap and model window:

Requested Agent cap Model window Effective
500,000 200,000 500,000 200,000
100,000 200,000 500,000 100,000
500,000 200,000 64,000 64,000

Native model-owned harnesses still return before OpenClaw context policy. Codex therefore continues to own its own model context window and automatic/manual compaction.

Best-Fix Decision

This PR is the canonical fix rather than #119277. A per-agent contextTokens value is an operator-configured ceiling, so a larger request must not override it. The broader durable-session and hot-reload provenance question in #118678 remains intentionally out of scope.

Production LOC: +47/-12 (net +35) | Tests: +115/-2 (net +113). The production growth establishes one selected-agent ownership boundary and carries the prepared fact to consumers; the rewrite removes the incoming duplicate safeguard-policy resolution.

Evidence

  • Focused context guard, embedded setup, extension, compaction-runtime, and overflow-compaction shards: 94 tests passed.
  • The typed compaction fixture correction reran its 40-test shard successfully.
  • Regression coverage asserts the 200,000-token attempt budget, effective model window, and result metadata, plus the precedence table above.
  • Existing overflow-compaction coverage proves the same 200,000-token budget reaches recovery compaction; no duplicate lifecycle test was added.
  • git diff --check: passed.
  • Maintainer autoreview of both the rewrite delta and full branch: no accepted/actionable findings.
  • The local E2E shard could not start in the fresh worktree because its stale-dist setup requires an unavailable UI workspace dependency; exact-head hosted CI/Testbox is required before merge.

Codex Ownership Audit

Verified against openai/codex commit c2bcb9a26b5bdbdc66c48cf3bc3bb382568e800c:

  • codex-rs/protocol/src/openai_models.rs:416-424,463-479 owns model context and automatic-compaction thresholds.
  • codex-rs/models-manager/src/model_info.rs:25-37 applies context and compaction overrides.
  • codex-rs/core/src/session/context_window.rs:23-79 decides native context-window pressure and compaction.
  • codex-rs/core/src/session/handlers.rs:444-448 and codex-rs/core/src/tasks/compact.rs:19-84 own manual compaction.
  • codex-rs/app-server-protocol/src/protocol/v2/thread.rs:988-998 and codex-rs/app-server/src/request_processors/thread_processor.rs:1913-1924 show thread/compact/start accepts only the thread id and delegates to native Op::Compact.

Refs: #118678

Co-authored-by: harjoth [email protected]

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Aug 7, 2026
@harjothkhara
harjothkhara marked this pull request as ready for review August 7, 2026 20:25
@harjothkhara
harjothkhara force-pushed the fix/embedded-per-agent-context-cap branch from 062ce32 to 5790a1d Compare August 7, 2026 20:57
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 7, 2026
@clawsweeper

clawsweeper Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 8, 2026, 12:40 PM ET / 16:40 UTC.

ClawSweeper review

What this changes

The branch makes an agent’s existing per-agent contextTokens cap govern embedded-run prechecks, effective model sizing, compaction, safeguard sizing, and remediation text.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep this PR open for maintainer selection: it is a coherent fix with strong owner-boundary evidence, but it overlaps the open PR #119277 with a different request-budget precedence and needs one canonical direction.

Priority: P1
Reviewed head: 73fee5fca9a1a4ca19a9199cf4901e69d6c8604e
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch and its real-path proof are strong; maintainer selection of the one canonical precedence rule remains necessary.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides a before/after built-distribution embedded-run trace with real model resolution, a real mock transport request, and an observed successful result.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides a before/after built-distribution embedded-run trace with real model resolution, a real mock transport request, and an observed successful result.
Evidence reviewed 6 items Current-main defect remains: Current main still calls embedded runtime policy without the selected agent cap, while the guard falls back to defaults.
PR repairs the owner path: The branch resolves the session-selected agent configuration and forwards its cap into the effective embedded model policy; the E2E regression asserts 200k rather than the 128k default.
Sibling budget paths agree: Queued and prepared compaction pass the selected agent identity; safeguard sizing cannot expand above the already-effective model window.
Findings None None.
Security None None.

How this fits together

Embedded runs derive a context budget from agent configuration and model metadata before attempting a model call. The same budget is consumed by prechecks, compaction, session metadata, and safeguard compaction.

flowchart LR
A[Agent configuration] --> B[Embedded run setup]
B --> C[Effective context budget]
C --> D[Prompt precheck]
C --> E[Compaction]
C --> F[Safeguard sizing]
D --> G[Model attempt]
Loading

Decision needed

Question Recommendation
Should a higher caller-resolved compaction budget remain constrained by the selected agent’s configured contextTokens cap, as this PR implements, or override that cap as the competing PR proposes? Use configured agent cap as the ceiling: Land this PR’s rule: explicit lower caller budgets remain effective, while a higher caller budget cannot exceed the selected agent’s configured cap.

Why: Both open PRs repair the same omission but encode different durable/session request precedence; source establishes the alternatives but not the intended permanent contract.

Before merge

  • Resolve merge risk (P1) - fix: honor selected agent context caps in embedded runs #119277 changes the same budget paths but gives a caller-supplied compaction budget different precedence; merging both would conflict and leave two competing policy interpretations.
  • Resolve merge risk (P1) - The native Codex-owned harness bypass was not independently verified against sibling Codex source, as required by repository policy.
  • Resolve merge risk (P1) - The branch intentionally does not define durable inherited-versus-explicit session-cap provenance during hot reload; [Bug]: Per-agent contextTokens and session status disagree with embedded precheck budget #118678 retains that broader persistence decision.
  • Complete next step (P2) - A maintainer must select the request-budget precedence and one overlapping PR before this otherwise-correct patch can be merged.
Agent review details

Security

None.

PR surface

Source +60, Tests +112. Total +172 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 64 4 +60
Tests 4 114 2 +112
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 178 6 +172

Review metrics

Metric Value Why it matters
Production versus regression coverage production +64/-4; tests +114/-2 The production growth is justified by propagating one existing configuration fact through independent embedded-run, compaction, and safeguard owners.

Merge-risk options

Maintainer options:

  1. Select one precedence rule before merge (recommended)
    Resolve the caller-budget versus per-agent-cap contract and land only one of the overlapping PRs.
  2. Pause for a shared session-budget design
    Hold both PRs if maintainers want inherited persisted-session caps and request-level budgets to be represented by one explicit policy before any change lands.

Technical review

Best possible solution:

Choose one canonical cap-precedence rule, land only its corresponding PR, and keep the broader durable-session provenance behavior tracked separately.

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

Yes: current main visibly omits the selected-agent cap in the embedded model-policy call, and the branch adds an end-to-end regression that distinguishes 200k from the 128k default.

Is this the best way to solve the issue?

Unclear: the propagation repair is coherent, but the competing PR establishes an unresolved request-budget precedence choice that should be decided once rather than merged twice.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 13e30a9d55e6.

Labels

Label justifications:

  • P1: An embedded agent can reject a normal tool-heavy turn below the configured budget and end without a reply.
  • merge-risk: 🚨 session-state: The PR changes budget propagation used by embedded sessions, compaction, and subsequent session metadata.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides a before/after built-distribution embedded-run trace with real model resolution, a real mock transport request, and an observed successful result.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a before/after built-distribution embedded-run trace with real model resolution, a real mock transport request, and an observed successful result.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: History attributes the existing policy call that omitted the cap to the model-setup refactor. (role: embedded-runner model-policy refactor author; confidence: high; commits: 4ea573edd2a6; files: src/agents/embedded-agent-runner/run/model-harness.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-08-07T21:22:56.175Z sha 5790a1d0f10666b42de5ebbf87d0b88f79a3fb63 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-07T22:41:05.312Z sha 5790a1d0f10666b42de5ebbf87d0b88f79a3fb63 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-07T23:37:23.847Z sha 5790a1d0f10666b42de5ebbf87d0b88f79a3fb63 :: needs changes before merge. :: [P2] Name both supported per-agent config paths
  • reviewed 2026-08-08T00:46:45.290Z sha 73fee5fca9a1a4ca19a9199cf4901e69d6c8604e :: needs maintainer review before merge. :: none

@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 author ClawSweeper has contributor-facing work open and is waiting for author action. 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 Aug 7, 2026
@harjothkhara
harjothkhara force-pushed the fix/embedded-per-agent-context-cap branch from 5790a1d to 73fee5f Compare August 7, 2026 23:56
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 8, 2026
@Yigtwxx

Yigtwxx commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

I was scanning the open PR queue for changed-file overlap and this branch matched #119277: the two PRs touch the same 10 files, and both are currently labelled status: 👀 ready for maintainer look.

Neither PR references the other. Both do carry a ClawSweeper Root-cause cluster block, but they were clustered against different canonical issues — this PR against #118678, #119277 against #71136 — and neither cluster lists the other PR as a member. So the overlap is between the two branches, not something either bot comment already covers.

What I compared: added production lines (tests, docs and generated files excluded) at 73fee5fca9a1 (this PR) and 954ebcaca028 (#119277).

this PR #119277
added production lines 64 40
byte-identical added lines 7 7
shared changed files 10 10
opened Aug 7, 20:24Z Aug 4, 16:10Z

Two independent implementations rather than a copy, same as the file-set match suggests. Both add import { resolveAgentConfig } from "../agent-scope.js" to compaction-runtime-context.ts, both add an agentId?: string parameter there, and both feed an agentContextTokens value into the same budget resolution.

Where they diverge is worth one decision rather than two:

They rewrite the same two user-facing strings differently. context-window-guard.ts:158 and :187 are edited by both branches:

  • this PR: `OpenClaw is capped by the agent's contextTokens setting (agents.list[].contextTokens or agents.entries.<id>.contextTokens, else agents.defaults.contextTokens)`
  • fix: honor selected agent context caps in embedded runs #119277: `OpenClaw is capped by an agent contextTokens setting` / Raise that cap for the active agent.

They resolve the agent id from different sources in compact.queued.ts: this PR derives compactionSessionAgentId via resolveSessionAgentIds({ sessionKey, config, agentId }), while #119277 passes the existing runtimePolicyAgentId straight through.

They compute the cap differently. #119277 passes requestedTokenBudget ?? configuredAgentTokenBudget as agentContextTokens and simplifies the trailing Math.min accordingly; this PR passes the resolved per-agent value alone. On a session where a request-level budget is present and the per-agent cap is lower, those two do not reduce to the same number.

Scope of what I checked: file sets, added production lines, and the budget-resolution path on both heads. I did not run either branch's tests, and I have not formed a view on which cap-resolution order is correct.

Since both branches edit the same two message strings and the same budget call, the second to merge will conflict there. Which one lands is your call; the thing to avoid is both landing.

@harjothkhara

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Apply the selected agent contextTokens ceiling to embedded-run prechecks, effective model sizing, compaction, safeguard sizing, and result metadata. Prepared attempts now carry one canonical budget into extension setup instead of re-resolving mutable policy.

Caller-requested compaction budgets remain bounded by both the selected agent cap and the model window. Native model-owned harnesses continue to own their context and compaction policy.

Refs: openclaw#118678

Co-authored-by: harjoth <[email protected]>
@steipete
steipete force-pushed the fix/embedded-per-agent-context-cap branch from 73fee5f to 68d6d3c Compare August 9, 2026 00:11
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 9, 2026
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Exact head: 68d6d3c71a5cf78d45774e9095928d6e2eb6841c.

The maintainer rewrite selects this PR's agent-cap-as-ceiling semantics over #119277, removes duplicate safeguard policy resolution by carrying the prepared attempt budget, and personally verifies the unchanged native Codex ownership boundary against openai/codex commit c2bcb9a26b5bdbdc66c48cf3bc3bb382568e800c. The PR body contains the exact source citations and focused proof.

@clawsweeper

clawsweeper Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 9, 2026
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Exact head: a2146886ac4c50ed2ff91e029dd10a7f2f5af6cc.

The maintainer rewrite selects this PR's agent-cap-as-ceiling semantics over #119277, removes duplicate safeguard policy resolution by carrying the prepared attempt budget, and personally verifies the unchanged native Codex ownership boundary against openai/codex commit c2bcb9a26b5bdbdc66c48cf3bc3bb382568e800c. The only change since the prior request types the compaction test fixture after exact-head CI identified the missing cast; its 40-test shard is green. The PR body contains the exact source citations and focused proof.

@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 9, 2026
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Maintainer evidence and resolved rank-up moves

The batch's maintainer authority selects #120343 as the canonical fix over #119277. A configured per-agent contextTokens value is an operator ceiling: a 500,000-token request with a 200,000-token agent cap resolves to 200,000; a 100,000 request remains 100,000; a smaller model window remains authoritative. #119277's alternative request precedence is therefore not the selected contract. The broader #118678 hot-reload/provenance question remains separate and is not needed to land this bounded repair.

I personally inspected sibling ../codex at commit c2bcb9a26b5bdbdc66c48cf3bc3bb382568e800c before the verdict:

  • codex-rs/protocol/src/openai_models.rs:416-424,463-479 owns model context and automatic-compaction limits.
  • codex-rs/models-manager/src/model_info.rs:25-37 applies context-window and compaction overrides.
  • codex-rs/core/src/session/context_window.rs:23-79 evaluates native context-window pressure and automatic compaction.
  • codex-rs/core/src/session/handlers.rs:444-448 creates the native default turn and CompactTask; codex-rs/core/src/tasks/compact.rs:19-84 executes native manual compaction.
  • codex-rs/app-server-protocol/src/protocol/v2/thread.rs:988-998 defines thread/compact/start with only thread_id; codex-rs/app-server/src/request_processors/thread_processor.rs:1913-1924 loads that thread and submits native Op::Compact.

That contract proves the unchanged nativeModelOwned early return is correct: Codex context and compaction policy remain native-owned. The Codex inspection rank-up move is applied.

No authenticated-provider run was added. This defect is internal prepared-budget ownership, so a cloud request would not prove it more directly than the deterministic embedded boundary. Exact-head coverage asserts the 200,000-token prepared attempt budget, effective model context window, and result.meta.agentMeta.contextTokens; the precedence table covers the agent and model ceilings, and existing overflow-compaction coverage proves the same 200,000 budget reaches recovery compaction. The focused run passed 94 tests, the typed-fixture correction reran its 40-test shard green, all exact-head CI contexts are green, and maintainer autoreview reported no accepted/actionable findings. This batch requires focused owner-boundary proof rather than an external live provider call, so the live-provider rank-up move is intentionally skipped with that reason.

Local proof limitations are recorded rather than hidden: the fresh worktree's E2E setup attempted a stale-dist rebuild without the UI @lit/context workspace dependency, and local check-changed could not allocate a Crabbox/Testbox provider because broker authentication was unavailable. Exact-head hosted CI covered the type, lint, build, and test gates; its first type failure was fixed and the replacement run is fully green.

ClawSweeper's exact-head immutable artifact for a2146886ac4c50ed2ff91e029dd10a7f2f5af6cc reports the patch correct, zero review findings, and security cleared. Its remaining maintainer-choice and rank-up items are resolved above under the explicit batch authority.

@steipete
steipete merged commit af9b872 into openclaw:main Aug 9, 2026
127 checks passed
vincentkoc added a commit that referenced this pull request Aug 9, 2026
Punchcard-Session: amber-workshop-workshop-36

* origin/main:
  fix(agents): apply per-agent contextTokens cap to embedded run context budget (#120343)
  fix(cloud-workers): preserve accepted workspace after SSH loss (#120717)
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Merged via squash after the maintainer rewrite and exact-head proof.

GitHub and the local fetch both verify the landed commit is the current main tip. #119277 remains open for separate orchestrator disposition; no close authority was exercised here.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 9, 2026
…t budget (openclaw#120343)

* fix(agents): honor per-agent context budgets

Apply the selected agent contextTokens ceiling to embedded-run prechecks, effective model sizing, compaction, safeguard sizing, and result metadata. Prepared attempts now carry one canonical budget into extension setup instead of re-resolving mutable policy.

Caller-requested compaction budgets remain bounded by both the selected agent cap and the model window. Native model-owned harnesses continue to own their context and compaction policy.

Refs: openclaw#118678

Co-authored-by: harjoth <[email protected]>

* test(agents): type compaction model fixtures

---------

Co-authored-by: Peter Steinberger <[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 merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants