docs(rfc): restructure plan-mode RFC and drop its Chinese counterpart
Reorganize along Problem / Proposal / High-level API / Detailed design / Roadmap / FAQ / Prior art / Alternatives / Acceptance / Risks. The product survey and Pi failure shapes move to Prior art; user-facing behavior (walkthrough, cordis.yml config, stdio, ACP, ctx.modes) gets its own High-level API section; FAQ collects behavioral clarifications of the chosen design, disjoint from Alternatives (rejected designs) and Risks (accepted costs). The zh counterpart and its pairing metadata are removed; the RFC is English-only (not in the required-pairs manifest).
This commit is contained in:
@@ -1,6 +0,0 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write
|
||||
2026-07-07-plan-mode.md: b28984bfad7e9a1adb8bbaaa4daa79a5c00fdf65
|
||||
2026-07-07-plan-mode.zh.md: 2b9be1cea702362ec3852c3da48909e6acdf25cf
|
||||
@@ -2,49 +2,63 @@
|
||||
|
||||
Status: proposed
|
||||
|
||||
English | [中文](2026-07-07-plan-mode.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The harness has no way to put an agent into a reduced-authority working state. The canonical feature that needs one is plan mode — the agent explores and designs under a read-only tool policy, produces a reviewable plan, and crosses back into full authority only through an explicit approval. [The extension cookbook](../../../cookbook/extension-cookbook.md) already reserves the row ("Plan mode — `tools/pre-execute` (deny writes) + a mode prompt section"), and [the ACP feature matrix](../../../../packages/ui/acp/acp-feature-support.md) records session modes as a known gap both reference adapters ship (Claude's plan auto-mode, Codex's read-only / agent / full-access presets). Neither says where the mode STATE lives, how it survives resume and fork, or how its model-visible consequences stay honest with the session log.
|
||||
The harness has no way to put an agent into a reduced-authority working state. The canonical feature that needs one is plan mode — the agent explores and designs under a read-only tool policy, produces a reviewable plan, and crosses back into full authority only through an explicit approval. [The extension cookbook](../../../cookbook/extension-cookbook.md) already reserves the row ("Plan mode — `tools/pre-execute` (deny writes) + a mode prompt section"), and [the ACP feature matrix](../../../../packages/ui/acp/acp-feature-support.md) records session modes as a known gap both reference adapters ship. Neither says where the mode STATE lives, how it survives resume and fork, or how its model-visible consequences stay honest with the session log.
|
||||
|
||||
A survey of shipped plan modes (Claude Code, Cursor, Copilot, OpenCode, Gemini CLI, Cline, Windsurf, Codex) shows the same five parts everywhere: a low-authority tool policy, a plan artifact, an approval moment, an execution-state switch, and durable state. Four of the five already exist here as gated infrastructure: what the model is TOLD it can do is shaped per step at [`system-prompt/assemble`](../../../../packages/core/system-prompt/README.md) and whatever ships is logged as `request/header*` events ([reconstructability](../../implemented/architecture/2026-07-05-reconstructable-requests.md)); what can RUN is gated at `tools/pre-execute` with typed decisions ([interception seams](../../implemented/feature/2026-06-30-interception-seams.md)); the approval moment is the `ask` vocabulary, serviced by the approval seam (`docs/rfc/proposed/feature/2026-07-06-approval-seam.md`, in flight on `feat/sandbox-support` as this is written — link it on merge); durable per-agent facts are `SessionEventMap` members ([the `todo/write` precedent](../../implemented/feature/2026-06-29-todo-write-tool.md)). The missing fifth is the mode itself: a named, durable, per-agent policy state the policy listeners can read.
|
||||
|
||||
The ecosystems that leave modes to convention show the failure shapes to avoid. Pi-style mode extensions fight over a last-wins global active-tool list, enforce "read-only" by prompt text alone (a hallucinated call to a still-registered tool executes), and re-inject plan state into every request to survive compaction. Each of those holes closes structurally here — but only if the mode is logged session state, not plugin-private memory.
|
||||
Every shipped plan mode decomposes into the same five parts — a low-authority tool policy, a plan artifact, an approval moment, an execution-state switch, and durable state ([Prior art](#prior-art) carries the survey). Four of the five already exist here as gated infrastructure: what the model is TOLD it can do is shaped per step at [`system-prompt/assemble`](../../../../packages/core/system-prompt/README.md) and whatever ships is logged as `request/header*` events ([reconstructability](../../implemented/architecture/2026-07-05-reconstructable-requests.md)); what can RUN is gated at `tools/pre-execute` with typed decisions ([interception seams](../../implemented/feature/2026-06-30-interception-seams.md)); the approval moment is the `ask` vocabulary, serviced by the approval seam (`docs/rfc/proposed/feature/2026-07-06-approval-seam.md`, in flight on `feat/sandbox-support` as this is written — link it on merge); durable per-agent facts are `SessionEventMap` members ([the `todo/write` precedent](../../implemented/feature/2026-06-29-todo-write-tool.md)). The missing fifth is the mode itself: a named, durable, per-agent policy state the policy listeners can read.
|
||||
|
||||
## Proposal
|
||||
|
||||
The deliverable is **plan mode**. It ships as the first **session mode** — a named, logged, per-agent policy state: mode definitions — which tools stay visible, what guidance section renders — are deployment config, and the mode IN FORCE for an agent is session state, folded from its log. One new product package, `@deepseek-ai/dsh-mode` at `packages/mode/mode/` (a new top-level group, the `packages/approval/` shape), owns the event vocabulary, a thin `ctx.modes` service, and every policy listener; the loop does not change. `plan` is the only shipped definition — the mode-shaped vocabulary exists so a second mode never renames durable event types, not because more modes ship now.
|
||||
|
||||
### The mode state is a session event
|
||||
The state is one `SessionEventMap` member: **`mode/set`**, a log-only, non-surface event carrying `{ mode: string }` with whole-value-replace semantics, plus a pure `foldMode(events)` that returns the mode in force — the last `mode/set`, or the default mode when none exists. Because [the log is the fact channel](../../implemented/architecture/2026-06-30-event-domain-semantics.md), resume, fork, and compaction restore the mode with no extra machinery, and UIs read flips off `session/event`. The default mode is the absence of policy — no section, no filtering, no gate — so an agent that never sees a `mode/set` behaves byte-identically to a deployment that never loads `dsh-mode`, which keeps every existing snapshot golden stable and makes the plugin safe to compose unconditionally.
|
||||
|
||||
`dsh-mode` declaration-merges **`mode/set`** into `SessionEventMap`: a log-only, non-surface event carrying `{ mode: string }`, whole-value-replace semantics like `todo/write`. A pure `foldMode(events)` returns the mode in force — the last `mode/set`, or the default mode when none exists — and the plugin caches the fold per session with a lazy cursor (the `foldRequestHeader` idiom). Because the event is log-only it never enters the model transcript, and because it is not a surface node compaction can never shadow it: the fold sees the whole log on live sessions, resume, and fork alike. Per [event-domain semantics](../../implemented/architecture/2026-06-30-event-domain-semantics.md) the log is the fact channel, so mode state needs no live `agent/*` mirror — UIs read `mode/set` off `session/event`.
|
||||
Enforcement is two layers that cover each other. The **soft** layer is a `system-prompt/assemble` listener that filters the tool schemas down to the mode's allowlist and appends the mode's guidance section — every transition therefore surfaces as an attributable `request/header-delta` on the next step, keeping the [reconstructability](../../implemented/architecture/2026-07-05-reconstructable-requests.md) invariant green by construction. The **hard** layer is a `tools/pre-execute` listener that denies, deny-by-default against the same allowlist, any call the mode does not permit — so a hallucinated call to a still-registered tool, or a schema re-widened by a foreign assemble listener, still cannot run.
|
||||
|
||||
The default mode is the absence of policy: no section, no filtering, no gate. An agent that never sees a `mode/set` behaves byte-identically to a deployment that never loads `dsh-mode` — which keeps every existing snapshot golden stable and makes the plugin safe to compose unconditionally.
|
||||
The model leaves plan mode through the **`exit_plan_mode`** tool: its single argument is the plan text, which makes the plan a durable log artifact, and the hard gate turns exactly this call into the approval moment (`ask`, routed by the approval seam) — approval flips the logged mode back to the default, rejection becomes the corrective error that keeps the model planning. A user flips the mode from any surface through `ctx.modes.set()`; the flip is applied at the next turn boundary (session events are turn-enclosed) and narrated to the model once, only when the model-visible state actually changed.
|
||||
|
||||
### Two layers of enforcement
|
||||
## High-level API
|
||||
|
||||
**Soft — what the model sees.** A `system-prompt/assemble` waterfall listener reads the calling agent's mode (the `AssembleContext` carries `agent`) and, in plan mode, filters `assembly.tools` down to the mode's allowlist and appends the mode's guidance section. The loop already renders per step and logs the result: entering or leaving a mode surfaces as a `request/header-delta` on the next step, so every mode transition is an attributable, diffable log fact and the [reconstructability](../../implemented/architecture/2026-07-05-reconstructable-requests.md) invariant stays green by construction. The section is static per mode and the plan itself stays in the conversation (messages and tool args, already in context), so a mode does not add per-step prompt churn — the pi-style "re-inject the plan file every request" hack is unnecessary and would only burn prefix cache.
|
||||
### A plan-mode session end to end
|
||||
|
||||
**Hard — what can run.** A `tools/pre-execute` listener denies, with a mode-naming reason that steers the model back to planning, any call outside the mode's allowlist. This layer is not redundant with the filter: [`ToolRegistry.execute()`](../../../../packages/core/tools/README.md) dispatches any registered tool by name, so a model hallucinating a filtered-out (or MCP-registered) tool would still run it without the gate. Deny-by-default against the allowlist also means the two layers cover each other — a peer `assemble` listener that re-widens the schema set cannot make the widened tools executable. An agent-less execution (no session to fold) passes through, mirroring the approval seam's agent-less degrade.
|
||||
The user switches the session to plan mode — the ACP mode picker or the stdio `/mode plan` — and from the next turn every request ships the filtered read-only toolset plus the plan-mode guidance section.
|
||||
|
||||
### Mode changes and turn enclosure
|
||||
The model explores and designs with what remains; if it attempts a write anyway, the gate denies with a reason naming the mode and pointing at `exit_plan_mode`, and the transcript keeps planning.
|
||||
|
||||
Two writers flip the mode. A **tool** (`exit_plan_mode`) appends `mode/set` from inside its own execution — already turn-enclosed, the `todo/write` path. A **user** flips it through `ctx.modes.set(agent, mode)` (a stdio command, ACP `session/set_mode`), and that path cannot append immediately: [every session event is turn-enclosed](../../implemented/architecture/2026-06-15-turn-enclosure-invariant.md), and an idle agent has no open turn. The service therefore records a pending intent and flushes it as the first append after the next `turn/start`. Sequencing makes this correct for the request the turn sends: the loop assembles the prompt after the turn opens and before each step, so a flush at `turn/start` is folded by step 1's assembly, while a mid-turn flip lands at the next boundary and takes effect on the following step — the same "applies to subsequent requests" semantics every surveyed product ships. A user flip is also **narrated**: when the flushed mode differs from the fold at the last `request/header`, the service appends one coalesced notice in the same frame ("The user switched this session to plan mode."), so a net-zero flip sequence narrates nothing, a tool-driven exit narrates through its own tool result instead, and a mode set before the first turn narrates nothing (the section is the state statement) — the boundary-narration principle of the in-flight env-state proposal (`docs/rfc/proposed/feature/2026-07-06-env-state-visibility.md`): a silently flipped prompt surface leaves the transcript arguing from a state the header no longer has. The cost is honest and bounded: a pending intent set while idle is lost if the process dies before the next turn (the UI that set it still holds it and re-applies); promoting user flips to a durable idle-time fact would need a generalized idle-record primitive, which stays out of scope until the loss proves real.
|
||||
When ready, the model calls `exit_plan_mode` with the plan markdown as its argument; the UI renders the plan as the call card and the approval prompt attaches to that same card, so what the human approves is exactly the logged artifact.
|
||||
|
||||
### The plan artifact and the exit tool
|
||||
On approve, the tool flips the logged mode back to the default: the next step runs with the full toolset and the widening `request/header-delta` in the log, and execution tracking from there is already `todo_write`'s job. On reject, the model receives the registry's "user rejected" error, revises, and re-presents.
|
||||
|
||||
The model-facing **`exit_plan_mode`** tool closes the loop, visible only in plan mode (the assemble filter adds it there and drops it elsewhere; the pre-execute gate denies it outside plan mode). Its single argument is the plan text — which makes the plan a durable, replayable log artifact riding the ordinary `tool/call` event, with no parallel plan-file store to invent or drift. Its [render intent](../../implemented/architecture/2026-07-02-tool-render-intent-union.md), decided up front: a `generic` call card titled by the plan's first heading with the plan markdown as content, and a `generic` result card. The approval moment is not new machinery: the mode gate returns `ask` for this one call, the approval seam routes it (ACP: `session/request_permission` attached to the streamed call, one-shot allow/reject), `allowed-once` lets the tool body append `mode/set` back to the default mode, and every other outcome becomes the corrective `isError` that tells the model to keep planning. Execution tracking after approval is already covered by `todo_write`. A deployment that composes no answerer keeps a safe but manual shape: the gate's `ask` resolves `unavailable` and denies (the seam's fail-closed default), so the exit degrades to the user toggling modes — never to an unapproved exit.
|
||||
### Deployment configuration
|
||||
|
||||
### Package shape
|
||||
Mode definitions are validated plugin Config — per repo convention, changeable from `cordis.yml` with no code edit. The shipped `plan` definition works with zero config; overriding it, or adding a mode, is a config entry:
|
||||
|
||||
`dsh-mode` is one product package, not a capability-seam trio — there is no swappable implementation; the variable parts are config values and the fixed listeners ([capability seams](../../implemented/architecture/2026-06-13-capability-seams.md): don't split preemptively; the approval seam made the same call). It is more than an [fs-policy-style](../../../../packages/fs/fs-policy/README.md) pure event-gate plugin only because UIs need a call surface: `ctx.modes` exposes `list()` (the configured definitions, for a mode picker), `get(agent)` (the fold plus any pending intent), and `set(agent, mode)` (validate against config, record intent, flush at the boundary). Everything else participates through listeners, so dropping the package gracefully removes modes rather than breaking a consumer.
|
||||
```yaml
|
||||
- id: mode
|
||||
name: '@deepseek-ai/dsh-mode'
|
||||
config:
|
||||
modes:
|
||||
plan:
|
||||
section: |
|
||||
You are in plan mode: explore and design, then present the
|
||||
plan for approval through exit_plan_mode.
|
||||
tools: [read, todo_write, web_search, web_fetch, exit_plan_mode]
|
||||
```
|
||||
|
||||
Mode definitions are validated plugin Config — per repo convention (changeable from `cordis.yml`, no code edit): each names its tool allowlist and its section text, and `plan`'s shipped default allowlist is the read-only surface (`read`, `todo_write`, `web_search`/`web_fetch`, `exit_plan_mode`) with `bash` and `subagent` excluded until the sandbox family can actually confine them. `AgentOptions` is merge-extensible, so `dsh-mode` declares an optional `mode` field: a creator (or a subagent provider forwarding its parent's mode) seeds the child's initial mode, applied through the same pending-intent flush on the first turn.
|
||||
`plan`'s shipped default allowlist is the read-only surface (`read`, `todo_write`, `web_search`/`web_fetch`, `exit_plan_mode`) with `bash` and `subagent` excluded until the sandbox family can actually confine them — a deployment that accepts the risk widens its own config today. `default` is reserved (the absence of policy) and rejected as a key; an unknown mode name fails validation loudly at `set()` time.
|
||||
|
||||
### Protocol and UI surfaces
|
||||
### In the terminal
|
||||
|
||||
The stdio app gains a mode toggle command, a banner line, and a readline answerer on the approval waterfall, so the exit approval prompts right in the terminal (riding the in-flight user-interaction stdio provider's one-prompt-owns-stdin queue where that seam is mounted — a yes/no confirm is a degenerate single-select — and raw readline otherwise). On ACP, the mode PICKER is this package's surface: `session/new`/`session/load` advertise `availableModes`/`currentModeId` from `ctx.modes` (consumed opportunistically via `ctx.get`, the `tool-bash` pattern), `session/set_mode` calls `set()` and notifies `current_mode_update` optimistically (the pending mode IS the user's selection; the logged `mode/set` follows at the boundary), and a `session/event` listener re-notifies on each logged flip that differs from the last sent. Individual environment knobs — sandbox mode, approval policy, the model — are NOT modes: they belong to `session/set_config_option`, and the in-flight env-state proposal's config-phase sketch, which currently routes `set_mode` to env facts, is the ONE overlap between the two proposals — the division proposed here is picker-to-modes / knobs-to-config-options, a mode definition may later bundle env facts (applied through `ctx.envState` where mounted) so a Codex-style preset stays a single mode, and whichever proposal lands second amends its wiring to match. The exit tool's approval needs no new ACP work at all — it rides the approval seam's answerer.
|
||||
The stdio app gains `/mode` (print the current and available modes) and `/mode <name>` (switch + banner — a command line, never sent to the model). The exit approval prompts right in the terminal: a readline answerer on the approval waterfall, riding the in-flight user-interaction stdio provider's one-prompt-owns-stdin queue where that seam is mounted (a yes/no confirm is a degenerate single-select) and raw readline otherwise.
|
||||
|
||||
### Over ACP
|
||||
|
||||
The mode PICKER is this package's surface: `session/new`/`session/load` advertise `availableModes`/`currentModeId` from `ctx.modes` (consumed opportunistically via `ctx.get`, the `tool-bash` pattern), `session/set_mode` calls `set()` and notifies `current_mode_update` optimistically (the pending mode IS the user's selection; the logged `mode/set` follows at the boundary), and a `session/event` listener re-notifies on each logged flip that differs from the last sent. The exit tool's approval needs no new ACP work at all — it rides the approval seam's `session/request_permission`, attached to the already-streamed call. Individual environment knobs — sandbox mode, approval policy, the model — are NOT modes and belong to `session/set_config_option` ([FAQ](#faq)).
|
||||
|
||||
### For agent creators
|
||||
|
||||
`ctx.modes` is the whole programmatic surface: `list()` returns the configured definitions plus the synthetic `default` entry (for pickers), `get(agent)` returns the folded mode plus any pending intent, and `set(agent, mode)` validates the name against config and records the boundary-applied intent. A creator seeds a child's initial mode through `AgentOptions.mode` (`AgentOptions` is merge-extensible; `dsh-mode` declares the optional field). There is no live `agent/*` mirror to subscribe: UIs read `mode/set` off `session/event`, per [event-domain semantics](../../implemented/architecture/2026-06-30-event-domain-semantics.md).
|
||||
|
||||
## Detailed design
|
||||
|
||||
@@ -72,14 +86,20 @@ The allowlist is deliberately the degenerate form of a future per-tool decision
|
||||
|
||||
### The fold, the service, and the flush
|
||||
|
||||
`foldMode(events)` is pure (exported for reconstructors and tests); the service tracks it per session with a lazy cursor in a `WeakMap<Session, { cursor, mode }>` — O(new events) per read, never invalidated, because the log is append-only and `mode/set` is not a surface node (compaction cannot rewrite it). `ctx.modes` (a cordis Service, key `modes`) exposes `list()` — the synthetic `default` entry plus the configured definitions, for pickers — `get(agent): { current, pending? }`, and `set(agent, mode)`, which validates the name against config, drops a no-op (target equals pending ?? current), and otherwise records the intent in a `WeakMap<Session, string>`. A contained `session/event` listener ([defensive patterns](../../../defensive-patterns.md): a policy plugin must not kill the feed) flushes the pending intent as a `mode/set` append on the next `turn/start` or `step/end` — both sit outside the step's tool-execution window, so the executions of a step always run under the mode its assembly folded — and, when the flushed mode differs from the fold at the last `request/header`, appends the one coalesced `context/message` notice in the same frame. Seeding rides `agent/created`: a declaration-merged `AgentOptions.mode` becomes a pending intent, so explicit options beat the logged baseline on create AND resume — the same precedence the call-config seed follows — while a fork child needs no mechanism at all (the parent's `mode/set` is inside the seeded prefix). One read-path rule closes the resume-with-edited-config gap: a folded mode name the current config no longer defines behaves as the default mode plus one boundary notice naming the dropped definition — never a silent substitute restriction, never a bricked session; `set()`'s loud validation covers only the write path, and a resumed log answers to the config it finds.
|
||||
`foldMode(events)` is pure (exported for reconstructors and tests); the service tracks it per session with a lazy cursor in a `WeakMap<Session, { cursor, mode }>` — O(new events) per read, never invalidated, because the log is append-only and `mode/set` is not a surface node (compaction cannot rewrite it). `set(agent, mode)` validates the name against config, drops a no-op (target equals pending ?? current), and otherwise records the intent in a `WeakMap<Session, string>` — it cannot append immediately, because [every session event is turn-enclosed](../../implemented/architecture/2026-06-15-turn-enclosure-invariant.md) and an idle agent has no open turn.
|
||||
|
||||
A contained `session/event` listener ([defensive patterns](../../../defensive-patterns.md): a policy plugin must not kill the feed) flushes the pending intent as a `mode/set` append on the next `turn/start` or `step/end` — both sit outside the step's tool-execution window, so the executions of a step always run under the mode its assembly folded — and, when the flushed mode differs from the fold at the last `request/header`, appends one coalesced `context/message` notice in the same frame ("The user switched this session to plan mode."); the user-visible narration cases are enumerated in the [FAQ](#faq). Seeding rides `agent/created`: `AgentOptions.mode` becomes a pending intent, so explicit options beat the logged baseline on create AND resume — the same precedence the call-config seed follows.
|
||||
|
||||
### The soft layer: a computed section and a post-`next()` filter
|
||||
|
||||
The guidance section is an ordinary registered section, `{ name: 'mode:policy', order: 50, text: context => … }` — order 50 sits after the persona (0) and before tool guidance (100–199); it resolves to the folded mode's configured text and to `''` (dropped at render) for the default mode or an agent-less assembly. The tool filter is a `system-prompt/assemble` waterfall listener that wraps: it awaits `next()` and filters the RETURNED assembly's `tools`, so additions made anywhere inside its wrap are covered. The filter enforces one rule in every mode: `exit_plan_mode` is visible IFF the agent's folded mode is `plan` — which is also what keeps a default-mode assembly byte-identical to a no-`dsh-mode` deployment even though the tool is always registered. In a non-default mode it additionally intersects with the mode's allowlist.
|
||||
A `system-prompt/assemble` waterfall listener reads the calling agent's mode (the `AssembleContext` carries `agent`) and, in a non-default mode, filters `assembly.tools` down to the mode's allowlist and appends the mode's guidance section. The loop already renders per step and logs the result: entering or leaving a mode surfaces as a `request/header-delta` on the next step, so every mode transition is an attributable, diffable log fact. The section is static per mode and the plan itself stays in the conversation (messages and tool args, already in context), so a mode does not add per-step prompt churn — re-injecting plan state into every request ([Prior art](#prior-art)'s compaction-survival hack) is unnecessary and would only burn prefix cache.
|
||||
|
||||
The guidance section is an ordinary registered section, `{ name: 'mode:policy', order: 50, text: context => … }` — order 50 sits after the persona (0) and before tool guidance (100–199); it resolves to the folded mode's configured text and to `''` (dropped at render) for the default mode or an agent-less assembly. The tool filter wraps: it awaits `next()` and filters the RETURNED assembly's `tools`, so additions made anywhere inside its wrap are covered. The filter enforces one rule in every mode: `exit_plan_mode` is visible IFF the agent's folded mode is `plan` — which is also what keeps a default-mode assembly byte-identical to a no-`dsh-mode` deployment even though the tool is always registered. In a non-default mode it additionally intersects with the mode's allowlist.
|
||||
|
||||
### The hard layer: the gate
|
||||
|
||||
The gate denies, with a mode-naming reason that steers the model back to planning, any call outside the mode's allowlist. This layer is not redundant with the filter: [`ToolRegistry.execute()`](../../../../packages/core/tools/README.md) dispatches any registered tool by name, so a model hallucinating a filtered-out (or MCP-registered) tool would still run it without the gate. Deny-by-default against the allowlist also means the two layers cover each other — a peer `assemble` listener that re-widens the schema set cannot make the widened tools executable.
|
||||
|
||||
```text
|
||||
tools/pre-execute: no exec.agent → next() // agent-less calls have no session to fold
|
||||
folded mode = default → next()
|
||||
@@ -90,15 +110,17 @@ tools/pre-execute: no exec.agent → next() // agent-less calls have no
|
||||
otherwise → deny // reason names the mode and points at exit_plan_mode
|
||||
```
|
||||
|
||||
The gate folds the LOGGED mode only, never the pending intent — enforcement judges by the same state the request's header shipped under. Because the `ask` is produced here and resolved by `ToolRegistry.execute()` through `ctx.approval`, `dsh-mode` takes no dependency on the approval package; a deployment without the seam gets the registry's fail-closed degrade.
|
||||
The agent-less pass-through mirrors the approval seam's agent-less degrade. The gate folds the LOGGED mode only, never the pending intent — enforcement judges by the same state the request's header shipped under. Because the `ask` is produced here and resolved by `ToolRegistry.execute()` through `ctx.approval`, `dsh-mode` takes no dependency on the approval package; the no-answerer degrade is pinned in the [FAQ](#faq).
|
||||
|
||||
### `exit_plan_mode`
|
||||
|
||||
`defineTool` with one required `plan: string` argument. `execute` rejects an agent-less call (the [`todo_write` precedent](../../implemented/feature/2026-06-29-todo-write-tool.md)), re-checks the folded mode as defense in depth, appends `mode/set { mode: 'default' }` in-turn, and returns a short confirmation; the next step's assembly restores the full toolset and logs the widening `request/header-delta`. `presentCall` is a `generic` card carrying the plan markdown as content — the approval prompt attaches to this already-streamed call by `callId`, so what the human approves is exactly the logged artifact. A rejection reaches the model as the registry's "user rejected" `isError`, and it revises and re-presents.
|
||||
`defineTool` with one required `plan: string` argument — the plan is thereby a durable, replayable log artifact riding the ordinary `tool/call` event. `execute` rejects an agent-less call (the [`todo_write` precedent](../../implemented/feature/2026-06-29-todo-write-tool.md)), re-checks the folded mode as defense in depth, appends `mode/set { mode: 'default' }` in-turn (a tool execution is already turn-enclosed — the `todo/write` path), and returns a short confirmation; the next step's assembly restores the full toolset and logs the widening `request/header-delta`.
|
||||
|
||||
Its [render intent](../../implemented/architecture/2026-07-02-tool-render-intent-union.md), decided up front: `presentCall` is a `generic` card titled by the plan's first heading with the plan markdown as content, plus a `generic` result card — the approval prompt attaches to this already-streamed call by `callId`. The approval moment is not new machinery: the gate returns `ask` for this one call, the approval seam routes it (one-shot allow/reject), `allowed-once` lets the tool body run, and every other outcome becomes the registry's "user rejected" `isError` that tells the model to revise and re-present.
|
||||
|
||||
### Dependencies and surfaces
|
||||
|
||||
`dsh-mode` peers on `cordis`, `dsh-session`, `dsh-agent`, `dsh-tools`, `dsh-system-prompt` (manifest shape mirrors `dsh-tool-todo`), injects `['tools', 'systemPrompt']`, and depends on neither the approval package nor any UI. The stdio app adds a `/mode [name]` line-handler branch (print or switch + banner, never sent to the model) and the readline answerer for its own agent. The ACP wire mapping is pinned in Protocol and UI surfaces; package-wise the bridge takes a type-only peer edge on `dsh-mode` and reads the service opportunistically, so a bridge without the plugin behaves exactly as today.
|
||||
`dsh-mode` is one product package, not a capability-seam trio ([Alternatives considered](#alternatives-considered)): it peers on `cordis`, `dsh-session`, `dsh-agent`, `dsh-tools`, `dsh-system-prompt` (manifest shape mirrors `dsh-tool-todo`), injects `['tools', 'systemPrompt']`, and depends on neither the approval package nor any UI. Beyond the `ctx.modes` call surface everything participates through listeners, so dropping the package gracefully removes modes rather than breaking a consumer. The stdio app adds a `/mode [name]` line-handler branch and the readline answerer for its own agent. The ACP wire mapping is pinned in [High-level API](#over-acp); package-wise the bridge takes a type-only peer edge on `dsh-mode` and reads the service opportunistically, so a bridge without the plugin behaves exactly as today.
|
||||
|
||||
### The recorded scenario and the harness op
|
||||
|
||||
@@ -112,7 +134,7 @@ No new cordis event is declared (`mode/set` rides `session/event`; the listeners
|
||||
|
||||
Plan mode is one feature and lands as one. An agent that can be locked into planning but has no sanctioned way to propose leaving it is not a smaller version of the feature — it is a different and worse one, where every plan ends with the model asking the user to flip a switch it cannot see. The two stages below are therefore build-and-review order for one stacked landing ([stacked-review guide](../../../cookbook/responding-to-pr-review-on-a-stack.md)): stage 2 stacks on stage 1 and the stack merges together; neither stage is a shippable milestone on its own.
|
||||
|
||||
The one hard prerequisite is the approval seam (`docs/rfc/proposed/feature/2026-07-06-approval-seam.md`): the exit approval is its `ask` routing end to end. It is already implemented on `feat/sandbox-support`, so the coupling is merge order, not unbuilt work — this stack bases on that branch until it lands on master. The wider in-flight neighborhood is convergent, not conflicting: the sandbox-escalation branch ships the first live approval composition (its example and scripted-answer harness are the precedent our recorded scenarios follow), the env-state proposal pins the same fold-from-log + boundary-application idiom for environment facts (its `session/set_mode` config-phase sketch is the single coordination point, resolved in Protocol and UI surfaces), and the user-interaction seam supplies the stdio answerer's stdin discipline where mounted.
|
||||
The one hard prerequisite is the approval seam (`docs/rfc/proposed/feature/2026-07-06-approval-seam.md`): the exit approval is its `ask` routing end to end. It is already implemented on `feat/sandbox-support`, so the coupling is merge order, not unbuilt work — this stack bases on that branch until it lands on master. The wider in-flight neighborhood is convergent, not conflicting: the sandbox-escalation branch ships the first live approval composition (its example and scripted-answer harness are the precedent our recorded scenarios follow), the env-state proposal pins the same fold-from-log + boundary-application idiom for environment facts (its `session/set_mode` config-phase sketch is the single coordination point, resolved in the [FAQ](#faq)), and the user-interaction seam supplies the stdio answerer's stdin discipline where mounted.
|
||||
|
||||
### Stage 1 — the mode core
|
||||
|
||||
@@ -124,6 +146,30 @@ The `dsh-mode` package: `mode/set` + `foldMode`, the assemble filter and mode se
|
||||
|
||||
Deferred beyond this landing, each behind its own decision: subagent mode inheritance via a forwarded `AgentOptions.mode` (the option field itself ships in stage 1), per-tool `ask` policies inside mode definitions (an OpenCode-style "bash asks in plan mode"), preset modes beyond `plan` (read-only, accept-edits), sandbox-backed bash confinement in plan mode, and the idle-record primitive if pending-intent loss proves real.
|
||||
|
||||
## FAQ
|
||||
|
||||
Behavioral clarifications of the chosen design; rejected designs live in [Alternatives considered](#alternatives-considered), accepted costs in [Risks](#risks).
|
||||
|
||||
**When does a user's mode flip take effect?** At the next turn boundary: `set()` records a pending intent, the service flushes it as the first append after the next `turn/start`, and the loop assembles the prompt after the turn opens and before each step — so step 1 already folds it. A mid-turn flip lands at the next boundary and takes effect on the following step. This is the "applies to subsequent requests" semantics every product in [Prior art](#prior-art) ships.
|
||||
|
||||
**When is a mode change narrated to the model?** Only when the model-visible state actually changed: the flush compares the flushed mode against the fold at the last `request/header` and narrates once, coalesced. A net-zero flip sequence (plan then back, all before the boundary) narrates nothing; a tool-driven exit narrates through its own tool result instead; a mode set before the first turn narrates nothing — the section is the state statement. The principle is the in-flight env-state proposal's boundary narration: a silently flipped prompt surface leaves the transcript arguing from a state the header no longer has.
|
||||
|
||||
**What happens on resume when the config no longer defines the folded mode?** One read-path rule closes the gap: a folded mode name the current config no longer defines behaves as the default mode plus one boundary notice naming the dropped definition — never a silent substitute restriction, never a bricked session. `set()`'s loud validation covers only the write path; a resumed log answers to the config it finds.
|
||||
|
||||
**What if a deployment composes no approval answerer?** Plan mode stays safe but manual: the gate's `ask` resolves `unavailable` and denies (the seam's fail-closed default), so the exit degrades to the user toggling modes — never to an unapproved exit. The mode section tells the model to present its plan through `exit_plan_mode` — and to ask the user if that is denied — so it never thrashes against the gate.
|
||||
|
||||
**Do subagents inherit the parent's mode?** A fork child inherits for free — the parent's `mode/set` is inside the seeded prefix. A spawn child starts in the default mode unless its creator seeds `AgentOptions.mode`; automatic forwarding by subagent providers is deferred ([Roadmap](#roadmap)).
|
||||
|
||||
**Why aren't sandbox mode, approval policy, or the model themselves modes?** They are individual environment knobs and belong to ACP's `session/set_config_option`; the division this proposal pins is picker-to-modes / knobs-to-config-options. The in-flight env-state proposal's config-phase sketch currently routes `session/set_mode` to env facts — the one overlap between the two proposals. A mode definition may later bundle env facts (applied through `ctx.envState` where mounted) so a Codex-style preset stays a single mode; fusing approval policy into the mode CONCEPT itself is rejected in [Alternatives considered](#alternatives-considered).
|
||||
|
||||
## Prior art
|
||||
|
||||
A survey of shipped plan modes (Claude Code, Cursor, Copilot, OpenCode, Gemini CLI, Cline, Windsurf, Codex) shows the same five parts everywhere — the low-authority tool policy, plan artifact, approval moment, execution-state switch, and durable state that [Problem](#problem) builds on.
|
||||
|
||||
The mode surface is a LIST everywhere it is advertised, never a boolean: Claude Code's picker offers `plan` beside `acceptEdits` (plus an auto-mode entry into plan), and Codex — whose plan feature itself is `/plan` — fills its list with its approval presets (read-only / agent / full-access). This is the surface [the ACP feature matrix](../../../../packages/ui/acp/acp-feature-support.md) records as the gap, and what sizes the vocabulary as named modes rather than a flag.
|
||||
|
||||
The ecosystems that leave modes to convention show the failure shapes to avoid. Pi-style mode extensions fight over a last-wins global active-tool list, enforce "read-only" by prompt text alone (a hallucinated call to a still-registered tool executes), and re-inject plan state into every request to survive compaction. Each hole closes structurally here, but only because the mode is logged session state rather than plugin-private memory: per-agent folded state replaces the contested global list, the hard gate closes the prompt-only hole, and a log-only non-surface event that compaction cannot shadow makes the re-injection hack unnecessary.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Permission modes as the concept (the Claude Code shape).** One `permissionMode` fusing approval policy and tool policy. Here those are two axes with two owners: the approval seam owns "who answers this question", modes own "what surface does the model get". ACP models them as related but distinct (a mode may select an approval policy later — a mode definition gains a field, not a merger).
|
||||
@@ -132,7 +178,7 @@ Deferred beyond this landing, each behind its own decision: subagent mode inheri
|
||||
|
||||
**Loop-owned mode state.** Rejected on the standing rule (plugins, not loop changes): every hook the feature needs — assemble, pre-execute, turn boundaries, session events — is already a documented seam, so a loop edit would buy nothing but coupling.
|
||||
|
||||
**Prompt-only plan mode (no hard gate).** The Pi failure shape: filtering schemas (or asking nicely) does not stop a dispatch of a still-registered tool. The pre-execute gate is the enforcement layer; the filter is UX and cache hygiene.
|
||||
**Prompt-only plan mode (no hard gate).** The Pi failure shape ([Prior art](#prior-art)): filtering schemas (or asking nicely) does not stop a dispatch of a still-registered tool. The pre-execute gate is the enforcement layer; the filter is UX and cache hygiene.
|
||||
|
||||
**Runtime-only mode (UI- or bridge-local, unlogged).** Resume and fork would silently drop the mode, and the header deltas a mode causes would have no attributable cause in the log. Logged state is what makes the mode auditable and restorable for free.
|
||||
|
||||
@@ -140,7 +186,7 @@ Deferred beyond this landing, each behind its own decision: subagent mode inheri
|
||||
|
||||
**A plan-file store (`.plans/` directory).** A second durable home for what the log already carries replayably; a deployment wanting files can add a tool that writes them. One home per fact.
|
||||
|
||||
**A boolean `planMode` instead of named modes.** Too narrow for the surface the repo already tracks: ACP advertises a mode LIST, Claude Code's picker lists `plan` beside `acceptEdits`, and Codex — whose plan feature is `/plan` — fills its list with its approval presets (read-only / agent / full-access); generalizing later would rename durable event vocabulary. The string-shaped mechanism costs nothing extra now; only `plan` ships as a definition.
|
||||
**A boolean `planMode` instead of named modes.** Too narrow for the surface the repo already tracks: ACP advertises a mode LIST and the shipped pickers fill it with more than plan ([Prior art](#prior-art)); generalizing later would rename durable event vocabulary. The string-shaped mechanism costs nothing extra now; only `plan` ships as a definition.
|
||||
|
||||
**A tool-policy-stack service (the Pi-critique remedy).** A dedicated composition service for tool policies is premature: waterfall listeners compose by construction, and the deny-by-default hard gate makes filter-order races non-exploitable. Formalize only if real conflicts appear.
|
||||
|
||||
@@ -158,4 +204,4 @@ Deferred beyond this landing, each behind its own decision: subagent mode inheri
|
||||
|
||||
## Risks
|
||||
|
||||
A pending user flip set while idle is lost if the process dies before the next turn — accepted (the UI re-applies; the idle-record primitive is the escape hatch if this bites in practice). Every mode transition is a logged header change and therefore a prefix-cache reset at the provider — inherent, visible in per-step usage, and an argument against mode-flapping UIs, not against the design. Sibling-listener order is not deterministic, so a foreign assemble listener wrapping OUTSIDE the mode listener could re-widen filtered schemas — the filter runs on the assembly `next()` returns (so everything inside its wrap is covered), and the hard gate keeps anything re-widened non-executable; the residual cost is cosmetic (the model sees a tool it cannot use), accepted rather than mechanized. Plan mode's shipped allowlist excludes `bash` and `subagent`, which costs real exploration power (no `git log`, no read-only delegate) until the sandbox family and mode inheritance land — a deployment that accepts the risk can widen its own config today. The whole landing gates on the approval seam merging first — a deliberate schedule coupling accepted in place of shipping the mode core alone (an incomplete feature, per the roadmap); the seam is implemented on its branch, and this stack bases on it meanwhile. A deployment that composes no answerer keeps a safe but manual plan mode (`ask` → `unavailable` → deny), and the mode section tells the model to present its plan through `exit_plan_mode` — and to ask the user if that is denied — so it never thrashes against the gate. Two in-flight proposals touch the ACP mode surface (this one and the env-state config phase): the picker-to-modes / knobs-to-config-options division in Protocol and UI surfaces is the proposed contract, landing order decides who wires `session/set_mode`, and the second lander owes the amendment. Branch-heavy policy code under the per-file 100% coverage gate is real work, accepted as the ACP bridge did.
|
||||
A pending user flip set while idle is lost if the process dies before the next turn — accepted (the UI re-applies; the idle-record primitive is the escape hatch if this bites in practice). Every mode transition is a logged header change and therefore a prefix-cache reset at the provider — inherent, visible in per-step usage, and an argument against mode-flapping UIs, not against the design. Sibling-listener order is not deterministic, so a foreign assemble listener wrapping OUTSIDE the mode listener could re-widen filtered schemas — the filter runs on the assembly `next()` returns (so everything inside its wrap is covered), and the hard gate keeps anything re-widened non-executable; the residual cost is cosmetic (the model sees a tool it cannot use), accepted rather than mechanized. Plan mode's shipped allowlist excludes `bash` and `subagent`, which costs real exploration power (no `git log`, no read-only delegate) until the sandbox family and mode inheritance land — a deployment that accepts the risk can widen its own config today. The whole landing gates on the approval seam merging first — a deliberate schedule coupling accepted in place of shipping the mode core alone (an incomplete feature, per the roadmap); the seam is implemented on its branch, and this stack bases on it meanwhile. Two in-flight proposals touch the ACP mode surface (this one and the env-state config phase): the picker-to-modes / knobs-to-config-options division pinned in the [FAQ](#faq) is the proposed contract, landing order decides who wires `session/set_mode`, and the second lander owes the amendment. Branch-heavy policy code under the per-file 100% coverage gate is real work, accepted as the ACP bridge did.
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
# RFC: Plan mode——日志化的每-agent 会话模式
|
||||
|
||||
Status: proposed
|
||||
|
||||
[English](2026-07-07-plan-mode.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
harness 目前没有办法把一个 agent 置入低权限的工作状态。最需要这个能力的经典 feature 就是 plan mode——agent 在只读工具策略下探索与设计,产出一份可评审的计划,只有经过一次显式批准才跨回完整权限。[扩展 cookbook](../../../cookbook/extension-cookbook.md) 已经预留了这一行(「Plan mode——`tools/pre-execute`(deny writes)+ 一个模式提示 section」),[ACP 功能矩阵](../../../../packages/ui/acp/acp-feature-support.md) 把会话模式记录为两个参照 adapter 都已发布的已知缺口(Claude 的 plan 自动模式、Codex 的 read-only / agent / full-access 预设)。但两处都没有说:模式**状态**存在哪里,它如何在 resume 与 fork 之间存活,它对模型可见的后果如何与会话日志保持诚实。
|
||||
|
||||
对已发布 plan mode 的调研(Claude Code、Cursor、Copilot、OpenCode、Gemini CLI、Cline、Windsurf、Codex)显示出处处相同的五个组成部分:低权限工具策略、计划工件、审批时刻、执行态切换、持久状态。其中四个在本仓库已经以带门禁的基础设施形态存在:模型「被告知能做什么」在每个 step 由 [`system-prompt/assemble`](../../../../packages/core/system-prompt/README.md) 塑形,实际发出的内容以 `request/header*` 事件记入日志([可重构性](../../implemented/architecture/2026-07-05-reconstructable-requests.md));「什么能真正运行」由 `tools/pre-execute` 以类型化决定把关([拦截 seam](../../implemented/feature/2026-06-30-interception-seams.md));审批时刻就是 `ask` 词汇,由审批 seam 服务(`docs/rfc/proposed/feature/2026-07-06-approval-seam.md`,写作本文时在 `feat/sandbox-support` 分支在途——合入后改为链接);持久的每-agent 事实是 `SessionEventMap` 成员([`todo/write` 先例](../../implemented/feature/2026-06-29-todo-write-tool.md))。缺失的第五个就是模式本身:一个命名的、持久的、策略 listener 能读取的每-agent 策略状态。
|
||||
|
||||
把模式留给约定的生态展示了要避开的失败形态。Pi 式的模式扩展会争抢一份 last-wins 的全局激活工具列表,仅靠 prompt 文本执行「只读」(对仍然注册着的工具的幻觉调用照样执行),并且为了在 compaction(历史压缩)后存活而把计划状态重注入每一个请求。这些洞在这里都能结构性地关闭——但前提是模式是日志化的会话状态,而不是插件私有内存。
|
||||
|
||||
## 提案
|
||||
|
||||
交付物是 **plan mode**。它以第一个**会话模式(session mode)**的形态发布——一个命名的、日志化的、每-agent 的策略状态:模式定义——哪些工具保持可见、渲染哪段指导 section——是部署配置,对某个 agent **生效中**的模式则是会话状态,从它的日志 fold 出来。一个新的 product 包 `@deepseek-ai/dsh-mode`(位于 `packages/mode/mode/`,新顶层组,`packages/approval/` 的形态)拥有事件词汇、一个薄薄的 `ctx.modes` 服务和全部策略 listener;loop 不改。`plan` 是唯一发布的定义——模式形态的词汇存在是为了第二个模式到来时不必重命名持久事件类型,不是为了现在就发布更多模式。
|
||||
|
||||
### 模式状态是一条会话事件
|
||||
|
||||
`dsh-mode` 把 **`mode/set`** 声明合并进 `SessionEventMap`:log-only、非 surface 的事件,携带 `{ mode: string }`,整值替换语义同 `todo/write`。纯函数 `foldMode(events)` 返回生效中的模式——最后一条 `mode/set`,一条都没有则为默认模式——插件用惰性游标按会话缓存这个 fold(`foldRequestHeader` 的习语)。因为事件是 log-only 的,它永不进入模型 transcript;因为它不是 surface 节点,compaction 永远遮蔽不了它:无论活跃会话、resume 还是 fork,fold 看到的都是完整日志。按[事件域语义](../../implemented/architecture/2026-06-30-event-domain-semantics.md),日志就是事实通道,所以模式状态不需要任何实时 `agent/*` 镜像——UI 从 `session/event` 上读 `mode/set`。
|
||||
|
||||
默认模式就是策略的缺席:没有 section、没有过滤、没有闸门。一个从未见过 `mode/set` 的 agent,行为与从未加载 `dsh-mode` 的部署逐字节相同——这让所有既有快照 goldens 保持稳定,也让这个插件可以无条件进入任何组合。
|
||||
|
||||
### 两层执行
|
||||
|
||||
**软层——模型看见什么。**一个 `system-prompt/assemble` waterfall(瀑布式事件)listener 读取调用方 agent 的模式(`AssembleContext` 携带 `agent`),在 plan 模式下把 `assembly.tools` 过滤到该模式的 allowlist(白名单)并追加该模式的指导 section。loop 本来就每 step 渲染并把结果记账:进入或离开一个模式在下一个 step 表现为一条 `request/header-delta`,于是每次模式转换都是可归因、可 diff 的日志事实,[可重构性](../../implemented/architecture/2026-07-05-reconstructable-requests.md)不变量靠构造保持常绿。section 按模式静态,计划本身留在对话里(消息与工具参数,本就在上下文中),所以模式不带来逐 step 的 prompt 抖动——Pi 式「每个请求重注入计划文件」的 hack 在这里没有必要,只会白烧前缀缓存。
|
||||
|
||||
**硬层——什么能运行。**一个 `tools/pre-execute` listener 对 allowlist 之外的任何调用 deny,理由文本点名当前模式并把模型引回规划。这一层与过滤器并不冗余:[`ToolRegistry.execute()`](../../../../packages/core/tools/README.md) 按名字分发任何已注册工具,模型幻觉调用一个被过滤掉的(或 MCP 注册的)工具,没有闸门照样会执行。对着 allowlist 的 deny-by-default 也让两层互为掩护——某个兄弟 `assemble` listener 把 schema 集合重新放宽,也无法让放宽的工具变得可执行。无 agent 的执行(没有可 fold 的会话)直接放行,与审批 seam 的无 agent 降级一致。
|
||||
|
||||
### 模式切换与 turn 封闭
|
||||
|
||||
翻转模式的写者有两个。**工具**(`exit_plan_mode`)在自身执行内部追加 `mode/set`——天然被 turn 封闭,即 `todo/write` 的路径。**用户**经 `ctx.modes.set(agent, mode)` 翻转(stdio 命令、ACP `session/set_mode`),而这条路径不能立即追加:[每条会话事件都被 turn 封闭](../../implemented/architecture/2026-06-15-turn-enclosure-invariant.md),空闲的 agent 没有敞开的 turn。因此服务先记下一个待落账意图(pending intent),在下一个 `turn/start` 之后作为第一条追加落账。时序保证了它对本 turn 发出的请求是正确的:loop 在 turn 打开之后、每个 step 之前组装 prompt,所以 `turn/start` 处的落账会被 step 1 的组装 fold 到,而 turn 中途的翻转落在下一个边界、于下一个 step 生效——与所有被调研产品「对后续请求生效」的语义一致。用户翻转还会被**叙述**:当落账的模式与最后一条 `request/header` 处的 fold 不同,服务在同一帧内追加一条合并后的通知(「The user switched this session to plan mode.」),因此净值为零的翻转序列什么也不说,工具驱动的退出改由它自己的工具结果叙述,首个 turn 之前设定的模式也不叙述(section 就是状态陈述)——这是在途 env-state 提案(`docs/rfc/proposed/feature/2026-07-06-env-state-visibility.md`)钉下的边界叙述原则:被静默翻转的 prompt 面会让 transcript 继续用 header 已经不再持有的状态说话。代价诚实且有界:空闲时设置的待落账意图,若进程在下一个 turn 前死亡即丢失(设置它的 UI 手里仍有状态,重新应用即可);把用户翻转升格为空闲时的持久事实需要一个泛化的空闲记录原语,在损失被证明真实之前不进范围。
|
||||
|
||||
### 计划工件与退出工具
|
||||
|
||||
模型侧的 **`exit_plan_mode`** 工具收拢闭环,仅在 plan 模式可见(assemble 过滤器在那里加入它、在别处丢弃它;pre-execute 闸门在 plan 模式之外 deny 它)。它唯一的参数就是计划文本——这让计划成为骑在普通 `tool/call` 事件上的持久、可回放日志工件,无需发明一个会漂移的平行计划文件存储。它的[渲染意图](../../implemented/architecture/2026-07-02-tool-render-intent-union.md)在设计期定死:`generic` 调用卡以计划的第一个标题为题、计划 markdown 为内容,结果卡也是 `generic`。审批时刻不是新机器:模式闸门只对这一个调用返回 `ask`,审批 seam 负责路由(ACP:`session/request_permission` 挂到已流出的调用上,一次性 allow/reject),`allowed-once` 让工具体把 `mode/set` 追加回默认模式,其余任何结局都变成告诉模型继续规划的纠正性 `isError`。批准之后的执行跟踪已由 `todo_write` 覆盖。没有组合任何 answerer 的部署保持安全但手动的形态:闸门的 `ask` 解析为 `unavailable` 并 deny(seam 的失败关闭默认),退出退化为用户手动切换模式——绝不会退化为未经批准的退出。
|
||||
|
||||
### 包形态
|
||||
|
||||
`dsh-mode` 是一个 product 包,不是 capability-seam 三件套——没有可替换的实现;可变的部分是配置值和固定的 listener([capability seams](../../implemented/architecture/2026-06-13-capability-seams.md):不要抢先拆分;审批 seam 做了同样的判断)。它比 [fs-policy 式](../../../../packages/fs/fs-policy/README.md)的纯事件闸门插件多出一点,只因为 UI 需要一个调用面:`ctx.modes` 暴露 `list()`(配置的定义集,给模式选择器)、`get(agent)`(fold 加上任何待落账意图)与 `set(agent, mode)`(对配置校验、记录意图、在边界落账)。其余一切都通过 listener 参与,所以卸载这个包是优雅地失去模式,而不是弄坏某个消费者。
|
||||
|
||||
模式定义是经校验的插件 Config——按仓库惯例(从 `cordis.yml` 可改、无需改代码):每个定义给出工具 allowlist 和 section 文本,`plan` 内置的默认 allowlist 是只读面(`read`、`todo_write`、`web_search`/`web_fetch`、`exit_plan_mode`),`bash` 与 `subagent` 被排除,直到沙盒家族真能约束它们。`AgentOptions` 可声明合并,所以 `dsh-mode` 声明一个可选 `mode` 字段:创建者(或转发父模式的 subagent provider)为子代理播种初始模式,经同一条待落账路径在第一个 turn 应用。
|
||||
|
||||
### 协议与 UI 表面
|
||||
|
||||
stdio 应用获得模式切换命令、一行 banner,以及审批 waterfall 上的 readline answerer,退出审批就在终端里提问(user-interaction stdio provider 在场时骑它的「一次一个提示拥有 stdin」队列——yes/no 确认就是退化的单选——否则用裸 readline)。在 ACP 上,模式**选择器**是本包的表面:`session/new`/`session/load` 从 `ctx.modes` 通告 `availableModes`/`currentModeId`(经 `ctx.get` 伺机消费,即 `tool-bash` 模式),`session/set_mode` 调用 `set()` 并乐观地通知 `current_mode_update`(待落账模式就是用户的选择;日志化的 `mode/set` 随后在边界落地),一个 `session/event` listener 对每条与上次通知不同的日志翻转再通知一次。各个环境旋钮——沙盒模式、审批策略、模型——**不是**模式:它们属于 `session/set_config_option`,而在途 env-state 提案的 config 阶段草图目前把 `set_mode` 接到环境事实上,这是两份提案之间**唯一**的重叠——此处提议的分界是选择器归模式 / 旋钮归 config options,模式定义将来可以捆绑环境事实(在 `ctx.envState` 在场时顺带应用),让 Codex 式预设仍是单个模式,后合入的提案修正自己的接线以对齐。退出工具的审批完全不需要新的 ACP 工作——它骑审批 seam 的 answerer。
|
||||
|
||||
## 详细设计
|
||||
|
||||
### 词汇
|
||||
|
||||
```text
|
||||
'mode/set': { mode: string } // SessionEventMap merge in dsh-mode: log-only, non-surface,
|
||||
// whole-value replace — the last one in the log wins
|
||||
DEFAULT_MODE = 'default' // the fold of a log with no mode/set; reserved, not definable
|
||||
```
|
||||
|
||||
载荷不携带 reason/来源字段:工具驱动的翻转紧邻它的 `tool/call`,用户翻转坐在它的 turn 边界上,因果就在日志相邻处——与[可重构性 RFC](../../implemented/architecture/2026-07-05-reconstructable-requests.md)对 header delta 做出的「叙事字段可推导」同一判断(在途的 `env/state` 事件携带 `source`,恰因它的 drift 变体**没有**日志相邻的因——是对照,不是冲突)。模式名是配置声明的词汇,不是跨边界的不透明 id,所以保持裸字符串(不用 `Branded<B>`)。
|
||||
|
||||
### 配置与 resolve 步骤
|
||||
|
||||
```text
|
||||
interface ModeDefinition { section: string; tools: string[] } // prompt text; allowlist of tool NAMES
|
||||
interface ModeConfig { modes?: Record<string, ModeDefinition> } // plan's built-in definition merged unless overridden
|
||||
resolveConfig(config): ResolvedModes // explicit resolve (the dsh-bash template), fail-loud:
|
||||
// 'default' as a key rejected; allowlists may name
|
||||
// not-yet-registered tools (registration is dynamic)
|
||||
```
|
||||
|
||||
allowlist 刻意是未来按工具决定映射(`allow | deny | ask`)的退化形式:执行期的 ask 策略(「每次写都问」的 guarded 模式)推迟到审批 seam 长出持久授权(`allow_always`——它自己的开放问题)之后,而配置形状必须在它们到来时无需迁移。
|
||||
|
||||
### fold、服务与落账
|
||||
|
||||
`foldMode(events)` 是纯函数(导出给重构器与测试);服务用 `WeakMap<Session, { cursor, mode }>` 里的惰性游标按会话跟踪它——每次读取 O(新事件数),永不失效,因为日志仅追加且 `mode/set` 不是 surface 节点(compaction 改写不了它)。`ctx.modes`(cordis Service,键 `modes`)暴露 `list()`——合成的 `default` 条目加上配置的定义集,给选择器——`get(agent): { current, pending? }`,以及 `set(agent, mode)`:对配置校验名字、丢弃 no-op(目标等于 pending ?? current)、否则把意图记进 `WeakMap<Session, string>`。一个被收容的 `session/event` listener([防御模式](../../../defensive-patterns.md):策略插件不得杀死事件流)在下一个 `turn/start` 或 `step/end` 把待落账意图作为 `mode/set` 追加落账——两处都在 step 的工具执行窗口之外,所以一个 step 的执行永远运行在其组装所 fold 的模式下——并且当落账模式与最后一条 `request/header` 处的 fold 不同时,在同一帧内追加那条合并的 `context/message` 通知。播种骑 `agent/created`:声明合并的 `AgentOptions.mode` 变成待落账意图,于是显式选项在 create 与 resume 上都压过日志基线——与调用配置种子相同的优先级——而 fork 子代理完全不需要机制(父的 `mode/set` 就在种子前缀里)。一条读路径规则补上「resume 时配置已改」的缺口:fold 出的模式名若当前配置已不再定义,按默认模式行事,并在下一个边界追加一条点名被移除定义的通知——绝不静默替换一个别的限制,也绝不让会话变砖;`set()` 的大声校验只覆盖写路径,恢复出来的日志面对的是它所遇到的配置。
|
||||
|
||||
### 软层:计算型 section 与 post-`next()` 过滤器
|
||||
|
||||
指导 section 是一个普通注册的 section:`{ name: 'mode:policy', order: 50, text: context => … }`——order 50 位于 persona(0)之后、工具指南(100–199)之前;它解析为 fold 出的模式的配置文本,对默认模式或无 agent 的组装解析为 `''`(渲染时丢弃)。工具过滤器是一个包裹式的 `system-prompt/assemble` waterfall listener:先 await `next()`,再过滤**返回的** assembly 的 `tools`,于是其包裹之内任何位置的添加都被覆盖。过滤器在所有模式下执行一条规则:`exit_plan_mode` 可见当且仅当 agent fold 出的模式是 `plan`——这也正是让默认模式的组装与无 `dsh-mode` 部署逐字节相同的原因,即便该工具始终注册着。在非默认模式下它再与该模式的 allowlist 求交。
|
||||
|
||||
### 硬层:闸门
|
||||
|
||||
```text
|
||||
tools/pre-execute: no exec.agent → next() // agent-less calls have no session to fold
|
||||
folded mode = default → next()
|
||||
exec.name = exit_plan_mode:
|
||||
plan mode → { kind: 'ask' } // the approval moment; the registry routes it
|
||||
otherwise → deny
|
||||
allowlisted → next()
|
||||
otherwise → deny // reason names the mode and points at exit_plan_mode
|
||||
```
|
||||
|
||||
闸门只 fold **已落账**的模式,绝不看待落账意图——执法依据与请求 header 出厂时的状态相同。因为 `ask` 在这里产生、由 `ToolRegistry.execute()` 经 `ctx.approval` 解析,`dsh-mode` 对审批包零依赖;没有该 seam 的部署得到注册表的失败关闭降级。
|
||||
|
||||
### `exit_plan_mode`
|
||||
|
||||
`defineTool`,一个必填参数 `plan: string`。`execute` 拒绝无 agent 调用([`todo_write` 先例](../../implemented/feature/2026-06-29-todo-write-tool.md)),复查 fold 模式作纵深防御,turn 内追加 `mode/set { mode: 'default' }`,返回一句简短确认;下一个 step 的组装恢复完整工具集并记账变宽的 `request/header-delta`。`presentCall` 是携带计划 markdown 为内容的 `generic` 卡——审批提示按 `callId` 挂到这张已流出的调用卡上,人批准的正是日志里的工件。驳回以注册表的「user rejected」`isError` 到达模型,模型修订后重新提交。
|
||||
|
||||
### 依赖与接入面
|
||||
|
||||
`dsh-mode` 以 peer 依赖 `cordis`、`dsh-session`、`dsh-agent`、`dsh-tools`、`dsh-system-prompt`(manifest 形状镜像 `dsh-tool-todo`),inject `['tools', 'systemPrompt']`,既不依赖审批包也不依赖任何 UI。stdio 应用加一个 `/mode [name]` 行处理分支(打印或切换 + banner,绝不发给模型)和为它自己的 agent 服务的 readline answerer。ACP 线上映射钉在「协议与 UI 表面」;包层面 bridge 对 `dsh-mode` 只取 type-only 的 peer 边并伺机读取服务,没有该插件的 bridge 行为与今天完全一致。
|
||||
|
||||
### 录制场景与 harness op
|
||||
|
||||
`input.json` 增加一个 step op:`{ "op": "setMode", "mode": "plan" }`,经真实的 `session/set_mode` RPC 驱动。`plan-mode` 场景:initialize → newSession → setMode(plan) → 一个「探索并试图 `write`」的 prompt(被闸门 deny,逐字钉住)→ 模型经 `exit_plan_mode` 提交计划 → 脚本化 `permissionAnswers` 批准 → 后续 prompt 真正写入。因为模式在 turn 1 之前设定,**首个** `request/header` 快照就已经是 plan 形态(过滤后的工具 + section,reason `initial`)——变宽的 delta 出现在退出处;场景把这两者连同 `mode/set` 对一起钉住。姊妹场景 `plan-mode-reject` 脚本化驳回并钉住纠正结果。两者都需要带 key 的录制会话;deny/驳回文案在此之前先在单测层逐字钉死(审批 RFC 的同一立场)。
|
||||
|
||||
### 机械尾巴
|
||||
|
||||
没有声明任何新的 cordis 事件(`mode/set` 骑 `session/event`;listener 挂在既有 waterfall 上),所以事件 catalog 不动;同一变更中再生成:持久化日志 catalog(`mode/set`)、服务 catalog(`ctx.modes`,JSDoc 完备)、配置 catalog(`ModeConfig`)、工具 catalog(`exit_plan_mode`)、生产者/消费者图与文档图、模块图。仓库管线:根 tsconfig `paths` 条目、新组 README 加 [packages 总表](../../../../packages/README.md)一行(新顶层组正是该表点名的深思熟虑之举)、`architecture.md` 的 capability-services 表为 `ctx.modes` 加一行(受预算门禁约束)、cookbook 行升级。
|
||||
|
||||
## 路线图
|
||||
|
||||
plan mode 是一个 feature,就作为一个整体落地。一个能被锁进规划态、却没有正当途径提议离开的 agent 不是这个 feature 的缩小版——而是另一个更糟的东西:每份计划都以模型请求用户去拨一个它看不见的开关收场。因此下面两个阶段是一次堆叠落地的构建与评审顺序([堆叠评审指南](../../../cookbook/responding-to-pr-review-on-a-stack.md)):阶段 2 叠在阶段 1 上,整叠一起合入;任何一个阶段都不是可独立交付的里程碑。
|
||||
|
||||
唯一的硬前置是审批 seam(`docs/rfc/proposed/feature/2026-07-06-approval-seam.md`):退出审批就是它的 `ask` 路由端到端。它已在 `feat/sandbox-support` 上实现,所以耦合是合入顺序,不是未建的工作——本栈在它落 master 之前基于该分支。更广的在途邻域是收敛而非冲突:sandbox-escalation 分支带来第一个真实的审批组合(它的示例与脚本化应答 harness 是我们录制场景遵循的先例),env-state 提案为环境事实钉下同一套 fold-from-log + 边界应用习语(它的 `session/set_mode` config 阶段草图是唯一协调点,已在「协议与 UI 表面」解决),user-interaction seam 在场时为 stdio answerer 提供 stdin 纪律。
|
||||
|
||||
### 阶段 1——模式内核
|
||||
|
||||
`dsh-mode` 包:`mode/set` + `foldMode`、assemble 过滤器与模式 section、pre-execute 闸门、带 `plan` 定义的经校验 Config、带待落账机制的 `ctx.modes`、`AgentOptions.mode` 合并,以及 stdio 切换命令。计划期点名的覆盖:单测层覆盖 fold、过滤器、闸门矩阵、落账时序与合并边界通知;一个快照场景把 `mode/set` 连同随之的 `request/header-delta` 钉进 `session.jsonl`;所有既有 goldens 逐字节不变(默认模式不可见)。文档尾巴同阶段落地:包 + 组 README、[packages 总表](../../../../packages/README.md)一行、再生成的持久化/配置 catalog、cookbook 的 plan-mode 行从草图升级为包指针。
|
||||
|
||||
### 阶段 2——退出闭环与协议面
|
||||
|
||||
`exit_plan_mode`(ask 门控、携带计划、渲染意图如上)、stdio readline answerer,以及 ACP 会话模式映射(`session/set_mode`、`current_mode_update`、通告可用模式)。覆盖:单测层覆盖 ask 路由与两条结局路径以及 stdio answerer;一个经脚本化 `permissionAnswers` 驱动批准与驳回的录制快照场景;bridge 协议测试里的 ACP 模式往返。
|
||||
|
||||
推迟到本次落地之外、各自独立决策:经转发 `AgentOptions.mode` 的 subagent 模式继承(选项字段本身随阶段 1 落地)、模式定义内的按工具 `ask` 策略(OpenCode 式「plan 模式里 bash 要问」)、`plan` 之外的预设模式(read-only、accept-edits)、plan 模式中沙盒背书的 bash 约束,以及待落账丢失被证明真实时的空闲记录原语。
|
||||
|
||||
## 备选方案
|
||||
|
||||
**以权限模式为概念(Claude Code 形态)。**一个融合审批策略与工具策略的 `permissionMode`。在这里它们是两条轴、两个所有者:审批 seam 拥有「谁来回答这个问题」,模式拥有「模型得到什么表面」。ACP 把它们建模为相关但不同(模式将来可以选择审批策略——模式定义加一个字段,而非合并两个概念)。
|
||||
|
||||
**capability-seam 三件套。**接口/实现/消费者适合可替换的后端;模式的可变部分是配置值,不是实现。拆分只会制造一个空的实现包——与审批 seam 和 [`todo/`](../../implemented/feature/2026-06-29-todo-write-tool.md) 相同的「不要抢先拆分」判断。
|
||||
|
||||
**loop 拥有模式状态。**按常规规则拒绝(plugins, not loop changes):这个 feature 需要的每个挂点——assemble、pre-execute、turn 边界、会话事件——都已是成文 seam,改 loop 除了耦合什么也买不到。
|
||||
|
||||
**纯 prompt 的 plan mode(无硬闸门)。**Pi 的失败形态:过滤 schema(或好言相劝)拦不住对仍注册工具的分发。pre-execute 闸门是执行层;过滤器是 UX 与缓存卫生。
|
||||
|
||||
**仅运行时的模式(UI 或 bridge 本地、不入日志)。**resume 与 fork 会静默丢掉模式,模式引起的 header delta 在日志里失去可归因的因。日志化状态正是模式免费获得可审计与可恢复的原因。
|
||||
|
||||
**经 `agent.inject()` 以 `context/message` 承载模式翻转。**复用了现成的 turn 封闭路径,却把策略状态放进模型 transcript——模型不需要被告知两次(section 已经在说),log-only 的事实不应占据 surface。
|
||||
|
||||
**计划文件存储(`.plans/` 目录)。**为日志已能可回放地携带的东西建第二个持久之家;想要文件的部署可以后加一个写文件的工具。一个事实一个家。
|
||||
|
||||
**用布尔 `planMode` 而不是命名模式。**对仓库已经跟踪的表面太窄:ACP 通告的是模式**列表**,Claude Code 的选择器里 `plan` 与 `acceptEdits` 并列,而 Codex——它的 plan 功能是 `/plan`——用自己的审批预设(read-only / agent / full-access)填充列表;日后泛化还要重命名持久事件词汇。字符串形态的机制现在零额外成本;只有 `plan` 作为定义发布。
|
||||
|
||||
**工具策略栈服务(对 Pi 批评的对症药)。**专门的工具策略组合服务为时过早:waterfall listener 靠构造可组合,deny-by-default 硬闸门让过滤顺序竞争无法被利用。真冲突出现再机制化。
|
||||
|
||||
**用散文或 steering 退出而不是工具。**没有工件也没有审批时刻——工具的参数就是可评审的计划,它的 `ask` 才给了人一个挂在确切转换上的结构化是/否。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 生效中的模式是会话日志的纯函数:resume 与 fork 零额外机制地恢复它,`mode/set` 之后下一个 step 跟着匹配的 `request/header-delta`,dev 不变量全程常绿。
|
||||
- 用户驱动的翻转在下一个边界恰好叙述一次,净值为零的翻转序列不叙述;工具驱动的退出只经它的工具结果叙述。
|
||||
- 默认模式下插件不可见:加载与不加载 `dsh-mode` 的组装逐字节相同,所有既有快照 goldens 不变。
|
||||
- plan 模式下过滤后的 schema 与模式 section 同时到达线上请求与日志化 header;对已注册但被过滤的变更工具的调用在 `tools/pre-execute` 被 deny,理由点名模式。
|
||||
- 模式定义(allowlist、section 文本)从 `cordis.yml` 可改、无需改代码;未知模式名在 `set()` 时大声报错。
|
||||
- `exit_plan_mode` 的批准路径翻转模式并在下一个 step 恢复完整工具集;驳回路径返回纠正性 `isError` 并停留在 plan 模式;两者都由经脚本化权限应答的录制快照场景钉住;ACP `session/set_mode` 往返更新 `current_mode_update`,stdio answerer 在终端里提问。
|
||||
- 文档尾巴随落地一起交付:README、再生成的 catalog(持久化日志、配置、cordis 服务)、cookbook 行。
|
||||
|
||||
## 风险
|
||||
|
||||
空闲时设置的待落账用户翻转在进程于下一个 turn 前死亡时丢失——接受(UI 重新应用;空闲记录原语是实践中真咬人时的逃生口)。每次模式转换都是一次日志化的 header 变化、因而是 provider 侧的一次前缀缓存重置——固有、在逐 step 用量中可见,是反对「模式反复横跳的 UI」的论据,不是反对本设计的。兄弟 listener 顺序不确定,包裹在模式 listener **之外**的外部 assemble listener 可能把过滤后的 schema 重新放宽——过滤器作用于 `next()` 返回的 assembly(其包裹之内全部覆盖),硬闸门让任何被放宽的东西不可执行;残余代价是表面性的(模型看见一个用不了的工具),接受而不机制化。plan 模式内置 allowlist 排除 `bash` 与 `subagent`,在沙盒家族与模式继承落地之前确实损失探索力(没有 `git log`、没有只读委托)——接受该风险的部署今天就能在自己的配置里放宽。整个落地以审批 seam 先行合入为门——一次深思熟虑的进度耦合,取代单独交付模式内核(按路线图,那是不完整的 feature);该 seam 已在其分支上实现,本栈暂以它为基。没有组合任何 answerer 的部署保持安全但手动的 plan 模式(`ask` → `unavailable` → deny),模式 section 告诉模型经 `exit_plan_mode` 提交计划——被 deny 就请用户切换——所以它绝不会对着闸门反复冲撞。两份在途提案触及 ACP 模式表面(本文与 env-state 的 config 阶段):「协议与 UI 表面」中的选择器归模式 / 旋钮归 config options 分界是提议中的契约,合入顺序决定谁来接线 `session/set_mode`,后合入者负责修正。分支繁多的策略代码在 per-file 100% 覆盖门禁下是实打实的工作量,如 ACP bridge 一样照单接受。
|
||||
Reference in New Issue
Block a user