Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Rewrite plan-mode deep dive as implementation blueprint

Julius Marmingedf6bb188d477
diff --git a/docs/plan-mode-deep-dive.md b/docs/plan-mode-deep-dive.md
index da374b3cc..a51c3c85a 100644
--- a/docs/plan-mode-deep-dive.md
+++ b/docs/plan-mode-deep-dive.md
@@ -1,629 +1,648 @@
-# Plan Mode Deep Dive
+# Plan Mode Implementation Plan
## Goal
-Understand how the three providers expose:
-
-- planning / read-only execution modes
-- structured plan updates
-- structured user-input / question prompts
-- response plumbing needed for a provider-agnostic adapter layer
-
-Providers covered:
+Implement plan mode in a provider-agnostic way across:
- Codex App Server
- Claude Agent SDK / Claude Code
- Cursor ACP
----
-
-## Existing T3 Code groundwork
-
-Current repo groundwork already exists in these places:
-
-- `EVENTS.md`
-- `packages/contracts/src/providerRuntime.ts`
-- `apps/server/src/provider/Layers/CodexAdapter.ts`
-- `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
-- `apps/server/src/provider/Layers/CursorAdapter.ts`
-- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
-
-Canonical runtime events already modeled:
+The implementation must support:
-- `turn.plan.updated`
-- `content.delta` with `streamKind: "plan_text"`
-- `user-input.requested`
-- `user-input.resolved`
-- `request.opened`
-- `request.resolved`
+- provider-native or adapter-derived plan mode state
+- structured user-input question flows where available
+- graceful fallback when a provider lacks structured prompts or structured plan updates
+- a front-end UX that renders from capabilities and canonical events rather than provider-specific conditionals
-This is a good base, but provider coverage is uneven:
+This document now serves as both:
-- Codex: strong native support for both structured plans and structured user questions.
-- Claude: native plan mode exists, but plan updates are mostly implicit via tool/message stream; user questioning appears tool-based rather than a dedicated runtime event.
-- Cursor ACP: native plan mode exists, but current ACP surface appears to expose neither structured plan updates nor structured ask-user prompts in the same way as Codex.
+- the architecture plan for shared orchestration and UI wiring
+- the provider adapter implementation plan for each supported agent runtime
---
-## Provider 1: Codex App Server
-
-### What exists natively
-
-Codex has the richest first-class support for this feature set.
-
-### Real local session evidence
+## Source of truth
-The local Codex rollout file confirms at least one important distinction:
+### Codex
-- session metadata explicitly records collaboration mode as plan via `turn_context.payload.collaboration_mode.mode = "plan"`
-- final plan handoff is emitted as a normal assistant message containing a `<proposed_plan>` block
+Codex protocol decisions should be based on the open-source app-server protocol, not on local rollout session files.
-From the sampled rollout file, I did **not** find raw `event_msg.plan_update` / `event_msg.plan_delta` records, which suggests either:
+Upstream Codex app-server explicitly supports:
-- this particular session never emitted incremental structured plan updates, or
-- the desktop rollout file persists a higher-level message projection rather than every low-level app-server event
-
-That means the app-server protocol still supports native structured plan events, but local rollout files should not be assumed to contain every transport-level plan artifact.
-
-
-Native surfaces confirmed from upstream docs/source:
-
-- collaboration mode with plan behavior
- `turn/plan/updated`
- `item/plan/delta`
- `item/tool/requestUserInput`
-- `serverRequest/resolved` cleanup / completion notification for user input
-- `request_user_input` tool in core/runtime
+- `serverRequest/resolved`
+- lower-level `EventMsg` variants `plan_update`, `plan_delta`, and `request_user_input`
-Evidence inspected:
+Important implication:
-- upstream `codex-rs/app-server/README.md`
-- upstream `codex-rs/app-server-protocol` schemas
-- upstream `codex-rs/core/src/tools/handlers/request_user_input.rs`
-- upstream `codex-rs/core/templates/collaboration_mode/plan.md`
+- local Codex rollout JSONL files are a lossy or higher-level projection
+- they may preserve plan mode state and final `<proposed_plan>` output
+- they should not be treated as proof that low-level plan events do or do not exist
-### Semantics
+### Claude
-#### Plan mode
+Claude protocol decisions should be based on:
-Codex plan mode is not just “tool execution denied”. It has explicit behavioral guidance and explicit planning outputs.
+- installed SDK typings
+- real local session JSONL evidence
-Two distinct plan surfaces exist:
+Confirmed from local Claude transcript:
-1. **Structured plan state**
- - `turn/plan/updated`
- - payload contains:
- - optional `explanation`
- - `plan: Array<{ step, status }>`
- - statuses are `pending | inProgress | completed`
+- `AskUserQuestion` is a native `tool_use`
+- `ExitPlanMode` is a native `tool_use`
+- `AskUserQuestion.input.questions[]` is structured and adapter-parseable
-2. **Plan text stream**
- - `item/plan/delta`
- - useful for rendering streaming plan prose / bullet lists before or alongside structured state
+### Cursor
-This maps very cleanly to our canonical events:
+Cursor protocol decisions should be based on:
-- `turn/plan.updated` -> `turn.plan.updated`
-- `item/plan/delta` -> `content.delta(plan_text)`
+- ACP docs
+- current local ACP probe output
-#### Structured user questions
+Confirmed from probe:
-Codex has a dedicated `request_user_input` capability.
+- ACP session modes include `agent`, `plan`, and `ask`
+- currently observed ACP updates do not include native structured plan updates or native structured question prompts comparable to Codex or Claude
-Server request:
+---
-- `item/tool/requestUserInput`
+## High-level product model
-Shape characteristics from upstream protocol/docs:
+The implementation should separate three concepts that are currently easy to conflate.
-- 1–3 questions
-- each question has:
- - prompt text
- - stable id
- - required options
-- response carries answers per question
-- freeform notes are supported in UX and answer model
+### 1. Operating mode
-Important nuance:
+This is the agent runtime mode.
-- upstream handler currently requires non-empty options for every question
-- Codex TUI also supports an optional freeform note / text alongside selected options
-- pending question requests are turn-scoped and cleaned up on turn completion/interruption
+Canonical operating modes:
-### Why Codex is the reference model
+- `default`
+- `plan`
+- `ask`
+- `execute`
+- `unknown`
-Codex should be treated as the reference shape for our provider-agnostic abstraction because it already matches the desired UI:
+This should be represented at runtime independently of plan content or prompt cards.
-- explicit plan lifecycle
-- explicit multi-question prompt flow
-- explicit answer submission
-- explicit pending/resolved bookkeeping
+### 2. Structured plan state
-### Adapter implications
+This is the current structured plan snapshot, if the provider can supply one natively or if the adapter can synthesize one confidently.
-For Codex, the provider adapter layer should stay close to native protocol:
+Canonical model:
-- keep `turn.plan.updated`
-- keep `content.delta(plan_text)`
-- map `item/tool/requestUserInput` to `user-input.requested` and `request.opened`
-- map answer completion / cleanup to `user-input.resolved` and `request.resolved`
+```ts
+interface CanonicalPlanState {
+ explanation?: string | null;
+ steps: Array<{
+ id?: string;
+ text: string;
+ status: 'pending' | 'inProgress' | 'completed';
+ source: 'native' | 'synthesized';
+ }>;
+}
+```
----
+### 3. Structured user-input prompt
-## Provider 2: Claude Agent SDK / Claude Code
+This is the product-level question card model.
-### What exists natively
-
-Claude has an explicit plan permission mode:
-
-### Real local session evidence
-
-The sampled Claude session file provides concrete payloads for both key plan-mode tools:
-
-1. `AskUserQuestion` appears as a normal assistant `tool_use` block with input like:
-
-```json
-{
- "type": "tool_use",
- "name": "AskUserQuestion",
- "input": {
- "questions": [
- {
- "question": "What does 'adding profiles to canvas' mean to you? What should profiles enable in canvas?",
- "header": "Scope",
- "options": [
- { "label": "Organize by profile", "description": "..." },
- { "label": "Profile icon bar in canvas", "description": "..." },
- { "label": "Per-profile canvas settings", "description": "..." },
- { "label": "All of the above", "description": "..." }
- ],
- "multiSelect": false
- }
- ]
- }
-}
-```
+Canonical model:
-2. `ExitPlanMode` also appears as a `tool_use` block, with a long-form `plan` string payload containing the finalized implementation spec.
+```ts
+interface CanonicalUserInputPrompt {
+ promptId: string;
+ title?: string;
+ description?: string;
+ questions: Array<{
+ id: string;
+ header?: string;
+ label: string;
+ description?: string;
+ options: Array<{
+ id: string;
+ label: string;
+ description?: string;
+ recommended?: boolean;
+ }>;
+ multiSelect?: boolean;
+ allowFreeform?: boolean;
+ freeformPlaceholder?: string;
+ required?: boolean;
+ }>;
+ source: 'native' | 'tool-derived' | 'synthesized';
+}
-That gives us two strong adapter conclusions:
+interface CanonicalUserInputAnswer {
+ promptId: string;
+ answers: Array<{
+ questionId: string;
+ selectedOptionIds?: string[];
+ text?: string;
+ }>;
+}
+```
-- Claude user-input prompting is definitely tool-based and structurally parseable.
-- Claude final plan handoff is tool-based too, not necessarily a dedicated transport event like Codex `turn/plan/updated`.
+This should remain distinct from approvals.
-### Concrete adapter mapping from transcript evidence
+---
-Recommended Claude mapping based on real session data:
+## Shared orchestration plan
-- `tool_use.name === "AskUserQuestion"` -> `user-input.requested`
-- user answer submission / tool result -> `user-input.resolved`
-- `tool_use.name === "ExitPlanMode"` with `input.plan` -> final plan handoff event or synthesized `turn.plan.updated` snapshot
+## Summary
-The `AskUserQuestion` payload shape is already close to the UI we want:
+Implement a canonical plan-mode interaction pipeline that starts in provider adapters, flows through provider runtime ingestion and orchestration projection, and terminates in capability-driven frontend rendering and response submission.
-- `questions[]` array
-- each question has `header` and `question`
-- each question has `options[]` with `label` + `description`
-- `multiSelect` is explicit
+### Shared goals
-The main remaining unknown is the exact runtime shape of the **answer** payload that Claude expects back for this tool.
+- normalize plan mode state from each provider
+- normalize structured prompts where possible
+- preserve native payloads for later refinement
+- avoid UI coupling to provider names
+- support degraded conversational fallback where native structured prompts are unavailable
+---
-- `PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk'`
+## Orchestration work items
-Confirmed from installed SDK typings:
+### 1. Extend canonical provider runtime contracts
-- `/Users/julius/.bun/install/cache/@anthropic-ai/[email protected]@@@1/sdk.d.ts`
-- `/Users/julius/.bun/install/cache/@anthropic-ai/[email protected]@@@1/sdk-tools.d.ts`
+Files:
-Claude also exposes plan-related tools/types:
+- `packages/contracts/src/providerRuntime.ts`
+- `packages/contracts/src/provider.ts`
+- `EVENTS.md`
-- `ExitPlanMode`
-- `AskUserQuestion`
+Add or formalize the following runtime concepts:
-These are strong signals that Claude’s plan UX is built around tool usage within a `permissionMode: 'plan'` session rather than a dedicated standalone `turn.plan.updated` event.
+- provider interactive capability payload
+- plan-mode state event or mode metadata surface
+- canonical structured user-input payload schema
+- canonical structured user-input answer payload schema
+- final-plan handoff payload for providers that emit a completed plan as text or tool output
-### What the wire stream exposes
+Required additions:
-Claude adapter input today is built from SDK messages like:
+```ts
+interface ProviderInteractiveCapabilities {
+ supportsPlanMode: boolean;
+ supportsAskMode: boolean;
+ supportsStructuredPlanUpdates: boolean;
+ supportsPlanTextStreaming: boolean;
+ supportsStructuredUserInput: boolean;
+ supportsFreeformUserInput: boolean;
+ supportsExitPlanMode: boolean;
+}
+```
-- `system:init`
-- `system:status`
-- `stream_event`
-- `assistant`
-- `result`
-- hook/task/tool summary events
+Canonical runtime behavior:
-The SDK stream exposes:
+- `request.opened/request.resolved` remain transport-oriented
+- `user-input.requested/user-input.resolved` remain product-oriented
+- `turn.plan.updated` remains the canonical structured plan update event
+- `content.delta(streamKind=plan_text)` remains the canonical streaming plan text surface
-- message deltas
-- tool-use starts/stops via content blocks
-- permission-mode metadata
-- final result and usage
+### 2. Add canonical mode/capability publication from providers
-What it does **not** appear to expose as a first-class event:
+Files:
-- no direct equivalent to Codex `turn/plan/updated`
-- no direct equivalent to Codex `item/plan/delta`
-- no dedicated top-level `user-input.requested` transport event in the SDK stream
+- `apps/server/src/provider/Layers/*Adapter.ts`
+- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
-Instead, plan-mode-related behavior appears to surface through tool uses:
+Each adapter should publish provider capabilities and current operating mode early in session startup and when mode changes.
-- `AskUserQuestion` tool
-- `ExitPlanMode` tool
-- regular content/tool stream events
+Preferred shape:
-### Semantics
+- capabilities included in `session.configured`
+- current mode included in `session.configured`, `session.state.changed`, or a dedicated mode field on turn/session runtime metadata
-#### Plan mode
+### 3. Preserve and project plan/user-input state in orchestration
-Claude’s plan mode is primarily a **permission / behavior mode**:
+Files:
-- session or turn is created with `permissionMode: 'plan'`
-- tool execution is prevented / constrained
-- assistant can explore, reason, and propose a plan
-- eventually it may call `ExitPlanMode` to transition toward implementation
+- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
+- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts`
+- any orchestration projection models feeding the web socket domain events
-That means Claude plan mode is native, but **structured plan state is not guaranteed**.
+Implementation requirements:
-In practice, there are two likely UI strategies:
+- persist latest structured plan snapshot per active turn
+- persist pending structured user-input prompts per turn
+- persist resolved answers for history rendering
+- preserve raw/native payloads for debugging and future adapter improvements
-1. **Best-effort structured extraction**
- - detect plan-like assistant/tool outputs
- - synthesize `turn.plan.updated` from them
-2. **Text-first plan rendering**
- - show reasoning / assistant output as plan narrative
- - only emit `turn.plan.updated` when we can confidently extract steps
+### 4. Add frontend state model for plan mode
-#### Asking user questions
+Files likely involved:
-Claude’s `AskUserQuestion` appears to be a tool, not a dedicated transport-level question request primitive.
+- web app session/thread stores
+- conversation/event rendering layer
+- input composer / pending interaction surfaces
-That means the adapter likely needs to:
+Add frontend state for:
-- identify `tool_use` for `AskUserQuestion`
-- parse its input payload into canonical question schema
-- expose `user-input.requested`
-- accept a user answer and feed it back as the tool result / synthetic user response, depending SDK control path
+- current provider capabilities
+- current operating mode
+- pending structured prompt
+- structured plan snapshot
+- streaming plan text buffer
+- final plan handoff state when present
-This is adapter work, not just schema plumbing.
+### 5. Implement capability-driven UI rendering
-### Recommended stance for Claude
+UI rules:
-Claude should support the same canonical user-facing contract, but the adapter will need to **manufacture structure from native tool activity**.
+- if `supportsStructuredUserInput`, render the multi-question card UI
+- if not, fall back to standard conversational reply flow
+- if `supportsStructuredPlanUpdates`, render status-tracked plan steps
+- if only `supportsPlanTextStreaming`, render streaming plan prose
+- if neither exists, render standard assistant content in plan mode with clear mode indicator
-Recommended mapping:
+### 6. Implement front-to-back response submission path
-- `permissionMode: 'plan'` => canonical session/turn metadata `mode = plan`
-- `AskUserQuestion` tool use => canonical `user-input.requested`
-- submitted answer => canonical `user-input.resolved`
-- `ExitPlanMode` tool use => canonical state transition or request to continue with implementation
-- assistant text / tool summaries in plan mode => optional synthesized `turn.plan.updated`
+Requirements:
-### Risk / uncertainty
+- question card submit sends canonical answer payload to server
+- server routes answer to the correct provider adapter pending request/tool context
+- resolved provider response emits both:
+ - `user-input.resolved`
+ - `request.resolved` when applicable
-Claude currently appears less deterministic than Codex for structured plans.
+### 7. History and reconnect behavior
-Main unknowns to resolve during implementation:
+Requirements:
-- exact `AskUserQuestion` tool input/output payload shapes at runtime
-- whether freeform responses are supported natively or need synthetic augmentation
-- whether `ExitPlanMode` should be exposed to UI explicitly or handled internally by the adapter/session controller
+- pending structured prompts should survive reconnect/resubscribe if still active
+- resolved prompts should be rendered in history as completed interactions
+- plan snapshots should be replayable from persisted orchestration activity
+- current streaming plan text should resume cleanly on reconnect if provider continues emitting deltas
---
-## Provider 3: Cursor ACP
+## Provider adapter plans
-### What exists natively
+## Provider 1: Codex App Server
-Cursor ACP does have native session modes.
+### Summary
-Confirmed by local probe output in `.tmp/acp-plan-probe/summary.json`:
+Codex is the reference implementation and should be wired as the strongest native provider.
-- `agent`
-- `plan`
-- `ask`
-
-The probe also confirmed current primary ACP update surfaces:
+### Native protocol mapping
-- `available_commands_update`
-- `agent_thought_chunk`
-- `agent_message_chunk`
-- `tool_call`
-- `tool_call_update`
-- `session/request_permission`
+Source of truth: upstream open-source app-server protocol.
-### What the probe did not find
+Native incoming surfaces:
-The existing probe did **not** surface:
+- `turn/plan/updated`
+- `item/plan/delta`
+- `item/tool/requestUserInput`
+- `serverRequest/resolved`
+- lower-level `EventMsg.plan_update`
+- lower-level `EventMsg.plan_delta`
+- lower-level `EventMsg.request_user_input`
-- structured plan update events
-- a dedicated “ask user question” request
-- a dedicated plan delta stream
+### Adapter implementation
-The current ACP surface therefore looks much thinner than Codex.
+Files:
-### Semantics
+- `apps/server/src/provider/Layers/CodexAdapter.ts`
+- related tests in `apps/server/src/provider/Layers/*Codex*.test.ts`
-#### Plan mode
+Implementation requirements:
-Cursor `plan` mode clearly exists as a session mode, but as currently observed it seems to mean:
+1. Keep native structured plan updates as-is:
+- `turn/plan/updated` -> `turn.plan.updated`
-- read-only / design-first behavior
-- regular thought/message chunk streaming
-- no dedicated structured plan payload
+2. Keep native plan text streaming as-is:
+- `item/plan/delta` -> `content.delta` with `streamKind: "plan_text"`
-So the plan is native as a mode, but not obviously as a structured protocol surface.
+3. Keep native structured user-input as-is:
+- `item/tool/requestUserInput` -> `user-input.requested`
+- also emit `request.opened` with a transport request type
-#### Asking the user questions
+4. On client answer submission:
+- route answer to the corresponding Codex pending request id
+- emit `user-input.resolved`
+- observe/forward `serverRequest/resolved` -> `request.resolved`
-Cursor ACP currently gives us a nearby primitive only for **permission requests**:
+5. Publish capabilities:
+- `supportsPlanMode = true`
+- `supportsAskMode = false` unless Codex exposes a distinct ask mode separately
+- `supportsStructuredPlanUpdates = true`
+- `supportsPlanTextStreaming = true`
+- `supportsStructuredUserInput = true`
+- `supportsFreeformUserInput = true` if answer payload supports note/text in practice
+- `supportsExitPlanMode = false` unless a separate explicit tool/event is introduced
-- `session/request_permission`
+### Codex-specific tests
-That is not the same as product-level question asking.
+- `turn/plan/updated` maps to canonical structured plan state
+- `item/plan/delta` maps to `plan_text`
+- `item/tool/requestUserInput` maps to canonical structured prompt shape
+- answer response resolves pending request and emits both canonical resolved events
+- reconnect/history replay preserves plan snapshot and pending prompt
-The existence of `ask` mode suggests Cursor may handle asking by:
+---
-- normal assistant prose in ask mode
-- possibly mode-switch semantics
-- possibly skills/commands that we have not yet triggered
+## Provider 2: Claude Agent SDK / Claude Code
-But based on current probe evidence, we should **not assume** a Codex-style structured question API exists in ACP.
+### Summary
-### Recommended stance for Cursor
+Claude requires tool-aware adaptation. Native structured interaction exists, but it is surfaced through `tool_use` blocks rather than dedicated transport events equivalent to Codex.
-Treat Cursor as:
+### Real native evidence
-- native support for `mode = plan`
-- no proven native support for structured plan steps
-- no proven native support for structured user-input questions
+From the local Claude session transcript:
-Therefore Cursor likely needs the most adapter synthesis:
+- `AskUserQuestion` arrives as:
+ - assistant message
+ - content block type `tool_use`
+ - `name: "AskUserQuestion"`
+ - `input.questions[]`
+- `ExitPlanMode` arrives as:
+ - assistant message
+ - content block type `tool_use`
+ - `name: "ExitPlanMode"`
+ - `input.plan` containing finalized plan text/spec
-- derive plan-mode state from ACP session mode
-- optionally synthesize `turn.plan.updated` from assistant text if we can extract steps safely
-- for interactive questions, likely fall back to regular conversational turns unless a richer ACP mechanism is discovered
+Claude also has native:
-### Important product implication
+- `permissionMode: 'plan'`
+- `system:init.permissionMode`
+- `system:status.permissionMode`
-If we want the same rich “multiple-choice question card” UX across all providers, Cursor may need one of these paths:
+### Adapter implementation
-1. **Provider-native path** if later ACP exploration finds structured user question primitives
-2. **Adapter-mediated path** where the provider is instructed to emit a machine-readable question block in text and adapter parses it
-3. **Capability downgrade** where Cursor only supports conversational follow-up, not full structured plan-question cards
+Files:
-Today, evidence supports option 3 as the safe baseline.
+- `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
+- `apps/server/src/provider/Layers/ClaudeCodeAdapter.test.ts`
+
+Implementation requirements:
+
+1. Publish native operating mode:
+- `permissionMode: 'plan'` -> canonical mode `plan`
+- if future values map cleanly, publish `ask` or `default` accordingly
+
+2. Detect `AskUserQuestion` tool uses:
+- inspect `tool_use` blocks in assistant messages / stream events
+- when `name === 'AskUserQuestion'`, convert `input.questions[]` to canonical `user-input.requested`
+- also emit `request.opened` using a Claude-specific tool-user-input request type
+
+3. Canonical question mapping for Claude:
+- `header` -> canonical `header`
+- `question` -> canonical `label`
+- `options[].label` -> canonical option label
+- `options[].description` -> canonical option description
+- `multiSelect` -> canonical `multiSelect`
+- source = `tool-derived`
+
+4. Implement answer submission path:
+- on UI answer submit, convert canonical answers back into whatever Claude expects for the `AskUserQuestion` tool result path
+- emit `user-input.resolved`
+- emit `request.resolved`
+
+5. Detect `ExitPlanMode` tool uses:
+- when `name === 'ExitPlanMode'`, parse `input.plan`
+- emit a final plan handoff event and/or synthesize a `turn.plan.updated` snapshot if safe
+- treat this as the boundary between planning and implementation readiness
+
+6. Structured plan behavior:
+- Claude does not currently appear to expose a native `turn/plan/updated` equivalent
+- initial implementation should not over-synthesize incremental steps
+- use two-tier strategy:
+ - tier 1: preserve plan-related assistant text in `plan_text` only if clearly attributable
+ - tier 2: optionally synthesize `turn.plan.updated` from explicit structured plan strings only when parsing is robust
+
+7. Publish capabilities:
+- `supportsPlanMode = true`
+- `supportsAskMode = false` unless explicit Claude mode is observed
+- `supportsStructuredPlanUpdates = partial/false initially`
+- `supportsPlanTextStreaming = partial`
+- `supportsStructuredUserInput = true`
+- `supportsFreeformUserInput = unknown/false until answer path confirmed`
+- `supportsExitPlanMode = true`
+
+### Claude-specific tests
+
+- `system:init` and `system:status` publish plan mode metadata
+- `AskUserQuestion` tool maps into canonical prompt schema
+- multi-select and option descriptions round-trip correctly
+- answer submission resolves the pending prompt
+- `ExitPlanMode` tool emits final plan handoff state
+- ordinary tool uses do not get misclassified as prompts or plan exits
+
+### Claude-specific open question to resolve during implementation
+
+- exact runtime shape expected for the answer payload returned to `AskUserQuestion`
+
+Implementation default:
+
+- build adapter abstraction so only the final answer-serialization function is provider-specific and easily swappable once runtime shape is confirmed
---
-## Cross-provider comparison
+## Provider 3: Cursor ACP
-### Capability matrix
+### Summary
-| Capability | Codex App Server | Claude Agent SDK | Cursor ACP |
-| --- | --- | --- | --- |
-| Native plan mode | Yes | Yes | Yes |
-| Structured plan update event | Yes | Not obvious / likely no | Not observed |
-| Plan text delta stream | Yes | Not first-class | Not observed |
-| Native structured user question API | Yes | Tool-based, likely yes-ish | Not observed |
-| Native answer resolution lifecycle | Yes | Likely adapter-mediated | Not observed |
-| Best provider for canonical contract | Strong | Medium | Weak |
+Cursor should initially ship with degraded plan-mode support: native mode awareness, but no claim of structured prompt cards or structured plan steps until protocol evidence exists.
-### Core insight
+### Real native evidence
-“Plan mode” means **different things** across providers:
+From the ACP probe:
-- **Codex**: plan mode is a first-class runtime concept with structured plan and question surfaces.
-- **Claude**: plan mode is a first-class permission mode, but structured plan/question UI likely needs adapter interpretation.
-- **Cursor**: plan mode is a first-class session mode, but richer plan/question structure is not currently exposed.
+- available modes include `agent`, `plan`, and `ask`
+- observed updates include:
+ - `available_commands_update`
+ - `agent_thought_chunk`
+ - `agent_message_chunk`
+ - `tool_call`
+ - `tool_call_update`
+- observed request type:
+ - `session/request_permission`
----
+Not observed:
-## Recommended provider-agnostic contract
+- native structured plan update events
+- native plan text delta event distinct from normal message chunks
+- native structured ask-user-question event
-We should separate three concerns that are currently easy to conflate.
+### Adapter implementation
-### 1. Session / turn mode
+Files:
-A canonical mode flag:
-
-- `default`
-- `plan`
-- `ask`
-- `execute`
-- `unknown`
+- `apps/server/src/provider/Layers/CursorAdapter.ts`
+- `apps/server/src/provider/Layers/CursorAdapter.test.ts`
+- probe scripts under `scripts/`
-This is about **agent operating mode**, not UI widgets.
+Implementation requirements:
-### 2. Structured plan state
+1. Publish native operating mode:
+- map ACP `plan` mode -> canonical `plan`
+- map ACP `ask` mode -> canonical `ask`
+- map ACP `agent` mode -> canonical `default` or `execute` depending product semantics
-A canonical plan model:
+2. Do not claim unsupported structured capabilities:
+- no native `turn.plan.updated`
+- no native `user-input.requested`
+- no native `ExitPlanMode` equivalent confirmed
-```ts
-interface CanonicalPlanState {
- explanation?: string | null;
- steps: Array<{
- id?: string;
- text: string;
- status: 'pending' | 'inProgress' | 'completed';
- source: 'native' | 'synthesized';
- }>;
-}
-```
+3. Use graceful fallback behavior:
+- render plan mode as mode state + assistant text stream
+- render ask mode as conversational mode + normal user composer
+- do not render structured question cards for Cursor initially
-Rules:
+4. Preserve room for future enrichment:
+- keep raw ACP notifications available in native event logs
+- extend the ACP probe to search for hidden or uncommon prompt/mode-change surfaces
-- Codex can populate this natively.
-- Claude/Cursor may populate it only when extraction is confident.
-- UI should tolerate absence of structured plan state.
+5. Publish capabilities:
+- `supportsPlanMode = true`
+- `supportsAskMode = true`
+- `supportsStructuredPlanUpdates = false`
+- `supportsPlanTextStreaming = false` initially
+- `supportsStructuredUserInput = false`
+- `supportsFreeformUserInput = false` via structured prompt path
+- `supportsExitPlanMode = false`
-### 3. Structured user-input prompt
+### Cursor-specific tests
-Canonical prompt should be modeled independently of approvals:
+- ACP mode metadata maps correctly into canonical mode
+- `agent_thought_chunk` and `agent_message_chunk` still render normally in plan mode
+- UI does not try to open structured prompt cards for Cursor
+- fallback conversational flow remains functional
-```ts
-interface CanonicalUserInputPrompt {
- promptId: string;
- title?: string;
- description?: string;
- questions: Array<{
- id: string;
- label: string;
- description?: string;
- options: Array<{
- id: string;
- label: string;
- description?: string;
- recommended?: boolean;
- }>;
- allowFreeform?: boolean;
- freeformPlaceholder?: string;
- required?: boolean;
- }>;
- source: 'native' | 'tool-derived' | 'synthesized';
-}
-```
+### Cursor-specific follow-up probe work
-And answers:
+Add dedicated probes for:
-```ts
-interface CanonicalUserInputAnswer {
- promptId: string;
- answers: Array<{
- questionId: string;
- selectedOptionId?: string;
- text?: string;
- }>;
-}
-```
+- mode-switching during an active session
+- ask-mode prompt behavior
+- any request types besides `session/request_permission`
+- whether specific built-in skills or prompt styles trigger structured question surfaces
-### Why separate `request.opened` from `user-input.requested`
+---
-Because they are not the same abstraction:
+## Frontend implementation plan
-- approvals = “may I run/edit/do X?”
-- user-input prompts = “which direction do you want?”
+### Summary
-Codex already blurs these at transport level because `item/tool/requestUserInput` is a request.
-But product and UI should keep them separate.
+Render plan mode through a single UI model driven by canonical events and provider capabilities.
-Recommended rule:
+### UI states to support
-- keep `request.opened/request.resolved` for transport-level correlation
-- keep `user-input.requested/user-input.resolved` for product-level UX
+- standard conversation
+- plan mode with structured steps
+- plan mode with text-only plan stream
+- pending structured question card
+- resolved question card in history
+- final plan handoff / completed plan artifact
----
+### Rendering rules
-## Adapter strategy by provider
+1. Show operating mode indicator whenever current mode is `plan` or `ask`
+2. Show structured question card only when a pending `user-input.requested` exists
+3. Show structured plan step list when a current `turn.plan.updated` snapshot exists
+4. Append `plan_text` streaming content beneath or alongside structured steps when both exist
+5. Fall back to assistant text rendering when provider capabilities do not support structure
+6. Show completed selected answers in history after `user-input.resolved`
-### Codex adapter
+### Submission behavior
-Use native primitives directly.
+- option click / freeform answer submits canonical answer payload
+- disable duplicate submits while request is pending resolution
+- preserve pending-card state across reconnects if request remains open
-Implementation target:
+---
-- preserve `turn.plan.updated`
-- preserve `content.delta(plan_text)`
-- preserve `user-input.requested`
-- preserve `user-input.resolved`
-- expose raw/native metadata for future UI improvements
+## Data flow end to end
-### Claude adapter
+1. Provider starts session and publishes capabilities + mode
+2. User starts plan-mode turn or provider enters plan mode
+3. Adapter emits structured plan and/or plan text events when available
+4. Adapter emits `user-input.requested` when provider asks a structured question
+5. Frontend renders question card or fallback conversational prompt based on capabilities
+6. User submits answer
+7. Server routes answer back to provider adapter pending request/tool context
+8. Adapter emits `user-input.resolved` and `request.resolved`
+9. Provider may continue planning, emit more plan updates, or emit final plan handoff
+10. Frontend renders final completed plan state and history
-Implement tool-aware adaptation.
+---
-Implementation target:
+## Test plan
-- treat `permissionMode: 'plan'` as native plan-mode state
-- detect `AskUserQuestion` tool uses and convert to canonical user-input prompt
-- convert question answers back into Claude-native tool response path
-- detect `ExitPlanMode` and emit a canonical mode-change / handoff event
-- optionally synthesize plan steps from assistant output in plan mode
+### Contracts
-### Cursor adapter
+Files:
-Implement conservative degraded support first.
+- `packages/contracts/src/providerRuntime.test.ts`
+- related schema tests
-Implementation target:
+Add coverage for:
-- expose native session mode including `plan` and `ask`
-- do not claim structured plan updates unless proven
-- do not claim structured user-input prompts unless proven
-- optionally add a provider capability flag so UI can fall back to conversational follow-up
+- provider capabilities schema
+- structured user-input prompt schema
+- structured user-input answer schema
+- mode metadata schema
----
+### Server/provider tests
-## Capability flags we should add
+Files:
-To avoid overpromising in the UI, add provider runtime capabilities such as:
+- `apps/server/src/provider/Layers/CodexAdapter.test.ts`
+- `apps/server/src/provider/Layers/ClaudeCodeAdapter.test.ts`
+- `apps/server/src/provider/Layers/CursorAdapter.test.ts`
+- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts`
-```ts
-interface ProviderInteractiveCapabilities {
- supportsPlanMode: boolean;
- supportsAskMode: boolean;
- supportsStructuredPlanUpdates: boolean;
- supportsPlanTextStreaming: boolean;
- supportsStructuredUserInput: boolean;
- supportsFreeformUserInput: boolean;
- supportsExitPlanMode: boolean;
-}
-```
+Add coverage for:
-Expected initial values:
+- capabilities emission
+- mode propagation
+- plan update propagation
+- plan text propagation
+- structured prompt lifecycle
+- answer resolution lifecycle
+- reconnect/history replay behavior
-- Codex: all or nearly all `true`
-- Claude: `supportsPlanMode=true`, `supportsStructuredUserInput=likely true via adapter`, `supportsStructuredPlanUpdates=partial`
-- Cursor: `supportsPlanMode=true`, `supportsAskMode=true`, most structured flags `false`
+### Web/UI tests
-This lets the UI:
+Add coverage for:
-- render rich plan cards only when supported
-- fall back to plain assistant text + reply box otherwise
-- avoid coupling the design to Codex-specific assumptions
+- question card rendering from canonical prompt
+- question answer submission
+- resolved question history rendering
+- structured plan step rendering
+- text-only plan rendering
+- capability-based fallback rendering for Cursor
----
+### Probe / fixture tests
-## Suggested implementation order
-
-1. **Formalize provider capability flags**
- - make support explicit before UI work
-2. **Finish canonical user-input contracts**
- - question schema, answer schema, source markers
-3. **Codex end-to-end implementation first**
- - closest match to desired UX
-4. **Claude adapter translation second**
- - parse `AskUserQuestion` and `ExitPlanMode`
-5. **Cursor degraded plan-mode support third**
- - mode awareness first, richer structure later
-6. **UI renders by capability, not provider name**
- - prevents provider-specific branching from leaking upward
+- preserve the Claude transcript-derived `AskUserQuestion` and `ExitPlanMode` payloads as fixtures
+- preserve Codex protocol fixtures for `turn/plan/updated`, `item/plan/delta`, and `item/tool/requestUserInput`
+- preserve ACP probe summaries as fixtures for unsupported-capability assertions
---
-## Open questions
+## Assumptions and defaults
-1. Claude runtime payloads:
- - what exact `AskUserQuestion` input/output shapes arrive over the stream?
-2. Claude answer submission path:
- - should answers be injected as tool results, control responses, or synthetic user turns?
-3. Cursor ACP:
- - is there an undocumented or less common interactive prompt primitive beyond `session/request_permission`?
-4. Cursor mode switching:
- - can ACP session mode change mid-session, and is that surfaced as `session/update` or request/response only?
-5. Plan synthesis:
- - do we want best-effort extraction of numbered/bulleted plans into `turn.plan.updated` for Claude/Cursor, or should we keep structured plans native-only at first?
+- Codex is the reference provider for full structured plan/question UX.
+- Claude supports structured prompts via tool adaptation, but incremental structured plan updates are not assumed initially.
+- Cursor supports plan and ask modes, but not structured prompt cards or structured plan step updates initially.
+- Product/UI should degrade gracefully rather than invent unsupported provider behavior.
+- Raw provider payloads should always be retained where feasible to support future adapter refinement.
---
-## Immediate recommendation
-
-Build the product contract around **capabilities**, not around the assumption that every provider has Codex-style plan/question primitives.
-
-Concretely:
-
-- Codex should drive the first full UX implementation.
-- Claude should be supported with adapter-derived question handling and partial/synthesized plan state.
-- Cursor should initially support mode-aware UX with graceful fallback to conversational replies rather than full structured question cards.
+## Recommended execution order
-That gives us a provider-agnostic architecture without pretending the underlying protocols are already equivalent.
+1. Formalize canonical capabilities + mode + structured prompt contracts
+2. Wire capabilities/mode through orchestration and web socket projections
+3. Finish Codex end-to-end plan mode implementation first
+4. Implement Claude `AskUserQuestion` and `ExitPlanMode` adapter mapping
+5. Add Cursor degraded plan/ask mode support
+6. Build capability-driven frontend rendering and answer submission
+7. Add reconnect/history coverage and transcript/protocol fixtures