- v1 envelope across browser/daemon/plugin - SessionState model + reducer rules (pi events + pi2:* derived events) - fixtures for basic turn, queue/todo/attention and abort/exit - 9 conformance tests pinning the reducer
12 KiB
pi2 wire protocol (v1)
Single vocabulary, three surfaces. The plugin inside nvim is the only authority for session state.
browser <──HTTP + WS/SSE──> pi2d <──JSONL over unix socket──> plugin (nvim)
pi2dnever spawnspi, never parses session JSONL, never stores session state.- The browser keeps a render cache only; a
snapshotreplaces it wholesale. - One workspace maps to exactly one managed nvim instance.
1. Envelope
Every record is one JSON object per line (plugin↔daemon) or one WS message (browser↔daemon):
{
"v": 1,
"type": "hello | hello_ack | instance_state | workspace_update | subscribe | sub.subscribe | sub.unsubscribe
| snapshot | event | cmd | ack | error | resync_required | presence | bye",
"id": "req-…", // request/response correlation for cmd/ack
"workspaceId": "ws-…",
"sessionId": "…",
"epoch": "instance-uuid", // restart detection; seq is only valid within an epoch
"seq": 42, // per session, monotonic, produced by the plugin
"ts": 1733234400123, // wall clock, produced by the plugin
"mono": 918273, // monotonic ms, produced by the plugin (durations)
"origin": { "clientId": "…", "kind": "nvim|web|cli|daemon|system" },
"payload": { … }
}
Rules:
seqis per session and assigned by the plugin. The daemon never renumbers.epochchanges when the plugin process (re)starts or the session is re-opened by a different instance. A client holding a(epoch, seq)pair that no longer exists mustresync.ts/monoare authoritative; browsers never compare clocks across hosts.
2. Plugin ↔ daemon
The plugin dials the daemon (<runtime>/d.sock), sends hello first.
// plugin → daemon
{"v":1,"type":"hello","instanceId":"i-…","workspaceId":"ws-…","cwd":"/repo","pid":1234,
"hasUI":true,"listenAddr":"/run/user/1000/pi2/i/ab12.sock","pluginVersion":"1.8.0","capabilities":["snapshot","attention"]}
// daemon → plugin
{"v":1,"type":"hello_ack","daemonId":"d-…","limits":{"maxFrameBytes":8388608},"policy":{"attention":"all"}}
// plugin → daemon
{"v":1,"type":"instance_state","payload":{"status":"ready","sessions":[{"sessionId":"s1","status":"busy","name":"Refactor","tab":2,"model":{"provider":"anthropic","id":"claude-sonnet-4-5"}}]}}
{"v":1,"type":"snapshot","sessionId":"s1","epoch":"e1","seq":10,"payload":{"state":{ /* SessionState */ },"entries":[]}}
{"v":1,"type":"event","sessionId":"s1","epoch":"e1","seq":11,"ts":1733234400123,"payload":{"event":{ /* SessionEvent */ }}}
{"v":1,"type":"ack","id":"req-1","seq":12,"payload":{"disposition":"started"}}
{"v":1,"type":"error","id":"req-1","payload":{"code":"E_LEASE","message":"session is owned by instance i-2","retryable":false}}
// daemon → plugin
{"v":1,"type":"cmd","id":"req-1","sessionId":"s1","payload":{"method":"prompt.send","params":{"text":"hi"},"clientRequestId":"c-9"}}
{"v":1,"type":"sub.subscribe","sessionId":"s1"}
{"v":1,"type":"sub.unsubscribe","sessionId":"s1"}
{"v":1,"type":"instance.shutdown","payload":{"mode":"drain"}}
{"v":1,"type":"workspace.query","id":"req-2","payload":{"kind":"sessions"}}
Plugin obligations:
- Subscribe before prompt: the daemon calls
sub.subscribebefore forwarding a command; the plugin answers every new subscription with asnapshot(state + a tail of entries). - Throttle deltas:
text_delta/thinking_deltacoalesced to ≤30 fps (50 ms),tool_execution_updateto 100 ms. - Write-queue cap 4 MB per connection; on overflow drop low-priority events and emit one
droppedmarker. - Reconnect forever with exponential backoff (200 ms → 5 s). Never exit because the daemon is down.
3. Browser ↔ daemon
3.1 REST (reads)
| Endpoint | Notes |
|---|---|
GET /api/v1/info |
{v, daemonId, machineId, platform, capabilities, limits} |
GET /api/v1/health |
{ok, items:[{name, ok, detail}]} |
GET /api/v1/workspaces |
WorkspaceInfo[] (registry + disk index + instance state) |
GET /api/v1/workspaces/:id/sessions |
relayed workspace.query{kind:"sessions"} |
GET /api/v1/sessions/:sid/entries?before=&limit= |
relayed; plugin paginates |
GET /api/v1/attention?workspaceId= |
pending attention for one workspace |
GET /api/v1/devices |
paired devices (daemon-owned) |
GET /api/v1/models?workspaceId= |
relayed to the instance |
GET /api/v1/resources |
instances, sessions, RSS totals for the soft-limit notice |
GET /api/v1/diagnostics |
connections, event rates, slow queries, instance table |
3.2 Commands (writes)
POST /api/v1/cmd with {method, params, sessionId?, clientRequestId?} → 202 {accepted, disposition}.
Routing:
| Method | Routed to |
|---|---|
instance.ensure, instance.shutdown, workspace.*, pair.*, device.revoke, system.* |
daemon |
everything else (session.*, prompt.*, queue.*, attention.*, subagent.*, task.*) |
plugin of the workspace that owns sessionId (or of params.workspaceId for session.create/session.open) |
Idempotency: clientRequestId is deduplicated for 5 minutes; replays return the original ack.
3.3 WS events
Client → server: {"type":"subscribe","payload":{"workspaceId":"ws-1"}} (workspace scope) or
{"type":"subscribe","payload":{"sessionIds":["s1"]}}; {"type":"unsubscribe",...}; {"type":"ping"}.
Server → client (same envelope as above): hello_ack, instance_state, workspace_update, snapshot,
event, presence, resync_required, dropped, error.
GET /events (SSE) emits the same event records for degraded transports.
4. Session state
interface SessionState {
sessionId: string; workspaceId: string; cwd: string; name: string | null;
status: "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted";
flags: { attention: boolean; done: boolean; error: boolean };
model: { provider: string; id: string } | null;
thinking: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | null;
usage: { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number };
contextUsage: { tokens: number; window: number; percent: number } | null;
queue: { id: string; text: string; steer: boolean }[];
todos: { content: string; status: "pending" | "in_progress" | "completed"; activeForm?: string }[];
tasks: { id: string; command: string; status: "running" | "completed" | "failed" | "stopped";
startTime: number; durationMs?: number; exitCode?: number | null; outputFile?: string }[];
batches: { batchId: string; status: "running" | "completed" | "partial" | "failed" | "cancelled";
items: { ref: string; name?: string; status: string; error?: string }[];
summary?: { total: number; done: number; ok: number; failed: number; cancelled: number; running: number } }[];
subagents: { id: string; name?: string; status: "active" | "completed" | "failed" | "interrupted" | "dormant";
model?: string; thinking?: string; task?: string; children?: unknown[] }[];
attention: { requestId: string; method: string; title?: string; message?: string;
options?: { id: string; label: string }[]; payload?: unknown; timeoutSec?: number;
createdAt: number; receivedAt: number }[];
entries: Entry[];
}
type Block =
| { type: "text"; text: string }
| { type: "thinking"; text: string; redacted?: boolean }
| { type: "tool"; toolCallId: string; name: string; args?: unknown; output?: { text?: string; details?: unknown; isError?: boolean };
state: "pending" | "running" | "done" | "error"; durationMs?: number }
| { type: "error"; text: string };
interface Entry {
id: string; role: "user" | "assistant" | "system" | "notice";
ts: number; blocks: Block[]; done: boolean;
messageId?: string; images?: { mimeType: string; data: string }[];
}
4.1 Reducer rules (canonical, src/protocol/reducer.ts)
| Event | Effect |
|---|---|
agent_start |
status=busy, flags.done=false, flags.error=false |
agent_settled{aborted} |
status=idle (unless exited/interrupted), flags.done=!aborted, flags.error |= aborted |
compaction_start / compaction_end |
status=compacting / back to idle |
session_info_changed{name} |
name = name ?? null |
thinking_level_changed{level} |
thinking = level |
queue_update{steering,followUp} |
queue = [{id:"q:steer:N",steer:true}, {id:"q:follow:N",steer:false}] |
message_start{message} |
user/assistant entry created (m1, m2, …), blocks from content, done=false |
message_update{assistantMessageEvent} |
text/thinking deltas by contentIndex; toolcall_* creates/updates a tool block; error appends an error block |
tool_execution_start/update/end |
updates the tool block by toolCallId (running → `done |
message_end{message} |
replaces the entry blocks with authoritative content (tool blocks keep execution state), done=true, assistant usage is accumulated into session totals (cost.total → usage.cost) |
pi2:session{session} |
shallow patch of status/name/model/thinking/usage/contextUsage/flags |
pi2:todo{todos} |
replaces todos |
pi2:batch{batchId,status,items,summary} |
upserts into batches |
pi2:task{task} |
upserts into tasks by id |
pi2:subagents{subagents} |
replaces subagents |
pi2:attention_request{…} |
upserts into attention, flags.attention=true |
pi2:attention_resolved{requestId} |
removes from attention, flags.attention = attention.length>0 |
pi2:process_exit{code} |
status = code===0 ? exited : interrupted, flags.done=true |
pi2:error{message} |
appends an error block, flags.error=true |
Fixtures: fixtures/<case>/events.jsonl + expected.json (generated by pnpm tsx scripts/gen-expected.ts,
reviewed, committed). Both the TypeScript and Lua reducers must reproduce expected.json byte-for-byte.
5. Routing and lifecycle
browser cmd(sessionId=s1)
└─ daemon: find session owner
├─ known session → instance of that workspace → relay
├─ unknown → resolve workspace from session file → ensure instance (spawn if needed) → relay
└─ instance missing/degraded → start it (once), else 503 E_INSTANCE_UNAVAILABLE
instance.ensure{workspaceId}is idempotent and returns the currentinstance_state.- The daemon enforces one managed instance per workspace; a second nvim for the same cwd is reported
as
unmanagedand never receives browser commands. - Instances are never stopped automatically. Only
instance.shutdown(user action, confirm in UI) stops one. - On disconnect the daemon marks the instance
degraded; sessions becomeinterruptedwhen the instance reports process exit, or when the instance is restarted (epoch change).
6. Attention
pi2:attention_requestis broadcast to every client subscribed to that session and to the workspace inbox. The local nvim dialog is shown only when#nvim_list_uis() > 0.- The first successful
attention.respondwins; the plugin emitspi2:attention_resolved{requestId,by,response}. Everyone else closes and shows "resolved by ". - A second response returns
E_ATTENTION_RESOLVED. - Requests without a pi-level timeout are cancelled by the plugin after 120 s (
cancelled).
7. Errors
| Code | HTTP | Meaning |
|---|---|---|
E_BAD_REQUEST |
400 | malformed JSON / missing field |
E_UNAUTHORIZED |
401 | missing/invalid device token |
E_FORBIDDEN |
403 | bad Origin, insufficient scope |
E_NOT_FOUND |
404 | unknown workspace/session/instance |
E_PROTOCOL_VERSION |
426 | v unsupported |
E_PAYLOAD_TOO_LARGE |
413 | body/frame > limits |
E_RATE_LIMITED |
429 | per-IP or per-room limit |
E_INSTANCE_STARTING |
409 (retryable) | instance is booting |
E_INSTANCE_UNAVAILABLE |
503 (retryable) | no instance and spawn failed |
E_INSTANCE_UNMANAGED |
409 | workspace served by an unmanaged nvim |
E_LEASE |
409 | session owned by another instance |
E_EXTERNAL_SESSION |
409 | session written by a process outside pi2 |
E_SESSION_NOT_FOUND |
404 | |
E_ATTENTION_RESOLVED |
409 | already answered elsewhere |
E_UNSUPPORTED |
501 | capability missing |
E_INTERNAL |
500 |
message is English/debug only; the browser maps code to localized text.