Skip to content

feat(plugins): fork a session's live context for background side questions - #170146

Merged
obviyus merged 18 commits into
mainfrom
feat/plugin-session-fork
Oct 13, 2026
Merged

obviyus merged 18 commits into
mainfrom
feat/plugin-session-fork

Conversation

@obviyus

@obviyus obviyus commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #169564 (Advisor, the first consumer)

What Problem This Solves

Plugins that review or summarize an ongoing conversation in the background can only see what they rebuild themselves: a bounded excerpt sent through api.runtime.subagent.complete. That loses detail and costs a fresh, uncached prompt every time. In a real-API evaluation, an excerpt-based reviewer produced 2 false corrections in 5 runs (it misread polled background commands as extra launches), while a review that saw the session's full context was correct in all 5.

Fix

Adds api.runtime.subagent.forkSession({ sessionKey, message, signal?, timeoutMs? }). It asks one question against an ephemeral fork of the session's current context and returns { text, usage }. It works mid-run, at agent_end, and after the parent turn has finished.

  • Same prefix, warm cache. The fork reuses the parent's exact request prefix, so the provider prompt cache hits:
    • Codex runtime: ephemeral thread/fork on the parent's own app-server client, replaying the parent's recorded developer instructions, private persona/skills context, tool surface and turn settings. The parent's last tool declarations are kept in a bounded in-memory LRU (32 MiB global) and restored into the fork request byte for byte. When the parent used a WebSocket continuation (previous_response_id), history comes from native Codex reconstruction; no response output is buffered or rebuilt.
    • Built-in runtime: the embedded runner records the exact request it sent at the model-call boundary (bounded, in memory, cleared with session cleanup) and replays it with one appended user message through the same stream function and payload hooks. Anthropic cache breakpoints and the OpenAI prompt_cache_key stay where they were. The parent's one-shot continuation onPayload callback is not replayed.
  • No tool execution. Tool definitions stay byte-identical, but every call is denied:
    • dynamic and native Codex tools are denied at dispatch (this also fixes a fail-open path: the native hook relay dropped PreToolUse when no global hook was installed);
    • hosted tools: tool_choice: "none" on OpenAI and { type: "none" } on Anthropic for every fork request; unsupported APIs fail before dispatch;
    • Codex native web_search stays disabled. Its web.run declaration is still sent (copied from the parent), so the cache prefix matches but nothing can execute it.
  • No side effects. Nothing is written to the transcript, delivered, counted as a turn, or drained from queued next-turn context.
  • Authority. Same background admission as subagent.complete (plugin lifetime, cancellation, revalidation after awaits), plus the conversation-access grant, sessions.get session visibility, and live Gateway caller authority. These are checked right before every physical send through the guarded-fetch request authority, including DNS/proxy setup, retries and redirects; native ChatGPT WebSocket and SSE sends check them through the existing Responses request lifecycle. Ordinary parent settlement and usage updates (including a briefly unmaterialized session row) do not revoke a fork. A session reset or deletion, a replaced Codex client or thread, withdrawn conversation access, or a retired plugin still revokes it.
  • Same network policy as the parent. Built-in replay takes the current proxy, TLS and local-service settings (including the local-service reconciler) from the existing transport owner, not from the snapshot. Native ChatGPT forks open their own transient WebSocket and never change the parent's socket, continuation or SSE fallback state.
  • Supported APIs. OpenAI Completions, OpenAI Responses (including native ChatGPT), Anthropic Messages, and Codex. APIs whose sends the fork cannot fence (for example Bedrock) fail closed before dispatch with Session forks do not support provider API <api>.
  • Runtimes. CLI runtimes (for example claude-cli) have no prepared context to fork, so a fork fails closed before any CLI or provider I/O. Ordinary /btw on CLI is unchanged.
  • Concurrency. Forks run on the same subagent lane as subagent.complete (CommandLane.Subagent), so agents.defaults.subagents.maxConcurrent caps both together.
  • Fails closed with an actionable error when no parent request was prepared by this runtime (for example after a Gateway restart).
  • Fixes forked-turn usage reporting on Codex (forks only emit thread/tokenUsage/updated) and admits forked requests through the private inference proxy.

Ordinary /btw is unchanged from main. An earlier revision rejected /btw when tools were present, and rejected CLI backends with nativeToolMode: "none" and no sideQuestionToolMode; both are restored, and CLI admission stays with prepareCliRunContext (this answers the review note about #70413). The provider-review continuation callback from #155214 is not replayed by forks.

User Impact

None by default: no core feature calls forkSession yet. Plugins that opt in get full-context side questions at cached-input prices.

Evidence

Live, real provider APIs, isolated Gateway at the PR head, a throwaway plugin that calls forkSession from its service scheduler on each agent_end: one fork immediately (parent still settling), then two forks 8 s later (summary, plus a "use web search now" bait). Each parent turn makes 3 tool calls.

Runtime / provider Parent last input Fork at agent_end: cache read Late fork: cache read Search bait
Codex, OpenAI (API key, WebSocket continuation) ~19.7k 19,642 19,967, cacheWrite 0 NO_SEARCH
Built-in, OpenAI gpt-5.6-luna — 15,660 (input 566) 15,660 (input 608) NO_SEARCH
Built-in, Anthropic claude-sonnet-5-5 — 19,595 (input 73) 19,595 (input 73) NO_SEARCH
  • Codex wire check: the fork's additional_tools item (51,233 bytes) has the same SHA-256 as the parent's, and prompt_cache_key matches. Before this fix, the late fork read 0 cached tokens because disabling web_search removed web.run from the exec catalog (10,831 bytes).
  • Before the admission fix, a fork started at agent_end failed with agent harness host capability is no longer active: the session-read fence required a fully materialized row while the parent was settling.
  • Ordinary Codex /btw on the same session: I ran echo one, then echo two, then echo three.

Not proven against a real provider: the session-visibility rejection needs an identified Gateway client, and the live probe plugin runs as a service with no caller identity. The composed test below covers it against a real local HTTP provider.

Tests (regressions fail before their fix):

  • byte identity of the replayed request through the real transport seam (OpenAI Completions, OpenAI Responses, Anthropic);
  • Codex tool-declaration parity after continuation, and child previous_response_id cleared on full-prefix replay;
  • tool denial for dynamic, native and hosted tools with no global hooks installed;
  • fork admission during parent settlement and row rematerialization; revocation on reset, deletion, lifecycle replacement, access withdrawal and visibility change;
  • authority withdrawal during preparation, during guarded DNS/proxy setup (no request leaves), during native WebSocket acquisition (no response.create), and before an SSE redirect hop (redirect body not sent); rejection of callers outside session visibility;
  • current explicit-proxy and TLS policy and the local-service reconciler applied to the replay; native fork failures leave the parent's socket and SSE fallback state unchanged; Bedrock rejected before dispatch;
  • a deny fork on a claude-cli session is rejected with no CLI spawn or provider call; with maxConcurrent: 1, three forks run one at a time and wait while a completion holds the lane;
  • composed visibility proof: an identified caller outside session visibility gets Session not found with zero requests at a real local provider server (real guarded-fetch transport, no inference mock); the session owner reaches it and gets the prepared-context answer;
  • ordinary CLI /btw with nativeToolMode: "none" and no sideQuestionToolMode works as on main;
  • fork usage from thread token updates, real inference-proxy owner admission, parent→fork on the parent's exact client, snapshot release on committed session reset, and the restart fail-closed path.

Separate observation, not changed here: with an explicit multi-agent config, /btw on the system agent fails with prepared model runtime owner was not published unless agents.entries.main.workspace is set. The published owner uses the startup workspace (/…/workspace), but /btw asks for /…/workspace/main.

@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Adds a plugin API for tool-denied background questions using a session’s prepared context and prompt-cache prefix.

Example: A plugin calls forkSession for agent:research:fork-parent with the message “Review the current work”.

  • Before: The plugin must reconstruct an excerpt for an independent background completion.
  • After: The plugin receives an answer and usage from an ephemeral context fork without changing the parent transcript.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, correct, and exercised end to end, with substantial cross-runtime replay code supported by focused authorization and transport coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied isolated-Gateway provider results exercise immediate and delayed forks, cache reuse, search denial, and ordinary Codex side questions; inspected production-path scenarios cover allowed versus forbidden session readers and revocation before physical HTTP, redirect, and WebSocket sends.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Background plugins lose conversation detail and prompt-cache reuse when they rebuild excerpts for independent completions.
Reason: The maintainer-authored proposal identifies a concrete consumer and supplies provider results supporting context reuse through a generic plugin seam.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR supplies a useful plugin capability absent from current main, with meaningful behavior proof and no actionable introduced defect found.

Priority: P2
Reviewed head: dec646e4a693ab939db5919d554049f9395a6eb1

Before merge

None.

Findings

None.

Agent review details

How this fits together

The plugin runtime admits background requests through Gateway session and caller authorization, then delegates to the existing embedded or Codex side-question owners and returns text with usage.

flowchart TD
  A[Plugin background request] --> B[Gateway authorization]
  B --> C[Shared subagent queue]
  C --> D[Prepared session context]
  D --> E[Embedded provider replay]
  D --> F[Ephemeral Codex thread]
  E --> G[Guarded inference]
  F --> G
  G --> H[Text and usage]
Loading

Technical review

Best possible solution:

Land the additive fork capability with its existing authorization, tool-denial, bounded-memory, and parent-isolation contracts.

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

This is a capability addition: current-main types and implementation lack session-context forking, while the PR supplies concrete Gateway/provider scenarios for the proposed behavior.

Is this the best way to solve the issue?

The existing subagent namespace and side-question owners are appropriate boundaries, with separate replay adapters for embedded and Codex runtimes and preserved ordinary side-question behavior.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Capability remains absent from main: Current main exposes subagent.complete and session-running operations but no forkSession method; the reviewed head adds the documented operation through the existing runtime namespace. (src/plugins/runtime/types.ts:201, 7c5d6c80fb28)
  • Live authority reaches the network boundary: Fork admission composes plugin lifetime, conversation access, caller authority, and session visibility; embedded replay carries those assertions into guarded HTTP sends and the native Responses lifecycle. (src/agents/embedded-agent-runner/session-fork.ts:298, dec646e4a693)
  • Forbidden-principal and revocation coverage: The composed transport scenario uses real Gateway authorization and guarded HTTP transport: a different operator receives a session-not-found rejection with zero provider requests, while the owner reaches the provider; separate boundary scenarios withdraw authority during DNS preparation, WebSocket acquisition, and redirect handling. (src/gateway/server-plugin-subagent-runtime.fork-transport.test.ts:50, dec646e4a693)
  • Supplied behavior proof: The PR records isolated-Gateway runs on real OpenAI and Anthropic APIs, immediate and delayed cache hits, denied search bait, identical Codex tool declarations, and an ordinary Codex side-question result. Inspected downloaded screenshots concern linked features and were not counted as fork proof. (dec646e4a693)
  • Current-head validation: The complete check listing has no failed or pending checks; the CI, dependency-review, and security-sensitive-review status contexts succeed. CodeQL has a neutral configuration-comparison warning, with no diff-caused failure established. (dec646e4a693)
  • Distinct consumer and accepted API direction: The collaborator-authored PR explicitly proposes the additive SDK contract; feat(labs): add experimental Advisor that steers agents off avoidable work #169564 identifies it as a dependency for Advisor, rather than an implementation that supersedes this work. Public docs: docs/plugins/sdk-runtime.md. (docs/plugins/sdk-runtime.md:84, dec646e4a693)

Likely related people:

  • Peter Steinberger: Raw commit 2409cd6 adds src/gateway/server-plugin-subagent-runtime.ts:267 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2409cd6489b4; files: src/gateway/server-plugin-subagent-runtime.ts)
  • Nimrod Gutman: Raw commit 9aac55d adds src/agents/btw.ts:294 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 9aac55d30614; files: src/agents/btw.ts)
  • pashpashpash: Raw commit 42e259a adds extensions/codex/src/app-server/side-question.ts:58 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 42e259a696a2; files: extensions/codex/src/app-server/side-question.ts)

PR surface

Source +1402, Tests +2869, Docs +80, Other -1. Total +4350 across 73 files. Added test files: 6.

View PR surface stats
Area Files Added Removed Net
Source 38 2371 969 +1402
Tests 32 2920 51 +2869
Docs 2 80 0 +80
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 73 5371 1021 +4350

Review metrics

Metric Value Why it matters
Plugin API expansion 1 method with 2 required and 2 optional request fields The additive forkSession contract uses existing conversation-access and concurrency settings without adding persisted configuration.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Useful optional plugin infrastructure with no default consumer or urgent broken user workflow.
  • merge-risk: 🚨 compatibility: Expands the public plugin runtime and harness contract; the maintainer-authored direction is explicit, existing methods remain, and bundled adapters and mocks receive the new member.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-13T00:27:11.290Z sha 90924c0 :: needs real behavior proof before merge. :: [P1] Bind fork authority to the final guarded network request | [P1] Preserve current provider transport policy during replay | [P2] Keep CLI no-tools admission in its existing owner
  • reviewed 2026-10-13T00:58:26.008Z sha 3ae6ec0 :: needs real behavior proof before merge. :: [P1] Bind fork authority to the final guarded network request | [P1] Preserve current provider transport policy during replay | [P2] Keep CLI no-tools admission in its existing owner
  • reviewed 2026-10-13T01:46:54.249Z sha 1180977 :: needs real behavior proof before merge. :: [P1] Reject CLI backends before dispatching cache-parity forks | [P2] Queue session forks through the configured subagent lane
  • reviewed 2026-10-13T02:11:06.581Z sha 4a42a40 :: needs changes before merge. :: [P2] Restore the required line-cap ratchet
  • reviewed 2026-10-13T02:20:48.878Z sha 4a42a40 :: needs changes before merge. :: [P2] Restore the required line-cap ratchets
  • reviewed 2026-10-13T02:39:41.051Z sha b12d318 :: needs changes before merge. :: none
  • reviewed 2026-10-13T02:54:21.699Z sha b12d318 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-13T03:04:00.924Z sha b12d318 :: needs maintainer review before merge. :: none

Reviewed October 13, 2026, 6:21 AM ET / 10:21 UTC (Revision 13).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@clawsweeper clawsweeper Bot removed the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label Oct 13, 2026
@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit 164bd67 into main Oct 13, 2026
316 of 318 checks passed
@obviyus
obviyus deleted the feat/plugin-session-fork branch October 13, 2026 10:23
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 164bd67.

  • Problem: background plugins could only send a rebuilt, uncached excerpt of a conversation.
  • Fix: api.runtime.subagent.forkSession forks the session's live context. Tool schemas and the cache prefix stay byte-identical, but no tool can run. The fork keeps the parent's network policy. Authority, including session visibility, is checked right before every network send. Forks share the subagent concurrency limit, and CLI and Bedrock runtimes fail closed.
  • Proof: live with real APIs on Codex, built-in OpenAI and built-in Anthropic. Forks ran at agent_end and after the parent finished, read about 99% of their input from cache, and always answered search bait with NO_SEARCH. Focused regressions cover each authority and transport case. Exact-head CI is green.

obviyus added a commit that referenced this pull request Oct 13, 2026
Related: #170146 (session fork), #169564 (Advisor, the first consumer)

## What Problem This Solves

Plugins that notice a problem while an agent is still working can only queue context for the agent's next turn (`api.session.workflow.enqueueNextTurnInjection`). By then the run has already finished, so the agent spends the rest of the turn on the wasteful path. Core already lets users and `sessions_send` steer an active run; plugins have no access to it.

## Fix

Adds `api.session.workflow.steerActiveRun({ sessionKey, text, idempotencyKey? })`, returning `{ steered: true, runId? }` or `{ steered: false, reason }`.

- Uses the existing steering owner (`queueEmbeddedAgentMessageWithOutcomeAsync`) with the same call shape as `sessions_send` steer mode, so the built-in runner injects before the next model step and Codex receives native `turn/steer`.
- Plugin-authored and hidden: `internal_system` provenance with `sourceTool: "plugin:<id>"`, no sender or owner authority, never answers a pending user question.
- Requires the existing prompt-injection grant (`plugins.entries.<id>.hooks.allowPromptInjection`).
- Never throws for "no run accepts it": no active run, not streaming, backend rejection and missing grant return `steered: false` with the reason, so callers can fall back to `enqueueNextTurnInjection`.
- Respects plugin lifetime: the caller's plugin instance is revalidated after the lazy import and immediately before dispatch.

## User Impact

None by default; no core feature calls it. Plugins that opt in can correct an agent mid-run instead of after it finishes.

## Evidence

- Contract tests through the real plugin API factory and embedded steering queue: an active run receives the steer with plugin provenance and no sender/owner authority and does not answer a pending question; no active run returns `steered: false`; a plugin with `allowPromptInjection=false` is refused; an expired plugin instance cannot dispatch.
- Live (Codex runtime, real OpenAI API, isolated Gateway, via the Advisor plugin in #169564): a plugin steer issued mid-run was accepted (`steered: true`) and appears in the running turn's native rollout as a user item before the turn's next model request. Not observed live: the built-in runtime path, and whether the agent then changed course.
- Plugin revocation reaches final native admission (fix: `message-injection-target.ts` now composes the plugin lifetime assertion into the guard handed to V2 sinks; Codex already rechecks that guard after recorder persistence and right before the physical write, `attempt-steering.ts:302-304,350-359`). Real Codex client against a synthetic native app-server (`run-attempt.plugin-steering.test.ts`):
  - allowed guidance reaches the native server;
  - plugin disposed after the recorder persisted the item, before dispatch: rejected, `{ steered: false, reason: "runtime_rejected" }`, nothing written. Before the fix this returned `{ steered: true, runId: "run-1" }`;
  - an already-disabled plugin is rejected before queueing.
  - Totals: 3 native + 6 steering contract + 21 API lifecycle tests pass.
- Only source-guarded (V2) sinks accept plugin steering: `steerActiveRun` uses `queueGuardedEmbeddedAgentMessageWithOutcomeAsync`, so the plugin-lifetime assertion is checked up to native dispatch. A run whose runtime only has a legacy V1 sink (for example Copilot) returns `{ steered: false, reason: "active runtime does not support guarded steering" }` and nothing is queued; the caller can use next-turn injection instead. Regression: before the fix, a V1 run returned `{ steered: true }`. Totals: 62 tests across steering contract (7), `runs.steering` (31), API lifecycle (21), Codex plugin steering (3).
- Live at `0e6acc4`, real APIs, isolated Gateway, throwaway plugin that steers on the 2nd tool start (`"Also run 'echo STEERED' before you answer."`):

| Agent | Allowed steer | Effect | Plugin disabled mid-run (config hot reload) |
|---|---|---|---|
| Codex, OpenAI | `{ steered: true, runId }` | native rollout has the injected guidance, then `echo STEERED` and output `STEERED` | `{ steered: false, reason: 'Plugin "steer-probe" is no longer loaded' }`; no injected item in the rollout |
| Built-in, OpenAI `gpt-5.6-luna` | `{ steered: true, runId }` | transcript has hidden `internal_system` guidance from `plugin:steer-probe`, then `echo STEERED` output | same rejection; no injected item in the transcript |

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

Related: openclaw#169564 (Advisor, the first consumer)

## What Problem This Solves

Plugins that review or summarize an ongoing conversation in the background can only see what they rebuild themselves: a bounded excerpt sent through `api.runtime.subagent.complete`. That loses detail and costs a fresh, uncached prompt every time. In a real-API evaluation, an excerpt-based reviewer produced 2 false corrections in 5 runs (it misread polled background commands as extra launches), while a review that saw the session's full context was correct in all 5.

## Fix

Adds `api.runtime.subagent.forkSession({ sessionKey, message, signal?, timeoutMs? })`. It asks one question against an ephemeral fork of the session's current context and returns `{ text, usage }`. It works mid-run, at `agent_end`, and after the parent turn has finished.

- **Same prefix, warm cache.** The fork reuses the parent's exact request prefix, so the provider prompt cache hits:
  - Codex runtime: ephemeral `thread/fork` on the parent's own app-server client, replaying the parent's recorded developer instructions, private persona/skills context, tool surface and turn settings. The parent's last tool declarations are kept in a bounded in-memory LRU (32 MiB global) and restored into the fork request byte for byte. When the parent used a WebSocket continuation (`previous_response_id`), history comes from native Codex reconstruction; no response output is buffered or rebuilt.
  - Built-in runtime: the embedded runner records the exact request it sent at the model-call boundary (bounded, in memory, cleared with session cleanup) and replays it with one appended user message through the same stream function and payload hooks. Anthropic cache breakpoints and the OpenAI `prompt_cache_key` stay where they were. The parent's one-shot continuation `onPayload` callback is not replayed.
- **No tool execution.** Tool definitions stay byte-identical, but every call is denied:
  - dynamic and native Codex tools are denied at dispatch (this also fixes a fail-open path: the native hook relay dropped `PreToolUse` when no global hook was installed);
  - hosted tools: `tool_choice: "none"` on OpenAI and `{ type: "none" }` on Anthropic for every fork request; unsupported APIs fail before dispatch;
  - Codex native `web_search` stays disabled. Its `web.run` declaration is still sent (copied from the parent), so the cache prefix matches but nothing can execute it.
- **No side effects.** Nothing is written to the transcript, delivered, counted as a turn, or drained from queued next-turn context.
- **Authority.** Same background admission as `subagent.complete` (plugin lifetime, cancellation, revalidation after awaits), plus the conversation-access grant, `sessions.get` session visibility, and live Gateway caller authority. These are checked right before every physical send through the guarded-fetch request authority, including DNS/proxy setup, retries and redirects; native ChatGPT WebSocket and SSE sends check them through the existing Responses request lifecycle. Ordinary parent settlement and usage updates (including a briefly unmaterialized session row) do not revoke a fork. A session reset or deletion, a replaced Codex client or thread, withdrawn conversation access, or a retired plugin still revokes it.
- **Same network policy as the parent.** Built-in replay takes the current proxy, TLS and local-service settings (including the local-service reconciler) from the existing transport owner, not from the snapshot. Native ChatGPT forks open their own transient WebSocket and never change the parent's socket, continuation or SSE fallback state.
- **Supported APIs.** OpenAI Completions, OpenAI Responses (including native ChatGPT), Anthropic Messages, and Codex. APIs whose sends the fork cannot fence (for example Bedrock) fail closed before dispatch with `Session forks do not support provider API <api>`.
- **Runtimes.** CLI runtimes (for example `claude-cli`) have no prepared context to fork, so a fork fails closed before any CLI or provider I/O. Ordinary `/btw` on CLI is unchanged.
- **Concurrency.** Forks run on the same subagent lane as `subagent.complete` (`CommandLane.Subagent`), so `agents.defaults.subagents.maxConcurrent` caps both together.
- **Fails closed** with an actionable error when no parent request was prepared by this runtime (for example after a Gateway restart).
- Fixes forked-turn usage reporting on Codex (forks only emit `thread/tokenUsage/updated`) and admits forked requests through the private inference proxy.

Ordinary `/btw` is unchanged from `main`. An earlier revision rejected `/btw` when tools were present, and rejected CLI backends with `nativeToolMode: "none"` and no `sideQuestionToolMode`; both are restored, and CLI admission stays with `prepareCliRunContext` (this answers the review note about openclaw#70413). The provider-review continuation callback from openclaw#155214 is not replayed by forks.

## User Impact

None by default: no core feature calls `forkSession` yet. Plugins that opt in get full-context side questions at cached-input prices.

## Evidence

Live, real provider APIs, isolated Gateway at the PR head, a throwaway plugin that calls `forkSession` from its service scheduler on each `agent_end`: one fork immediately (parent still settling), then two forks 8 s later (summary, plus a "use web search now" bait). Each parent turn makes 3 tool calls.

| Runtime / provider | Parent last input | Fork at `agent_end`: cache read | Late fork: cache read | Search bait |
|---|---|---|---|---|
| Codex, OpenAI (API key, WebSocket continuation) | ~19.7k | 19,642 | 19,967, cacheWrite 0 | `NO_SEARCH` |
| Built-in, OpenAI `gpt-5.6-luna` | — | 15,660 (input 566) | 15,660 (input 608) | `NO_SEARCH` |
| Built-in, Anthropic `claude-sonnet-5-5` | — | 19,595 (input 73) | 19,595 (input 73) | `NO_SEARCH` |

- Codex wire check: the fork's `additional_tools` item (51,233 bytes) has the same SHA-256 as the parent's, and `prompt_cache_key` matches. Before this fix, the late fork read 0 cached tokens because disabling `web_search` removed `web.run` from the `exec` catalog (10,831 bytes).
- Before the admission fix, a fork started at `agent_end` failed with `agent harness host capability is no longer active`: the session-read fence required a fully materialized row while the parent was settling.
- Ordinary Codex `/btw` on the same session: `I ran echo one, then echo two, then echo three.`

Not proven against a real provider: the session-visibility rejection needs an identified Gateway client, and the live probe plugin runs as a service with no caller identity. The composed test below covers it against a real local HTTP provider.

Tests (regressions fail before their fix):
- byte identity of the replayed request through the real transport seam (OpenAI Completions, OpenAI Responses, Anthropic);
- Codex tool-declaration parity after continuation, and child `previous_response_id` cleared on full-prefix replay;
- tool denial for dynamic, native and hosted tools with no global hooks installed;
- fork admission during parent settlement and row rematerialization; revocation on reset, deletion, lifecycle replacement, access withdrawal and visibility change;
- authority withdrawal during preparation, during guarded DNS/proxy setup (no request leaves), during native WebSocket acquisition (no `response.create`), and before an SSE redirect hop (redirect body not sent); rejection of callers outside session visibility;
- current explicit-proxy and TLS policy and the local-service reconciler applied to the replay; native fork failures leave the parent's socket and SSE fallback state unchanged; Bedrock rejected before dispatch;
- a deny fork on a `claude-cli` session is rejected with no CLI spawn or provider call; with `maxConcurrent: 1`, three forks run one at a time and wait while a completion holds the lane;
- composed visibility proof: an identified caller outside session visibility gets `Session not found` with zero requests at a real local provider server (real guarded-fetch transport, no inference mock); the session owner reaches it and gets the prepared-context answer;
- ordinary CLI `/btw` with `nativeToolMode: "none"` and no `sideQuestionToolMode` works as on `main`;
- fork usage from thread token updates, real inference-proxy owner admission, parent→fork on the parent's exact client, snapshot release on committed session reset, and the restart fail-closed path.

Separate observation, not changed here: with an explicit multi-agent config, `/btw` on the system agent fails with `prepared model runtime owner was not published` unless `agents.entries.main.workspace` is set. The published owner uses the startup workspace (`/…/workspace`), but `/btw` asks for `/…/workspace/main`.

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

Related: openclaw#170146 (session fork), openclaw#169564 (Advisor, the first consumer)

## What Problem This Solves

Plugins that notice a problem while an agent is still working can only queue context for the agent's next turn (`api.session.workflow.enqueueNextTurnInjection`). By then the run has already finished, so the agent spends the rest of the turn on the wasteful path. Core already lets users and `sessions_send` steer an active run; plugins have no access to it.

## Fix

Adds `api.session.workflow.steerActiveRun({ sessionKey, text, idempotencyKey? })`, returning `{ steered: true, runId? }` or `{ steered: false, reason }`.

- Uses the existing steering owner (`queueEmbeddedAgentMessageWithOutcomeAsync`) with the same call shape as `sessions_send` steer mode, so the built-in runner injects before the next model step and Codex receives native `turn/steer`.
- Plugin-authored and hidden: `internal_system` provenance with `sourceTool: "plugin:<id>"`, no sender or owner authority, never answers a pending user question.
- Requires the existing prompt-injection grant (`plugins.entries.<id>.hooks.allowPromptInjection`).
- Never throws for "no run accepts it": no active run, not streaming, backend rejection and missing grant return `steered: false` with the reason, so callers can fall back to `enqueueNextTurnInjection`.
- Respects plugin lifetime: the caller's plugin instance is revalidated after the lazy import and immediately before dispatch.

## User Impact

None by default; no core feature calls it. Plugins that opt in can correct an agent mid-run instead of after it finishes.

## Evidence

- Contract tests through the real plugin API factory and embedded steering queue: an active run receives the steer with plugin provenance and no sender/owner authority and does not answer a pending question; no active run returns `steered: false`; a plugin with `allowPromptInjection=false` is refused; an expired plugin instance cannot dispatch.
- Live (Codex runtime, real OpenAI API, isolated Gateway, via the Advisor plugin in openclaw#169564): a plugin steer issued mid-run was accepted (`steered: true`) and appears in the running turn's native rollout as a user item before the turn's next model request. Not observed live: the built-in runtime path, and whether the agent then changed course.
- Plugin revocation reaches final native admission (fix: `message-injection-target.ts` now composes the plugin lifetime assertion into the guard handed to V2 sinks; Codex already rechecks that guard after recorder persistence and right before the physical write, `attempt-steering.ts:302-304,350-359`). Real Codex client against a synthetic native app-server (`run-attempt.plugin-steering.test.ts`):
  - allowed guidance reaches the native server;
  - plugin disposed after the recorder persisted the item, before dispatch: rejected, `{ steered: false, reason: "runtime_rejected" }`, nothing written. Before the fix this returned `{ steered: true, runId: "run-1" }`;
  - an already-disabled plugin is rejected before queueing.
  - Totals: 3 native + 6 steering contract + 21 API lifecycle tests pass.
- Only source-guarded (V2) sinks accept plugin steering: `steerActiveRun` uses `queueGuardedEmbeddedAgentMessageWithOutcomeAsync`, so the plugin-lifetime assertion is checked up to native dispatch. A run whose runtime only has a legacy V1 sink (for example Copilot) returns `{ steered: false, reason: "active runtime does not support guarded steering" }` and nothing is queued; the caller can use next-turn injection instead. Regression: before the fix, a V1 run returned `{ steered: true }`. Totals: 62 tests across steering contract (7), `runs.steering` (31), API lifecycle (21), Codex plugin steering (3).
- Live at `0e6acc4`, real APIs, isolated Gateway, throwaway plugin that steers on the 2nd tool start (`"Also run 'echo STEERED' before you answer."`):

| Agent | Allowed steer | Effect | Plugin disabled mid-run (config hot reload) |
|---|---|---|---|
| Codex, OpenAI | `{ steered: true, runId }` | native rollout has the injected guidance, then `echo STEERED` and output `STEERED` | `{ steered: false, reason: 'Plugin "steer-probe" is no longer loaded' }`; no injected item in the rollout |
| Built-in, OpenAI `gpt-5.6-luna` | `{ steered: true, runId }` | transcript has hidden `internal_system` guidance from `plugin:steer-probe`, then `echo STEERED` output | same rejection; no injected item in the transcript |

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 14, 2026
… work (#169564)

Built on #170146 (`forkSession`), #170152 (`steerActiveRun`), #171307 (shared `api.runContext`), #171534 (event `phases`), #171580 (forks show in-flight calls as pending) and #171610 (`payload: "metadata"`), #171651 (internal skill-workshop reviews are not user turns) and #171661 (Codex outer tool-call lifecycle), all on `main`. Related: #169558.

## What Problem This Solves

Agents sometimes spend turns on work nobody asked for, repeat failing or stalled tool calls, or report results the tools do not support. Nothing notices until the user does.

## User Impact

Operators can turn on **Settings → Agents & Tools → Labs → Advisor** (default off). While the agent works, Advisor reviews the conversation every few tool calls or minutes, on the session's own model. If it finds avoidable work, it steers the running turn with one short correction, or queues the correction for the next turn when steering is unavailable. Otherwise nothing happens. It never runs tools, delays, stops or approves anything. **Configure** beside the switch opens the plugin settings page:
- `everyToolCalls` (default 10) and `everyMinutes` (default 20); `0` turns a trigger off.
- **Review instructions** (`reviewInstructions`, optional, at most 4,000 characters): edits what Advisor looks for and when it stays quiet. A blank field uses the evaluated built-in guidance, which is shown as placeholder text. Changes apply on the next review without a restart. The output format, the safety rules and the verify step stay fixed, so custom guidance cannot bypass fail-closed parsing or verification. Custom guidance is not covered by the evaluation below.

## Why This Change Was Made

A default-off bundled plugin (`advisor`) built only on public SDK seams:
- **Admission:** the history-free `before_agent_reply` hook (`eligibleTriggers: ["user"]`) records each user-triggered run in `api.runContext` and never claims the turn. Advisor does not subscribe to `llm_input`, `agent_end` or `after_tool_call`, because subscribing makes the host copy the conversation history or tool results on every turn.
- **Trigger:** the service's single subscription to the agent-event stream counts `tool` starts, so stalled and backgrounded commands count too. Every N tool starts or M minutes, a review becomes due. It uses `phases` and `payload: "metadata"`, so the host never clones tool results, updates or arguments for Advisor.
- **Safe boundary:** a due review (and its verify step) dispatches only when no tool call is in flight. Built-in calls settle on their `result` event; Codex calls settle on native item completion (`codex_app_server.item` `completed`, which fires after codex-rs records the output), including outer code-mode calls. Run end is always a safe boundary. Forking mid-call would show the open call as `aborted` (codex-rs normalization). Live, before this rule, that led to a false "retry it" correction that made an agent repeat successful commands. Run timing starts at lifecycle start, and end or error closes the run.
- **Review, stage 1:** `api.runtime.subagent.forkSession` runs on the plugin service scheduler. The review sees the full live context at cached-input prices and runs no tools. The reply's first line must be `NO_CHANGE` or `CORRECTION`.
- **Verify, stage 2:** runs only after a `CORRECTION`. A second fork of the same cached context checks the draft against the conversation. The problem must be shown by tool results or user messages, not by pending work. The advice must keep every user requirement (prohibitions, scope, ordering, timing, environment), and its next step must be cheaper and still complete the request. The fork replies `APPROVE` (with the final text) or `REJECT`.
- **Fail closed:** both replies are parsed structurally. A malformed reply, a reserved decision word inside the body, a timeout or an error means no steering. The warning is bounded and content-free; it never contains model or provider text.
- **Delivery:** `api.session.workflow.steerActiveRun`, falling back to `enqueueNextTurnInjection` (24 h TTL).
- One review in flight per session, covering both stages under one deadline. Reviews are cancelled on reset, disable and service stop. The interval counter restarts when a review finishes. Tool events from channel runs, which carry no `sessionKey`, are routed through the admitted run's key.

An earlier version reviewed a bounded text excerpt with a separately configured model. In a real-API evaluation it made 2 false corrections in 5 runs: it misread polled background commands as extra launches. The full-context fork made none, so the excerpt reviewer and the model setting were removed.

Settings UI: a new generic, optional `multiline` hint in plugin manifest `uiHints` (manifest types, normalizer, and an additive optional field in the Gateway protocol config schema) renders a string field as a textarea in the existing config form. Fields without the hint render exactly as before. Advisor is its first user.

Labs: **Configure** follows the settings-row control slot (a ghost action beside the switch), through a new optional `actions` slot on `SettingsToggleRow`. The shared toggle-row click handler now ignores clicks on links, buttons and fields. Before, clicking a Labs "Documentation" link also toggled the lab; a regression test fails on the old handler.

## Evidence

Labs before (current `main`, no Advisor row):

![Labs before](https://github.com/user-attachments/assets/3d5234db-8b6f-43b9-aec4-d32db7e6ca0a)

Labs after, with Advisor enabled:

![Labs after](https://github.com/user-attachments/assets/bc894ba5-30e6-407b-8296-51c57e8a07e5)

Plugin settings page opened by **Configure**, with the multiline **Review instructions** field:

![Advisor plugin settings](https://github.com/user-attachments/assets/549bc02c-54c7-419e-98c4-3bccb7911843)

Ordinary-turn overhead, with Advisor enabled and no review due. Clones were counted per call site with an instrumented `structuredClone` across 10 real Gateway turns per workload, in a pinned Linux container (mock provider). The table shows serialized bytes the host clones for Advisor per turn:

| Workload | Before this change (`llm_input` + unfiltered events) | This PR | Advisor disabled |
|---|---:|---:|---:|
| Short turn | 2,988 | 1,375 | 0 |
| 200 KiB history | 209,377 | 1,380 | 0 |
| 1 MiB history | 1,053,153 | 1,380 | 0 |
| 5 tools × 256 KiB results | 1,326,523 | 2,899 | 0 |

Hot-path CPU, measured as interleaved microbenchmarks (median per turn): the history copy at 1 MiB costs 0.28 ms before and 0 ms now; the event dispatch on a tool-heavy turn costs 0.90 ms before and 0.14 ms now. Latency on whole turns was not resolvable on the shared host: block drift reached 35%. That pilot is recorded as exploratory and makes no p95 claim. A review itself (two forks at most) runs only when a trigger fires.

Review-decision evaluation, real APIs. Each scenario's conversation is replayed in the provider's native format (tool calls, tool results, tool schemas with `tool_choice: none`), with the review message appended, as the fork sends it. Corrections were graded by a model judge with a written rubric: evidence, a cheaper step that still completes the request, user instructions kept, at most 120 words. Final numbers come from a **blind holdout**: 40 new scenarios written by a separate agent that never saw the prompt, frozen before the run, 3 runs per model.

| Model | Variant | False corrections | Recall | Correction quality |
|---|---|---|---|---|
| `gpt-5.6-luna` | single pass | 3/60 | 60/60 | 87.3% |
| `gpt-5.6-luna` | **with verify step** | **0/60** | 60/60 | **95.0%** |
| `gpt-6.1-sol` (Codex default) | with verify step | 0/60 | 60/60 | 95.0% |
| `claude-sonnet-5-5` | with verify step | 3/60 (one scenario) | 60/60 | 84.1% |

The original prompt corrected 9–16 of 24 legitimate runs per model on the first scenario set. Its live failure: told an agent to run a requested wait loop in parallel. The verify step costs about 1.4–2.1 s and well under a cent, and it runs only when stage 1 proposes a correction.

Live on this branch (isolated Gateway, Codex and built-in luna, review every 3 tool calls):
- **Requested polling** (8 checks, 2 s apart): Codex reviewed 4 times, `NO_CHANGE` each time (4.2–5.3 s, about 15–16k cached tokens, input 75). Luna drafted 2 corrections; stage 2 rejected both. No steering, and every requested check ran.
- **Search task:** both agents broadened the search after one miss, so there was no waste to correct. Codex said `NO_CHANGE`; luna drafted a correction and stage 2 rejected it.
- **Steering delivery:** shown live on an earlier head of this branch (luna, `steered: true`, guidance in the next provider request, the agent changed course). On this head, the approve-then-steer path is covered by the tests below.

Known limits:
- `claude-sonnet-5-5` falsely corrects one hard negative scenario in all 3 runs, and its correction quality is below 95%.
- On Codex with a restricted tool profile (for example `tools.profile: coding`), the existing `/btw` native-tool rule refuses forks, so Advisor cannot review those sessions. It logs the refusal once per review interval.

Tests:
- Plugin: 46 tests. The default guidance composes to the byte-identical evaluated prompt; custom guidance replaces only the guidance part; whitespace-only means default; the verify message is unaffected; config edits apply on the next review. Earlier coverage: through the real plugin API surface. They cover: hook and service as separate registrations; channel tool events without `sessionKey`; approve then steer and the next-turn fallback; reject, malformed, conflicting-token, empty and timed-out stage 1 or 2 replies, each with zero deliveries and one bounded, content-free warning; the interval restarting after a slow or failed review; cancellation on reset, disable and stop.
- Config form: the textarea renders and edits save for `multiline` fields; manifest hint normalization is tested.
- Labs page: 65 tests, covering on/off writes, the Configure link and in-app navigation under a base path, and no toggle on link click.

**Merge danger:** two-way door; default off. A revert removes the plugin, its Labs row and the Configure link. A saved `plugins.entries.advisor` entry would remain in config.

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

Built on openclaw#170146 (`forkSession`), openclaw#170152 (`steerActiveRun`), openclaw#171307 (shared `api.runContext`), openclaw#171534 (event `phases`), openclaw#171580 (forks show in-flight calls as pending) and openclaw#171610 (`payload: "metadata"`), openclaw#171651 (internal skill-workshop reviews are not user turns) and openclaw#171661 (Codex outer tool-call lifecycle), all on `main`. Related: openclaw#169558.

## What Problem This Solves

Agents sometimes spend turns on work nobody asked for, repeat failing or stalled tool calls, or report results the tools do not support. Nothing notices until the user does.

## User Impact

Operators can turn on **Settings → Agents & Tools → Labs → Advisor** (default off). While the agent works, Advisor reviews the conversation every few tool calls or minutes, on the session's own model. If it finds avoidable work, it steers the running turn with one short correction, or queues the correction for the next turn when steering is unavailable. Otherwise nothing happens. It never runs tools, delays, stops or approves anything. **Configure** beside the switch opens the plugin settings page:
- `everyToolCalls` (default 10) and `everyMinutes` (default 20); `0` turns a trigger off.
- **Review instructions** (`reviewInstructions`, optional, at most 4,000 characters): edits what Advisor looks for and when it stays quiet. A blank field uses the evaluated built-in guidance, which is shown as placeholder text. Changes apply on the next review without a restart. The output format, the safety rules and the verify step stay fixed, so custom guidance cannot bypass fail-closed parsing or verification. Custom guidance is not covered by the evaluation below.

## Why This Change Was Made

A default-off bundled plugin (`advisor`) built only on public SDK seams:
- **Admission:** the history-free `before_agent_reply` hook (`eligibleTriggers: ["user"]`) records each user-triggered run in `api.runContext` and never claims the turn. Advisor does not subscribe to `llm_input`, `agent_end` or `after_tool_call`, because subscribing makes the host copy the conversation history or tool results on every turn.
- **Trigger:** the service's single subscription to the agent-event stream counts `tool` starts, so stalled and backgrounded commands count too. Every N tool starts or M minutes, a review becomes due. It uses `phases` and `payload: "metadata"`, so the host never clones tool results, updates or arguments for Advisor.
- **Safe boundary:** a due review (and its verify step) dispatches only when no tool call is in flight. Built-in calls settle on their `result` event; Codex calls settle on native item completion (`codex_app_server.item` `completed`, which fires after codex-rs records the output), including outer code-mode calls. Run end is always a safe boundary. Forking mid-call would show the open call as `aborted` (codex-rs normalization). Live, before this rule, that led to a false "retry it" correction that made an agent repeat successful commands. Run timing starts at lifecycle start, and end or error closes the run.
- **Review, stage 1:** `api.runtime.subagent.forkSession` runs on the plugin service scheduler. The review sees the full live context at cached-input prices and runs no tools. The reply's first line must be `NO_CHANGE` or `CORRECTION`.
- **Verify, stage 2:** runs only after a `CORRECTION`. A second fork of the same cached context checks the draft against the conversation. The problem must be shown by tool results or user messages, not by pending work. The advice must keep every user requirement (prohibitions, scope, ordering, timing, environment), and its next step must be cheaper and still complete the request. The fork replies `APPROVE` (with the final text) or `REJECT`.
- **Fail closed:** both replies are parsed structurally. A malformed reply, a reserved decision word inside the body, a timeout or an error means no steering. The warning is bounded and content-free; it never contains model or provider text.
- **Delivery:** `api.session.workflow.steerActiveRun`, falling back to `enqueueNextTurnInjection` (24 h TTL).
- One review in flight per session, covering both stages under one deadline. Reviews are cancelled on reset, disable and service stop. The interval counter restarts when a review finishes. Tool events from channel runs, which carry no `sessionKey`, are routed through the admitted run's key.

An earlier version reviewed a bounded text excerpt with a separately configured model. In a real-API evaluation it made 2 false corrections in 5 runs: it misread polled background commands as extra launches. The full-context fork made none, so the excerpt reviewer and the model setting were removed.

Settings UI: a new generic, optional `multiline` hint in plugin manifest `uiHints` (manifest types, normalizer, and an additive optional field in the Gateway protocol config schema) renders a string field as a textarea in the existing config form. Fields without the hint render exactly as before. Advisor is its first user.

Labs: **Configure** follows the settings-row control slot (a ghost action beside the switch), through a new optional `actions` slot on `SettingsToggleRow`. The shared toggle-row click handler now ignores clicks on links, buttons and fields. Before, clicking a Labs "Documentation" link also toggled the lab; a regression test fails on the old handler.

## Evidence

Labs before (current `main`, no Advisor row):

![Labs before](https://github.com/user-attachments/assets/3d5234db-8b6f-43b9-aec4-d32db7e6ca0a)

Labs after, with Advisor enabled:

![Labs after](https://github.com/user-attachments/assets/bc894ba5-30e6-407b-8296-51c57e8a07e5)

Plugin settings page opened by **Configure**, with the multiline **Review instructions** field:

![Advisor plugin settings](https://github.com/user-attachments/assets/549bc02c-54c7-419e-98c4-3bccb7911843)

Ordinary-turn overhead, with Advisor enabled and no review due. Clones were counted per call site with an instrumented `structuredClone` across 10 real Gateway turns per workload, in a pinned Linux container (mock provider). The table shows serialized bytes the host clones for Advisor per turn:

| Workload | Before this change (`llm_input` + unfiltered events) | This PR | Advisor disabled |
|---|---:|---:|---:|
| Short turn | 2,988 | 1,375 | 0 |
| 200 KiB history | 209,377 | 1,380 | 0 |
| 1 MiB history | 1,053,153 | 1,380 | 0 |
| 5 tools × 256 KiB results | 1,326,523 | 2,899 | 0 |

Hot-path CPU, measured as interleaved microbenchmarks (median per turn): the history copy at 1 MiB costs 0.28 ms before and 0 ms now; the event dispatch on a tool-heavy turn costs 0.90 ms before and 0.14 ms now. Latency on whole turns was not resolvable on the shared host: block drift reached 35%. That pilot is recorded as exploratory and makes no p95 claim. A review itself (two forks at most) runs only when a trigger fires.

Review-decision evaluation, real APIs. Each scenario's conversation is replayed in the provider's native format (tool calls, tool results, tool schemas with `tool_choice: none`), with the review message appended, as the fork sends it. Corrections were graded by a model judge with a written rubric: evidence, a cheaper step that still completes the request, user instructions kept, at most 120 words. Final numbers come from a **blind holdout**: 40 new scenarios written by a separate agent that never saw the prompt, frozen before the run, 3 runs per model.

| Model | Variant | False corrections | Recall | Correction quality |
|---|---|---|---|---|
| `gpt-5.6-luna` | single pass | 3/60 | 60/60 | 87.3% |
| `gpt-5.6-luna` | **with verify step** | **0/60** | 60/60 | **95.0%** |
| `gpt-6.1-sol` (Codex default) | with verify step | 0/60 | 60/60 | 95.0% |
| `claude-sonnet-5-5` | with verify step | 3/60 (one scenario) | 60/60 | 84.1% |

The original prompt corrected 9–16 of 24 legitimate runs per model on the first scenario set. Its live failure: told an agent to run a requested wait loop in parallel. The verify step costs about 1.4–2.1 s and well under a cent, and it runs only when stage 1 proposes a correction.

Live on this branch (isolated Gateway, Codex and built-in luna, review every 3 tool calls):
- **Requested polling** (8 checks, 2 s apart): Codex reviewed 4 times, `NO_CHANGE` each time (4.2–5.3 s, about 15–16k cached tokens, input 75). Luna drafted 2 corrections; stage 2 rejected both. No steering, and every requested check ran.
- **Search task:** both agents broadened the search after one miss, so there was no waste to correct. Codex said `NO_CHANGE`; luna drafted a correction and stage 2 rejected it.
- **Steering delivery:** shown live on an earlier head of this branch (luna, `steered: true`, guidance in the next provider request, the agent changed course). On this head, the approve-then-steer path is covered by the tests below.

Known limits:
- `claude-sonnet-5-5` falsely corrects one hard negative scenario in all 3 runs, and its correction quality is below 95%.
- On Codex with a restricted tool profile (for example `tools.profile: coding`), the existing `/btw` native-tool rule refuses forks, so Advisor cannot review those sessions. It logs the refusal once per review interval.

Tests:
- Plugin: 46 tests. The default guidance composes to the byte-identical evaluated prompt; custom guidance replaces only the guidance part; whitespace-only means default; the verify message is unaffected; config edits apply on the next review. Earlier coverage: through the real plugin API surface. They cover: hook and service as separate registrations; channel tool events without `sessionKey`; approve then steer and the next-turn fallback; reject, malformed, conflicting-token, empty and timed-out stage 1 or 2 replies, each with zero deliveries and one bounded, content-free warning; the interval restarting after a slow or failed review; cancellation on reset, disable and stop.
- Config form: the textarea renders and edits save for `multiline` fields; manifest hint normalization is tested.
- Labs page: 65 tests, covering on/off writes, the Configure link and in-app navigation under a base path, and no toggle on link click.

**Merge danger:** two-way door; default off. A revert removes the plugin, its Labs row and the Configure link. A saved `plugins.entries.advisor` entry would remain in config.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 17, 2026
…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]>
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]>
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)
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 extensions: codex extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant