feat(protocol): wire contract, canonical reducer and golden fixtures
- 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
This commit is contained in:
commit
9d817f35b7
19 files changed
+2922
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
coverage/
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
tmp/
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# pi2d — pi2 web console daemon
|
||||||
|
|
||||||
|
The always-on web side of [pi2.nvim](https://github.com/…/pi2.nvim). It is a **router + supervisor**, not an agent runtime:
|
||||||
|
|
||||||
|
```
|
||||||
|
browser ──HTTP/WS──▶ pi2d ──JSONL unix socket──▶ one nvim per workspace (pi2.nvim)
|
||||||
|
└── one pi --mode rpc per active session
|
||||||
|
```
|
||||||
|
|
||||||
|
Hard rules (see `docs/protocol.md`):
|
||||||
|
|
||||||
|
1. `pi2d` never spawns `pi`, never reads session JSONL, never owns session state.
|
||||||
|
2. A workspace maps to **exactly one** managed nvim instance.
|
||||||
|
3. All mutations are commands relayed to the plugin; the plugin (inside nvim) is the single source of truth.
|
||||||
|
4. The web client keeps a render cache only; a `snapshot` from the plugin replaces it wholesale.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
pnpm test
|
||||||
|
pnpm dev # starts on 127.0.0.1:7676
|
||||||
|
```
|
||||||
|
|
||||||
|
The plugin starts the daemon lazily when it is not running; you normally do not start it by hand.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
| Path | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `src/protocol/` | wire types, event/command vocabulary, error codes, canonical reducer |
|
||||||
|
| `src/daemon/` | HTTP/WS/SSE, auth, static assets, routing, event relay |
|
||||||
|
| `src/instances/` | discovery, lazy spawn, single-instance enforcement, crash handling |
|
||||||
|
| `src/workspaces/` | workspace registry, disk discovery, aliases/trust |
|
||||||
|
| `src/cli/` | `pi2d` (daemon) and `pi2` (attach/status/doctor) |
|
||||||
|
| `fixtures/` | golden event streams + expected session state (shared with pi2.nvim tests) |
|
||||||
|
| `docs/protocol.md` | the wire contract (browser ↔ daemon ↔ plugin) |
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
# 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)
|
||||||
|
```
|
||||||
|
|
||||||
|
- `pi2d` never spawns `pi`, never parses session JSONL, never stores session state.
|
||||||
|
- The browser keeps a **render cache** only; a `snapshot` replaces 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):
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"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:
|
||||||
|
|
||||||
|
- `seq` is **per session** and assigned by the plugin. The daemon never renumbers.
|
||||||
|
- `epoch` changes 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 must `resync`.
|
||||||
|
- `ts`/`mono` are authoritative; browsers never compare clocks across hosts.
|
||||||
|
|
||||||
|
## 2. Plugin ↔ daemon
|
||||||
|
|
||||||
|
The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
// 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.subscribe` before forwarding a command; the plugin
|
||||||
|
answers every new subscription with a `snapshot` (state + a tail of entries).
|
||||||
|
- Throttle deltas: `text_delta`/`thinking_delta` coalesced to ≤30 fps (50 ms), `tool_execution_update` to 100 ms.
|
||||||
|
- Write-queue cap 4 MB per connection; on overflow drop low-priority events and emit one `dropped` marker.
|
||||||
|
- 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
|
||||||
|
|
||||||
|
```ts
|
||||||
|
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|error`, `output`, `durationMs`) |
|
||||||
|
| `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 current `instance_state`.
|
||||||
|
- The daemon enforces **one managed instance per workspace**; a second nvim for the same cwd is reported
|
||||||
|
as `unmanaged` and 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 become `interrupted` when the instance
|
||||||
|
reports process exit, or when the instance is restarted (epoch change).
|
||||||
|
|
||||||
|
## 6. Attention
|
||||||
|
|
||||||
|
- `pi2:attention_request` is 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.respond` wins; the plugin emits `pi2:attention_resolved{requestId,by,response}`.
|
||||||
|
Everyone else closes and shows "resolved by <client>".
|
||||||
|
- 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.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{"type":"pi2:session","ts":1000,"session":{"status":"idle","cwd":"/repo","model":{"provider":"anthropic","id":"claude-sonnet-4-5"},"thinking":"medium","contextUsage":{"tokens":1200,"window":200000,"percent":0.6}}}
|
||||||
|
{"type":"agent_start","ts":1010}
|
||||||
|
{"type":"turn_start","ts":1011}
|
||||||
|
{"type":"message_start","ts":1012,"message":{"role":"user","content":"List the files","timestamp":1012}}
|
||||||
|
{"type":"message_end","ts":1013,"message":{"role":"user","content":"List the files","timestamp":1012}}
|
||||||
|
{"type":"message_start","ts":1014,"message":{"role":"assistant","content":[],"timestamp":1014}}
|
||||||
|
{"type":"message_update","ts":1015,"assistantMessageEvent":{"type":"thinking_start","contentIndex":0}}
|
||||||
|
{"type":"message_update","ts":1016,"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"I should "}}
|
||||||
|
{"type":"message_update","ts":1017,"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"list files."}}
|
||||||
|
{"type":"message_update","ts":1018,"assistantMessageEvent":{"type":"thinking_end","contentIndex":0,"content":"I should list files."}}
|
||||||
|
{"type":"message_update","ts":1019,"assistantMessageEvent":{"type":"text_start","contentIndex":1}}
|
||||||
|
{"type":"message_update","ts":1020,"assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"Let me "}}
|
||||||
|
{"type":"message_update","ts":1021,"assistantMessageEvent":{"type":"toolcall_start","contentIndex":2,"id":"call_1","toolName":"bash"}}
|
||||||
|
{"type":"message_update","ts":1022,"assistantMessageEvent":{"type":"toolcall_delta","contentIndex":2,"delta":"{\"command\":"}}
|
||||||
|
{"type":"message_update","ts":1023,"assistantMessageEvent":{"type":"toolcall_delta","contentIndex":2,"delta":"\"ls\"}"}}
|
||||||
|
{"type":"message_update","ts":1024,"assistantMessageEvent":{"type":"toolcall_end","contentIndex":2,"toolCall":{"type":"toolCall","id":"call_1","name":"bash","arguments":{"command":"ls"}}}}
|
||||||
|
{"type":"message_update","ts":1025,"assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"list them."}}
|
||||||
|
{"type":"message_end","ts":1030,"message":{"role":"assistant","content":[{"type":"thinking","thinking":"I should list files."},{"type":"text","text":"Let me list them."},{"type":"toolCall","id":"call_1","name":"bash","arguments":{"command":"ls"}}],"usage":{"input":100,"output":20,"cacheRead":0,"cacheWrite":0,"totalTokens":120,"cost":{"input":0.001,"output":0.002,"cacheRead":0,"cacheWrite":0,"total":0.003}},"timestamp":1030}}
|
||||||
|
{"type":"tool_execution_start","ts":1031,"toolCallId":"call_1","toolName":"bash","args":{"command":"ls"}}
|
||||||
|
{"type":"tool_execution_update","ts":1034,"toolCallId":"call_1","toolName":"bash","args":{"command":"ls"},"partialResult":{"content":[{"type":"text","text":"a.txt"}],"details":{}}}
|
||||||
|
{"type":"tool_execution_end","ts":1040,"toolCallId":"call_1","toolName":"bash","result":{"content":[{"type":"text","text":"a.txt\nb.txt"}],"details":{}},"isError":false,"durationMs":9}
|
||||||
|
{"type":"turn_end","ts":1041,"message":{"role":"assistant","content":[],"timestamp":1041},"toolResults":[]}
|
||||||
|
{"type":"agent_end","ts":1042,"messages":[],"willRetry":false}
|
||||||
|
{"type":"agent_settled","ts":1050,"aborted":false}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
{
|
||||||
|
"sessionId": "basic-turn",
|
||||||
|
"workspaceId": "ws-fixture",
|
||||||
|
"cwd": "/repo",
|
||||||
|
"name": null,
|
||||||
|
"status": "idle",
|
||||||
|
"flags": {
|
||||||
|
"attention": false,
|
||||||
|
"done": true,
|
||||||
|
"error": false
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"provider": "anthropic",
|
||||||
|
"id": "claude-sonnet-4-5"
|
||||||
|
},
|
||||||
|
"thinking": "medium",
|
||||||
|
"usage": {
|
||||||
|
"input": 100,
|
||||||
|
"output": 20,
|
||||||
|
"cacheRead": 0,
|
||||||
|
"cacheWrite": 0,
|
||||||
|
"cost": 0.003
|
||||||
|
},
|
||||||
|
"contextUsage": {
|
||||||
|
"tokens": 1200,
|
||||||
|
"window": 200000,
|
||||||
|
"percent": 0.6
|
||||||
|
},
|
||||||
|
"queue": [],
|
||||||
|
"todos": [],
|
||||||
|
"tasks": [],
|
||||||
|
"batches": [],
|
||||||
|
"subagents": [],
|
||||||
|
"attention": [],
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"id": "m1",
|
||||||
|
"role": "user",
|
||||||
|
"ts": 1012,
|
||||||
|
"blocks": [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": "List the files"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"done": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "m2",
|
||||||
|
"role": "assistant",
|
||||||
|
"ts": 1014,
|
||||||
|
"blocks": [
|
||||||
|
{
|
||||||
|
"type": "thinking",
|
||||||
|
"text": "I should list files."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": "Let me list them."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "tool",
|
||||||
|
"toolCallId": "call_1",
|
||||||
|
"name": "bash",
|
||||||
|
"state": "done",
|
||||||
|
"args": {
|
||||||
|
"command": "ls"
|
||||||
|
},
|
||||||
|
"output": {
|
||||||
|
"text": "a.txt\nb.txt",
|
||||||
|
"details": {}
|
||||||
|
},
|
||||||
|
"durationMs": 9
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"done": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{"type":"pi2:session","ts":3000,"session":{"status":"idle","cwd":"/repo","model":{"provider":"anthropic","id":"claude-sonnet-4-5"},"thinking":"off"}}
|
||||||
|
{"type":"agent_start","ts":3001}
|
||||||
|
{"type":"message_start","ts":3002,"message":{"role":"assistant","content":[],"timestamp":3002}}
|
||||||
|
{"type":"message_update","ts":3003,"assistantMessageEvent":{"type":"text_start","contentIndex":0}}
|
||||||
|
{"type":"message_update","ts":3004,"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"partial answer"}}
|
||||||
|
{"type":"message_update","ts":3005,"assistantMessageEvent":{"type":"error","reason":"aborted","error":"Aborted by user"}}
|
||||||
|
{"type":"pi2:error","ts":3006,"message":"Aborted by user"}
|
||||||
|
{"type":"agent_settled","ts":3007,"aborted":true}
|
||||||
|
{"type":"compaction_start","ts":3010,"reason":"manual"}
|
||||||
|
{"type":"compaction_end","ts":3020,"reason":"manual","success":true}
|
||||||
|
{"type":"pi2:process_exit","ts":3030,"code":0,"signal":null}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"sessionId": "error-abort-compaction",
|
||||||
|
"workspaceId": "ws-fixture",
|
||||||
|
"cwd": "/repo",
|
||||||
|
"name": null,
|
||||||
|
"status": "exited",
|
||||||
|
"flags": {
|
||||||
|
"attention": false,
|
||||||
|
"done": false,
|
||||||
|
"error": true
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"provider": "anthropic",
|
||||||
|
"id": "claude-sonnet-4-5"
|
||||||
|
},
|
||||||
|
"thinking": "off",
|
||||||
|
"usage": {
|
||||||
|
"input": 0,
|
||||||
|
"output": 0,
|
||||||
|
"cacheRead": 0,
|
||||||
|
"cacheWrite": 0,
|
||||||
|
"cost": 0
|
||||||
|
},
|
||||||
|
"contextUsage": null,
|
||||||
|
"queue": [],
|
||||||
|
"todos": [],
|
||||||
|
"tasks": [],
|
||||||
|
"batches": [],
|
||||||
|
"subagents": [],
|
||||||
|
"attention": [],
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"id": "m1",
|
||||||
|
"role": "assistant",
|
||||||
|
"ts": 3002,
|
||||||
|
"blocks": [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": "partial answer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"text": "Aborted by user"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"text": "Aborted by user"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"done": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{"type":"pi2:session","ts":2000,"session":{"status":"busy","cwd":"/repo","model":{"provider":"anthropic","id":"claude-sonnet-4-5"},"thinking":"high","contextUsage":{"tokens":1234,"window":200000,"percent":0.6}}}
|
||||||
|
{"type":"session_info_changed","ts":2001,"name":"Refactor auth"}
|
||||||
|
{"type":"queue_update","ts":2002,"steering":["use pnpm"],"followUp":["then run the tests"]}
|
||||||
|
{"type":"pi2:todo","ts":2003,"todos":[{"content":"read auth.ts","status":"completed","activeForm":"reading auth.ts"},{"content":"refactor","status":"in_progress","activeForm":"refactoring"},{"content":"test","status":"pending"}],"completed":1,"total":3}
|
||||||
|
{"type":"pi2:batch","ts":2004,"batchId":"b1","status":"running","items":[{"ref":"0","name":"audit","status":"ok"},{"ref":"1","name":"refactor","status":"running"}],"summary":{"total":2,"done":1,"ok":1,"failed":0,"cancelled":0,"running":1}}
|
||||||
|
{"type":"pi2:task","ts":2005,"task":{"id":"t1","command":"pnpm test","status":"running","startTime":2005}}
|
||||||
|
{"type":"pi2:subagents","ts":2006,"subagents":[{"id":"s2","name":"audit","status":"completed","model":"claude-sonnet-4-5"},{"id":"s3","name":"refactor","status":"active","model":"deepseek-v4.1"}],"parentId":"s1"}
|
||||||
|
{"type":"pi2:attention_request","ts":2007,"requestId":"att1","method":"select","title":"Apply diff?","message":"3 files changed","options":[{"id":"accept","label":"Accept"},{"id":"reject","label":"Reject"}],"timeoutSec":120}
|
||||||
|
{"type":"pi2:attention_resolved","ts":2008,"requestId":"att1","by":{"clientId":"c1","kind":"web"},"response":{"id":"accept"}}
|
||||||
|
{"type":"agent_settled","ts":2010,"aborted":false}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
{
|
||||||
|
"sessionId": "queue-todo-attention",
|
||||||
|
"workspaceId": "ws-fixture",
|
||||||
|
"cwd": "/repo",
|
||||||
|
"name": "Refactor auth",
|
||||||
|
"status": "idle",
|
||||||
|
"flags": {
|
||||||
|
"attention": false,
|
||||||
|
"done": true,
|
||||||
|
"error": false
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"provider": "anthropic",
|
||||||
|
"id": "claude-sonnet-4-5"
|
||||||
|
},
|
||||||
|
"thinking": "high",
|
||||||
|
"usage": {
|
||||||
|
"input": 0,
|
||||||
|
"output": 0,
|
||||||
|
"cacheRead": 0,
|
||||||
|
"cacheWrite": 0,
|
||||||
|
"cost": 0
|
||||||
|
},
|
||||||
|
"contextUsage": {
|
||||||
|
"tokens": 1234,
|
||||||
|
"window": 200000,
|
||||||
|
"percent": 0.6
|
||||||
|
},
|
||||||
|
"queue": [
|
||||||
|
{
|
||||||
|
"id": "q:steer:0",
|
||||||
|
"text": "use pnpm",
|
||||||
|
"steer": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "q:follow:0",
|
||||||
|
"text": "then run the tests",
|
||||||
|
"steer": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"todos": [
|
||||||
|
{
|
||||||
|
"content": "read auth.ts",
|
||||||
|
"status": "completed",
|
||||||
|
"activeForm": "reading auth.ts"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"content": "refactor",
|
||||||
|
"status": "in_progress",
|
||||||
|
"activeForm": "refactoring"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"content": "test",
|
||||||
|
"status": "pending"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"id": "t1",
|
||||||
|
"command": "pnpm test",
|
||||||
|
"status": "running",
|
||||||
|
"startTime": 2005
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"batches": [
|
||||||
|
{
|
||||||
|
"batchId": "b1",
|
||||||
|
"status": "running",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"ref": "0",
|
||||||
|
"name": "audit",
|
||||||
|
"status": "ok"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ref": "1",
|
||||||
|
"name": "refactor",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"summary": {
|
||||||
|
"total": 2,
|
||||||
|
"done": 1,
|
||||||
|
"ok": 1,
|
||||||
|
"failed": 0,
|
||||||
|
"cancelled": 0,
|
||||||
|
"running": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subagents": [
|
||||||
|
{
|
||||||
|
"id": "s2",
|
||||||
|
"name": "audit",
|
||||||
|
"status": "completed",
|
||||||
|
"model": "claude-sonnet-4-5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "s3",
|
||||||
|
"name": "refactor",
|
||||||
|
"status": "active",
|
||||||
|
"model": "deepseek-v4.1"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attention": [],
|
||||||
|
"entries": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "pi2d",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "pi2 web console daemon: HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"pi2d": "./dist/cli/pi2d.js",
|
||||||
|
"pi2": "./dist/cli/pi2.js"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/cli/pi2d.ts",
|
||||||
|
"build": "tsc -p tsconfig.json",
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"lint": "tsc -p tsconfig.json --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@hono/node-server": "^1.13.7",
|
||||||
|
"hono": "^4.6.14",
|
||||||
|
"ws": "^8.18.0",
|
||||||
|
"zod": "^3.24.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.10.2",
|
||||||
|
"@types/ws": "^8.5.13",
|
||||||
|
"tsx": "^4.19.2",
|
||||||
|
"typescript": "^5.7.2",
|
||||||
|
"vitest": "^2.1.8"
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1266
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
|||||||
|
allowBuilds:
|
||||||
|
esbuild: set this to true or false
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/**
|
||||||
|
* Regenerates `fixtures/<case>/expected.json` from the canonical reducer.
|
||||||
|
*
|
||||||
|
* pnpm tsx scripts/gen-expected.ts
|
||||||
|
*
|
||||||
|
* The generated files are reviewed and committed; both the TypeScript and the
|
||||||
|
* Lua reducers must reproduce them exactly (see `test/reducer.conformance.test.ts`
|
||||||
|
* and `pi2.nvim/tests/web_state_conformance_spec.lua`).
|
||||||
|
*/
|
||||||
|
import { readFileSync, writeFileSync, readdirSync, existsSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { reduceAll } from "../src/protocol/reducer.js";
|
||||||
|
import type { SessionEvent } from "../src/protocol/types.js";
|
||||||
|
|
||||||
|
const root = join(import.meta.dirname, "..", "fixtures");
|
||||||
|
for (const name of readdirSync(root)) {
|
||||||
|
const dir = join(root, name);
|
||||||
|
const eventsPath = join(dir, "events.jsonl");
|
||||||
|
if (!existsSync(eventsPath)) continue;
|
||||||
|
const events = readFileSync(eventsPath, "utf8")
|
||||||
|
.split("\n")
|
||||||
|
.filter((line) => line.trim().length > 0)
|
||||||
|
.map((line) => JSON.parse(line) as SessionEvent);
|
||||||
|
const first = events[0]?.session as Record<string, unknown> | undefined;
|
||||||
|
const state = reduceAll(
|
||||||
|
{
|
||||||
|
sessionId: name,
|
||||||
|
workspaceId: "ws-fixture",
|
||||||
|
cwd: typeof first?.cwd === "string" ? first.cwd : "/repo",
|
||||||
|
},
|
||||||
|
events,
|
||||||
|
);
|
||||||
|
const out = join(dir, "expected.json");
|
||||||
|
writeFileSync(out, JSON.stringify(state, null, 2) + "\n");
|
||||||
|
console.log(`wrote ${out}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
/** Stable error codes. The browser translates codes; `message` is English/debug only. */
|
||||||
|
|
||||||
|
export const ERROR_CODES = {
|
||||||
|
BAD_REQUEST: "E_BAD_REQUEST",
|
||||||
|
UNAUTHORIZED: "E_UNAUTHORIZED",
|
||||||
|
FORBIDDEN: "E_FORBIDDEN",
|
||||||
|
NOT_FOUND: "E_NOT_FOUND",
|
||||||
|
METHOD_NOT_ALLOWED: "E_METHOD_NOT_ALLOWED",
|
||||||
|
PROTOCOL_VERSION: "E_PROTOCOL_VERSION",
|
||||||
|
PAYLOAD_TOO_LARGE: "E_PAYLOAD_TOO_LARGE",
|
||||||
|
RATE_LIMITED: "E_RATE_LIMITED",
|
||||||
|
INSTANCE_STARTING: "E_INSTANCE_STARTING",
|
||||||
|
INSTANCE_UNMANAGED: "E_INSTANCE_UNMANAGED",
|
||||||
|
INSTANCE_UNAVAILABLE: "E_INSTANCE_UNAVAILABLE",
|
||||||
|
LEASE_CONFLICT: "E_LEASE",
|
||||||
|
EXTERNAL_SESSION: "E_EXTERNAL_SESSION",
|
||||||
|
SESSION_NOT_FOUND: "E_SESSION_NOT_FOUND",
|
||||||
|
ATTENTION_RESOLVED: "E_ATTENTION_RESOLVED",
|
||||||
|
UNSUPPORTED: "E_UNSUPPORTED",
|
||||||
|
INTERNAL: "E_INTERNAL",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
||||||
|
|
||||||
|
export function errorBody(code: ErrorCode | string, message: string, retryable = false, details?: Record<string, unknown>) {
|
||||||
|
return { code, message, retryable, ...(details ? { details } : {}) };
|
||||||
|
}
|
||||||
@@ -0,0 +1,565 @@
|
|||||||
|
/**
|
||||||
|
* Canonical session-state reducer.
|
||||||
|
*
|
||||||
|
* This is the reference implementation of the projection that turns a pi event
|
||||||
|
* stream (plus `pi2:` derived events) into `SessionState`. The plugin keeps the
|
||||||
|
* authoritative copy in Lua (`lua/pi/web/state.lua`); the browser keeps a render
|
||||||
|
* cache reduced by this file; both must agree on `fixtures/*` (see
|
||||||
|
* `test/reducer.conformance.test.ts`).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type {
|
||||||
|
AttentionItem,
|
||||||
|
Batch,
|
||||||
|
Block,
|
||||||
|
ContextUsage,
|
||||||
|
Entry,
|
||||||
|
ModelRef,
|
||||||
|
QueueItem,
|
||||||
|
SessionEvent,
|
||||||
|
SessionState,
|
||||||
|
Subagent,
|
||||||
|
TaskItem,
|
||||||
|
ThinkingLevel,
|
||||||
|
TodoItem,
|
||||||
|
ToolOutput,
|
||||||
|
UsageTotals,
|
||||||
|
} from "./types.js";
|
||||||
|
|
||||||
|
export interface ReducerContext {
|
||||||
|
nextEntry: number;
|
||||||
|
assistantEntryId: string | null;
|
||||||
|
userEntryId: string | null;
|
||||||
|
/** toolCallId -> location of the tool block */
|
||||||
|
toolBlocks: Map<string, { entryId: string; index: number }>;
|
||||||
|
/** streamed tool call argument buffers, keyed by toolCallId */
|
||||||
|
toolArgs: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Reducer {
|
||||||
|
state: SessionState;
|
||||||
|
ctx: ReducerContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StateInit {
|
||||||
|
sessionId: string;
|
||||||
|
workspaceId?: string;
|
||||||
|
cwd?: string;
|
||||||
|
name?: string | null;
|
||||||
|
status?: SessionState["status"];
|
||||||
|
model?: ModelRef | null;
|
||||||
|
thinking?: ThinkingLevel | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_USAGE: UsageTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
||||||
|
|
||||||
|
export function createReducer(init: StateInit): Reducer {
|
||||||
|
return {
|
||||||
|
state: {
|
||||||
|
sessionId: init.sessionId,
|
||||||
|
workspaceId: init.workspaceId ?? "",
|
||||||
|
cwd: init.cwd ?? "",
|
||||||
|
name: init.name ?? null,
|
||||||
|
status: init.status ?? "starting",
|
||||||
|
flags: { attention: false, done: false, error: false },
|
||||||
|
model: init.model ?? null,
|
||||||
|
thinking: init.thinking ?? null,
|
||||||
|
usage: { ...EMPTY_USAGE },
|
||||||
|
contextUsage: null,
|
||||||
|
queue: [],
|
||||||
|
todos: [],
|
||||||
|
tasks: [],
|
||||||
|
batches: [],
|
||||||
|
subagents: [],
|
||||||
|
attention: [],
|
||||||
|
entries: [],
|
||||||
|
},
|
||||||
|
ctx: {
|
||||||
|
nextEntry: 1,
|
||||||
|
assistantEntryId: null,
|
||||||
|
userEntryId: null,
|
||||||
|
toolBlocks: new Map(),
|
||||||
|
toolArgs: new Map(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceAll(init: StateInit, events: SessionEvent[]): SessionState {
|
||||||
|
const r = createReducer(init);
|
||||||
|
for (const e of events) applyEvent(r, e);
|
||||||
|
return r.state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* helpers */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
function num(v: unknown, fallback = 0): number {
|
||||||
|
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function str(v: unknown): string | undefined {
|
||||||
|
return typeof v === "string" ? v : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rec(v: unknown): Record<string, unknown> | undefined {
|
||||||
|
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function arr(v: unknown): unknown[] {
|
||||||
|
return Array.isArray(v) ? v : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryOf(r: Reducer, id: string | null): Entry | undefined {
|
||||||
|
if (!id) return undefined;
|
||||||
|
return r.state.entries.find((e) => e.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function newEntry(r: Reducer, role: Entry["role"], ts: number, blocks: Block[] = [], done = false): Entry {
|
||||||
|
const entry: Entry = { id: `m${r.ctx.nextEntry++}`, role, ts, blocks, done };
|
||||||
|
r.state.entries.push(entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Index of the block for a `contentIndex`, creating placeholders as needed. */
|
||||||
|
function blockAt(entry: Entry, index: number, template: () => Block): Block {
|
||||||
|
while (entry.blocks.length <= index) entry.blocks.push({ type: "text", text: "" });
|
||||||
|
const existing = entry.blocks[index];
|
||||||
|
if (existing && existing.type === template().type) return existing;
|
||||||
|
const block = template();
|
||||||
|
entry.blocks[index] = block;
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendDelta(entry: Entry, index: number, type: "text" | "thinking", delta: string) {
|
||||||
|
const block = blockAt(entry, index, () => ({ type, text: "" })) as { type: "text" | "thinking"; text: string };
|
||||||
|
block.text += delta;
|
||||||
|
}
|
||||||
|
|
||||||
|
function contentToBlocks(content: unknown, ts: number): Block[] {
|
||||||
|
if (typeof content === "string") return [{ type: "text", text: content }];
|
||||||
|
const blocks: Block[] = [];
|
||||||
|
for (const raw of arr(content)) {
|
||||||
|
const b = rec(raw);
|
||||||
|
if (!b) continue;
|
||||||
|
switch (b.type) {
|
||||||
|
case "text":
|
||||||
|
blocks.push({ type: "text", text: str(b.text) ?? "" });
|
||||||
|
break;
|
||||||
|
case "thinking":
|
||||||
|
blocks.push({ type: "thinking", text: str(b.thinking) ?? str(b.text) ?? "" });
|
||||||
|
break;
|
||||||
|
case "toolCall":
|
||||||
|
blocks.push({
|
||||||
|
type: "tool",
|
||||||
|
toolCallId: str(b.id) ?? `call_${ts}_${blocks.length}`,
|
||||||
|
name: str(b.name) ?? "tool",
|
||||||
|
args: b.arguments,
|
||||||
|
state: "pending",
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "error":
|
||||||
|
blocks.push({ type: "error", text: str(b.text) ?? str(b.error) ?? "error" });
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
function imagesOf(content: unknown): { mimeType: string; data: string }[] | undefined {
|
||||||
|
const out: { mimeType: string; data: string }[] = [];
|
||||||
|
for (const raw of arr(content)) {
|
||||||
|
const b = rec(raw);
|
||||||
|
if (b?.type === "image" && typeof b.data === "string" && typeof b.mimeType === "string") {
|
||||||
|
out.push({ mimeType: b.mimeType, data: b.data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.length ? out : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addUsage(state: SessionState, usage: unknown) {
|
||||||
|
const u = rec(usage);
|
||||||
|
if (!u) return;
|
||||||
|
state.usage.input += num(u.input);
|
||||||
|
state.usage.output += num(u.output);
|
||||||
|
state.usage.cacheRead += num(u.cacheRead);
|
||||||
|
state.usage.cacheWrite += num(u.cacheWrite);
|
||||||
|
state.usage.cost += num(rec(u.cost)?.total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* event handlers */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export function applyEvent(r: Reducer, e: SessionEvent): void {
|
||||||
|
const ts = num(e.ts);
|
||||||
|
switch (e.type) {
|
||||||
|
case "agent_start":
|
||||||
|
r.state.status = "busy";
|
||||||
|
r.state.flags.done = false;
|
||||||
|
r.state.flags.error = false;
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "agent_settled": {
|
||||||
|
if (r.state.status !== "exited" && r.state.status !== "interrupted") r.state.status = "idle";
|
||||||
|
r.state.flags.done = e.aborted !== true;
|
||||||
|
r.state.flags.error = e.aborted === true ? true : r.state.flags.error;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "compaction_start":
|
||||||
|
r.state.status = "compacting";
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "compaction_end":
|
||||||
|
if (r.state.status === "compacting") r.state.status = "idle";
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "session_info_changed":
|
||||||
|
r.state.name = str(e.name) ?? null;
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "thinking_level_changed":
|
||||||
|
r.state.thinking = (str(e.level) as ThinkingLevel | undefined) ?? r.state.thinking;
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "queue_update": {
|
||||||
|
const queue: QueueItem[] = [];
|
||||||
|
arr(e.steering).forEach((text, i) => {
|
||||||
|
if (typeof text === "string") queue.push({ id: `q:steer:${i}`, text, steer: true });
|
||||||
|
});
|
||||||
|
arr(e.followUp).forEach((text, i) => {
|
||||||
|
if (typeof text === "string") queue.push({ id: `q:follow:${i}`, text, steer: false });
|
||||||
|
});
|
||||||
|
r.state.queue = queue;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "message_start": {
|
||||||
|
const msg = rec(e.message);
|
||||||
|
if (!msg) return;
|
||||||
|
const role = str(msg.role);
|
||||||
|
if (role === "user") {
|
||||||
|
const entry = newEntry(r, "user", ts, contentToBlocks(msg.content, ts));
|
||||||
|
entry.images = imagesOf(msg.content);
|
||||||
|
r.ctx.userEntryId = entry.id;
|
||||||
|
} else if (role === "assistant") {
|
||||||
|
const entry = newEntry(r, "assistant", ts, []);
|
||||||
|
r.ctx.assistantEntryId = entry.id;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "message_update": {
|
||||||
|
const update = rec(e.assistantMessageEvent);
|
||||||
|
if (!update) return;
|
||||||
|
const entry = entryOf(r, r.ctx.assistantEntryId);
|
||||||
|
if (!entry) return;
|
||||||
|
const index = num(update.contentIndex);
|
||||||
|
switch (update.type) {
|
||||||
|
case "text_start":
|
||||||
|
blockAt(entry, index, () => ({ type: "text", text: "" }));
|
||||||
|
break;
|
||||||
|
case "text_delta":
|
||||||
|
appendDelta(entry, index, "text", str(update.delta) ?? "");
|
||||||
|
break;
|
||||||
|
case "text_end": {
|
||||||
|
const block = blockAt(entry, index, () => ({ type: "text", text: "" })) as {
|
||||||
|
type: "text";
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
block.text = str(update.content) ?? block.text;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "thinking_start":
|
||||||
|
blockAt(entry, index, () => ({ type: "thinking", text: "" }));
|
||||||
|
break;
|
||||||
|
case "thinking_delta":
|
||||||
|
appendDelta(entry, index, "thinking", str(update.delta) ?? "");
|
||||||
|
break;
|
||||||
|
case "thinking_end": {
|
||||||
|
const block = blockAt(entry, index, () => ({ type: "thinking", text: "" })) as {
|
||||||
|
type: "thinking";
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
block.text = str(update.content) ?? block.text;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "toolcall_start": {
|
||||||
|
const toolCallId = str(update.id) ?? `call_${ts}_${index}`;
|
||||||
|
const block: Block = {
|
||||||
|
type: "tool",
|
||||||
|
toolCallId,
|
||||||
|
name: str(update.toolName) ?? "tool",
|
||||||
|
state: "pending",
|
||||||
|
};
|
||||||
|
while (entry.blocks.length <= index) entry.blocks.push({ type: "text", text: "" });
|
||||||
|
entry.blocks[index] = block;
|
||||||
|
r.ctx.toolBlocks.set(toolCallId, { entryId: entry.id, index });
|
||||||
|
r.ctx.toolArgs.set(toolCallId, "");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "toolcall_delta": {
|
||||||
|
const toolCallId = findToolCallIdAt(r, entry.id, index);
|
||||||
|
if (toolCallId) {
|
||||||
|
r.ctx.toolArgs.set(toolCallId, (r.ctx.toolArgs.get(toolCallId) ?? "") + (str(update.delta) ?? ""));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "toolcall_end": {
|
||||||
|
const call = rec(update.toolCall);
|
||||||
|
const toolCallId = str(call?.id) ?? findToolCallIdAt(r, entry.id, index);
|
||||||
|
if (!toolCallId) break;
|
||||||
|
const block = ensureToolBlock(r, toolCallId, entry.id, index);
|
||||||
|
block.name = str(call?.name) ?? block.name;
|
||||||
|
if (call) block.args = call.arguments;
|
||||||
|
r.ctx.toolArgs.delete(toolCallId);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "error": {
|
||||||
|
const text = str(update.error) ?? str(update.reason) ?? "error";
|
||||||
|
entry.blocks.push({ type: "error", text });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tool_execution_start": {
|
||||||
|
const toolCallId = str(e.toolCallId);
|
||||||
|
if (!toolCallId) return;
|
||||||
|
const block = ensureToolBlock(r, toolCallId, r.ctx.assistantEntryId);
|
||||||
|
block.name = str(e.toolName) ?? block.name;
|
||||||
|
block.args = e.args;
|
||||||
|
block.state = "running";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tool_execution_update": {
|
||||||
|
const toolCallId = str(e.toolCallId);
|
||||||
|
if (!toolCallId) return;
|
||||||
|
const block = ensureToolBlock(r, toolCallId, r.ctx.assistantEntryId);
|
||||||
|
const output = toolOutputOf(e.partialResult);
|
||||||
|
if (output) block.output = output;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tool_execution_end": {
|
||||||
|
const toolCallId = str(e.toolCallId);
|
||||||
|
if (!toolCallId) return;
|
||||||
|
const block = ensureToolBlock(r, toolCallId, r.ctx.assistantEntryId);
|
||||||
|
const output = toolOutputOf(e.result);
|
||||||
|
if (output) block.output = output;
|
||||||
|
block.state = e.isError === true ? "error" : "done";
|
||||||
|
if (typeof e.durationMs === "number") block.durationMs = e.durationMs;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "message_end": {
|
||||||
|
const msg = rec(e.message);
|
||||||
|
if (!msg) return;
|
||||||
|
const role = str(msg.role);
|
||||||
|
if (role === "user") {
|
||||||
|
const entry = entryOf(r, r.ctx.userEntryId);
|
||||||
|
if (entry) {
|
||||||
|
entry.blocks = contentToBlocks(msg.content, ts);
|
||||||
|
entry.images = imagesOf(msg.content);
|
||||||
|
entry.done = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (role !== "assistant") return;
|
||||||
|
const entry = entryOf(r, r.ctx.assistantEntryId);
|
||||||
|
if (!entry) return;
|
||||||
|
entry.blocks = rebuildBlocks(r, contentToBlocks(msg.content, ts));
|
||||||
|
entry.done = true;
|
||||||
|
addUsage(r.state, msg.usage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:session": {
|
||||||
|
const patch = rec(e.session);
|
||||||
|
if (!patch) return;
|
||||||
|
for (const key of ["status", "name", "model", "thinking", "usage", "contextUsage", "flags"] as const) {
|
||||||
|
if (key in patch) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(r.state as any)[key] = patch[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (r.state.attention.length > 0) r.state.flags.attention = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:todo":
|
||||||
|
r.state.todos = arr(e.todos).map((raw) => {
|
||||||
|
const t = rec(raw) ?? {};
|
||||||
|
return {
|
||||||
|
content: str(t.content) ?? "",
|
||||||
|
status: (str(t.status) as TodoItem["status"]) ?? "pending",
|
||||||
|
...(typeof t.activeForm === "string" ? { activeForm: t.activeForm } : {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "pi2:batch": {
|
||||||
|
const batch: Batch = {
|
||||||
|
batchId: str(e.batchId) ?? "batch",
|
||||||
|
status: (str(e.status) as Batch["status"]) ?? "running",
|
||||||
|
items: arr(e.items).map((raw) => {
|
||||||
|
const item = rec(raw) ?? {};
|
||||||
|
return {
|
||||||
|
ref: str(item.ref) ?? "",
|
||||||
|
...(typeof item.name === "string" ? { name: item.name } : {}),
|
||||||
|
status: (str(item.status) as Batch["items"][number]["status"]) ?? "queued",
|
||||||
|
...(typeof item.error === "string" ? { error: item.error } : {}),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
...(rec(e.summary) ? { summary: rec(e.summary) as unknown as Batch["summary"] } : {}),
|
||||||
|
};
|
||||||
|
const idx = r.state.batches.findIndex((b) => b.batchId === batch.batchId);
|
||||||
|
if (idx >= 0) r.state.batches[idx] = batch;
|
||||||
|
else r.state.batches.push(batch);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:task": {
|
||||||
|
const t = rec(e.task);
|
||||||
|
if (!t) return;
|
||||||
|
const task: TaskItem = {
|
||||||
|
id: str(t.id) ?? "task",
|
||||||
|
command: str(t.command) ?? "",
|
||||||
|
status: (str(t.status) as TaskItem["status"]) ?? "running",
|
||||||
|
startTime: num(t.startTime, ts),
|
||||||
|
...(typeof t.durationMs === "number" ? { durationMs: t.durationMs } : {}),
|
||||||
|
...(t.exitCode === null || typeof t.exitCode === "number" ? { exitCode: t.exitCode as number | null } : {}),
|
||||||
|
...(typeof t.outputFile === "string" ? { outputFile: t.outputFile } : {}),
|
||||||
|
};
|
||||||
|
const idx = r.state.tasks.findIndex((x) => x.id === task.id);
|
||||||
|
if (idx >= 0) r.state.tasks[idx] = task;
|
||||||
|
else r.state.tasks.push(task);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:subagents":
|
||||||
|
r.state.subagents = arr(e.subagents) as Subagent[];
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "pi2:attention_request": {
|
||||||
|
const item: AttentionItem = {
|
||||||
|
requestId: str(e.requestId) ?? `att_${ts}`,
|
||||||
|
method: str(e.method) ?? "select",
|
||||||
|
...(typeof e.title === "string" ? { title: e.title } : {}),
|
||||||
|
...(typeof e.message === "string" ? { message: e.message } : {}),
|
||||||
|
...(Array.isArray(e.options) ? { options: e.options as AttentionItem["options"] } : {}),
|
||||||
|
...(e.payload !== undefined ? { payload: e.payload } : {}),
|
||||||
|
...(typeof e.timeoutSec === "number" ? { timeoutSec: e.timeoutSec } : {}),
|
||||||
|
createdAt: num(e.createdAt, ts),
|
||||||
|
receivedAt: ts,
|
||||||
|
};
|
||||||
|
r.state.attention = r.state.attention.filter((a) => a.requestId !== item.requestId).concat(item);
|
||||||
|
r.state.flags.attention = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:attention_resolved": {
|
||||||
|
const id = str(e.requestId);
|
||||||
|
r.state.attention = r.state.attention.filter((a) => a.requestId !== id);
|
||||||
|
r.state.flags.attention = r.state.attention.length > 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:process_exit": {
|
||||||
|
const code = e.code;
|
||||||
|
r.state.status = code === 0 || code === null || code === undefined ? "exited" : "interrupted";
|
||||||
|
// An exit is not a completed turn: keep `done` untouched so the UI shows
|
||||||
|
// the hollow "exited" dot instead of a green "done" mark.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pi2:error": {
|
||||||
|
const text = str(e.message) ?? "error";
|
||||||
|
const entry = entryOf(r, r.ctx.assistantEntryId) ?? newEntry(r, "notice", ts, []);
|
||||||
|
entry.blocks.push({ type: "error", text });
|
||||||
|
if (!r.ctx.assistantEntryId) entry.done = true;
|
||||||
|
r.state.flags.error = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findToolCallIdAt(r: Reducer, entryId: string, index: number): string | undefined {
|
||||||
|
for (const [id, loc] of r.ctx.toolBlocks) {
|
||||||
|
if (loc.entryId === entryId && loc.index === index) return id;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureToolBlock(r: Reducer, toolCallId: string, entryId: string | null, index?: number): Extract<Block, { type: "tool" }> {
|
||||||
|
const loc = r.ctx.toolBlocks.get(toolCallId);
|
||||||
|
const entry = (loc ? entryOf(r, loc.entryId) : undefined) ?? entryOf(r, entryId);
|
||||||
|
if (entry && loc) {
|
||||||
|
const block = entry.blocks[loc.index];
|
||||||
|
if (block && block.type === "tool") return block;
|
||||||
|
}
|
||||||
|
const target = entry ?? newEntry(r, "assistant", Date.now(), []);
|
||||||
|
const at = index ?? target.blocks.length;
|
||||||
|
const block: Extract<Block, { type: "tool" }> = {
|
||||||
|
type: "tool",
|
||||||
|
toolCallId,
|
||||||
|
name: "tool",
|
||||||
|
state: "pending",
|
||||||
|
};
|
||||||
|
while (target.blocks.length < at) target.blocks.push({ type: "text", text: "" });
|
||||||
|
target.blocks[at] = block;
|
||||||
|
r.ctx.toolBlocks.set(toolCallId, { entryId: target.id, index: at });
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rebuildBlocks(r: Reducer, blocks: Block[]): Block[] {
|
||||||
|
const out: Block[] = [];
|
||||||
|
for (const block of blocks) {
|
||||||
|
if (block.type !== "tool") {
|
||||||
|
out.push(block);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const loc = r.ctx.toolBlocks.get(block.toolCallId);
|
||||||
|
const existing = loc ? entryOf(r, loc.entryId)?.blocks[loc.index] : undefined;
|
||||||
|
if (existing && existing.type === "tool") {
|
||||||
|
existing.name = block.name || existing.name;
|
||||||
|
if (block.args !== undefined) existing.args = block.args;
|
||||||
|
out.push(existing);
|
||||||
|
} else {
|
||||||
|
out.push(block);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// re-index tool blocks for late execution events
|
||||||
|
for (const [id, loc] of [...r.ctx.toolBlocks]) {
|
||||||
|
const idx = out.findIndex((b) => b.type === "tool" && b.toolCallId === id);
|
||||||
|
if (idx >= 0) r.ctx.toolBlocks.set(id, { entryId: loc.entryId, index: idx });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toolOutputOf(value: unknown): ToolOutput | undefined {
|
||||||
|
const v = rec(value);
|
||||||
|
if (!v) return undefined;
|
||||||
|
const texts: string[] = [];
|
||||||
|
for (const raw of arr(v.content)) {
|
||||||
|
const b = rec(raw);
|
||||||
|
if (b?.type === "text" && typeof b.text === "string") texts.push(b.text);
|
||||||
|
}
|
||||||
|
const out: ToolOutput = {};
|
||||||
|
if (texts.length) out.text = texts.join("\n");
|
||||||
|
if (v.details !== undefined) out.details = v.details;
|
||||||
|
if (typeof v.isError === "boolean") out.isError = v.isError;
|
||||||
|
return Object.keys(out).length ? out : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const __internal = { contentToBlocks, rebuildBlocks, ensureToolBlock };
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
/**
|
||||||
|
* pi2 wire protocol — shared types.
|
||||||
|
*
|
||||||
|
* Three surfaces, one vocabulary:
|
||||||
|
* browser <-> daemon (HTTP + WS)
|
||||||
|
* plugin <-> daemon (JSONL over unix socket)
|
||||||
|
* daemon <-> plugin (same JSONL envelope, reversed direction)
|
||||||
|
*
|
||||||
|
* The plugin is the single source of truth for session state; the daemon only
|
||||||
|
* routes, the browser only renders.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const PROTOCOL_VERSION = 1;
|
||||||
|
|
||||||
|
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
||||||
|
|
||||||
|
export type SessionStatus = "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted";
|
||||||
|
|
||||||
|
export type ClientKind = "nvim" | "web" | "cli" | "daemon" | "system";
|
||||||
|
|
||||||
|
export interface ClientRef {
|
||||||
|
clientId: string;
|
||||||
|
kind: ClientKind;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModelRef {
|
||||||
|
provider: string;
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UsageTotals {
|
||||||
|
input: number;
|
||||||
|
output: number;
|
||||||
|
cacheRead: number;
|
||||||
|
cacheWrite: number;
|
||||||
|
cost: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContextUsage {
|
||||||
|
tokens: number;
|
||||||
|
window: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ToolOutput {
|
||||||
|
text?: string;
|
||||||
|
details?: unknown;
|
||||||
|
isError?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Block =
|
||||||
|
| { type: "text"; text: string }
|
||||||
|
| { type: "thinking"; text: string; redacted?: boolean }
|
||||||
|
| {
|
||||||
|
type: "tool";
|
||||||
|
toolCallId: string;
|
||||||
|
name: string;
|
||||||
|
args?: unknown;
|
||||||
|
output?: ToolOutput;
|
||||||
|
state: "pending" | "running" | "done" | "error";
|
||||||
|
durationMs?: number;
|
||||||
|
}
|
||||||
|
| { type: "error"; text: string };
|
||||||
|
|
||||||
|
export type EntryRole = "user" | "assistant" | "system" | "notice";
|
||||||
|
|
||||||
|
export interface Entry {
|
||||||
|
id: string;
|
||||||
|
role: EntryRole;
|
||||||
|
ts: number;
|
||||||
|
blocks: Block[];
|
||||||
|
done: boolean;
|
||||||
|
messageId?: string;
|
||||||
|
images?: { mimeType: string; data: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TodoItem {
|
||||||
|
content: string;
|
||||||
|
status: "pending" | "in_progress" | "completed";
|
||||||
|
activeForm?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QueueItem {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
steer: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskItem {
|
||||||
|
id: string;
|
||||||
|
command: string;
|
||||||
|
status: "running" | "completed" | "failed" | "stopped";
|
||||||
|
startTime: number;
|
||||||
|
durationMs?: number;
|
||||||
|
exitCode?: number | null;
|
||||||
|
outputFile?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BatchItemStatus = "queued" | "spawning" | "running" | "ok" | "failed" | "cancelled";
|
||||||
|
|
||||||
|
export interface BatchItem {
|
||||||
|
ref: string;
|
||||||
|
name?: string;
|
||||||
|
status: BatchItemStatus;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchItemCounts {
|
||||||
|
total: number;
|
||||||
|
done: number;
|
||||||
|
ok: number;
|
||||||
|
failed: number;
|
||||||
|
cancelled: number;
|
||||||
|
running: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Batch {
|
||||||
|
batchId: string;
|
||||||
|
status: "running" | "completed" | "partial" | "failed" | "cancelled";
|
||||||
|
items: BatchItem[];
|
||||||
|
summary?: BatchItemCounts;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Subagent {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
status: "active" | "completed" | "failed" | "interrupted" | "dormant";
|
||||||
|
model?: string;
|
||||||
|
thinking?: ThinkingLevel;
|
||||||
|
task?: string;
|
||||||
|
createdAt?: number;
|
||||||
|
lastActiveAt?: number;
|
||||||
|
live?: boolean;
|
||||||
|
children?: Subagent[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttentionOption {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttentionItem {
|
||||||
|
requestId: string;
|
||||||
|
method: string;
|
||||||
|
title?: string;
|
||||||
|
message?: string;
|
||||||
|
options?: AttentionOption[];
|
||||||
|
/** Free-form payload; `diff` requests carry `{files:[{path,before,after}]}`. */
|
||||||
|
payload?: unknown;
|
||||||
|
timeoutSec?: number;
|
||||||
|
createdAt: number;
|
||||||
|
receivedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionFlags {
|
||||||
|
attention: boolean;
|
||||||
|
done: boolean;
|
||||||
|
error: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionState {
|
||||||
|
sessionId: string;
|
||||||
|
workspaceId: string;
|
||||||
|
cwd: string;
|
||||||
|
name: string | null;
|
||||||
|
status: SessionStatus;
|
||||||
|
flags: SessionFlags;
|
||||||
|
model: ModelRef | null;
|
||||||
|
thinking: ThinkingLevel | null;
|
||||||
|
usage: UsageTotals;
|
||||||
|
contextUsage: ContextUsage | null;
|
||||||
|
queue: QueueItem[];
|
||||||
|
todos: TodoItem[];
|
||||||
|
tasks: TaskItem[];
|
||||||
|
batches: Batch[];
|
||||||
|
subagents: Subagent[];
|
||||||
|
attention: AttentionItem[];
|
||||||
|
entries: Entry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Events */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pi native events are relayed verbatim (`message_start`, `message_update`,
|
||||||
|
* `tool_execution_*`, `queue_update`, `agent_*`, `turn_*`, `compaction_*`,
|
||||||
|
* `session_info_changed`, `thinking_level_changed`, `entry_appended`).
|
||||||
|
*
|
||||||
|
* Derived events are prefixed `pi2:` and are computed by the plugin only.
|
||||||
|
*/
|
||||||
|
export type SessionEventType =
|
||||||
|
| "agent_start"
|
||||||
|
| "agent_end"
|
||||||
|
| "agent_settled"
|
||||||
|
| "turn_start"
|
||||||
|
| "turn_end"
|
||||||
|
| "message_start"
|
||||||
|
| "message_update"
|
||||||
|
| "message_end"
|
||||||
|
| "tool_execution_start"
|
||||||
|
| "tool_execution_update"
|
||||||
|
| "tool_execution_end"
|
||||||
|
| "queue_update"
|
||||||
|
| "session_info_changed"
|
||||||
|
| "thinking_level_changed"
|
||||||
|
| "entry_appended"
|
||||||
|
| "compaction_start"
|
||||||
|
| "compaction_end"
|
||||||
|
| "pi2:session"
|
||||||
|
| "pi2:todo"
|
||||||
|
| "pi2:batch"
|
||||||
|
| "pi2:task"
|
||||||
|
| "pi2:subagents"
|
||||||
|
| "pi2:attention_request"
|
||||||
|
| "pi2:attention_resolved"
|
||||||
|
| "pi2:process_exit"
|
||||||
|
| "pi2:error";
|
||||||
|
|
||||||
|
export interface SessionEvent {
|
||||||
|
type: SessionEventType | string;
|
||||||
|
ts: number;
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Envelopes */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export interface InstanceState {
|
||||||
|
workspaceId: string;
|
||||||
|
instanceId: string;
|
||||||
|
status: "starting" | "ready" | "degraded" | "stopping" | "stopped" | "unmanaged";
|
||||||
|
nvimPid: number | null;
|
||||||
|
pluginVersion: string | null;
|
||||||
|
hasUI: boolean;
|
||||||
|
attachedClients: number;
|
||||||
|
listenAddr: string | null;
|
||||||
|
startedAt: number | null;
|
||||||
|
reason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WorkspaceInfo {
|
||||||
|
workspaceId: string;
|
||||||
|
cwd: string;
|
||||||
|
name: string;
|
||||||
|
alias?: string | null;
|
||||||
|
pinned?: boolean;
|
||||||
|
hidden?: boolean;
|
||||||
|
trusted: boolean;
|
||||||
|
exists: boolean;
|
||||||
|
/** Number of session files discovered on disk (header scan). */
|
||||||
|
sessionCount: number;
|
||||||
|
/** Number of live sessions reported by the instance, if any. */
|
||||||
|
liveCount: number;
|
||||||
|
lastActiveAt: number | null;
|
||||||
|
instance: InstanceState | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DaemonCommandMethod =
|
||||||
|
| "instance.ensure"
|
||||||
|
| "instance.shutdown"
|
||||||
|
| "workspace.add"
|
||||||
|
| "workspace.update"
|
||||||
|
| "workspace.remove"
|
||||||
|
| "workspace.refresh"
|
||||||
|
| "pair.create"
|
||||||
|
| "pair.redeem"
|
||||||
|
| "device.revoke"
|
||||||
|
| "session.create"
|
||||||
|
| "session.open"
|
||||||
|
| "session.close"
|
||||||
|
| "session.resume"
|
||||||
|
| "session.rename"
|
||||||
|
| "session.fork"
|
||||||
|
| "session.compact"
|
||||||
|
| "session.setModel"
|
||||||
|
| "session.setThinking"
|
||||||
|
| "session.hibernate"
|
||||||
|
| "prompt.send"
|
||||||
|
| "prompt.abort"
|
||||||
|
| "queue.remove"
|
||||||
|
| "queue.setSteer"
|
||||||
|
| "attention.respond"
|
||||||
|
| "subagent.dispatch"
|
||||||
|
| "subagent.stop"
|
||||||
|
| "subagent.steer"
|
||||||
|
| "subagent.read"
|
||||||
|
| "task.stop"
|
||||||
|
| "system.doctor"
|
||||||
|
| "system.shutdown";
|
||||||
|
|
||||||
|
export interface CommandRequest {
|
||||||
|
method: DaemonCommandMethod | string;
|
||||||
|
params?: Record<string, unknown>;
|
||||||
|
sessionId?: string;
|
||||||
|
clientRequestId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ErrorBody {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
retryable: boolean;
|
||||||
|
details?: Record<string, unknown>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { readFileSync, readdirSync, existsSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { reduceAll } from "../src/protocol/reducer.js";
|
||||||
|
import type { SessionEvent, SessionState } from "../src/protocol/types.js";
|
||||||
|
|
||||||
|
const FIXTURES = join(import.meta.dirname, "..", "fixtures");
|
||||||
|
|
||||||
|
function loadCase(name: string): { events: SessionEvent[]; expected: SessionState } {
|
||||||
|
const dir = join(FIXTURES, name);
|
||||||
|
const events = readFileSync(join(dir, "events.jsonl"), "utf8")
|
||||||
|
.split("\n")
|
||||||
|
.filter((l) => l.trim().length > 0)
|
||||||
|
.map((l) => JSON.parse(l) as SessionEvent);
|
||||||
|
const expected = JSON.parse(readFileSync(join(dir, "expected.json"), "utf8")) as SessionState;
|
||||||
|
return { events, expected };
|
||||||
|
}
|
||||||
|
|
||||||
|
function cases(): string[] {
|
||||||
|
return readdirSync(FIXTURES).filter((n) => existsSync(join(FIXTURES, n, "events.jsonl")));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("session reducer conformance", () => {
|
||||||
|
for (const name of cases()) {
|
||||||
|
it(`replays ${name} to the committed expected state`, () => {
|
||||||
|
const { events, expected } = loadCase(name);
|
||||||
|
const first = events[0]?.session as Record<string, unknown> | undefined;
|
||||||
|
const actual = reduceAll(
|
||||||
|
{
|
||||||
|
sessionId: name,
|
||||||
|
workspaceId: expected.workspaceId,
|
||||||
|
cwd: expected.cwd,
|
||||||
|
},
|
||||||
|
events,
|
||||||
|
);
|
||||||
|
expect(actual).toEqual(expected);
|
||||||
|
// guard against fixtures that forgot to include the session seed
|
||||||
|
expect(first?.cwd ?? expected.cwd).toBe(expected.cwd);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of cases()) {
|
||||||
|
it(`is idempotent when replayed twice on a fresh reducer (${name})`, () => {
|
||||||
|
const { events } = loadCase(name);
|
||||||
|
const a = reduceAll({ sessionId: name, workspaceId: "ws-fixture", cwd: "/repo" }, events);
|
||||||
|
const b = reduceAll({ sessionId: name, workspaceId: "ws-fixture", cwd: "/repo" }, events);
|
||||||
|
expect(a).toEqual(b);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it("keeps tool execution attached to the assistant entry after message_end", () => {
|
||||||
|
const { events } = loadCase("basic-turn");
|
||||||
|
const state = reduceAll({ sessionId: "basic-turn", workspaceId: "ws-fixture", cwd: "/repo" }, events);
|
||||||
|
const assistant = state.entries.find((e) => e.role === "assistant");
|
||||||
|
expect(assistant).toBeDefined();
|
||||||
|
const tool = assistant?.blocks.find((b) => b.type === "tool");
|
||||||
|
expect(tool).toMatchObject({
|
||||||
|
type: "tool",
|
||||||
|
toolCallId: "call_1",
|
||||||
|
name: "bash",
|
||||||
|
state: "done",
|
||||||
|
durationMs: 9,
|
||||||
|
output: { text: "a.txt\nb.txt" },
|
||||||
|
});
|
||||||
|
expect(state.usage).toEqual({ input: 100, output: 20, cacheRead: 0, cacheWrite: 0, cost: 0.003 });
|
||||||
|
expect(state.status).toBe("idle");
|
||||||
|
expect(state.flags.done).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears pending attention and refreshes derived panels", () => {
|
||||||
|
const { events } = loadCase("queue-todo-attention");
|
||||||
|
const state = reduceAll({ sessionId: "qta", workspaceId: "ws-fixture", cwd: "/repo" }, events);
|
||||||
|
expect(state.attention).toHaveLength(0);
|
||||||
|
expect(state.flags.attention).toBe(false);
|
||||||
|
expect(state.queue.map((q) => [q.text, q.steer])).toEqual([
|
||||||
|
["use pnpm", true],
|
||||||
|
["then run the tests", false],
|
||||||
|
]);
|
||||||
|
expect(state.todos).toHaveLength(3);
|
||||||
|
expect(state.todos[1]).toMatchObject({ status: "in_progress", activeForm: "refactoring" });
|
||||||
|
expect(state.subagents).toHaveLength(2);
|
||||||
|
expect(state.batches[0]).toMatchObject({ batchId: "b1", status: "running" });
|
||||||
|
expect(state.name).toBe("Refactor auth");
|
||||||
|
expect(state.thinking).toBe("high");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("marks aborted runs as error and exited processes as exited", () => {
|
||||||
|
const { events } = loadCase("error-abort-compaction");
|
||||||
|
const state = reduceAll({ sessionId: "eac", workspaceId: "ws-fixture", cwd: "/repo" }, events);
|
||||||
|
expect(state.flags.error).toBe(true);
|
||||||
|
expect(state.flags.done).toBe(false);
|
||||||
|
expect(state.status).toBe("exited");
|
||||||
|
const blocks = state.entries[0]?.blocks ?? [];
|
||||||
|
expect(blocks.some((b) => b.type === "error")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2023",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"exactOptionalPropertyTypes": false,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"declaration": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"],
|
||||||
|
"exclude": ["node_modules", "dist", "test", "fixtures"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
include: ["test/**/*.test.ts"],
|
||||||
|
environment: "node",
|
||||||
|
testTimeout: 20000,
|
||||||
|
hookTimeout: 20000,
|
||||||
|
pool: "forks",
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in new issue
Block a user