commit 9d817f35b7ed3071504e22b61107a65fef9e5117 Author: yuez Date: Wed Oct 21 10:58:46 2026 +0800 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72d8a00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +coverage/ +*.log +.DS_Store +tmp/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a4ba86 --- /dev/null +++ b/README.md @@ -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) | diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..df1e653 --- /dev/null +++ b/docs/protocol.md @@ -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 (`/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//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 ". +- 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. diff --git a/fixtures/basic-turn/events.jsonl b/fixtures/basic-turn/events.jsonl new file mode 100644 index 0000000..bceb8db --- /dev/null +++ b/fixtures/basic-turn/events.jsonl @@ -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} diff --git a/fixtures/basic-turn/expected.json b/fixtures/basic-turn/expected.json new file mode 100644 index 0000000..f49b95f --- /dev/null +++ b/fixtures/basic-turn/expected.json @@ -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 + } + ] +} diff --git a/fixtures/error-abort-compaction/events.jsonl b/fixtures/error-abort-compaction/events.jsonl new file mode 100644 index 0000000..9c2e9d4 --- /dev/null +++ b/fixtures/error-abort-compaction/events.jsonl @@ -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} diff --git a/fixtures/error-abort-compaction/expected.json b/fixtures/error-abort-compaction/expected.json new file mode 100644 index 0000000..028b0fd --- /dev/null +++ b/fixtures/error-abort-compaction/expected.json @@ -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 + } + ] +} diff --git a/fixtures/queue-todo-attention/events.jsonl b/fixtures/queue-todo-attention/events.jsonl new file mode 100644 index 0000000..45eac65 --- /dev/null +++ b/fixtures/queue-todo-attention/events.jsonl @@ -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} diff --git a/fixtures/queue-todo-attention/expected.json b/fixtures/queue-todo-attention/expected.json new file mode 100644 index 0000000..90df098 --- /dev/null +++ b/fixtures/queue-todo-attention/expected.json @@ -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": [] +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..880f9e9 --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..ed6131c --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1266 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@hono/node-server': + specifier: ^1.13.7 + version: 1.19.17(hono@4.13.13) + hono: + specifier: ^4.6.14 + version: 4.13.13 + ws: + specifier: ^8.18.0 + version: 8.22.0 + zod: + specifier: ^3.24.1 + version: 3.25.76 + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.20.5 + '@types/ws': + specifier: ^8.5.13 + version: 8.18.2 + tsx: + specifier: ^4.19.2 + version: 4.23.15 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + vitest: + specifier: ^2.1.8 + version: 2.1.9(@types/node@22.20.5) + +packages: + + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@hono/node-server@1.19.17': + resolution: {integrity: sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==} + engines: {node: '>=18.14.1'} + peerDependencies: + hono: ^4 + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} + engines: {node: ^22.20 || ^24.12 || >=25} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-android-arm-eabi@4.64.10': + resolution: {integrity: sha512-oJ9ZfVIZjSjts0ZIYA48+5T0vurE5fQfX/Liad2U52Y6EN99x/OCdjGGuKMDP6jSk2i2lY6jwwA3X0drEc4PBg==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.64.10': + resolution: {integrity: sha512-LylBINgYYwgHNz8OMCy5+Y0w/LEgRYE0PcAIZfEuTuLNMf0S40GSLX6SFwqZsBLplS7RIHHy4zOAbl8Y5cQEvg==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.64.10': + resolution: {integrity: sha512-vbuT3VT1GBI2fAOoUJUrsHVoOg9nbrFXTM7e3DSnb9PYf4n6jZCN8v4Vo8O6x4u5B67+/c803b8BtCZe2nIeqA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.64.10': + resolution: {integrity: sha512-qYUp/qYvM3T4cF+VWalPl+przBUESILxi+qZ1m1MVRHpg06vS+jHaxXubjCaRpXjLJPDFdXzOZ0FABDghHOhNQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.64.10': + resolution: {integrity: sha512-v9NRQG+JztbP4DP/0yuhSyDcEJk047lYbqeNnqIgbXITcVDjGDS7OpkW5nadSY3tJ7MY8W1qIMMqP4Q3Q8BDjQ==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.64.10': + resolution: {integrity: sha512-CHc9LBHdxhn6/NXfb9IegXCWoz5VlvcDOx9QrzZ9q+XYhFlfzwymSWJjOlZcEMMtC1zgMV7qxDe6U18AI1SG0A==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.64.10': + resolution: {integrity: sha512-ble2WR7kWfzZFJUd3ODMGCJn1XDszptfRC0QvWc0h9/EA6MxnrQ1mvbjPZifEdgHyfHhDrwWeKeJONDITcrHSg==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.64.10': + resolution: {integrity: sha512-DMCYegihxBMKvLpODdk4OsvIgxtHTi+Oddf1Pm3d6wMVNjcBiG2pqyXjMPy55HgG1gCdEFr9VfhB1CmvuKn1lw==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.64.10': + resolution: {integrity: sha512-HQ6HuVH9TmhvPWIas7MA/KeAROgdwqH3REpUU6hZq47NW7m1b1QCrHgM+M3+N/B8DfMt88x1/z79ppRc9RflCQ==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.64.10': + resolution: {integrity: sha512-avBhxba1DdctX0kxKkN3JWdTSg72QsxSn6FdfhZ9MkL3TTYDOXqxY1GqbC7VNttlgviK7tCe2No5btfRkFgeIg==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.64.10': + resolution: {integrity: sha512-UtQMex7fiXq0W/GqcWRpy6XKqUbXgQeGKB+Bd5rJngmHzpI+3kjwpWFLAhKg02onFsIMSh+Zx0zp9JIMQ7/05A==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.64.10': + resolution: {integrity: sha512-0Aum2pUsCSuOopi6oka+nR1DTj/nfvc1xjL979lvh6kXUjNa30TCX7sKFjyMsrX7bK3bNVs0FsJwQcE2HCWX1Q==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.64.10': + resolution: {integrity: sha512-4dgsouKal3qfMFORgtNigLPt7K3HXiO6jTr7+nFJv1GWu1OkZx0kvQIXbK4sjrIGnaLBk0s80eQCQ9hPIelLrw==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.64.10': + resolution: {integrity: sha512-d7NE89try3jisYzBD7J9M5iwfgcrXYC4dwHEjQ3HIWBftvwch1U/cy3iZ26SthtUOyClKiu7iqYiFjQEwiOlqQ==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.64.10': + resolution: {integrity: sha512-dqB5ChSBp91JWXxpCKAS5ZVAE38esKQvdfyqANm0lF5JPiQrXnYwgG3oVBQmuNRcQ1WHkA3j5qYLsrl2CtfhCA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.64.10': + resolution: {integrity: sha512-7GMf3vbQQslorWLmfsbi5fdt9RVnglk205XpOMFvW6UY5jE5oJc6JLieQJPHtsYlZ2EO0PtC06nY9Hz/IG8guw==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.64.10': + resolution: {integrity: sha512-tuKbkB23DKc5LG+irPSUnZZztRHqC3CNmyxeWloueBteHB+i+1HkRCMzAE41lseLDlarybeLhqfibFitKOxKMg==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.64.10': + resolution: {integrity: sha512-ntHtQOMw7oIshHRF1swV3vyBw+beQt9PeZ04O3D32EeDZUMoHMJuZKp4/fDllH/+xogeK0GUCONVfjjKusqKLg==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.64.10': + resolution: {integrity: sha512-Dlh8q8r145aYgh+N3gNIG1dz35Fz/FCxe5hs/43orDsffjP8S1P4Xz5I4FpSJsDS4LpQw1QmswZkQlUbkCldjQ==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.64.10': + resolution: {integrity: sha512-VBJhHWz/55u45CWFv9OmfSRDgJDVENESgFxSAn13gIKJpTuFJbP4/7ymMZhDfeKFx1zGn1XBsLnNB7Ryy71qww==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.64.10': + resolution: {integrity: sha512-Vjcazg+EEzUfIz+LcaxS6YtbQHo+sv0sCD+5VbwhY504bCKNW4OOreVgKq61pHT2esRQ/+AXYVPStDwxSvAOdw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.64.10': + resolution: {integrity: sha512-jJAaP4El+HWxYkM0jeJghASaFgfnluY0FRHhyHXxU6STs/nBhKMIxIMDrJEFg2ftKz6orX9WAo4diVan5NugNA==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.64.10': + resolution: {integrity: sha512-bXXdRUfRx9PaHCToKt8R/7wjDV6Tbk/hmSHK0uQBKmD3rj4jkuYndct8uGX77ZuZsePrVkQbWUgPR2jJhCTMpQ==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.64.10': + resolution: {integrity: sha512-57Idx+VkEOQeG6Ys6sZOBFT7FfbeyxGv9A3k1m+Lf/z2SwqT40rNWbAINzjPHSMoCCBvY7Fnb9RGZWQin/HHAw==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.64.10': + resolution: {integrity: sha512-vrvuasIpm/xf+BpZbzgirku0WnrQZMAc+H2Ai26jzqBxYEmQQE4DdJb7h8erkJMfRRipx0ma2Cty8jJwUm9ocQ==} + cpu: [x64] + os: [win32] + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/node@22.20.5': + resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + + '@vitest/expect@2.1.9': + resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==} + + '@vitest/mocker@2.1.9': + resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@2.1.9': + resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==} + + '@vitest/runner@2.1.9': + resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==} + + '@vitest/snapshot@2.1.9': + resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==} + + '@vitest/spy@2.1.9': + resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==} + + '@vitest/utils@2.1.9': + resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + hono@4.13.13: + resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==} + engines: {node: '>=16.9.0'} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + pathe@1.1.2: + resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + postcss@8.5.31: + resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} + engines: {node: ^10 || ^12 || >=14} + + rollup@4.64.10: + resolution: {integrity: sha512-8N52YH1B5JzBP+B1rkcBERG7rfRTGAM0RmUpyd76yyRfTljuG452GCNbVm6MPzs1+gXBha6Rw5/oHRFohOpfDg==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@1.2.0: + resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==} + engines: {node: '>=14.0.0'} + + tinyspy@3.0.2: + resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==} + engines: {node: '>=14.0.0'} + + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + vite-node@2.1.9: + resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + + vite@5.4.21: + resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vitest@2.1.9: + resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/node': ^18.0.0 || >=20.0.0 + '@vitest/browser': 2.1.9 + '@vitest/ui': 2.1.9 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + ws@8.22.0: + resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + zod@3.25.76: + resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} + +snapshots: + + '@esbuild/aix-ppc64@0.21.5': + optional: true + + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.21.5': + optional: true + + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.21.5': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.21.5': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.21.5': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.21.5': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.21.5': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.21.5': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.21.5': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.21.5': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@hono/node-server@1.19.17(hono@4.13.13)': + dependencies: + hono: 4.13.13 + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@rollup/rollup-android-arm-eabi@4.64.10': + optional: true + + '@rollup/rollup-android-arm64@4.64.10': + optional: true + + '@rollup/rollup-darwin-arm64@4.64.10': + optional: true + + '@rollup/rollup-darwin-x64@4.64.10': + optional: true + + '@rollup/rollup-freebsd-arm64@4.64.10': + optional: true + + '@rollup/rollup-freebsd-x64@4.64.10': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.64.10': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.64.10': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.64.10': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.64.10': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.64.10': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.64.10': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.64.10': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.64.10': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.64.10': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.64.10': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.64.10': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.64.10': + optional: true + + '@rollup/rollup-linux-x64-musl@4.64.10': + optional: true + + '@rollup/rollup-openbsd-x64@4.64.10': + optional: true + + '@rollup/rollup-openharmony-arm64@4.64.10': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.64.10': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.64.10': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.64.10': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.64.10': + optional: true + + '@types/estree@1.0.9': {} + + '@types/node@22.20.5': + dependencies: + undici-types: 6.21.0 + + '@types/ws@8.18.2': + dependencies: + '@types/node': 22.20.5 + + '@vitest/expect@2.1.9': + dependencies: + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + tinyrainbow: 1.2.0 + + '@vitest/mocker@2.1.9(vite@5.4.21(@types/node@22.20.5))': + dependencies: + '@vitest/spy': 2.1.9 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 5.4.21(@types/node@22.20.5) + + '@vitest/pretty-format@2.1.9': + dependencies: + tinyrainbow: 1.2.0 + + '@vitest/runner@2.1.9': + dependencies: + '@vitest/utils': 2.1.9 + pathe: 1.1.2 + + '@vitest/snapshot@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + magic-string: 0.30.21 + pathe: 1.1.2 + + '@vitest/spy@2.1.9': + dependencies: + tinyspy: 3.0.2 + + '@vitest/utils@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + loupe: 3.2.1 + tinyrainbow: 1.2.0 + + assertion-error@2.0.1: {} + + cac@6.7.14: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + check-error@2.1.3: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-eql@5.0.2: {} + + es-module-lexer@1.7.0: {} + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + + fsevents@2.3.3: + optional: true + + hono@4.13.13: {} + + loupe@3.2.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + ms@2.1.3: {} + + nanoid@3.3.20: {} + + pathe@1.1.2: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + postcss@8.5.31: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + rollup@4.64.10: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@napi-rs/lzma-linux-x64-gnu': 1.5.1 + '@rollup/rollup-android-arm-eabi': 4.64.10 + '@rollup/rollup-android-arm64': 4.64.10 + '@rollup/rollup-darwin-arm64': 4.64.10 + '@rollup/rollup-darwin-x64': 4.64.10 + '@rollup/rollup-freebsd-arm64': 4.64.10 + '@rollup/rollup-freebsd-x64': 4.64.10 + '@rollup/rollup-linux-arm-gnueabihf': 4.64.10 + '@rollup/rollup-linux-arm-musleabihf': 4.64.10 + '@rollup/rollup-linux-arm64-gnu': 4.64.10 + '@rollup/rollup-linux-arm64-musl': 4.64.10 + '@rollup/rollup-linux-loong64-gnu': 4.64.10 + '@rollup/rollup-linux-loong64-musl': 4.64.10 + '@rollup/rollup-linux-ppc64-gnu': 4.64.10 + '@rollup/rollup-linux-ppc64-musl': 4.64.10 + '@rollup/rollup-linux-riscv64-gnu': 4.64.10 + '@rollup/rollup-linux-riscv64-musl': 4.64.10 + '@rollup/rollup-linux-s390x-gnu': 4.64.10 + '@rollup/rollup-linux-x64-gnu': 4.64.10 + '@rollup/rollup-linux-x64-musl': 4.64.10 + '@rollup/rollup-openbsd-x64': 4.64.10 + '@rollup/rollup-openharmony-arm64': 4.64.10 + '@rollup/rollup-win32-arm64-msvc': 4.64.10 + '@rollup/rollup-win32-ia32-msvc': 4.64.10 + '@rollup/rollup-win32-x64-gnu': 4.64.10 + '@rollup/rollup-win32-x64-msvc': 4.64.10 + fsevents: 2.3.3 + + siginfo@2.0.0: {} + + source-map-js@1.2.2: {} + + stackback@0.0.2: {} + + std-env@3.10.0: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinypool@1.1.1: {} + + tinyrainbow@1.2.0: {} + + tinyspy@3.0.2: {} + + tsx@4.23.15: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + + typescript@5.9.3: {} + + undici-types@6.21.0: {} + + vite-node@2.1.9(@types/node@22.20.5): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 1.1.2 + vite: 5.4.21(@types/node@22.20.5) + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vite@5.4.21(@types/node@22.20.5): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.31 + rollup: 4.64.10 + optionalDependencies: + '@types/node': 22.20.5 + fsevents: 2.3.3 + + vitest@2.1.9(@types/node@22.20.5): + dependencies: + '@vitest/expect': 2.1.9 + '@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@22.20.5)) + '@vitest/pretty-format': 2.1.9 + '@vitest/runner': 2.1.9 + '@vitest/snapshot': 2.1.9 + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 1.1.2 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinypool: 1.1.1 + tinyrainbow: 1.2.0 + vite: 5.4.21(@types/node@22.20.5) + vite-node: 2.1.9(@types/node@22.20.5) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 22.20.5 + transitivePeerDependencies: + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + ws@8.22.0: {} + + zod@3.25.76: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..00f6fc4 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +allowBuilds: + esbuild: set this to true or false diff --git a/scripts/gen-expected.ts b/scripts/gen-expected.ts new file mode 100644 index 0000000..e95dbe6 --- /dev/null +++ b/scripts/gen-expected.ts @@ -0,0 +1,36 @@ +/** + * Regenerates `fixtures//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 | 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}`); +} diff --git a/src/protocol/errors.ts b/src/protocol/errors.ts new file mode 100644 index 0000000..c1c9bfd --- /dev/null +++ b/src/protocol/errors.ts @@ -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) { + return { code, message, retryable, ...(details ? { details } : {}) }; +} diff --git a/src/protocol/reducer.ts b/src/protocol/reducer.ts new file mode 100644 index 0000000..ffae3eb --- /dev/null +++ b/src/protocol/reducer.ts @@ -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; + /** streamed tool call argument buffers, keyed by toolCallId */ + toolArgs: Map; +} + +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 | undefined { + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : 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 { + 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 = { + 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 }; diff --git a/src/protocol/types.ts b/src/protocol/types.ts new file mode 100644 index 0000000..51bb5d1 --- /dev/null +++ b/src/protocol/types.ts @@ -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; + sessionId?: string; + clientRequestId?: string; +} + +export interface ErrorBody { + code: string; + message: string; + retryable: boolean; + details?: Record; +} diff --git a/test/reducer.conformance.test.ts b/test/reducer.conformance.test.ts new file mode 100644 index 0000000..7dd0828 --- /dev/null +++ b/test/reducer.conformance.test.ts @@ -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 | 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); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..57b4535 --- /dev/null +++ b/tsconfig.json @@ -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"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..a63e95b --- /dev/null +++ b/vitest.config.ts @@ -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", + }, +});