Repository navigation
refactor: let background chat forks reuse the chat's prompt cache - #200545
Conversation
- runSessionFork is the one fork owner; forkSession and runForkedTurn fork through it. - Forks replay the live parent's prepared request, or send the session's pinned system prompt and tool list, with the parent's cache key and thinking level. - Session tools stay listed; toolExecutionAllow gates which run; tool-free forks add tool_choice none. - Removed the #173889 clamps (excerpt, minimal prompt, 16k context, 2k output, low thinking, 120 s cap) and the Gateway-wide yield. - Removed the separate forkSession loop, its btw branch and the transport markers only it produced.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs changes before merge. What this changesThis PR unifies background session forks around the agent runner and reuses the parent conversation’s prompt and tool definitions. Example: A plugin asks a completed chat a background question through runForkedTurn with tools: [].
Review scores
ProductKind: Refactor · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 4 items remain Keep this maintainer-authored PR open: consolidating forks is useful, but model selection, pending-tool replay, and an incomplete consumer migration need repair. Priority: P2 Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherPlugin background requests enter the Gateway adapters, which authorize session access and invoke the fork runner; the runner reads conversation context, sends provider requests, gates tool execution, and returns text and usage without modifying the source transcript. flowchart TD
A[Plugin background request] --> B[Gateway authorization and adapter]
B --> C[Session fork runner]
D[Source transcript and prompt checkpoint] --> C
E[Live prepared provider request] --> C
C --> F[Embedded agent and tool gates]
F --> G[Provider request and response]
G --> H[Plugin result and usage]
Technical reviewBest possible solution: Keep one fork runner while preserving current-session model selection, non-error pending-tool context, and working consumers of the retired modules. Do we have a high-confidence way to reproduce the issue? Source establishes the routing and pending-result regressions, and exact-head CI independently confirms the deleted-import failure; no target code was executed during this review. Is this the best way to solve the issue? Reusing the existing fork runner is a sound simplification, but the shared adapter must preserve the distinct current-session and anchored-turn contracts. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against ae31ea3be6d5. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceAcceptance criteria:
What I checked:
PR surfaceSource -391, Tests -1116, Docs -41. Total -1548 across 43 files. Added test files: 1. View PR surface stats
Preflight sourceSource 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
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 17, 2026, 5:18 AM ET / 10:18 UTC. |
- Anchor a default fork at the last message; the leaf may be the prompt checkpoint. - Resolve the channel history limit from the policy key, so a fork keeps its source's window. - Show a still-running tool call to the fork as pending; a tool-free fork needs no requester. - Drop session-id pins from the live request reader; remove perf scripts for deleted owners.
|
Landed in 2a7ca16.
|
…enclaw#200545) ## What Problem This Solves Background work that reads a chat, such as Skill Workshop's learning review or a plugin reviewer, runs as a hidden "fork" of that chat. Forks that could use tools sent a cut-down request instead of the chat's own, so they paid full price for the whole conversation every time instead of reading it from the provider's prompt cache. They also stopped whenever anything else on the Gateway started (a cron job, a turn in another chat), and a Workshop review was silently cut off after two minutes. ## User Impact - Background reviews and plugin forks read the conversation from the provider's prompt cache. In the live probe below, the first request of a fork with tools read 98% of its input from cache on Anthropic and OpenAI (was 0%); tool-free forks on OpenAI went from 0% to 99%. - A fork keeps running when other chats or cron jobs run. - Skill Workshop reviews run for the agent's own run timeout instead of two minutes. - Reviews now see the full conversation, not a 32 KiB excerpt. ## Why This Change Was Made OpenClaw had two session forks: - `subagent.forkSession` (tool-free, openclaw#170146) replayed the parent's prepared request, so the provider cache hit. It ran its own 3-call model loop beside the agent runner. - `runSessionFork` / `subagent.runForkedTurn` (tools, openclaw#190158, openclaw#190950) built a fresh, cut-down request: a 32 KiB / 64-event excerpt with tool results dropped, `promptMode: "minimal"`, only the caller's tools listed, a 16,384-token context budget, 2,048 output tokens, low thinking, a 120 s ceiling (`Math.min(timeoutMs, 120_000)`), and it aborted whenever any session on the Gateway started a run. Every one of those clamps came from openclaw#173889 (a Skill Workshop rate-limit fix) and moved verbatim into the generic owner. Now there is one fork primitive: `runSessionFork` in `src/agents/session-fork-run.ts`. `forkSession`, `runForkedTurn` and Skill Workshop all fork through it. - **Same request as the parent.** While the parent's run is live, each fork request replays its last prepared request byte for byte and appends the fork's own items (`embedded-agent-runner/session-fork-request.ts`, the replay moved from the old `forkSession` loop). After the run settles, the fork reads the session's `openclaw.system-prompt` checkpoint and its own requests send that pinned system prompt verbatim (no prompt-update delta) and the pinned tool definitions in their order. It also sends the parent's `promptCacheKey` and the session's thinking level. - **Tools listed, gated at run time.** The session's tools stay in the request. Only the caller's tools run, through the existing `toolExecutionAllow` gate; others return "`<tool>` is not available in this background run." A tool-free fork is an empty allow list plus `tool_choice: none` (Anthropic, OpenAI Responses, Chat Completions). - **Clamps deleted:** the context excerpt, `promptMode: "minimal"`, `bootstrapContextMode: "lightweight"`, `contextTokenBudget: 16_384`, `maxTokens: 2_048`, `thinkLevel: "low"`, the narrowed `toolsAllow`, `codeModeOverride`/`disableToolSearch`/`forceMessageTool` overrides, and `Math.min(timeoutMs, 120_000)`. Output tokens follow the session; `runForkedTurn` gains an optional `maxTokens`. - **Global yield deleted.** Runs in other sessions (cron included) no longer stop a fork. No new cancellation code. - **Duplicate path deleted:** `embedded-agent-runner/session-fork.ts`, `session-fork-context.ts`, `tool-result-projection-replay.ts`, `runBtwSessionFork`, the built-in `toolCalls: "deny"` branch in `btw.ts`, the now-unproduced `uncachedSuffixMessage` / `independentResponsesRequest` transport markers, and the two perf scripts that only measured the deleted fork owner (`session-fork-retention-measure.mjs`, `responses-continuation-measure.mjs`). `btw.ts` keeps only harness dispatch for `forkSession`: Codex sessions still run Codex's own tool-free side question; built-in sessions call `runSessionFork`; CLI runtimes stay refused. - **The fork reads the chat as the chat does.** It keeps its source conversation's channel history window (`dmHistoryLimit` and the like): the run resolves the limit from the policy key (`sandboxSessionKey`), which only a fork sets apart from its own key. A fork without an explicit entry anchors at the last message, because the leaf can be the prompt checkpoint. A tool call still running at the anchor reads as pending ("still running"), not failed, and only the unfinished calls of a partly finished batch get that placeholder; the source transcript is never written. Safety checks kept: requester policy before any model call (`prepareSessionFork`), plugins grant only their own tools (openclaw#190950), detached admission and restart drain, plugin authority before each tool call and before `onSettled`, hidden run, never writing the source transcript, source checks for reset/replace/delete/rewrite, locked model with no fallbacks or transient retries. Changed on purpose: - A fork lists every session tool instead of only its own (execution is still gated). - Background forks no longer yield to other sessions' runs. Skill Workshop's 15/30/60-minute rate-limit backoff is unchanged and still protects interactive capacity. - A built-in tool-free fork now writes cache for its own suffix (~300 tokens in the probe below); the old loop opted its question out of Anthropic cache checkpoints. - A tool-free fork whose anchored turn no longer holds its input still runs; a fork with tools still refuses, because sender-specific tool policy needs the turn's requester. Accepted edge case: if a parent's turn crashed after its prompt checkpoint and before any reply, an idle-parent fork cannot see that checkpoint and sends its own rebuilt prompt (no cache hit). A running parent is replayed from its live request, and a completed turn ends with a reply after the checkpoint. Left out on purpose: - Codex `thread/fork` adapter (`extensions/codex/harness.ts:577`): unchanged, still reached through `btw.ts` for Codex-session `forkSession`. - Plain `/btw` with tools (`commands-btw.ts`, `tui/embedded-backend.ts`): unchanged. - CLI runtimes: forks stay refused. ### Plugin SDK impact `plugin-sdk-impact` on ClawHub (2026-11-17, 2,657 eligible releases; 2,235 complete, 420 partial, 2 failed): **0** static references to `runtime.subagent.forkSession` and **0** to `runtime.subagent.runForkedTurn`. Coverage is incomplete, so this is not proof of no use. Bundled callers (source search): Advisor (`forkSession`) and Skill Workshop (`runForkedTurn`). The `forkSession` signature is unchanged; `runForkedTurn` gains an optional `maxTokens`. No export added or removed. ## Evidence **Byte match on real providers.** Tier: source (`ocx src` scratch Gateways, isolated profile). A recording proxy captured every provider request. Each provider: two parent turns (one `ls` tool call), then one `runForkedTurn` (tools `[]`) and one `forkSession` through the plugin runtime. Digests are SHA-256 prefixes of `snapshotProviderPrefix` segments (`scripts/e2e/lib/anthropic-cache/prefix-stability.mts`). OpenAI Responses sends the system prompt as the first input item, so its `system` digest is `null` and the system prompt is checked as history item 0. Anthropic `claude-sonnet-5-5`, parent last request (after run): system `e18e68ef17d925ff`, tools `33603f8641deb7e5` (13), cache key `b8ccb287386e0e54`. The system digest differs between runs (each run uses a new scratch workspace); "same" compares fork and parent within one run. | Fork, first request | Before: system / tools / key / history | Before: cacheRead | After: system / tools / key / history | After: cacheRead / input | |---|---|---|---|---| | `runForkedTurn` | differs / differs (0 tools) / same / 7 of 7 | **0** (cacheWrite 2,810) | same / same / same / 7 of 7 | **19,141** / 19,446 | | `forkSession` | same / same / same / 7 of 7 | 19,141 | same / same / same / 7 of 7 | 19,141 / 19,446 | OpenAI `gpt-5.6-luna`, parent last request: tools `4481fd05f2c1d4c6` (12), cache key `975dd83e68fb404a`. | Fork, first request | Before: tools / key / history | Before: cacheRead | After: tools / key / history | After: cacheRead / input | |---|---|---|---|---| | `runForkedTurn` | differs (0 tools) / same / 0 of 9 | **0** | same / same / 9 of 9 | **11,332** / 11,605 | | `forkSession` | same / same / 9 of 9 | **0** (request dropped `text.verbosity`) | same / same / 9 of 9 | **11,530** / 11,605 | **Tests** (vitest-source): - `gateway-plugin-forked-turn.e2e`: the fork's first request now extends the parent's last request (system, tools, cache key, history) and its other fields (output limit, reasoning, instructions) equal the parent's. The reload-drain case now runs a turn in another session while the fork's model call is held, and the fork still settles `ok`. The mock model calls the plugin's tool through `dispatch_action`, because the fork now lists the session's tool catalog. - `session-fork-request.test.ts`: replay ordering and ID spelling, transport handles, continuation fallback, `tool_choice` per API, replay skip when the parent lacks the fork's tool or lists a hosted tool, caller output limit. - Unchanged assertions: `agent-tools.prefix-stability`, `session-fork-run`, Advisor, Skill Workshop suites. - `server-plugin-subagent-runtime.fork-transport`: a `forkSession` on a Telegram DM with `dmHistoryLimit: 1` and a compacted history sends the session's pinned system prompt, drops history outside the parent's window, and sends nothing for another operator's session. - `session-manager-model-context-limits`: a still-running call in a partly finished batch reads as pending while the finished call keeps its real result, and the source transcript is unchanged. - Contract assertions updated because the contract changed: the e2e "fork sees only the caller's tool" and "system message differs by design" checks; `btw` deny tests now pass `sessionFork`; three Codex WebSocket tests of the deleted fork loop and two tests of the deleted fork context builder are removed. **Size:** 51 files, +1,099 −3,438 (net −2,339). Production +776 −1,990; tests +222 −1,274; docs +101 −174. Co-authored-by: Ayaan Zaidi <[email protected]>
…d PRs (#201113) * test(gateway): update Workshop learning e2e for reviews that fork the session request #200545 made the Workshop review send the session's own request: the full conversation, the session's tool list (skill_workshop sits behind the tool catalog) and the session's output limit. This e2e file still asserted the removed 64 KiB / 2,048-token / skill_workshop-only review request and called skill_workshop directly, so both cases failed on main. Main CI does not run .e2e.test.ts files; only the per-PR changed-test plan selects it. * test(gateway): drop "bounded" from the Workshop rate-limit case title
…d PRs (openclaw#201113) * test(gateway): update Workshop learning e2e for reviews that fork the session request openclaw#200545 made the Workshop review send the session's own request: the full conversation, the session's tool list (skill_workshop sits behind the tool catalog) and the session's output limit. This e2e file still asserted the removed 64 KiB / 2,048-token / skill_workshop-only review request and called skill_workshop directly, so both cases failed on main. Main CI does not run .e2e.test.ts files; only the per-PR changed-test plan selects it. * test(gateway): drop "bounded" from the Workshop rate-limit case title
…00545) Background work that reads a chat, such as Skill Workshop's learning review or a plugin reviewer, runs as a hidden "fork" of that chat. Forks that could use tools sent a cut-down request instead of the chat's own, so they paid full price for the whole conversation every time instead of reading it from the provider's prompt cache. They also stopped whenever anything else on the Gateway started (a cron job, a turn in another chat), and a Workshop review was silently cut off after two minutes. - Background reviews and plugin forks read the conversation from the provider's prompt cache. In the live probe below, the first request of a fork with tools read 98% of its input from cache on Anthropic and OpenAI (was 0%); tool-free forks on OpenAI went from 0% to 99%. - A fork keeps running when other chats or cron jobs run. - Skill Workshop reviews run for the agent's own run timeout instead of two minutes. - Reviews now see the full conversation, not a 32 KiB excerpt. OpenClaw had two session forks: - `subagent.forkSession` (tool-free, #170146) replayed the parent's prepared request, so the provider cache hit. It ran its own 3-call model loop beside the agent runner. - `runSessionFork` / `subagent.runForkedTurn` (tools, #190158, #190950) built a fresh, cut-down request: a 32 KiB / 64-event excerpt with tool results dropped, `promptMode: "minimal"`, only the caller's tools listed, a 16,384-token context budget, 2,048 output tokens, low thinking, a 120 s ceiling (`Math.min(timeoutMs, 120_000)`), and it aborted whenever any session on the Gateway started a run. Every one of those clamps came from #173889 (a Skill Workshop rate-limit fix) and moved verbatim into the generic owner. Now there is one fork primitive: `runSessionFork` in `src/agents/session-fork-run.ts`. `forkSession`, `runForkedTurn` and Skill Workshop all fork through it. - **Same request as the parent.** While the parent's run is live, each fork request replays its last prepared request byte for byte and appends the fork's own items (`embedded-agent-runner/session-fork-request.ts`, the replay moved from the old `forkSession` loop). After the run settles, the fork reads the session's `openclaw.system-prompt` checkpoint and its own requests send that pinned system prompt verbatim (no prompt-update delta) and the pinned tool definitions in their order. It also sends the parent's `promptCacheKey` and the session's thinking level. - **Tools listed, gated at run time.** The session's tools stay in the request. Only the caller's tools run, through the existing `toolExecutionAllow` gate; others return "`<tool>` is not available in this background run." A tool-free fork is an empty allow list plus `tool_choice: none` (Anthropic, OpenAI Responses, Chat Completions). - **Clamps deleted:** the context excerpt, `promptMode: "minimal"`, `bootstrapContextMode: "lightweight"`, `contextTokenBudget: 16_384`, `maxTokens: 2_048`, `thinkLevel: "low"`, the narrowed `toolsAllow`, `codeModeOverride`/`disableToolSearch`/`forceMessageTool` overrides, and `Math.min(timeoutMs, 120_000)`. Output tokens follow the session; `runForkedTurn` gains an optional `maxTokens`. - **Global yield deleted.** Runs in other sessions (cron included) no longer stop a fork. No new cancellation code. - **Duplicate path deleted:** `embedded-agent-runner/session-fork.ts`, `session-fork-context.ts`, `tool-result-projection-replay.ts`, `runBtwSessionFork`, the built-in `toolCalls: "deny"` branch in `btw.ts`, the now-unproduced `uncachedSuffixMessage` / `independentResponsesRequest` transport markers, and the two perf scripts that only measured the deleted fork owner (`session-fork-retention-measure.mjs`, `responses-continuation-measure.mjs`). `btw.ts` keeps only harness dispatch for `forkSession`: Codex sessions still run Codex's own tool-free side question; built-in sessions call `runSessionFork`; CLI runtimes stay refused. - **The fork reads the chat as the chat does.** It keeps its source conversation's channel history window (`dmHistoryLimit` and the like): the run resolves the limit from the policy key (`sandboxSessionKey`), which only a fork sets apart from its own key. A fork without an explicit entry anchors at the last message, because the leaf can be the prompt checkpoint. A tool call still running at the anchor reads as pending ("still running"), not failed, and only the unfinished calls of a partly finished batch get that placeholder; the source transcript is never written. Safety checks kept: requester policy before any model call (`prepareSessionFork`), plugins grant only their own tools (#190950), detached admission and restart drain, plugin authority before each tool call and before `onSettled`, hidden run, never writing the source transcript, source checks for reset/replace/delete/rewrite, locked model with no fallbacks or transient retries. Changed on purpose: - A fork lists every session tool instead of only its own (execution is still gated). - Background forks no longer yield to other sessions' runs. Skill Workshop's 15/30/60-minute rate-limit backoff is unchanged and still protects interactive capacity. - A built-in tool-free fork now writes cache for its own suffix (~300 tokens in the probe below); the old loop opted its question out of Anthropic cache checkpoints. - A tool-free fork whose anchored turn no longer holds its input still runs; a fork with tools still refuses, because sender-specific tool policy needs the turn's requester. Accepted edge case: if a parent's turn crashed after its prompt checkpoint and before any reply, an idle-parent fork cannot see that checkpoint and sends its own rebuilt prompt (no cache hit). A running parent is replayed from its live request, and a completed turn ends with a reply after the checkpoint. Left out on purpose: - Codex `thread/fork` adapter (`extensions/codex/harness.ts:577`): unchanged, still reached through `btw.ts` for Codex-session `forkSession`. - Plain `/btw` with tools (`commands-btw.ts`, `tui/embedded-backend.ts`): unchanged. - CLI runtimes: forks stay refused. `plugin-sdk-impact` on ClawHub (2026-11-17, 2,657 eligible releases; 2,235 complete, 420 partial, 2 failed): **0** static references to `runtime.subagent.forkSession` and **0** to `runtime.subagent.runForkedTurn`. Coverage is incomplete, so this is not proof of no use. Bundled callers (source search): Advisor (`forkSession`) and Skill Workshop (`runForkedTurn`). The `forkSession` signature is unchanged; `runForkedTurn` gains an optional `maxTokens`. No export added or removed. **Byte match on real providers.** Tier: source (`ocx src` scratch Gateways, isolated profile). A recording proxy captured every provider request. Each provider: two parent turns (one `ls` tool call), then one `runForkedTurn` (tools `[]`) and one `forkSession` through the plugin runtime. Digests are SHA-256 prefixes of `snapshotProviderPrefix` segments (`scripts/e2e/lib/anthropic-cache/prefix-stability.mts`). OpenAI Responses sends the system prompt as the first input item, so its `system` digest is `null` and the system prompt is checked as history item 0. Anthropic `claude-sonnet-5-5`, parent last request (after run): system `e18e68ef17d925ff`, tools `33603f8641deb7e5` (13), cache key `b8ccb287386e0e54`. The system digest differs between runs (each run uses a new scratch workspace); "same" compares fork and parent within one run. | Fork, first request | Before: system / tools / key / history | Before: cacheRead | After: system / tools / key / history | After: cacheRead / input | |---|---|---|---|---| | `runForkedTurn` | differs / differs (0 tools) / same / 7 of 7 | **0** (cacheWrite 2,810) | same / same / same / 7 of 7 | **19,141** / 19,446 | | `forkSession` | same / same / same / 7 of 7 | 19,141 | same / same / same / 7 of 7 | 19,141 / 19,446 | OpenAI `gpt-5.6-luna`, parent last request: tools `4481fd05f2c1d4c6` (12), cache key `975dd83e68fb404a`. | Fork, first request | Before: tools / key / history | Before: cacheRead | After: tools / key / history | After: cacheRead / input | |---|---|---|---|---| | `runForkedTurn` | differs (0 tools) / same / 0 of 9 | **0** | same / same / 9 of 9 | **11,332** / 11,605 | | `forkSession` | same / same / 9 of 9 | **0** (request dropped `text.verbosity`) | same / same / 9 of 9 | **11,530** / 11,605 | **Tests** (vitest-source): - `gateway-plugin-forked-turn.e2e`: the fork's first request now extends the parent's last request (system, tools, cache key, history) and its other fields (output limit, reasoning, instructions) equal the parent's. The reload-drain case now runs a turn in another session while the fork's model call is held, and the fork still settles `ok`. The mock model calls the plugin's tool through `dispatch_action`, because the fork now lists the session's tool catalog. - `session-fork-request.test.ts`: replay ordering and ID spelling, transport handles, continuation fallback, `tool_choice` per API, replay skip when the parent lacks the fork's tool or lists a hosted tool, caller output limit. - Unchanged assertions: `agent-tools.prefix-stability`, `session-fork-run`, Advisor, Skill Workshop suites. - `server-plugin-subagent-runtime.fork-transport`: a `forkSession` on a Telegram DM with `dmHistoryLimit: 1` and a compacted history sends the session's pinned system prompt, drops history outside the parent's window, and sends nothing for another operator's session. - `session-manager-model-context-limits`: a still-running call in a partly finished batch reads as pending while the finished call keeps its real result, and the source transcript is unchanged. - Contract assertions updated because the contract changed: the e2e "fork sees only the caller's tool" and "system message differs by design" checks; `btw` deny tests now pass `sessionFork`; three Codex WebSocket tests of the deleted fork loop and two tests of the deleted fork context builder are removed. **Size:** 51 files, +1,099 −3,438 (net −2,339). Production +776 −1,990; tests +222 −1,274; docs +101 −174. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 2a7ca16) Release adaptation: preserve the baseline removal of the session identity allowlist; the remaining fork owner and callers apply unchanged. Follow-up disposition: source bounded owner history reviewed; focused prefix and fork proof required on this lane. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit f080b30127abe414dbf9a4fbe0be2b550139fa10)
Release adaptation: use the existing nonfollowing directory walker and avoid the link helper shadow. Give synthetic report E2E fixtures their own no-build setup, explicitly select plugin files when testing nested file-backed config, and retire the database inventory entry for the session-fork suite removed by #200545. No runtime policy, build requirement, or production test budget is weakened. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit e5fb56e7d99c2232171dca3ee40319712e535770)
What Problem This Solves
Background work that reads a chat, such as Skill Workshop's learning review or a plugin reviewer, runs as a hidden "fork" of that chat. Forks that could use tools sent a cut-down request instead of the chat's own, so they paid full price for the whole conversation every time instead of reading it from the provider's prompt cache. They also stopped whenever anything else on the Gateway started (a cron job, a turn in another chat), and a Workshop review was silently cut off after two minutes.
User Impact
Why This Change Was Made
OpenClaw had two session forks:
subagent.forkSession(tool-free, feat(plugins): fork a session's live context for background side questions #170146) replayed the parent's prepared request, so the provider cache hit. It ran its own 3-call model loop beside the agent runner.runSessionFork/subagent.runForkedTurn(tools, refactor(agents): run background session work as a fork of the stored session #190158, feat(plugins): plugins can run a hidden forked turn of a session with their own tools #190950) built a fresh, cut-down request: a 32 KiB / 64-event excerpt with tool results dropped,promptMode: "minimal", only the caller's tools listed, a 16,384-token context budget, 2,048 output tokens, low thinking, a 120 s ceiling (Math.min(timeoutMs, 120_000)), and it aborted whenever any session on the Gateway started a run.Every one of those clamps came from #173889 (a Skill Workshop rate-limit fix) and moved verbatim into the generic owner.
Now there is one fork primitive:
runSessionForkinsrc/agents/session-fork-run.ts.forkSession,runForkedTurnand Skill Workshop all fork through it.embedded-agent-runner/session-fork-request.ts, the replay moved from the oldforkSessionloop). After the run settles, the fork reads the session'sopenclaw.system-promptcheckpoint and its own requests send that pinned system prompt verbatim (no prompt-update delta) and the pinned tool definitions in their order. It also sends the parent'spromptCacheKeyand the session's thinking level.toolExecutionAllowgate; others return "<tool>is not available in this background run." A tool-free fork is an empty allow list plustool_choice: none(Anthropic, OpenAI Responses, Chat Completions).promptMode: "minimal",bootstrapContextMode: "lightweight",contextTokenBudget: 16_384,maxTokens: 2_048,thinkLevel: "low", the narrowedtoolsAllow,codeModeOverride/disableToolSearch/forceMessageTooloverrides, andMath.min(timeoutMs, 120_000). Output tokens follow the session;runForkedTurngains an optionalmaxTokens.embedded-agent-runner/session-fork.ts,session-fork-context.ts,tool-result-projection-replay.ts,runBtwSessionFork, the built-intoolCalls: "deny"branch inbtw.ts, the now-unproduceduncachedSuffixMessage/independentResponsesRequesttransport markers, and the two perf scripts that only measured the deleted fork owner (session-fork-retention-measure.mjs,responses-continuation-measure.mjs).btw.tskeeps only harness dispatch forforkSession: Codex sessions still run Codex's own tool-free side question; built-in sessions callrunSessionFork; CLI runtimes stay refused.dmHistoryLimitand the like): the run resolves the limit from the policy key (sandboxSessionKey), which only a fork sets apart from its own key. A fork without an explicit entry anchors at the last message, because the leaf can be the prompt checkpoint. A tool call still running at the anchor reads as pending ("still running"), not failed, and only the unfinished calls of a partly finished batch get that placeholder; the source transcript is never written.Safety checks kept: requester policy before any model call (
prepareSessionFork), plugins grant only their own tools (#190950), detached admission and restart drain, plugin authority before each tool call and beforeonSettled, hidden run, never writing the source transcript, source checks for reset/replace/delete/rewrite, locked model with no fallbacks or transient retries.Changed on purpose:
Accepted edge case: if a parent's turn crashed after its prompt checkpoint and before any reply, an idle-parent fork cannot see that checkpoint and sends its own rebuilt prompt (no cache hit). A running parent is replayed from its live request, and a completed turn ends with a reply after the checkpoint.
Left out on purpose:
thread/forkadapter (extensions/codex/harness.ts:577): unchanged, still reached throughbtw.tsfor Codex-sessionforkSession./btwwith tools (commands-btw.ts,tui/embedded-backend.ts): unchanged.Plugin SDK impact
plugin-sdk-impacton ClawHub (2026-11-17, 2,657 eligible releases; 2,235 complete, 420 partial, 2 failed): 0 static references toruntime.subagent.forkSessionand 0 toruntime.subagent.runForkedTurn. Coverage is incomplete, so this is not proof of no use. Bundled callers (source search): Advisor (forkSession) and Skill Workshop (runForkedTurn). TheforkSessionsignature is unchanged;runForkedTurngains an optionalmaxTokens. No export added or removed.Evidence
Byte match on real providers. Tier: source (
ocx srcscratch Gateways, isolated profile). A recording proxy captured every provider request. Each provider: two parent turns (onelstool call), then onerunForkedTurn(tools[]) and oneforkSessionthrough the plugin runtime. Digests are SHA-256 prefixes ofsnapshotProviderPrefixsegments (scripts/e2e/lib/anthropic-cache/prefix-stability.mts). OpenAI Responses sends the system prompt as the first input item, so itssystemdigest isnulland the system prompt is checked as history item 0.Anthropic
claude-sonnet-5-5, parent last request (after run): systeme18e68ef17d925ff, tools33603f8641deb7e5(13), cache keyb8ccb287386e0e54. The system digest differs between runs (each run uses a new scratch workspace); "same" compares fork and parent within one run.runForkedTurnforkSessionOpenAI
gpt-5.6-luna, parent last request: tools4481fd05f2c1d4c6(12), cache key975dd83e68fb404a.runForkedTurnforkSessiontext.verbosity)After merge: a fork that runs tools, every request. Same probe on the merge commit (
2a7ca163), with a third fork:runForkedTurngranted the probe plugin's own tool (forkprobe_note, declared in its manifestcontracts.tools) and told to call it twice, then replydone. The model first calledtool_describeon that tool (plugin tool schemas are deferred), then called it twice; both results (noted: one,noted: two) appear in requests 3 and 4, and both forks settleddone. Request 1 is compared with the parent's last request; each later request with the fork's previous one.The tool-free forks on the merge commit matched again:
forkSessionread 19,518 of 19,522 input tokens from cache on Anthropic and 11,599 of 11,674 on OpenAI.Tests (vitest-source):
gateway-plugin-forked-turn.e2e: the fork's first request now extends the parent's last request (system, tools, cache key, history) and its other fields (output limit, reasoning, instructions) equal the parent's. The reload-drain case now runs a turn in another session while the fork's model call is held, and the fork still settlesok. The mock model calls the plugin's tool throughdispatch_action, because the fork now lists the session's tool catalog.session-fork-request.test.ts: replay ordering and ID spelling, transport handles, continuation fallback,tool_choiceper API, replay skip when the parent lacks the fork's tool or lists a hosted tool, caller output limit.agent-tools.prefix-stability,session-fork-run, Advisor, Skill Workshop suites.server-plugin-subagent-runtime.fork-transport: aforkSessionon a Telegram DM withdmHistoryLimit: 1and a compacted history sends the session's pinned system prompt, drops history outside the parent's window, and sends nothing for another operator's session.session-manager-model-context-limits: a still-running call in a partly finished batch reads as pending while the finished call keeps its real result, and the source transcript is unchanged.btwdeny tests now passsessionFork; three Codex WebSocket tests of the deleted fork loop and two tests of the deleted fork context builder are removed.Size: 51 files, +1,099 −3,438 (net −2,339). Production +776 −1,990; tests +222 −1,274; docs +101 −174.