# AGENT_PROTOCOL.md — the cezar agent protocol cezar runs coding-agent CLIs behind **one backend-agnostic seam** and renders every backend through **one normalized event vocabulary**. This document is the operational contract for that seam: what a runner must implement, what it must emit, how the emissions are tested, and what a *new* runner (e.g. `pi`, PR #387) has to satisfy to be a first-class backend rather than a second-class one. It is the concise, load-bearing contract. The deep design record lives in `.ai/analysis/cockpit-ui-redesign/agent-event-protocols.md` (§7 schema, §7.1 the per-backend mapping tables) and the spec `.ai/specs/2026-07-14-cockpit-ui-redesign.md` (§"Normalized agent-event protocol v2", §"Backend parity requirement"). The code in `packages/cezar/src/core/` cites those two by section; this file cites the code. When the two disagree, **the code wins** — the golden fixtures and the parity test are executable, the prose is not. The protocol has **two layers that ship together**: - **v1 `AgentEvent`** — the original flat stream. Persisted in old NDJSON recordings and still consumed by `cezar run`'s console renderer. Never removed; old recordings must keep replaying forever. - **v2 `UiEvent`** — the normalized, item-lifecycle protocol the redesigned cockpit renders. Emitted **alongside** v1, never replacing it. A mixed NDJSON file (v1 + v2 lines) is valid by design. --- ## 1. The runner seam (`packages/cezar/src/core/agent-runner.ts`) Every backend is one class implementing `AgentRunner`, constructed through the single factory `createRunner(backend)` in `packages/cezar/src/core/runner-factory.ts`. Nothing outside `packages/cezar/src/core/` should ever `new` a concrete runner or branch on the backend id — that is the whole point of the seam. ### Identity ```ts const RUNNER_IDS = runnerSchema.options; // the contract's `runnerSchema` (packages/contract/src/health.ts) is the source of truth type RunnerId = (typeof RUNNER_IDS)[number]; // user-selectable type AgentBackend = RunnerId | 'claude-cli'; // + legacy id, still parses ``` `RUNNER_IDS` is the tuple every other enumeration derives from — the zod schemas (config, run store, workflow steps, the API bodies), the server-install "at least one agent CLI" gate, and the CLI-handoff registry. Re-listing the ids by hand is how a runner silently goes missing from one seam (#387 review); use `RUNNER_IDS` / `isRunnerId()` instead. `claude-cli` is a **legacy** backend id kept so old `runs.json` records and NDJSON transcripts still parse; `createRunner` maps it onto `claude`. Follow that precedent — never repurpose or remove a shipped id. ### `AgentRunner` ```ts interface AgentRunner { readonly backend: AgentBackend; run(spec: AgentRunSpec, onEvent?: (e: AgentEvent) => void): Promise; startSession(spec: AgentRunSpec, onEvent?: (e: AgentEvent) => void, opts?: SessionOptions): AgentSession; interrupt(): Promise; } ``` - `run()` is a one-shot convenience; `startSession()` is the real contract. - Each backend runs as a **persistent process** so multi-turn follow-ups, `waiting`, interrupt and resume all work: claude = stream-json over stdin/stdout; codex = `codex app-server` JSON-RPC 2.0 (JSONL) over stdin/stdout; opencode = `opencode serve` over HTTP + SSE; pi = `pi --mode rpc` over JSONL stdin/stdout; omp = `omp --mode rpc`, pi's successor on the same stdio family (own mapper, `omp-ui-mapper.ts`); antigravity = `agy --input-format stream-json --output-format stream-json` over NDJSON stdin/stdout; gemini = `gemini --acp`, the Agent Client Protocol (JSON-RPC 2.0 over NDJSON stdio) through the shared ACP layer (`acp-client.ts` + `acp-ui-mapper.ts`, spec `2026-09-19-runner-seam-native-backends`). ### `AgentSession` A live session over one spawned process, alive between turns: ```ts interface AgentSession { result: Promise; // resolves when the process exits readonly pid?: number; // root of the run's process tree (resource telemetry, #348) sendMessage(content: ContentBlock[]): boolean; // false when closed end(): void; // graceful: end input, SIGTERM→SIGKILL watchdog interrupt(): void; // hard stop (cancel) readonly open: boolean; } ``` A termination the runner itself caused is **not** an agent failure (#703). `end()` arms a SIGTERM→SIGKILL watchdog for CLIs that ignore EOF, and `interrupt()` signals outright; the agent CLIs install their own handlers and exit `128 + signal`. A runner MUST therefore record that it sent the signal and settle such an exit on the normal path — `isSignalTerminationExit(exitCode)` (`packages/cezar/src/core/agent-runner.ts`) plus a `note` — instead of throwing. Throwing makes a finished run settle as `failed` and a cancelled run settle as `failed` too. That watchdog MUST gate its SIGKILL escalation on real termination, never on `ChildProcess.killed` (#844). Node sets `killed` when a signal is *delivered*, so the watchdog's own SIGTERM flips it while the CLI — which handles the signal — keeps running, and the escalation written for exactly that case is skipped. Use `trackChildExit(child)` (`packages/cezar/src/core/agent-runner.ts`), which seeds from `exitCode`/`signalCode` and listens for `exit`. `SessionOptions`: - `autoEndAfterFirstTurn?` — single-turn behavior for non-interactive workflow steps; interactive sessions control `end()` themselves. - `onUiEvent?: (e: UiEvent) => void` — the **v2 channel**. It receives the normalized `UiEvent` stream emitted alongside the v1 `AgentEvent`s passed to `onEvent`. A runner that omits `onUiEvent` support degrades to v1-only — but a first-class backend MUST wire it (see §7). - `canAskPermission?: () => boolean` — may a backend permission prompt become an `ask.requested` card and park the run? RunManager answers `true` only for a non-autonomous run with a cockpit (`CEZ_API_URL`); absent or `false`, the runner must answer the prompt itself, because a mid-turn park has no nudge and no idle timer to end it (#2042). Read it when the prompt arrives. ### `AgentRunSpec` The input to a run. Backend-agnostic; each runner translates it to its transport. Notable fields (full doc-comments in the source): - `userPrompt` (required), `systemPrompt?`, `images?` (first-message content blocks — pasted screenshots), `cwd` (the run dir and the only writable root), `model?`, `reasoningEffort?` (Codex `turn/start.effort` and Claude `--effort`, the `REASONING_EFFORT_RUNNERS` set in `packages/contract`; every other runner must refuse it with `assertReasoningEffortSupported`, never ignore it; antigravity's effort is a model variant, which managers and workflow steps resolve to the model id before the spawn — `core/antigravity-effort.ts`), `timeoutMs?`, `env?` (merged over `process.env` — carries `CEZ_HANDOFF_FILE` / `CEZ_TODOS_FILE` / `CEZ_TASK_ID`). Codex sends the current `systemPrompt` with each invocation's opening user turn, preserving native configured guidance for unrestricted tasks. Restricted tasks use the isolated profile described below. `developerInstructions` replaces native config and does not refresh retained developer history on resume/fork; it is unsuitable for task instructions. - `enforceReadOnly?` — set only for a manager's read-only work (its read-only tasks and its unattended watch turns, spec `2026-10-31-managers`); an Ask task never sets it and keeps only its read-only `allowedTools`. When set, the task must not change the repository or publish anything, on every backend: Claude through `allowedTools` plus `--disallowedTools` for the write tools (settings allow rules cannot widen a deny), Pi through `allowedTools` (no shell), Codex through an isolated home, environment-free native turns and cezar’s read broker, OpenCode denied `edit`/`bash` in `OPENCODE_CONFIG_CONTENT` at the top level and in every agent, Cursor `--mode ask` without `--force`, Copilot `--deny-tool` with its permission prompts refused, Junie without `brave_mode` with its prompts refused, Gemini `--approval-mode default` with its prompts refused. Kimi, omp and Antigravity cannot, so `runner-factory.ts` refuses a read-only run on them. `read-only-env.ts` is the shared floor (no `gh` login, no git credential). A new runner that cannot enforce it must fail the run, never ignore the field. - `allowedTools?` / `bashAllowlist?` / `additionalDirectories?` — tool access. **Caveat (#430):** the zero-config default (`DEFAULT_ALLOWED_TOOLS`) includes unrestricted `Bash`. OpenCode does not honor `allowedTools`. Codex preserves the historical omitted/exact-default unrestricted grant; explicit read-only subsets and an empty grant use isolated execution. Unsupported write tools, MCP grants, shell hooks and Bash prefixes refuse before spawning. A native sandbox or prompt alone is never considered enforcement. Treat the default `auto` permission mode as full shell access, not a sandbox: Codex uses `danger-full-access` with `approvalPolicy: never`, and OpenCode runs under its own permission config: a prompt it still raises is an ask card in an attended run (`canAskPermission`, #2042) and refused in an autonomous, headless or one-shot run, except this run's own files. Configurable restrictive modes are specified by `2026-07-17-permission-modes` (#475). - `brokeredShell?` — Codex only: a manager's Bash. The restricted session's broker passes each command to `verify` (the manager policy, `managerShellPlan`) and spawns the returned argv pipeline itself, with a heredoc body as stdin and no shell, in `env`. Claude enforces the same policy through `bashHookCommand`; any other backend ignores the field. The commands run directly on the host with the engine's environment: a Claude manager's `gh` stays inside the user's Claude Bash sandbox, a Codex manager's does not, so a sandbox network allowlist does not cover it. Under `CEZ_CODEX_NETWORK=0` only `offlinePrograms` run (a manager's: `cez-manager` and its pipe filters). Every program, there and in the read broker, is resolved from absolute `PATH` entries only, never the working directory. Restricted Codex refuses Windows today. The dormant Windows path uses `taskkill /T` to walk a live stage's tree. Async teardown can race with pid reuse. Synchronous teardown at server exit keeps the stage's handle open. If a reader quits, the writer is killed by handle and its descendants survive. A child that holds stdout open after its stage exits keeps the call to its timeout and survives. - `sessionId?` / `resume?` — stable session id for interactive takeover and for `--resume` ("Continue" after a run ends). **Restricted Codex execution** — `codex-restricted-policy.ts` snapshots the grant. The runner accepts Codex 0.169.0 or newer on macOS/Linux, validates the isolated config and its layers, requires no hooks/MCP and no managed requirements beyond ones that only narrow (a workspace's login methods and features forced off; its model-only `enterpriseManaged` layer is accepted), and verifies thread sandbox/approval settings before the first model turn. A 0.169.0 prerelease is refused; only the exact 0.169.0 build relies on the static list. Any other version (newer, or a `+build`) also reads every page of `experimentalFeature/list`, disables every enabled, non-`removed` feature for the thread (a newer Codex may add a native tool the static list does not know) and re-reads the thread's list; only `unified_exec`, which 0.170.0 keeps on and which has no shell or environment to run in, may stay on. Only flagged features can be disabled: a tool a future Codex adds without a feature flag is invisible to this check. Older versions, active system policy, unavailable controls and ambiguous legacy graph policies fail closed. Restricted steps use a separate account-and-cwd state directory under `cezarHomeDir()/codex-restricted/`. Only supported model/provider settings and the selected account's file-backed authentication travel; native hooks, rules, plugins and private MCP configuration do not. An auth symlink lets native refresh update the selected account. Keyring-only authentication and unsupported provider settings may be unavailable; cezar never silently picks another account. `CEZ_DRY_RUN=1` loads neither native credentials nor native config. Native shell/image/agent tools, apps/connectors, plugins and browser/computer features are disabled. Every `thread/start` and `turn/start` sends `environments: []`; resume can restore a local environment, so the turn override is mandatory. Every turn also pins read-only/network-off sandbox and `approvalPolicy: never`. All native approval/permission/MCP requests are denied; unknown requests return an RPC error. The dynamic `cezar_read` tool alone executes granted Read/Grep/Glob operations and supported read-only git/GitHub commands. It validates arguments at execution, starts no shell or PTY, closes stdin, bounds concurrency/output/time and aborts processes when the session closes. Files must remain inside cwd/additional read roots; Read accepts regular files up to 2 MB. Grep/Glob need `rg`. `CEZ_CODEX_NETWORK=0` also denies brokered GitHub reads. Write, push, PR mutation, arbitrary HTTP, interpreters, jq/templates and shell syntax are unavailable. GitHub positional repositories, explicit `--repo` values and inferred Git remote hosts must match github.com or `GH_HOST`; enterprise tokens travel only with an explicit `GH_HOST`. Restricted private MCP requests refuse. Each launched step persists an optional contract `toolPolicy` snapshot. Continue, restart and fresh-session retries reuse the owning snapshot, including synthetic/nested step policies and `enforceReadOnly`. Older linear definitions retain their existing fallback; a legacy graph step whose grant cannot be reconstructed refuses instead of widening it. Isolated resumes never load an unrestricted native thread's config; the existing missing-session recovery starts a fresh restricted session when appropriate. Native adversarial verification (local loopback provider, temporary fake accounts, no paid calls): `TMPDIR=/tmp node --import tsx packages/cezar/test/native/codex-restricted.mts`. This checks native shell/apply_patch refusal, real broker reads, narrowed grants, resume and the writer-lock fork path. Ordinary unit tests use the mock transport and need no Codex installation. **System prompt channel** — a backend without a dedicated system-prompt input must deliver `spec.systemPrompt` as a leading block of the opening user message. Use the shared helper so the mapping is uniform: ```ts prependSystemPrompt(spec.systemPrompt, spec.userPrompt) // claude: --append-system-prompt (native channel, do NOT prepend) // codex / opencode / gemini: prepended here ``` The opt-in native Codex regression inspects model requests against an isolated loopback stub: `node --import tsx --test packages/cezar/test/native/codex-instructions.test.ts` from the repo root. It requires a local Codex CLI and makes no real model calls; the ordinary unit gate remains CLI-free. `ContentBlock` mirrors the Anthropic wire format (`text` | `image` base64) so it can be written to the claude CLI's stdin verbatim. --- ## 2. v1 `AgentEvent` — the flat stream The original normalized stream. Still emitted by every runner, still persisted, still rendered by `cezar run`. **Do not remove or rename a variant** — v1 event `type` strings are part of the on-disk NDJSON format. ```ts type AgentEvent = | { type: 'text'; text: string } | { type: 'tool-call'; id: string; tool: string; input: unknown } | { type: 'tool-result'; toolCallId: string; result: string; isError: boolean } | { type: 'image'; mediaType: string; data: string } // base64; run manager re-emits a URL | { type: 'token-usage'; tokensUsed: number } | { type: 'cost'; usd: number } | { type: 'usage-status'; status: AgentUsageStatus } // live gauges; folded onto the run record, never persisted | { type: 'session'; sessionId: string } // backend's real session id, once known | { type: 'mcp-servers'; servers: { name: string; status: string }[]; tools: string[] } // Claude's system/init; never persisted | { type: 'turn-end'; reason?: 'context-compaction' } // optional, additive (#955) | { type: 'note'; message: string } | { type: 'done' } | { type: 'error'; message: string }; ``` `usage-status` carries the latest context fill (`contextTokens`, `contextWindow`) and plan usage windows (`limits`: `window`, `utilization` 0..1, ISO `resetsAt`) for the run header. The run manager merges it onto `RunRecord.liveUsage` and never writes it to the NDJSON transcript. Claude emits it from the main agent's message usage, `result.modelUsage[model].contextWindow` and `rate_limit_event.unifiedWindows`; a runner without those signals never emits it. Claude also adds two optional token splits that only a manager's turn stats read, and that the run record drops: `cacheWriteTokens` on a message's reading (what that request wrote to the prompt cache), and `turnTokens` (`cacheReadTokens`, `cacheWriteTokens`, `outputTokens`) from the result's own usage. `mcp-servers` is Claude's `system/init` `mcp_servers` and `tools`, emitted once per process. Only a manager reads it (connectors, spec `2026-11-12-manager-connectors`); the run manager drops it, and other runners never emit it. `AgentRunSpec.claudeSettings` is the matching Claude-only input: JSON for `--settings`, written to a `0600` temp file and removed when the process exits. `turn-end.reason` is optional and additive (#955), in the same shape as `note.tone` (#936): a runner emits the bare event unless it knows something the turn's text cannot say, an old recording with no `reason` replays unchanged, and an unrecognized value degrades to "no reason given". `context-compaction` means the turn's last act was the backend compacting its OWN context window with no assistant message or native ask after it — internal session maintenance, not the user being handed the next action — so the run manager keeps the run working and continues once on the same thread instead of parking it at `waiting`. Codex emits it off a completed `contextCompaction` item on its own thread; a runner that has no such signal simply never sets the field. Every v1 event stays **derivable** from the v2 stream, so a consumer can migrate one panel at a time. New work should read v2; v1 exists for the console renderer and old recordings. ### Cezar-owned run metadata events `provider-auth-required` is not emitted by a backend runner. The server derives it from an authoritative v1/v2 authentication error, persists a provider id, opaque incident id, and optional `stepId`, and the cockpit renders recovery guidance. It does not change backend parity or expose the raw error. --- ## 3. v2 `UiEvent` — the normalized protocol (`packages/cezar/src/core/ui-events.ts`) Pure vocabulary: no runtime imports, no runner coupling. Mirrored into the api-client package at `packages/api-client/src/protocol/ui-events.ts`; the mirror is **checked**, not trusted — `packages/cezar/src/server/api-types.test.ts` asserts type-exactness between the two, so drift fails `npm run typecheck` (the gate) rather than the UI at runtime. ### Design rules baked in 1. **Item-lifecycle model** (Codex/ACP style): one stable `id` per item with `started → delta → updated → completed` phases. Two of the three backends are natively item-shaped; claude maps trivially. 2. **ACP vocabulary** wherever a choice is arbitrary (tool status/kind, plan entries, diff shape, stop reasons) — ecosystem alignment. 3. **Per-capability degradation, never per-backend** — see §6. ### The item model (one id-keyed stream for text, reasoning and tools) ```ts type UiItem = UiMessageItem | UiReasoningItem | UiToolItem; ``` - `UiMessageItem` — `kind:'message'`, `role`, `text`, `phase?:'commentary'|'final'`. - `UiReasoningItem` — `kind:'reasoning'`, `text` (extended thinking / reasoning summary). - `UiToolItem` — `kind:'tool'`, `name` (backend tool name), `toolKind`, `title` (human line computed once — see §5), `status`, `input?`, `output?`, `error?`, `diffs?: FileDiff[]`, `locations?`, `exitCode?`, `parentItemId?`. `parentItemId` nests subagent work under the tool item that spawned it (claude `parent_tool_use_id`, opencode `subtask` parts, Codex collaboration receiver thread ids). `toolKind: 'task'` means a **subagent spawn** and nothing else — surfaces that count live fan-out (the cockpit's Agents dock, the history root-episode retention) key on it directly. A skill invocation is `toolKind: 'skill'`: instructions loaded into the current agent's turn, with no second agent behind it and no children to adopt. Conflating the two reports a fan-out that never happened (#1202). ### Enumerations ```ts type ToolStatus = 'pending' | 'running' | 'completed' | 'failed' | 'declined'; type ToolKind = 'read'|'edit'|'delete'|'move'|'search'|'execute'|'think'|'fetch'|'task'|'skill'|'plan'|'other'; type StopReason = 'end_turn'|'max_tokens'|'refusal'|'cancelled'|'timeout'|'error'; type PlanStatus = 'pending' | 'in_progress' | 'completed'; ``` Supporting shapes: `PlanEntry` (`content`, `status`, `priority?`, `activeForm?`), `TokenUsage` (raw `input`/`output`/`cacheRead?`/`cacheWrite?`/`reasoning?`/`total`, `contextWindow?` — **never pre-weighted**; cost weighting is a presentation concern), `FileDiff` (`path`, `oldText: string|null` where `null` = newly created, `newText?`, `unified?`), `ToolLocation`, and the reserved `PermissionOption`/`PermissionOptionKind`. ### The events ```ts type UiEvent = | UiSessionStartedEvent // 'session.started' — sessionId, backend, model?, cwd?, tools? | UiSessionEndedEvent // 'session.ended' — reason: StopReason (replaces v1 done / fatal error) | UiSessionErrorEvent // 'session.error' — message, fatal (v1 note + error unified) | UiTurnStartedEvent // 'turn.started' — turnId | UiTurnCompletedEvent // 'turn.completed' — turnId, stopReason, usage?, costUsd?, models? (models reported for the turn, with shares when known) | UiItemStartedEvent // 'item.started' — item (tools usually pending/running) | UiItemDeltaEvent // 'item.delta' — itemId, field:'text'|'reasoning'|'output', delta | UiItemUpdatedEvent // 'item.updated' — item (status flips, streamed snapshots) | UiItemCompletedEvent // 'item.completed' — item (final snapshot, safe to persist) | UiPlanUpdatedEvent // 'plan.updated' — entries: PlanEntry[] (FULL replacement, ACP semantics) | UiPermissionRequestedEvent // 'permission.requested' — RESERVED (types only; wired when approvals become optional) | UiPermissionResolvedEvent // 'permission.resolved' — RESERVED | UiAskRequestedEvent // 'ask.requested' — requestId, questions[] (AskUser; the cockpit renders option chips) | UiAskClosedEvent // 'ask.closed' — requestId, reason, detail?, replacedBy?, answer? (the card closes) | UiUsageUpdatedEvent // 'usage.updated' — usage: TokenUsage, costUsd? (cumulative-for-session) | UiImageEvent; // 'image' — itemId?, mediaType, data (base64; manager re-emits URL) ``` **AskUser (`ask.requested`, #473, #565).** The portable path remains backend-neutral: the agent asks a structured multiple-choice question by ending a turn with a `CEZ:ASK ` control marker (a sibling of `CEZ:DONE` / `CEZ:MONITORING`); the RunManager detects it on the *assembled* turn text — uniform across claude, codex and opencode with no mapper work — validates the payload (`packages/cezar/src/core/ask.ts`, shaped after Claude Code's `AskUserQuestion`: `header` ≤12 chars, 1–`ASK_MAX_QUESTIONS` questions, 2–`ASK_MAX_OPTIONS` options each — 20 and 10, finite for payload size and a scrollable card rather than for parity with that tool's 4 and 4), emits `ask.requested` and parks the run `waiting`. The cockpit renders clickable option chips; the user's pick rides the normal reply seam (`POST /api/v1/runs/:id/messages` with `askRequestId`). A `CEZ:ASK` card closes only with an **`ask.closed`** event in the run's NDJSON (Questions inbox spec, `.ai/specs/2026-11-17-questions-inbox.md`), so a replay draws the same closed card: `answered` (a message carrying its `askRequestId`), `dismissed` (the Questions inbox), `replaced` (a newer card with the same top-level `id`, or one whose headers cover every header of the old one; `replacedBy` names it), `retracted` (the agent's own `CEZ:ASK-CLOSE [reason]` line, stripped from the transcript), `expired` (the card's declared `about` PR merged or closed, or its `{task}` finished) and `ended` (the run reached done, review or cancelled, or was archived; `failed` keeps it open for Continue). A free-form composer reply closes nothing: it flags the card "may be out of date" on the run record (`RunRecord.asks`). The run record keeps each card's state; the event only redraws the thread. Codex additionally bridges its native `item/tool/requestUserInput` server request onto the same event and routes the next answer back as the documented JSON-RPC response. Malformed or unsupported native requests receive an error response rather than hanging the turn. A malformed marker degrades to plain text — the prose fallback is never made worse. Two bounded forgiveness layers sit **under** that schema, and neither loosens it. `normalizeAskRequest` recovers presentation drift (unknown keys dropped, an over-long `header`/`description` clipped) — never counts, never choices. `closeUnbalancedJson` (#936) recovers the one syntax slip agents actually make: a payload complete except for its closing brackets, because a hand-written one-line blob dropped a trailing `}` or the output-token limit cut the stream. It appends the missing closers and re-parses, but only when the payload ends on a **completed** structural value (`}` or `]`), the scan ends outside a string, and every closer matched its opener — a stream cut mid-string, after a `,`, or after a `:` is still refused, and an already-balanced payload (a trailing comma, say) has nothing to repair. The repaired text goes through the unchanged schema, so a repair yielding fewer than 2 options still degrades to plain text. What a repair *can* lose is whatever the cut already took: a stream severed exactly on an option boundary yields a real card missing a trailing option, or missing a trailing `multiSelect` — so a recovered card is never passed off as a clean parse. `AskMarkerParseResult` carries `repaired`, and the run records a danger-toned recovery note asking the user to check the options, and how many they may pick, against what was asked; the raw marker is stripped from the transcript along with the card it produced. A native `AskUserQuestion` control-protocol bridge for claude (the `control_request can_use_tool` path) is a possible future enhancement; the marker is the portable baseline. `item.completed` carries **snapshots**, not deltas — safe to persist. `item.delta` carries **appends** to one field of a live item and must not be persisted as a standalone truth. --- ## 4. Per-backend mapping (summary) Each backend has a mapper (`packages/cezar/src/core/-ui-mapper.ts`) turning its wire transport into `UiEvent`s. The authoritative table is `agent-event-protocols.md` §7.1; the load-bearing rows: | v2 event / field | claude (stream-json) | codex (app-server JSON-RPC) | opencode (serve HTTP+SSE) | cursor (stream-json print mode) | copilot (ACP over stdio) | gemini (ACP over stdio, `gemini --acp`) | kimi (ACP over stdio) | omp (rpc JSONL stdio) | |---|---|---|---|---|---|---|---|---| | `session.started` | `system/init` (model, tools, cwd) | `thread/started` / `thread/start` result | `POST /session` response | `system/init` (model, cwd) | `session/new` result (`sessionId`; the request's `cwd`) | `session/new` result (`sessionId`, `models.currentModelId`); `session/load` result (the requested id) | `session/new` or `session/resume` result (`sessionId`, cwd) | `get_state` response (`sessionId`, `model.id`) | | `turn.started` | each stdin user message | `turn/started` | each prompt POST | no stdin turn boundary in print mode — starts `turn_1` with the session | each outbound `session/prompt` | each outbound `session/prompt` | each outbound `session/prompt` | each `prompt` command cezar sends (turn = one user prompt) | | `turn.completed` + `stopReason` | `result` subtype (`success→end_turn`, `error_max_turns→max_tokens`, `error_during_execution→error`) | `turn/completed→end_turn`, `turn/failed→error`, interrupt→`cancelled` | `session.idle→end_turn` (or `error` if a `session.error` preceded) | `result` (`is_error→error`, `subtype=error_max_turns→max_tokens`, else `end_turn`) | the `session/prompt` result's `stopReason` (`end_turn`, `max_tokens`, `max_turn_requests→max_tokens`, `refusal`, `cancelled`) | `session/prompt` result `stopReason` (`max_turn_requests→max_tokens`); a JSON-RPC error answer → `error` | the `session/prompt` result's `stopReason` (`end_turn`, `max_tokens`, `cancelled`) | `prompt_result` (`completed→end_turn`, `aborted→cancelled`, `error→error`); `agentInvoked: false` (a local slash command) still closes the turn the prompt opened — `end_turn`, no usage | | message item | `assistant` `text` blocks (deltas via `--include-partial-messages`) | `agentMessage` items | text parts | `assistant` `text` content blocks | `agent_message_chunk` | `agent_message_chunk` | `agent_message_chunk` | `message_update` `text_start/text_delta/text_end` (one item per `messageId` + content index) | | reasoning item | `thinking` blocks | `reasoning` items (+ `textDelta`) | `reasoning` parts | *(none — docs: `thinking` events are suppressed in print mode)* | `agent_thought_chunk` | `agent_thought_chunk` | `agent_thought_chunk` | `message_update` `thinking_start/thinking_delta/thinking_end` | | tool item | `tool_use`→running, `tool_result`→completed/failed, `permission_denials`→`declined` | `commandExecution`→execute (+`exitCode`, `outputDelta`), `fileChange`→edit (`diffs`), `mcpToolCall`→other, `webSearch`→fetch, collaboration spawn→task | tool parts (state `pending/running/completed/error→failed`, `patch` parts→`diffs`) | `tool_call` started/completed (`readToolCall`/`writeToolCall`/`editToolCall`/`shellToolCall`, or the generic `tool_call.function` wrapper) | `tool_call`→running (Copilot announces a STARTED tool as ACP `pending` and never sends `in_progress`), `tool_call_update`→completed/failed, `content[].type: "diff"`→`diffs` | `tool_call` → `tool_call_update` (`in_progress→running`, `completed`, `failed`); ACP `kind` is the v2 `ToolKind`; `{type:'diff'}` content → `diffs`. Gemini: name = `toolCallId` prefix (no `rawInput` on its wire) | `tool_call` (pending, title is tool name) → `in_progress` args streaming → `tool_call_update` completed/failed with diffs/output | `toolcall_end` (the streamed function call) → pending; `tool_execution_start`→running (real args); `tool_execution_end`→completed/failed (`isError`) | | `item.delta` `output` (live terminal) | *(none — card fills on completion; per-capability degradation)* | `item/commandExecution/outputDelta` | running-state metadata | *(none)* | *(none — `tool.execution_progress` is dropped by Copilot's own ACP bridge)* | *(none — card fills on completion)* | *(none - Kimi streams args in `in_progress`, not output)* | *(none — card fills on completion)* | | `plan.updated` | `TodoWrite` input | `todoList` / `plan` items | `todowrite` tool | `TodoWrite` via `tool_call.function` — **tool name/shape not confirmed against a live CLI transcript** (#807) | the native `plan` update (`entries[] {content, priority, status}`) | ACP `plan` update (full replacement); dialect `planFromToolCall`. **Gemini 0.60: no plan on the wire** — a documented gap in `ui-parity.test.ts` (`WIRE_GAPS`) | native `plan` update and `TodoList` input (deduplicated) | the `todo` tool: `init` args (all pending) and the full phase snapshot in its result `details` | | subagent nesting (`parentItemId`) | `parent_tool_use_id` | collaboration receiver thread id (review mode remains childless) | child-session parts under a `subtask` | *(none — print-mode wire has no parent attribution; the task-kind tool item is the matrix cell)* | `_meta["github.com/copilot"].agentId`, which IS the delegating `task` call's `toolCallId` | none on the wire; substitute: one `task` item per delegation (Gemini `invoke_agent`) | *(none)* | *(none — the RPC wire carries no parent attribution)* | | `usage.updated` | `result.usage` + `total_cost_usd` | `thread/tokenUsage/updated` (no USD) | `message.updated` tokens/cost + `step-finish` | *(none — the documented terminal `result` frame carries no `usage`/`total_cost_usd` field)* | the `session/prompt` result's top-level `usage` (no USD). Its separate `usage_update` frame is a context-window gauge (`{used, size}`), NOT token counts, and is deliberately unmapped | `session/prompt` result: standard `usage`, or dialect `usageFromPromptResult` (Gemini `_meta.quota.token_count`), summed per session | parsed from `usage.record` lines in Kimi's session log (`~/.kimi-code/sessions/.../wire.jsonl`) polled at turn end, plus context-window from `usage_update` | assistant `message_end` `usage` — per-message, so the mapper accumulates: `usage.updated` is session-cumulative and the turn sum rides on `turn.completed` | `antigravity` speaks agy's own stream-json (`core/antigravity-ui-mapper.ts`): `init` → `session.started`, each stdin message's `user_input` step → `turn.started`, `agent_response` steps → message items (`text_delta`), `tool` / `subagent` steps → tool / task items, `result` → `turn.completed`. Turn usage is the sum of the steps' own `usage` — `result.usage` is cumulative for the whole conversation. The wire carries no plan, no reasoning text, no edit content and no parent attribution; `__fixtures__/antigravity/README.md` records the live captures behind each of those parity exceptions. Private MCP is a launch-side exception: agy has no launch-time MCP channel, so `antigravity` is not in `PRIVATE_MCP_RUNNERS`. `copilot` and `gemini` share one vendor-neutral transport and mapper with any future ACP backend (`core/acp-client.ts`, `core/acp-ui-mapper.ts`); what differs per agent is a small `AcpDialect` (`core/copilot-ui-mapper.ts`, `core/gemini-ui-mapper.ts`). Kimi Code uses its own ACP mapper (`core/kimi-ui-mapper.ts`) and runner (`core/kimi-runner.ts`) to handle Kimi-specific session log polling and tool call streaming. The wire record behind the copilot column above is `.ai/runs/2026-09-27-copilot-cli-runner/copilot-acp-notes.md`, and `__fixtures__/copilot/README.md` states exactly which of those frames are a live capture and which were read out of the CLI's own ACP bridge. The gemini column is pinned by real `gemini --acp` transcripts (`__fixtures__/gemini/README.md`). `omp`'s column is backed by real `omp --mode rpc` transcripts (`__fixtures__/omp/README.md`), mapped by `core/omp-ui-mapper.ts`. **Mapper robustness contract.** Inputs come off the wire and may be `null`, partial or malformed. A mapper **must never throw**: unparseable NDJSON lines are skipped (`packages/cezar/src/core/ndjson.ts` + the mapper), unknown message/content types produce **no events**, and malformed entries in a `plan.updated` payload are filtered out (a non-array plan emits no plan event at all). Mapper state is **explicit and immutable** — each mapper's map function takes `(frame, state)` and returns `{ events, state }`, never mutating the passed-in state (`mapClaudeMessage` / `mapCodexNotification` / `mapOpencodeEvent`, each paired with a `createUiState`; see the claude mapper's "state carries across messages" tests). --- ## 5. The tool display model (`packages/cezar/src/core/tool-display.ts`) `toolDisplay(name, input)` turns a backend tool name + raw input into `{ toolKind, title, subtitle? }`, computed **once** in the protocol layer (never in components) so the thread, activity groups and notifications all say the same thing. It is a pure function over untrusted input and **must never throw**. Tool names are matched case-insensitively, so claude's `Bash` and opencode's `bash` share one row; unknown tools keep the backend's name as the title with a heuristic subtitle. `mcp__server__tool` names collapse to `server.tool`. --- ## 6. Backend parity — the hard rule (`packages/cezar/src/core/ui-parity.test.ts`) > Every capability in the parity matrix MUST be emitted by **every first-class > backend**, so the GUI degrades **per-capability, never per-backend** — unless > the backend's own wire format provably cannot carry that capability, in which > case the exclusion is written down and cited (see below). This is made executable: `ui-parity.test.ts` asserts each capability over each backend's golden-fixture expected output. If a mapper change drops a capability — or a new fixture set forgets one — a named row fails. The matrix: - `plan.updated` with entries (TodoWrite / todoList / todowrite) - tool status `running`, `completed`, `failed` - reasoning items (thinking / reasoning items / reasoning parts) - structured diffs (Edit input / fileChange.changes / patch parts) - sub-agent task items (Task / review-mode span / subtask parts) — one item per sub-agent: codex's `enteredReviewMode`/`exitedReviewMode` pair folds into a single `task` item with a running→completed lifecycle, so a consumer counting task items counts agents, not frames (spec `.ai/specs/2026-07-20-grouped-subagent-display.md`, #474) - `usage.updated` with raw token counts - `turn.completed` with a `stopReason` - sub-agent **nesting** via `parentItemId` — only where the wire attributes work to its parent (claude's `parent_tool_use_id`, opencode's child-session parts under a `subtask`); codex, cursor and pi have no parent attribution in their wire format, so their matrix cell is the task-kind tool items above instead. junie (core ACP) has no parent attribution either, and its task-kind substitute is unavailable for the same protocol reason (core ACP's `tool_call.kind` has no `task` value), so that row carries a cited `except` A new backend is not "done" until it produces every row its wire format is capable of. **Documented exceptions are allowed** when a capability provably cannot be produced from the backend's own wire format — never for "not implemented yet". An exception must: (1) cite the upstream source proving the capability is absent (a vendor doc quote, or an honest "no live CLI available to verify" when that citation cannot be obtained), (2) exclude only that backend from that one row via `ui-parity.test.ts`'s `CAPABILITIES` table `except` list, and (3) still assert every row the backend's wire format can produce. Cursor is the first backend to use this: its documented print-mode `result` frame carries no `usage`, and `thinking` events are documented as suppressed in print mode — both cited inline next to the exclusion in the test. Gemini (ACP) is the first backend to use a `WIRE_GAPS` entry instead: its wire can carry a plan update but 0.60 never sends one, so the row is pinned BOTH ways (the gap must still hold — see `ui-parity.test.ts`). ## 7. The golden-fixture testing contract Each backend has, under `packages/cezar/src/core/__fixtures__//`: - `.ndjson` — a **wire-faithful** transcript of the backend's real output (shapes from `agent-event-protocols.md`, cross-checked against the backend's actual CLI / the dry-run mock, e.g. `packages/cezar/scripts/mock-claude.mjs`). - `.expected.json` — the **exact** `UiEvent[]` the mapper must produce for that transcript. `-ui-mapper.test.ts` replays each fixture **exactly as the runner drives the mapper** (seed turn started before the first line; malformed lines skipped), round-trips the result through JSON (so a stray `undefined` fails loudly, since these events get persisted as NDJSON), and asserts `toStrictEqual` against the `.expected.json`. The same `.expected.json` files feed the parity test in §6. > Verify fixtures against **upstream wire shapes**, never against your own > assumptions. PR #443's root cause was a fixture that encoded an *assumed* > codex shape (`todoList` items that the app-server never emits), which hid a bug > where a codex plan never rendered at all. When adding a fixture, cite the > upstream schema/source it was derived from, as #443 did. ## 8. Persistence & transport - **NDJSON** — one append-only `runs/.ndjson` per run, one JSON object per line (`seq`, `ts`, `type`, free extra keys). Never rewrite, reorder or re-number; readers skip bad lines. Both v1 and v2 events live here; a mixed file is valid. Cezar-owned task events are additive too: for example, `provider-auth-required` records only `{ provider, authFailureId, stepId? }` when a runtime rejection needs user authorization; it never carries vendor error text or credentials. - **SSE** — the server replays from NDJSON then streams live, deduped by `seq`. Event names: `run-event` (v1) and `ui-event` (v2 dotted types). These names are a protected contract (see `BACKWARD_COMPATIBILITY.md` §2). --- ## 9. Adding a new runner (the #387 `pi` checklist) A new backend is a **single class behind the seam** plus its mapper, fixtures and the parity row — never backend-specific types leaking past `packages/cezar/src/core/`. PR #387 added `pi` and enumerated every place the runner union was duplicated; that list is the concrete map, and the union now derives from one tuple — the contract's `runnerSchema` in `packages/contract/src/health.ts`, which `agent-runner.ts` re-exports as `RUNNER_IDS` — so most of it is typecheck-enforced rather than hand-tracked, and `packages/cezar/src/core/runner-union.test.ts` fails on any source file that spells the set out again. To be first-class: 1. **Runner** — `packages/cezar/src/core/pi-runner.ts` implementing `AgentRunner` / `AgentSession` (persistent process; `pid`; `sendMessage`/`end`/`interrupt`; `result`). Honor `AgentRunSpec` uniformly — use `prependSystemPrompt` if the backend has no native system-prompt channel. 2. **Factory** — add the id to the contract's `runnerSchema` (`packages/contract/src/health.ts`; `packages/contract/src/runners.ts` derives `RUNNER_IDS` / `perRunner` from it and `agent-runner.ts` re-exports `RUNNER_IDS` / `RunnerId` — nothing else lists the set), and a `case` in `createRunner` (`runner-factory.ts`). Add `UiBackend` in `ui-events.ts` **and its mirror** `packages/api-client/src/protocol/ui-events.ts` (the type-exactness test guards drift). 3. **Detection** — a `probePi()` in `backend-detect.ts` plus the `BackendCheck` name union; degrade gracefully when the CLI is absent (never fail boot). If it needs a binary override, add `CEZ_PI_BIN` — and per AGENTS.md's zero-config rule, document any new `CEZ_*` var in `.env.example` in the same commit. 4. **Mapper** — `packages/cezar/src/core/-ui-mapper.ts` emitting the full v2 `UiEvent` stream **alongside** v1. Never throw on malformed input; explicit immutable state. 5. **v1 alongside v2** — wire `SessionOptions.onUiEvent`; keep the v1 `AgentEvent` stream flowing unchanged. 6. **Golden fixtures** — `packages/cezar/src/core/__fixtures__/pi/*.ndjson` + `*.expected.json`, wire-faithful and citing their upstream source, covering every parity matrix capability the backend's wire format is able to produce (§6) — and a `pi-ui-mapper.test.ts` replaying them. Where a capability genuinely cannot be produced, cite why in the fixture/test the way cursor's `usage`/`thinking` exclusions do; never fabricate a frame to fill a row. 7. **Parity** — add `pi` to `BACKENDS` in `ui-parity.test.ts`; every capability row must pass, or be excluded via that row's `except` list with a cited reason (§6) — never silently skipped. (If the backend has no wire parent attribution, document the nesting cell's substitute the way codex's review-mode items are handled.) Gemini's fixtures are real `gemini --acp` transcripts (`__fixtures__/gemini/`); its plan row is the `WIRE_GAPS` entry (§6), not an `except`-list exclusion. 8. **Plumbing** — the run-store `runner` enum, workflow step schema, the `POST /api/runs` / `PUT /api/config` bodies, `resumeCommand()`, the web `Runner` type, composer pills/presets, and Settings → Agents. Keep additive so old `runs.json` records still parse (the `runner` enum keeps `claude-cli` parseable — follow that precedent). 9. **Model selection** — accept `provider/model` where relevant; #387 documents the existing inconsistencies (opencode drops a bare model silently) — do not reproduce a silent-drop. A backend with no default provider gets no entry in `BACKEND_MODEL_MAP`'s default column, so a bare id fails loud. 10. **Permissions** - a backend cezar starts in an "approve everything" mode MUST still answer an approval request that arrives anyway. No cockpit surface can answer one yet, so a run parked on a `session/request_permission` would be a state with no exit; `copilot-acp-runner.ts` auto-approves with a `note` instead, and `kimi-runner.ts` answers approval requests (auto-approving, while `Bash` can be denied if excluded by `allowedTools` or `bashAllowlist`). 11. **Credentials** — one entry in `BACKEND_ALLOW_PREFIXES` (`agent-env.ts`), and exact names in `BACKEND_ALLOW_NAMES` where a prefix would over-grant (gemini's `GOOGLE_API_KEY` rather than `GOOGLE_`): `buildChildEnv` is least-privilege per backend, so a multi-provider runner must receive credentials for every provider its own model ids can name without widening other backends. 12. **Private MCP** — honor `AgentRunSpec.mcpServers` through the backend's own launch-time channel (a flag, a config override, an env var, or ACP's `session/new` `mcpServers`), never by writing into `cwd`; translators live in `private-mcp.ts`. Add the id to `PRIVATE_MCP_RUNNERS` only once that works — a backend outside the list gets a run note naming the servers it could not attach (spec `.ai/specs/2026-10-07-private-project-mcp.md`). ## 10. The plan channel (PR #443) PR #443 (`fix/issue-433-render-plan-todo`, open at the time of writing) hardens `plan.updated` across all three backends after finding the plan never reached the cockpit dock — for a different reason on each backend. Its direction, which any new runner should follow: - **Claude** — current-session plans use `TaskCreate` / `TaskUpdate` / `TaskList` (not only `TodoWrite`); classify all of them as plan tools and fold them into a snapshot keyed by the task id the harness reports in each tool's **result**. - **Codex** — the real plan channel is the turn-level notification `turn/plan/updated`, not a `todoList` item (which the app-server never emits); map it to `plan.updated` as a full replacement. - **OpenCode** — `status` is free-form upstream; `cancelled` is a documented value. Don't whitelist a few statuses and silently drop the rest — an unrecognized status degrades to `pending` so a todo the agent wrote stays on screen. - **General** — `plan.updated` is full-replacement; only a genuinely empty list clears the dock (a malformed frame maps to zero events, never a wipe). The `plan.updated` **event name and payload structure are unchanged**; #443 extends the *handling*, not the wire shape (on `main`, `PlanStatus` is the three values in §3). --- ## Compatibility The agent event protocol is a protected surface: see `BACKWARD_COMPATIBILITY.md` §7. In short — v1 `AgentEvent` `type` strings and v2 `UiEvent` dotted types are additive-only; removing/renaming one, or breaking the parity requirement, is a breaking change requiring the documented deprecation path. ## Related documents - `AGENTS.md` — repo working rules; the "Agent runners / backends" routing row. - `BACKWARD_COMPATIBILITY.md` — §7 (this protocol) and §2/§3 (SSE names, NDJSON). - `.ai/analysis/cockpit-ui-redesign/agent-event-protocols.md` — the deep design record (§7, §7.1). - `.ai/specs/2026-07-14-cockpit-ui-redesign.md` — the spec (protocol v2, parity requirement). ## Optional account usage metadata (#1340 component) `AgentRunSpec.onUsageWindows?: (observation: UsageWindowsObservation) => void` receives backend-neutral metadata during **both** `run` and `startSession`. Claude maps `rate_limit_event`, including `allowed` and `unifiedWindows`, and canonical `Claude AI usage limit reached|` markers in errored terminal `result` frames, either in the string `result` or string entries of `errors[]`. Multiple canonical markers in one frame produce one observation with the latest trusted future reset. Terminal markers reuse the auto-resume parser and its seven-day bound, require a strictly future reset, and emit one account-wide blocked `terminal-limit` window (`kind: other`, unknown duration) through the same account-bound callback. No window cadence is inferred; expired markers are ignored. This metadata is retained independently of whether auto-resume is enabled; Codex maps `account/rateLimits/updated`. No model turn is created to refresh this channel. Missing events are normal. Callback failures cannot fail an agent run. The integration caller captures the **resolved account of that specific step** in its callback closure; a runner must not guess a workspace account. The Zod contract is `packages/contract/src/usage-windows.ts`. All times are epoch milliseconds. An observation carries provider, source, observation time and windows. Each window carries an id, kind, optional limit id, applicability, model list, nullable reset/duration/percentage, status and observation time. Percentages may exceed 100. Unknown applicability must make selection unavailable, not fall back to a different model's window. For `rate_limit_event`, Claude only marks the explicitly named rejected window blocked; a rejected overage does not override allowed main usage. Unknown Claude/model-specific limit names and non-general Codex buckets are deliberately `applicability: unknown`; names are not model selectors. Codex keyed buckets take precedence over the legacy alias. Missing windows are partial observations; explicit null windows clear previous knowledge. A primary window can be weekly and secondary can be null: labels must use duration. `saveUsageWindows(binding, observation)` and `loadUsageWindows(binding)` in `workspace/usage-windows.ts` bind snapshots to provider, account id, resolved profile location and optional hashed identity. Writes use the workspace sandbox guard, a bounded cross-process lease and atomic 0600 replacement under CEZ_HOME. Corrupt/unwritable state degrades to no data with one redacted warning per file. Newer observations replace older windows; other windows and accounts survive. A verified identity change discards the old login's windows. Unidentified observations cannot overwrite identified snapshots or remove established holds, including when the profile location changes. Bind the exact same identity when reading; absent identity is not a wildcard. `futureUsageWindows(snapshot, now)` retains each known reset until it expires, with **no snapshot TTL**. `isUsageWindowBlocking(window, now)` treats an observed block as active until that window resets; it does not assert live allowance. The parent selector must enforce applicability and the seven-day upper bound; these helpers never select or schedule a task. `probeCodexUsageWindows(resolvedProfile, { force?, identityOnly? })` takes a trusted server-resolved Codex profile, never an HTTP-supplied path, environment or executable. It returns `{ binding, observation } | null` and does not persist. Usage reads run during preview and when a scheduled start checks for a newer blocking reset at its due time. Account-binding revalidation uses `identityOnly`, which skips `account/rateLimits/read`. Ordinary Codex steps start no probe and record no usage windows. Only a scheduled run bound to a Codex identity attributes streamed observations, re-verifying through the short identity cache (at most one app-server per cache window); an unanswered check skips that observation and a changed identity disables collection for the stream. `probeCodexIdentity(profile, { force? })` tells an unanswered read (`{ unavailable: true }`) from a definitive answer (`{ identity }`, `null` for an API-key login). These checks never create model turns. It uses the existing executable resolver and curated runner environment with the resolved CODEX_HOME pinned, and the profile directory as cwd. It sends only `initialize`, `initialized`, `account/read` (`refreshToken: false`) and `account/rateLimits/read`: no thread, turn or model call. Runtime (including profile checks) is bounded to 5 seconds, combined stdout/stderr to 256 KiB, concurrency to four, cache to 64 entries/15 seconds and single-flight per account/location. `force` bypasses the cache for a fresh identity comparison. API-key/no-identity accounts cannot be bound by identity; scheduled starts bind them by profile location. Identity hashes stable account metadata; credentials and raw protocol/error messages are never returned or persisted. The short-lived process is killed when the read finishes or exceeds a bound. Fixtures and tests live alongside `core/usage-windows*`, `core/codex-usage-probe*` and `workspace/usage-windows.test.ts`.