Skip to content

fix(agents): fork subscription CLI chats through their own CLI - #202659

Merged
obviyus merged 5 commits into
mainfrom
fix/session-forks-on-cli
Nov 21, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/session-forks-on-cli

Conversation

@obviyus

@obviyus obviyus commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #202646 (secret input after an async stdin prompt); review the last commit.

What Problem This Solves

Plugin session forks (runForkedTurn, forkSession; for example Better Prompt and Skill Workshop reviews) always ran on the built-in runtime. On a Claude CLI chat signed in with a Claude subscription:

  • With only the CLI's own claude login, runForkedTurn failed with No API key found for provider "claude-cli".
  • With a Claude subscription token stored in OpenClaw, runForkedTurn sent the token to the Anthropic API directly, which bills metered extra usage instead of the plan (cliBackendDispatch notes in run/params.ts).
  • forkSession refused every CLI runtime: Session forks are not supported for CLI runtime claude-cli.

Why This Change Was Made

OpenClaw already has one owner for "run this embedded run on the subscription CLI": cliBackendDispatch: "subscription-auth" (Active Memory's recall uses it). The fork owner opts into it; no new path:

  • runSessionFork sets cliBackendDispatch: "subscription-auth". Eligibility is unchanged: subscription (oauth/token) or unresolvable credentials go to the CLI; API keys keep the request replay and its prompt cache.
  • Dispatch accepts the fork's in-memory conversation (sessionManager), and sends the CLI only the tools that may execute (toolExecutionAllow; an empty list is a tool-free run).
  • Dispatch now picks the CLI account the way a new CLI session does. Before, it passed only an explicit pin, so a stored Claude token never reached the CLI (Not logged in · Please run /login); Active Memory recalls had the same gap.
  • Runs that grant the plugin's own tools or set maxTokens keep the direct route: neither reaches a CLI process.
  • Dispatch carries the run's policy facts to the CLI: a run under another session's policy (a fork's sandboxSessionKey) passes that session's entry, the requester fields and internal_system provenance into the CLI's Gateway tool grant, so restricted-sender limits apply to the fork as to the chat's own turns.

Accepted: a CLI fork starts a fresh CLI session with the conversation as context, so it does not reuse the chat's cache, and each fork leaves one Claude session file under ~/.claude/projects, as Active Memory's CLI recalls already do. The source chat's native session is never resumed or written.

Permission modes (maintainer decision, now in docs/gateway/permission-modes.md): the sessionRoot boundary is enforced on the built-in runtime; CLI-backed chats use the CLI's own controls, and owner turns' Gateway tools are not limited to sessionRoot. Live, on a Claude CLI chat in workspace mode, an ordinary turn and a fork both read a file outside the workspace through mcp__openclaw__read, and the same chat on the built-in runtime refuses both with Path escapes sandbox root. A CLI fork therefore has the same file access as the chat's own CLI turns.

Not covered: Gemini CLI on a Google login (OpenClaw cannot limit its tools under OAuth), and harnesses that own their login with no limited one-shot turn (Copilot, Muse, acp-*).

Evidence

Real product, tier source (ocx src), isolated foreground Gateway, no API key in the environment or auth store; profiles: Claude subscription setup token, ChatGPT OAuth, Grok OAuth. Each chat: one turn ("Remember PELICAN-42"), then forks through a probe plugin.

Route runForkedTurn [read, ls] forkSession runForkedTurn cache read
claude-cli, Claude token PELICAN-42 | FORK-READ-OK 7f3a (dispatched to Claude CLI) PELICAN-42 6,985
ChatGPT OAuth, built-in PELICAN-42 | FORK-READ-OK 7f3a PELICAN-42 (cache read 9,856) 10,112
Codex app-server PELICAN-42 | FORK-READ-OK 7f3a PELICAN-42 (19,584) 8,704
Grok OAuth PELICAN-42 | FORK-READ-OK 7f3a PELICAN-42 (1,152) 1,152
  • main on the same Claude chat: runForkedTurn ran on the Anthropic API with the token (cache read 0, cache write 23,872), forkSession refused.
  • Every route: source transcript hash, message count and native binding unchanged; the Claude source session file holds only the chat's own turn.
  • Better Prompt 0.2.2 (start → take through plugins.sessionAction) produced an improved prompt on the Claude CLI chat and on the ChatGPT chat.
  • Dispatch tests: a fork runs on the CLI with only its own tools from its in-memory session; plugin tool grants and output caps keep the passthrough.

The direct child adapter released the secret pipe when construction returned, before readiness awaited prepareInput and wrote stdin. A CLI run with an OpenClaw-held login and a stdin prompt then failed with 'secret input file descriptor 3 is unavailable'. Readiness now owns the pipe until delivery settles, as the service relay path already does.
Plugin session forks ran every chat on the built-in runtime. A Claude CLI chat on a subscription login then failed (native login) or billed metered extra usage (OpenClaw-held Claude token), and forkSession refused CLI runtimes. Forks now opt into the existing subscription CLI dispatch: the fork's in-memory conversation runs on a fresh CLI process with only the fork's own tools, on the account new CLI sessions use. API-key chats keep the request replay.
@clawsweeper

clawsweeper Bot commented Nov 20, 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 agents Agent runtime and tooling plugin: file-transfer size: S labels Nov 20, 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. P1 High-priority user-facing bug, regression, or broken workflow. 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: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

Routes eligible subscription-backed session forks through the existing restricted CLI dispatcher.

Example: A Claude CLI subscription chat remembers PELICAN-42 and a plugin calls forkSession.

  • Before: The fork fails with “Session forks are not supported for CLI runtime claude-cli.”
  • After: The reported Gateway run returns PELICAN-42 through a fresh Claude CLI session.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful routing repair with reported product proof, blocked by a concrete source-policy regression and a diff-caused test failure.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR reports both fork APIs running through an isolated foreground Gateway and real Claude CLI subscription authentication, returning remembered context and a workspace-file marker while preserving the source transcript and binding; sibling provider routes are also reported.
Patch quality 🧂 unranked krab (1/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Plugin forks on Claude subscription chats fail or use metered API billing instead of the selected CLI subscription.
Reason: The collaborator-authored direction restores useful plugin behavior through an existing owner and explicitly records its CLI cache and persistence tradeoffs.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this PR open: it addresses a verified subscription-routing problem, but the newly enabled CLI path drops source-session policy context, and CI exposes an obsolete BTW assertion.

Priority: P1
Reviewed head: cd00fbbb167b528ca97b909c0abb0586c1853fd8

Before merge

  • Preserve source-session policy when enabling CLI fork dispatch (P1) - A fork of a sandbox-required Claude subscription session now enters an adapter that forwards the synthetic fork sessionKey but drops sandboxSessionKey, permissionMode, requester fields, and inputProvenance. prepareCliRunContext consequently selects the synthetic key as policySessionKey, and the MCP resolver classifies that key rather than the source session. With agent sandbox defaults off and the source marked sandbox: required, an allowed read can therefore be constructed under host policy instead of the source sandbox. Carry the source identity through runtimePolicySessionKey and preserve the associated requester, permission, and background execution context at the CLI handoff; retain the synthetic identity for fork effects.
  • Update the BTW regression for the newly supported CLI fork route (P2) - The changed branch returns sessionFork(), but btw.test.ts:811–826 still requires that call to reject with the removed unsupported-runtime error. Exact-head checks-node-changed-1 fails at line 815 with the resolved built-in fork result. Change this consumer test to verify delegation to the fork owner while retaining the ordinary CLI BTW assertions.
  • Resolve security concern: An exact tool list does not preserve resource authority - The MCP grant restricts tool names, but its resource-policy identity is also significant: a permitted read must remain confined by the source session’s required sandbox.
  • Explain or restore the original intent of Source sandbox ownership - 4f1c904: Sandbox-required forks must reuse the source session’s workspace and execution boundary.

Findings

  • [P1] Preserve source-session policy when enabling CLI fork dispatch — src/agents/session-fork-run.ts:595-596
  • [P2] Update the BTW regression for the newly supported CLI fork route — src/agents/btw.ts:525-526
  • [high] An exact tool list does not preserve resource authority — src/agents/session-fork-run.ts:595

Provenance

  • Source sandbox ownership changes intended behavior without addressing why it exists (4f1c904: Sandbox-required forks must reuse the source session’s workspace and execution boundary.)

Tests

  • Low-value test src/agents/embedded-agent-runner/cli-backend-dispatch.test.ts: The added fork case uses an empty in-memory session and asserts arguments passed to a mocked runCliAgent; replace it with boundary coverage that exercises conversation transfer and source policy enforcement.
Agent review details

How this fits together

Plugin fork APIs enter the shared session-fork owner, which supplies conversation context, model selection, and tool restrictions to either the embedded runtime or the CLI dispatcher.

flowchart TD
  A[Plugin fork APIs] --> B[Session fork owner]
  B --> C[Subscription dispatch eligibility]
  C --> D[Embedded provider runtime]
  C --> E[Fresh restricted CLI session]
  E --> F[Gateway MCP tool policy]
  D --> G[Fork result]
  E --> G
Loading

Technical review

Best possible solution:

Keep the existing dispatcher, carry the fork’s source policy and requester context through its CLI handoff, and update the BTW regression.

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

Current-main source shows both the CLI rejection and missing fork dispatch opt-in; the PR supplies matching before/after Gateway results, but this review ran no target code.

Is this the best way to solve the issue?

Reusing the existing subscription dispatcher is a small, coherent repair, provided its handoff preserves the source session’s execution policy.

Full review comments:

  • [P1] Preserve source-session policy when enabling CLI fork dispatch — src/agents/session-fork-run.ts:595-596
    A fork of a sandbox-required Claude subscription session now enters an adapter that forwards the synthetic fork sessionKey but drops sandboxSessionKey, permissionMode, requester fields, and inputProvenance. prepareCliRunContext consequently selects the synthetic key as policySessionKey, and the MCP resolver classifies that key rather than the source session. With agent sandbox defaults off and the source marked sandbox: required, an allowed read can therefore be constructed under host policy instead of the source sandbox. Carry the source identity through runtimePolicySessionKey and preserve the associated requester, permission, and background execution context at the CLI handoff; retain the synthetic identity for fork effects.
    Confidence: 0.95
  • [P2] Update the BTW regression for the newly supported CLI fork route — src/agents/btw.ts:525-526
    The changed branch returns sessionFork(), but btw.test.ts:811–826 still requires that call to reject with the removed unsupported-runtime error. Exact-head checks-node-changed-1 fails at line 815 with the resolved built-in fork result. Change this consumer test to verify delegation to the fork owner while retaining the ordinary CLI BTW assertions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • CLI fork rejection changes intended behavior with a stated reason (164bd67: CLI runtimes lacked a prepared provider request to replay safely.)
  • Dispatch transcript and tool eligibility changes intended behavior with a stated reason (3590f7d: Dispatch initially required caller-owned transcript storage and a nonempty named tool list to avoid widening tool access.)
  • Fork prompt-cache replay changes intended behavior with a stated reason (2a7ca16: One shared fork owner preserves the parent request and cached prefix rather than reconstructing a limited conversation.)

Testing

Proof path: shipped entry point.

Security

Needs attention: The new CLI fork route does not preserve the source session’s sandbox and requester boundary.

Evidence

Security concerns:

  • [high] An exact tool list does not preserve resource authority — src/agents/session-fork-run.ts:595
    The MCP grant restricts tool names, but its resource-policy identity is also significant: a permitted read must remain confined by the source session’s required sandbox.
    Confidence: 0.95

What I checked:

PR surface

Source +38, Tests +16, Docs +7. Total +61 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 47 9 +38
Tests 1 20 4 +16
Docs 1 9 2 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 76 15 +61

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.

Labels

Label changes:

  • add P1: The patch can lose a required source-session sandbox when a plugin fork executes tools.
  • add merge-risk: 🚨 compatibility: The public fork APIs gain subscription CLI behavior; the collaborator author explicitly accepts fresh-session context and native session-file retention.
  • add merge-risk: 🚨 security-boundary: Tool-name restrictions survive, but resource and requester policy can be resolved under the synthetic fork identity.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🐚 platinum hermit and patch quality is 🧂 unranked krab.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: The patch can lose a required source-session sandbox when a plugin fork executes tools.
  • merge-risk: 🚨 security-boundary: Tool-name restrictions survive, but resource and requester policy can be resolved under the synthetic fork identity.
  • merge-risk: 🚨 compatibility: The public fork APIs gain subscription CLI behavior; the collaborator author explicitly accepts fresh-session context and native session-file retention.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🐚 platinum hermit and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • 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.

Reviewed November 20, 2026, 1:53 PM ET / 18:53 UTC.

A fork dispatched to a subscription CLI lost its source session's entry, requester fields and internal provenance, so the CLI's Gateway tool grant could not see them. Dispatch now passes the policy session's entry, requester and provenance into the CLI run.
@obviyus
obviyus marked this pull request as draft November 20, 2026 18:59
@obviyus
obviyus marked this pull request as ready for review November 21, 2026 03:41
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Nov 21, 2026
Base automatically changed from fix/secret-input-after-stdin to main November 21, 2026 03:49
@obviyus
obviyus merged commit b7bf937 into main Nov 21, 2026
120 checks passed
@obviyus
obviyus deleted the fix/session-forks-on-cli branch November 21, 2026 04:12
@obviyus

obviyus commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

Landed. Plugin session forks (runForkedTurn, forkSession; Better Prompt, Skill Workshop) on a Claude CLI chat with a subscription login now run through that chat's own CLI on the plan, instead of failing (native login) or billing metered extra usage (stored Claude token); forkSession no longer refuses CLI runtimes. API-key chats keep the request replay. Proof: live isolated Gateway with no API key: Claude CLI, ChatGPT OAuth, Codex and Grok forks answer from the chat's context with source transcripts unchanged, and Better produced improved prompts on Claude CLI and ChatGPT chats.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…law#202659)

## What Problem This Solves

Plugin session forks (`runForkedTurn`, `forkSession`; for example Better Prompt and Skill Workshop reviews) always ran on the built-in runtime. On a Claude CLI chat signed in with a Claude subscription:

- With only the CLI's own `claude` login, `runForkedTurn` failed with `No API key found for provider "claude-cli"`.
- With a Claude subscription token stored in OpenClaw, `runForkedTurn` sent the token to the Anthropic API directly, which bills metered extra usage instead of the plan (`cliBackendDispatch` notes in `run/params.ts`).
- `forkSession` refused every CLI runtime: `Session forks are not supported for CLI runtime claude-cli.`

## Why This Change Was Made

OpenClaw already has one owner for "run this embedded run on the subscription CLI": `cliBackendDispatch: "subscription-auth"` (Active Memory's recall uses it). The fork owner opts into it; no new path:

- `runSessionFork` sets `cliBackendDispatch: "subscription-auth"`. Eligibility is unchanged: subscription (oauth/token) or unresolvable credentials go to the CLI; API keys keep the request replay and its prompt cache.
- Dispatch accepts the fork's in-memory conversation (`sessionManager`), and sends the CLI only the tools that may execute (`toolExecutionAllow`; an empty list is a tool-free run).
- Dispatch now picks the CLI account the way a new CLI session does. Before, it passed only an explicit pin, so a stored Claude token never reached the CLI (`Not logged in · Please run /login`); Active Memory recalls had the same gap.
- Runs that grant the plugin's own tools or set `maxTokens` keep the direct route: neither reaches a CLI process.
- Dispatch carries the run's policy facts to the CLI: a run under another session's policy (a fork's `sandboxSessionKey`) passes that session's entry, the requester fields and `internal_system` provenance into the CLI's Gateway tool grant, so restricted-sender limits apply to the fork as to the chat's own turns.

Accepted: a CLI fork starts a fresh CLI session with the conversation as context, so it does not reuse the chat's cache, and each fork leaves one Claude session file under `~/.claude/projects`, as Active Memory's CLI recalls already do. The source chat's native session is never resumed or written.

Permission modes (maintainer decision, now in `docs/gateway/permission-modes.md`): the `sessionRoot` boundary is enforced on the built-in runtime; CLI-backed chats use the CLI's own controls, and owner turns' Gateway tools are not limited to `sessionRoot`. Live, on a Claude CLI chat in `workspace` mode, an ordinary turn and a fork both read a file outside the workspace through `mcp__openclaw__read`, and the same chat on the built-in runtime refuses both with `Path escapes sandbox root`. A CLI fork therefore has the same file access as the chat's own CLI turns.

Not covered: Gemini CLI on a Google login (OpenClaw cannot limit its tools under OAuth), and harnesses that own their login with no limited one-shot turn (Copilot, Muse, `acp-*`).

## Evidence

Real product, tier source (`ocx src`), isolated foreground Gateway, no API key in the environment or auth store; profiles: Claude subscription setup token, ChatGPT OAuth, Grok OAuth. Each chat: one turn ("Remember PELICAN-42"), then forks through a probe plugin.

| Route | `runForkedTurn` `[read, ls]` | `forkSession` | `runForkedTurn` cache read |
|---|---|---|---|
| `claude-cli`, Claude token | `PELICAN-42 \| FORK-READ-OK 7f3a` (dispatched to Claude CLI) | `PELICAN-42` | 6,985 |
| ChatGPT OAuth, built-in | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (cache read 9,856) | 10,112 |
| Codex app-server | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (19,584) | 8,704 |
| Grok OAuth | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (1,152) | 1,152 |

- `main` on the same Claude chat: `runForkedTurn` ran on the Anthropic API with the token (cache read 0, cache write 23,872), `forkSession` refused.
- Every route: source transcript hash, message count and native binding unchanged; the Claude source session file holds only the chat's own turn.
- Better Prompt 0.2.2 (`start` → `take` through `plugins.sessionAction`) produced an improved prompt on the Claude CLI chat and on the ChatGPT chat.
- Dispatch tests: a fork runs on the CLI with only its own tools from its in-memory session; plugin tool grants and output caps keep the passthrough.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 21, 2026
…ol call (#202941)

## What Problem This Solves

A chat set to a permission mode (Read only, Ask me, Auto-review) bounds file tools to its `sessionRoot` on the built-in runtime. On a Claude CLI chat it did not: the CLI calls OpenClaw's own tools through the Gateway (`mcp__openclaw__read` and friends), and the Gateway applied the session's mode only to restricted senders. An owner's Claude CLI chat in `workspace` mode read files anywhere on the host.

## Why This Change Was Made

The Gateway runs these tools, so it owns the boundary. `resolveGatewayScopedTools` now applies the session's permission policy for every caller instead of only `inheritedToolPolicySource === "sender"` (that scope came from #165418, which kept "ordinary owner/profile authority unchanged"; nothing else relies on owners being unbounded). The prepared session workspace now also applies when the session has a mode, so relative paths resolve inside the same root the policy bounds.

Rule, now in `docs/gateway/permission-modes.md`: whoever runs a tool enforces the mode for it. The Gateway does for OpenClaw's tools on every runtime; Codex does for its own tools through its sandbox; host-only harnesses with their own tools (Muse, ACP) keep needing Full access. This replaces the paragraph from #202659 that said CLI chats use the CLI's own controls. A new sentence states that modes bound file tools and pick the exec reviewer; exec is not confined to `sessionRoot` unless the runtime sandboxes commands.

Effects:
- Sessions with no mode (the policy is undefined) are unchanged: cron, Skill Workshop, completion handoffs, subagents without a mode.
- Owner `POST /tools/invoke` on a mode-set session is bounded the same way (same resolver, already passed the policy).
- Subagent attachment roots stay readable: the Gateway builds tools through the same assembly that adds `subagentAttachmentRootForRun`.

## Evidence

- `src/gateway/tool-resolution.test.ts`: an owner's loopback `read` on a `read-only` session refuses a path outside the root and lists no `write`; with no mode it reads. Red on the merge base (`expected '{"content":[{"type":"text","text":"ou…' to contain 'escapes'`), green here.
- Real product, tier source (`ocx src`), isolated Gateway, a Claude CLI agent and a built-in ChatGPT agent, chat set to `permissionMode: "workspace"`, caller with full operator scopes, asked to read a file outside the workspace:

| | Merge base | This branch |
|---|---|---|
| Claude CLI | read it: `OUTSIDE-SECRET 91c2` | refused: `Path escapes sandbox root (…/workspace): …/outside.txt` |
| Built-in | refused, same error | refused, same error |

Exec on that Claude CLI chat is unchanged by this PR (both: `exec denied: Headless runs cannot wait for interactive exec approval … security=allowlist ask=on-miss`), while the built-in chat's exec goes through the auto-reviewer; that difference predates this change and is tracked separately.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 22, 2026
…ol call (openclaw#202941)

## What Problem This Solves

A chat set to a permission mode (Read only, Ask me, Auto-review) bounds file tools to its `sessionRoot` on the built-in runtime. On a Claude CLI chat it did not: the CLI calls OpenClaw's own tools through the Gateway (`mcp__openclaw__read` and friends), and the Gateway applied the session's mode only to restricted senders. An owner's Claude CLI chat in `workspace` mode read files anywhere on the host.

## Why This Change Was Made

The Gateway runs these tools, so it owns the boundary. `resolveGatewayScopedTools` now applies the session's permission policy for every caller instead of only `inheritedToolPolicySource === "sender"` (that scope came from openclaw#165418, which kept "ordinary owner/profile authority unchanged"; nothing else relies on owners being unbounded). The prepared session workspace now also applies when the session has a mode, so relative paths resolve inside the same root the policy bounds.

Rule, now in `docs/gateway/permission-modes.md`: whoever runs a tool enforces the mode for it. The Gateway does for OpenClaw's tools on every runtime; Codex does for its own tools through its sandbox; host-only harnesses with their own tools (Muse, ACP) keep needing Full access. This replaces the paragraph from openclaw#202659 that said CLI chats use the CLI's own controls. A new sentence states that modes bound file tools and pick the exec reviewer; exec is not confined to `sessionRoot` unless the runtime sandboxes commands.

Effects:
- Sessions with no mode (the policy is undefined) are unchanged: cron, Skill Workshop, completion handoffs, subagents without a mode.
- Owner `POST /tools/invoke` on a mode-set session is bounded the same way (same resolver, already passed the policy).
- Subagent attachment roots stay readable: the Gateway builds tools through the same assembly that adds `subagentAttachmentRootForRun`.

## Evidence

- `src/gateway/tool-resolution.test.ts`: an owner's loopback `read` on a `read-only` session refuses a path outside the root and lists no `write`; with no mode it reads. Red on the merge base (`expected '{"content":[{"type":"text","text":"ou…' to contain 'escapes'`), green here.
- Real product, tier source (`ocx src`), isolated Gateway, a Claude CLI agent and a built-in ChatGPT agent, chat set to `permissionMode: "workspace"`, caller with full operator scopes, asked to read a file outside the workspace:

| | Merge base | This branch |
|---|---|---|
| Claude CLI | read it: `OUTSIDE-SECRET 91c2` | refused: `Path escapes sandbox root (…/workspace): …/outside.txt` |
| Built-in | refused, same error | refused, same error |

Exec on that Claude CLI chat is unchanged by this PR (both: `exec denied: Headless runs cannot wait for interactive exec approval … security=allowlist ask=on-miss`), while the built-in chat's exec goes through the auto-reviewer; that difference predates this change and is tracked separately.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…ol call (#202941)

A chat set to a permission mode (Read only, Ask me, Auto-review) bounds file tools to its `sessionRoot` on the built-in runtime. On a Claude CLI chat it did not: the CLI calls OpenClaw's own tools through the Gateway (`mcp__openclaw__read` and friends), and the Gateway applied the session's mode only to restricted senders. An owner's Claude CLI chat in `workspace` mode read files anywhere on the host.

The Gateway runs these tools, so it owns the boundary. `resolveGatewayScopedTools` now applies the session's permission policy for every caller instead of only `inheritedToolPolicySource === "sender"` (that scope came from #165418, which kept "ordinary owner/profile authority unchanged"; nothing else relies on owners being unbounded). The prepared session workspace now also applies when the session has a mode, so relative paths resolve inside the same root the policy bounds.

Rule, now in `docs/gateway/permission-modes.md`: whoever runs a tool enforces the mode for it. The Gateway does for OpenClaw's tools on every runtime; Codex does for its own tools through its sandbox; host-only harnesses with their own tools (Muse, ACP) keep needing Full access. This replaces the paragraph from #202659 that said CLI chats use the CLI's own controls. A new sentence states that modes bound file tools and pick the exec reviewer; exec is not confined to `sessionRoot` unless the runtime sandboxes commands.

Effects:
- Sessions with no mode (the policy is undefined) are unchanged: cron, Skill Workshop, completion handoffs, subagents without a mode.
- Owner `POST /tools/invoke` on a mode-set session is bounded the same way (same resolver, already passed the policy).
- Subagent attachment roots stay readable: the Gateway builds tools through the same assembly that adds `subagentAttachmentRootForRun`.

- `src/gateway/tool-resolution.test.ts`: an owner's loopback `read` on a `read-only` session refuses a path outside the root and lists no `write`; with no mode it reads. Red on the merge base (`expected '{"content":[{"type":"text","text":"ou…' to contain 'escapes'`), green here.
- Real product, tier source (`ocx src`), isolated Gateway, a Claude CLI agent and a built-in ChatGPT agent, chat set to `permissionMode: "workspace"`, caller with full operator scopes, asked to read a file outside the workspace:

| | Merge base | This branch |
|---|---|---|
| Claude CLI | read it: `OUTSIDE-SECRET 91c2` | refused: `Path escapes sandbox root (…/workspace): …/outside.txt` |
| Built-in | refused, same error | refused, same error |

Exec on that Claude CLI chat is unchanged by this PR (both: `exec denied: Headless runs cannot wait for interactive exec approval … security=allowlist ask=on-miss`), while the built-in chat's exec goes through the auto-reviewer; that difference predates this change and is tracked separately.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit a1599a4)

Release adaptation: Insert the enforcement paragraphs because the stable baseline lacks the earlier CLI paragraph; retain stable-only guidance and clarify the native CLI distinction from #202957.

Companions: #202945/#202957 runtime changes cancel out (baseline-equivalent); #202957 documentation distinction is included here. #202306 is a separate project-move feature, not applicable. Neither #202659 CLI forking nor the adjacent sharing, file-write, role, and routing changes are dependencies.
Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Plugin session forks (`runForkedTurn`, `forkSession`; for example Better Prompt and Skill Workshop reviews) always ran on the built-in runtime. On a Claude CLI chat signed in with a Claude subscription:

- With only the CLI's own `claude` login, `runForkedTurn` failed with `No API key found for provider "claude-cli"`.
- With a Claude subscription token stored in OpenClaw, `runForkedTurn` sent the token to the Anthropic API directly, which bills metered extra usage instead of the plan (`cliBackendDispatch` notes in `run/params.ts`).
- `forkSession` refused every CLI runtime: `Session forks are not supported for CLI runtime claude-cli.`

OpenClaw already has one owner for "run this embedded run on the subscription CLI": `cliBackendDispatch: "subscription-auth"` (Active Memory's recall uses it). The fork owner opts into it; no new path:

- `runSessionFork` sets `cliBackendDispatch: "subscription-auth"`. Eligibility is unchanged: subscription (oauth/token) or unresolvable credentials go to the CLI; API keys keep the request replay and its prompt cache.
- Dispatch accepts the fork's in-memory conversation (`sessionManager`), and sends the CLI only the tools that may execute (`toolExecutionAllow`; an empty list is a tool-free run).
- Dispatch now picks the CLI account the way a new CLI session does. Before, it passed only an explicit pin, so a stored Claude token never reached the CLI (`Not logged in · Please run /login`); Active Memory recalls had the same gap.
- Runs that grant the plugin's own tools or set `maxTokens` keep the direct route: neither reaches a CLI process.
- Dispatch carries the run's policy facts to the CLI: a run under another session's policy (a fork's `sandboxSessionKey`) passes that session's entry, the requester fields and `internal_system` provenance into the CLI's Gateway tool grant, so restricted-sender limits apply to the fork as to the chat's own turns.

Accepted: a CLI fork starts a fresh CLI session with the conversation as context, so it does not reuse the chat's cache, and each fork leaves one Claude session file under `~/.claude/projects`, as Active Memory's CLI recalls already do. The source chat's native session is never resumed or written.

Permission modes (maintainer decision, now in `docs/gateway/permission-modes.md`): the `sessionRoot` boundary is enforced on the built-in runtime; CLI-backed chats use the CLI's own controls, and owner turns' Gateway tools are not limited to `sessionRoot`. Live, on a Claude CLI chat in `workspace` mode, an ordinary turn and a fork both read a file outside the workspace through `mcp__openclaw__read`, and the same chat on the built-in runtime refuses both with `Path escapes sandbox root`. A CLI fork therefore has the same file access as the chat's own CLI turns.

Not covered: Gemini CLI on a Google login (OpenClaw cannot limit its tools under OAuth), and harnesses that own their login with no limited one-shot turn (Copilot, Muse, `acp-*`).

Real product, tier source (`ocx src`), isolated foreground Gateway, no API key in the environment or auth store; profiles: Claude subscription setup token, ChatGPT OAuth, Grok OAuth. Each chat: one turn ("Remember PELICAN-42"), then forks through a probe plugin.

| Route | `runForkedTurn` `[read, ls]` | `forkSession` | `runForkedTurn` cache read |
|---|---|---|---|
| `claude-cli`, Claude token | `PELICAN-42 \| FORK-READ-OK 7f3a` (dispatched to Claude CLI) | `PELICAN-42` | 6,985 |
| ChatGPT OAuth, built-in | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (cache read 9,856) | 10,112 |
| Codex app-server | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (19,584) | 8,704 |
| Grok OAuth | `PELICAN-42 \| FORK-READ-OK 7f3a` | `PELICAN-42` (1,152) | 1,152 |

- `main` on the same Claude chat: `runForkedTurn` ran on the Anthropic API with the token (cache read 0, cache write 23,872), `forkSession` refused.
- Every route: source transcript hash, message count and native binding unchanged; the Claude source session file holds only the chat's own turn.
- Better Prompt 0.2.2 (`start` → `take` through `plugins.sessionAction`) produced an improved prompt on the Claude CLI chat and on the ChatGPT chat.
- Dispatch tests: a fork runs on the CLI with only its own tools from its in-memory session; plugin tool grants and output caps keep the passthrough.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit b7bf937)

Release adaptation: retain staged Gateway permission-mode documentation and enforcement; omit the superseded upstream documentation exception.

Companions: #202941 and #202646 are present-equivalent (9ec8d08 and 087c816); #201554 is staged as 5647120. #202957 is not applicable (reverts a separate native-tools path). #204219, #203999, #203901, #203919, #203601 and #203271 are independent prewarm, lifecycle, recovery, review or default-routing changes; not required for the selected fork path.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 8a592a33b7866a1306c60468e4aaf2c9fb23a93f)
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: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S 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