Repository navigation
refactor(agents): run background session work as a fork of the stored session - #190158
Conversation
|
🦞👀 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 maintainer review before merge. What this changesThis PR moves background Workshop execution into a shared session-fork runner that carries requester identity and reads stored session context. Example: Sender 42 queues a Workshop review before an operator denies skill_workshop for id:42.
Review scores
ProductKind: Refactor · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR remains useful, and the latest commit resolves the earlier settlement-lifetime finding; no additional production defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherCompleted agent turns schedule background reviews; the fork runner reads bounded transcript context, applies requester policy and source fences, runs the embedded agent, and retains admission through Workshop notification settlement. flowchart TD
A[Completed foreground turn] --> B[Workshop scheduler]
B --> C[Requester policy preparation]
C --> D[Session fork runner]
E[Stored session and transcript] --> D
D --> F[Embedded agent and Workshop tool]
F --> G[Change feed and Learned notice]
Technical reviewBest possible solution: Keep the shared fork owner and admitted settlement callback, then complete the required current-head CI gate. Do we have a high-confidence way to reproduce the issue? This is a behavior-preserving refactor; the supplied Gateway regressions cover its requester-policy and settlement invariants, and no target code was executed during review. Is this the best way to solve the issue? The extraction gives generic background execution one owner, removes the replaced Workshop runner and parameter, and preserves Workshop-specific scheduling and notification decisions. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c3fca6737b29. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +131, Tests +160, Docs +1, Other -1. Total +291 across 24 files. Added test files: 1. View PR surface stats
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 HistoryReview history (3 earlier review cycles)
Reviewed November 1, 2026, 6:28 AM ET / 11:28 UTC (Revision 4). |
184d20b to
343309a
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Maintainer override (approved by @obviyus): land past the unrelated
|
|
Landed in 22c1060 (maintainer override for the unrelated
|
… session (openclaw#190158) ## Problem Skill Workshop is moving from core into the bundled `skill-workshop` plugin. Its background review cannot move as it is: - The generic machinery (source-session fences, detached admission, hidden run, locked model, yielding to foreground work) lives inside Workshop files. - The review replays the finished turn's whole run context (`foregroundPromptContext`, including live per-turn capabilities) into the background run, although it uses only the turn's identity and policy facts. - The runner carries a Workshop-only `skillWorkshopReviewOf` parameter and a Workshop-only lane. ## Fix - **New core owner `src/agents/session-fork-run.ts`:** a background agent run over a bounded copy of one session's conversation, through one completed transcript entry. - `prepareSessionFork` refuses before any model call unless every fork tool passes current policy, and returns the session's durable workspace. - `runSessionFork` owns the fences, detached admission, hidden run registration, locked model, yielding to foreground work and the usage diagnostic. The code moved verbatim from Workshop. The caller's settlement (Workshop: change feed and Learned notice) runs inside the same detached admission, so a graceful restart waits for it, as before. - **Run context:** agent dir, sandbox key and delivery channel come from the stored session. The turn's requester identity (sender, owner flag, group, channel; `src/agents/session-fork-requester.ts`) is carried explicitly, because the session never records who sent a turn. Both admission and the run re-resolve policy for that requester against the current config, so a sender-specific revocation made while a review is queued stops it before any provider call. - Forks mark themselves through the existing `inputProvenance` field (`internal_system`, `sourceTool: "session_fork"`, `sourceSessionKey`). Tools and model-call urgency read that instead of `skillWorkshopReviewOf`, so tool contexts get no new field. - **Workshop review** keeps only its own decisions: eligibility, prompt, the feature switch, the change feed and the Learned notice. It receives only the requester projection of the turn context, never its live capabilities. `review-run.ts` is deleted. - **Removed:** `skillWorkshopReviewOf`. - **Lane:** `getSkillWorkshopReviewLane` becomes `getBackgroundOwnerLane(owner)`. Workshop's lane name is unchanged (`background:core:skill-workshop`). - **Docs:** the harness side-effects page now says what the turn context is used for (it also drops a stale prompt-cache claim). No schema, protocol or stored-data change. No new SDK exports, and harnesses change nothing. The plugin-facing `subagent.forkSession` additions ship with the plugin cutover that uses them. ## Impact - One core owner serves background session work; Workshop becomes its first user. - No intended behavior change: the review runs with the same requester policy as before, re-checked against current config. ## Evidence All end-to-end cases below run a real Gateway with real embedded foreground turns, a fixture model provider, and config changes through `config.patch`. | Check | Result | | --- | --- | | E2E: a sender-42 channel ingress turn (`agentCommandFromIngress`) queues a review; `tools.toolsBySender["id:42"].deny = ["skill_workshop"]` is added before it runs → no review model call, no change, skill file unchanged. The allowed counterpart learns normally | pass; the revoked case fails when the requester is not carried | | E2E turn gate: `tools.deny: ["skill_workshop"]` during the turn, lifted before the review → nothing queued (trace: the turn's `toolNames` lacks the tool) | pass | | E2E fork gate: the turn could call the tool; it is denied before the queued review runs → no review model call, no change (trace: fork policy check refuses) | pass | | E2E: the channel notice send is held open after the skill change commits and the model run ends → Gateway root work stays active (a graceful restart waits); it drains after the send settles. Unit counterpart holds the notice callback | pass; both fail when settlement runs outside the admission | | Unit: the source group's policy (from the session key) and wildcard sender rules refuse a fork (`session-fork-run.test.ts`) | pass | | Existing review suites: yield to foreground work; source fences for permission, reset, replacement, deletion, rewrite, membership and rewind; canonical worktree workspace; cleanup after failure; grouped notices and undo; channel notice with Undo; propose mode | pass | | `gateway-workshop-learning.e2e` (bounded request, `skill_workshop`-only tool list, patch and announce) | pass | | All `*.workshop-contract` suites (existing cases unchanged; four new cases added) | pass | | `pnpm check:changed` | pass, except the production dead-export scan, which flags `allowProviderModels` and `materializeSessionRepositoryWorkspaceOnGateway` in files this PR does not touch | | Touched suites in total | 28 files, 311 tests pass | | `git diff --check` | pass | One test was deleted: it asserted the review saw the foreground turn's tool schemas, which the review stopped doing when it began limiting the model to `skill_workshop`. Co-authored-by: Ayaan Zaidi <[email protected]>
…00545) ## 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, #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 `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]>
…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]>
…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)
Problem
Skill Workshop is moving from core into the bundled
skill-workshopplugin. Its background review cannot move as it is:foregroundPromptContext, including live per-turn capabilities) into the background run, although it uses only the turn's identity and policy facts.skillWorkshopReviewOfparameter and a Workshop-only lane.Fix
src/agents/session-fork-run.ts: a background agent run over a bounded copy of one session's conversation, through one completed transcript entry.prepareSessionForkrefuses before any model call unless every fork tool passes current policy, and returns the session's durable workspace.runSessionForkowns the fences, detached admission, hidden run registration, locked model, yielding to foreground work and the usage diagnostic. The code moved verbatim from Workshop. The caller's settlement (Workshop: change feed and Learned notice) runs inside the same detached admission, so a graceful restart waits for it, as before.src/agents/session-fork-requester.ts) is carried explicitly, because the session never records who sent a turn. Both admission and the run re-resolve policy for that requester against the current config, so a sender-specific revocation made while a review is queued stops it before any provider call.inputProvenancefield (internal_system,sourceTool: "session_fork",sourceSessionKey). Tools and model-call urgency read that instead ofskillWorkshopReviewOf, so tool contexts get no new field.review-run.tsis deleted.skillWorkshopReviewOf.getSkillWorkshopReviewLanebecomesgetBackgroundOwnerLane(owner). Workshop's lane name is unchanged (background:core:skill-workshop).No schema, protocol or stored-data change. No new SDK exports, and harnesses change nothing. The plugin-facing
subagent.forkSessionadditions ship with the plugin cutover that uses them.Impact
Evidence
All end-to-end cases below run a real Gateway with real embedded foreground turns, a fixture model provider, and config changes through
config.patch.agentCommandFromIngress) queues a review;tools.toolsBySender["id:42"].deny = ["skill_workshop"]is added before it runs → no review model call, no change, skill file unchanged. The allowed counterpart learns normallytools.deny: ["skill_workshop"]during the turn, lifted before the review → nothing queued (trace: the turn'stoolNameslacks the tool)session-fork-run.test.ts)gateway-workshop-learning.e2e(bounded request,skill_workshop-only tool list, patch and announce)*.workshop-contractsuites (existing cases unchanged; four new cases added)pnpm check:changedallowProviderModelsandmaterializeSessionRepositoryWorkspaceOnGatewayin files this PR does not touchgit diff --checkOne test was deleted: it asserted the review saw the foreground turn's tool schemas, which the review stopped doing when it began limiting the model to
skill_workshop.