Skip to content

refactor: let background chat forks reuse the chat's prompt cache - #200545

Merged
obviyus merged 4 commits into
mainfrom
fork-primitive
Nov 17, 2026
Merged

obviyus merged 4 commits into
mainfrom
fork-primitive

Conversation

@obviyus

@obviyus obviyus commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

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:

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

After merge: a fork that runs tools, every request. Same probe on the merge commit (2a7ca163), with a third fork: runForkedTurn granted the probe plugin's own tool (forkprobe_note, declared in its manifest contracts.tools) and told to call it twice, then reply done. The model first called tool_describe on 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 settled done. Request 1 is compared with the parent's last request; each later request with the fork's previous one.

Provider Request History prefix kept System / tools / cache key Input tokens Cache read Cache write
Anthropic parent, last 19,221 18,767 450
Anthropic fork 1 7 / 7 same / same / same 19,548 19,217 (98%) 327
Anthropic fork 2 10 / 10 same / same / same 19,765 19,544 (99%) 219
Anthropic fork 3 12 / 12 same / same / same 19,933 19,763 (99%) 168
Anthropic fork 4 14 / 14 same / same / same 20,101 19,931 (99%) 168
OpenAI parent, last 11,455 11,163
OpenAI fork 1 9 / 9 same / same / same 11,689 11,452 (98%)
OpenAI fork 2 13 / 13 same / same / same 11,873 11,686 (98%)
OpenAI fork 3 16 / 16 same / same / same 11,968 11,870 (99%)
OpenAI fork 4 18 / 18 same / same / same 12,063 11,965 (99%)

The tool-free forks on the merge commit matched again: forkSession read 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 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.

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

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling plugin: file-transfer plugin: skill-workshop size: XL labels Nov 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This 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: [].

  • Before: The supplied Anthropic probe reports zero cached input tokens.
  • After: The supplied probe reports 19,141 cached tokens out of 19,446 input tokens.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Promising consolidation with useful live measurements, but concrete contract regressions and incomplete tools-enabled proof prevent merge readiness.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Background reviews can repay the full conversation cost and stop because unrelated sessions become active.
Reason: The maintainer-authored direction has measured cache benefits and removes duplicate machinery; its explicit budget and scheduling tradeoffs do not need another product approval.

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
Reviewed head: 13b5ffd3e464d50de9bd8bb891b0ddb20e3ec368

Before merge

  • Preserve the current session model for tool-free forks (P1) - After a completed turn on model A, change the session to model B and call forkSession before sending another normal turn. Its new callback invokes this helper without a model override, so turn.model selects A even though the caller already resolved B. Previously forkSession used the current session selection. Preserve that resolved selection for forkSession while retaining anchored-turn model selection for runForkedTurn; otherwise the fork can contact the previous provider and use a different credential selection.
  • Restore pending results before normal fork replay repair (P2) - If forkSession runs while the parent’s exec call is still executing, the copied transcript contains its assistant call without a result. The deleted runEmbeddedSessionFork inserted a non-error 'still running' placeholder, covered by the removed integration and transport tests. This replacement enters normal agent replay without that preparation, where sanitizeToolUseResultPairingForModel synthesizes an error result ('aborted' on Responses). The reviewer therefore receives a false failure and can recommend repeating work that remains active. Preserve the pending-result projection at the unified fork boundary without writing it to the parent.
  • Migrate the benchmark consumer before deleting its helper (P2) - This import still points to tool-result-projection-replay.js, which the PR deletes. The prompt-cache retention test launches this script, and exact-head CI already reports ERR_MODULE_NOT_FOUND at this import. Update the benchmark to the retained projection owner, preserving its copied-state behavior, before removing the module.
  • Explain or restore the original intent of Pending parent tool results - f4f0255: Keep background reviewers from treating still-running calls as aborted and recommending repeated work.

Findings

  • [P1] Preserve the current session model for tool-free forks — src/gateway/server-plugin-forked-turn.ts:215-216
  • [P2] Restore pending results before normal fork replay repair — src/gateway/server-plugin-subagent-runtime.ts:345-346
  • [P2] Migrate the benchmark consumer before deleting its helper — scripts/perf/prompt-cache-observation-measure.ts:36

Provenance

  • Pending parent tool results changes intended behavior without addressing why it exists (f4f0255: Keep background reviewers from treating still-running calls as aborted and recommending repeated work.)

Tests

  • Missing end-to-end proof: Provide a redacted real-provider Gateway trace of runForkedTurn with a granted plugin tool, including its execution and subsequent request cache usage; baseline failure of the replacement regression coverage is also not shown.
Agent review details

How this fits together

Plugin 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]
Loading

Technical review

Best 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:

  • [P1] Preserve the current session model for tool-free forks — src/gateway/server-plugin-forked-turn.ts:215-216
    After a completed turn on model A, change the session to model B and call forkSession before sending another normal turn. Its new callback invokes this helper without a model override, so turn.model selects A even though the caller already resolved B. Previously forkSession used the current session selection. Preserve that resolved selection for forkSession while retaining anchored-turn model selection for runForkedTurn; otherwise the fork can contact the previous provider and use a different credential selection.
    Confidence: 0.98
  • [P2] Restore pending results before normal fork replay repair — src/gateway/server-plugin-subagent-runtime.ts:345-346
    If forkSession runs while the parent’s exec call is still executing, the copied transcript contains its assistant call without a result. The deleted runEmbeddedSessionFork inserted a non-error 'still running' placeholder, covered by the removed integration and transport tests. This replacement enters normal agent replay without that preparation, where sanitizeToolUseResultPairingForModel synthesizes an error result ('aborted' on Responses). The reviewer therefore receives a false failure and can recommend repeating work that remains active. Preserve the pending-result projection at the unified fork boundary without writing it to the parent.
    Confidence: 0.98
  • [P2] Migrate the benchmark consumer before deleting its helper — scripts/perf/prompt-cache-observation-measure.ts:36
    This import still points to tool-result-projection-replay.js, which the PR deletes. The prompt-cache retention test launches this script, and exact-head CI already reports ERR_MODULE_NOT_FOUND at this import. Update the benchmark to the retained projection owner, preserving its copied-state behavior, before removing the module.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Background context, output, timeout, and foreground-yield limits changes intended behavior with a stated reason (9a6c6b1: Protect interactive turns from background reviews competing for saturated provider token budgets.)
  • Lazy fork preparation and persisted-context reconstruction keeps the original intent (cb00966: Avoid preparing fork snapshots on ordinary requests and reconstruct optional forks through existing transcript owners.)
  • Prepared provider request replay keeps the original intent (d2ca84f: Preserve the parent’s actual request bytes when rebuilt history differs in ordering or tool-call ID spelling.)
  • Anthropic fork-suffix cache checkpoints changes intended behavior with a stated reason (83fd655: Avoid paying cache-write premiums for a tool-free fork’s suffix that subsequent requests do not reuse.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/server-plugin-subagent-runtime.fork.test.ts src/gateway/server-plugin-subagent-runtime.fork-transport.test.ts
  • pnpm test src/agents/embedded-agent-runner/session-fork-request.test.ts src/agents/session-fork-run.test.ts
  • pnpm test src/agents/embedded-agent-runner/prompt-cache-request-observer.test.ts
  • pnpm test src/agents/agent-tools.prefix-stability.test.ts
  • Run the Gateway forked-turn E2E suite and verify the changed regressions fail on the base for the intended reasons.

What I checked:

PR surface

Source -391, Tests -1116, Docs -41. Total -1548 across 43 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 29 718 1109 -391
Tests 12 153 1269 -1116
Docs 2 101 142 -41
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 43 972 2520 -1548

Preflight source

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

Review metrics

Metric Value Why it matters
Production versus test LOC Production +718/-1,109; tests +153/-1,269 The net production reduction supports consolidating the duplicate runner, but deleted consumers and a lost replay invariant show that the cutover is incomplete.
Plugin API addition 1 optional parameter: runForkedTurn.maxTokens Adds caller control over output limits; no persisted configuration field is added.

Labels

Label changes:

  • add P2: Useful background-inference cost and reliability work with focused repairs; no current upstream outage is established.
  • add merge-risk: 🚨 compatibility: The existing forkSession API changes implementation and loses its non-error representation of unfinished parent tools.
  • add merge-risk: 🚨 auth-provider: After a session model change, tool-free forks can route to the previous turn’s provider and model.
  • add merge-risk: 🚨 automation: Deleting a still-imported module demonstrably breaks the prompt-cache benchmark subprocess and its CI regression check.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Useful background-inference cost and reliability work with focused repairs; no current upstream outage is established.
  • merge-risk: 🚨 compatibility: The existing forkSession API changes implementation and loses its non-error representation of unfinished parent tools.
  • merge-risk: 🚨 auth-provider: After a session model change, tool-free forks can route to the previous turn’s provider and model.
  • merge-risk: 🚨 automation: Deleting a still-imported module demonstrably breaks the prompt-cache benchmark subprocess and its CI regression check.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

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

Workflow

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

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.
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 17, 2026
@obviyus
obviyus merged commit 2a7ca16 into main Nov 17, 2026
154 checks passed
@obviyus
obviyus deleted the fork-primitive branch November 17, 2026 11:54
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 2a7ca16.

  • Bug: background chat forks (Skill Workshop reviews, runForkedTurn, forkSession) sent a cut-down request with its own prompt and tools, so they never read the chat's provider prompt cache. They were capped at 120 s, 16k context and 2k output, and stopped when any other run started on the Gateway.
  • Fix: one fork owner, runSessionFork. It sends the parent's pinned prompt, tool list and cache key, and gates tool execution at run time. The fork keeps the source chat's history window and shows still-running tool calls as pending. The clamps and the global yield are gone.
  • Proof: live Anthropic and OpenAI probe, where a fork's first request read 98-99% of its input from cache (was 0%). Forked-turn e2e, fork-transport and history-window tests pass. The local review of this exact head was clean, and CI was green.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…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]>
freeqaz added a commit that referenced this pull request Nov 18, 2026
…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
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…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
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…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)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer plugin: skill-workshop rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant