repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

deletes ui extension

1122ba0a16ae4b3eeefeb06603ec6e2818148c84

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (84)

+30 / −10827 text lines · all files grouped into 32 bars

Diff layout

docs/super/plans/2026-07-01-ui-extension-phase-1-runtime-shell.md

Deleted
deleted file mode 100644

+0 / −63 text lines

1# UI Extension Phase 1 Implementation Plan
2
3> **For agentic workers:** Use `/skill:executing-plans` to implement this plan task-by-task.
4
5**Goal:** Build `/ui` Phase 1: token-authenticated LAN web shell, QR/link terminal widget, and clean shutdown.
6
7**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
8
9## Scope
11Included:
13- Create `extensions/ui` as a normal pi-ext workspace package.
14- Install UI deps through the root npm workspace lockfile so `mise run install` uses `npm ci`.
15- Register `/ui`, `/ui off`, `/ui status`, `/ui open`, and `/ui qr`.
16- Start HTTP server only from `/ui`, never during extension load.
17- Protect browser routes with random token auth, cookie auth, and bearer auth for API routes.
18- Render shell page, 401 page, and JSON status route.
19- Show terminal widget with OSC link, QR, state, session label, client count, ESC help, and `/ui off` help.
20- Stop server and clear widget on `/ui off`, ESC, and `session_shutdown`.
21- Add unit tests and harness tests.
23Excluded:
25- RPC subprocess.
26- Active-branch session seeding.
27- WebSocket event stream.
28- Browser composer.
29- Visual widgets.
30- Telemetry.
32## Tasks
34- [x] Scaffold `extensions/ui/package.json` and `README.md`.
35- [x] Add `qrcode` and `@types/qrcode` through `package-lock.json`.
36- [x] Verify `mise run install` installs UI deps via `npm ci`.
37- [x] Add network helpers and token redaction helpers.
38- [x] Add token-authenticated HTTP server.
39- [x] Add QR renderer and terminal widget renderer.
40- [x] Add cross-platform browser opener candidates.
41- [x] Add runtime state machine.
42- [x] Register `/ui` command and cleanup hooks.
43- [x] Add unit and harness tests.
44- [x] Run targeted UI tests.
45- [x] Run actual UI static check.
46- [x] Run `mise run check -- ui`.
47- [x] Run real Pi + browser smoke test.
49## Execution note
51Win32 zellij smoke passed with fallback disabled using `extensions/ui/scripts/zellij-smoke.mjs --no-fallback`.
52The run launched Pi in a zellij session, sent `/ui`, captured the exact token URL through the smoke-only local handoff file, verified tokenless `/api/status` returned `401`, verified the browser shell with Playwright, sent `/ui off`, and wrote a redacted summary.
54## Done criteria
56- `extensions/ui` exists and passes static extension checks.
57- Runtime starts only from `/ui`.
58- LAN server requires token and serves shell, 401, and status routes.
59- Terminal widget shows link, QR, state, session label, ESC help, and `/ui off` help.
60- `/ui off`, ESC, and `session_shutdown` stop server and clear widget.
61- Dependencies are in `package-lock.json`; `mise run install` succeeds.
62- Targeted unit and harness tests pass.
63- Real Pi + browser smoke test passes.

docs/super/plans/2026-07-01-ui-extension-phase-2-rpc-session-stream.md

Deleted
deleted file mode 100644

+0 / −127 text lines

1# UI Extension Phase 2 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Make `/ui` a minimal browser Pi frontend backed by a seeded active-branch RPC subprocess.
6
7**Architecture:** Keep Phase 1 server/runtime as owner. Add active-branch session seeding, a Pi RPC child-process bridge, a small event protocol, WebSocket fanout, and a no-framework browser shell that renders snapshots plus ordered events.
8
9**Tech Stack:** Node `child_process`, `fs`, `readline`, `crypto`; Pi `SessionManager`; browser WebSocket, Web Components, CSS; Vitest harness tests.
11**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
13**Phase:** Phase 2: Active-Branch RPC Session and Basic Web Stream
15---
17## Scope
19Included:
21- Seed a persistent web session from `ctx.sessionManager.createBranchedSession(ctx.sessionManager.getLeafId())`.
22- Spawn `pi --mode rpc --session <seeded-session>` with normal extensions/skills/settings.
23- Parse LF-delimited JSONL from RPC stdout and keep stderr diagnostics separate.
24- Add RPC request queue with ids, timeout, startup, death, and slow-start states.
25- Add `/api/snapshot`, `/ws`, event replay buffer, monotonic event ids, and JSON protocol types.
26- Replace Phase 1 shell page with a basic stream-first browser app and composer.
27- Send browser prompts through RPC and render user/assistant/tool/error stream items.
29Excluded:
31- Full slash-command parity.
32- Rich syntax/autocomplete.
33- Visual widgets.
34- Telemetry.
35- Nugu polish beyond readable brutal defaults.
37## Files
39Create:
41- `extensions/ui/session-seed.ts` — active-branch seed path and warnings.
42- `extensions/ui/rpc.ts` — child process, JSONL parser, request queue, lifecycle.
43- `extensions/ui/protocol.ts` — event/snapshot/request types.
44- `extensions/ui/events.ts` — monotonic event store and replay.
45- `extensions/ui/web/app.html.ts` — HTML shell.
46- `extensions/ui/web/app.css.ts` — minimal stream-first CSS.
47- `extensions/ui/web/app.js.ts` — browser app source emitted by server.
48- `extensions/ui/__tests__/session-seed.test.ts`.
49- `extensions/ui/__tests__/rpc.test.ts`.
50- `extensions/ui/__tests__/events.test.ts`.
51- `extensions/ui/__tests__/web-smoke.test.ts`.
53Modify:
55- `extensions/ui/runtime.ts` — own seed, RPC, event store.
56- `extensions/ui/server.ts` — add snapshot, app assets, WebSocket upgrade.
57- `extensions/ui/index.ts` — pass command context into runtime start.
58- `extensions/ui/terminal-widget.ts` — show RPC startup/connected/dead states.
59- `extensions/ui/package.json` — add `ws` and `@types/ws` if native upgrade handling is not enough.
61## Tasks
63### Task 1: Event protocol and store
65- [x] Write `events.test.ts` for monotonic ids, bounded replay, and snapshot shape.
66- [x] Implement `protocol.ts` and `events.ts` with `UiEvent`, `UiSnapshot`, `EventStore.append`, `EventStore.snapshot`, and `EventStore.replayAfter`.
67- [x] Run `npx vitest run extensions/ui/__tests__/events.test.ts`; expect PASS.
68- [x] Commit `Add ui event protocol`.
70### Task 2: Active-branch session seed
72- [x] Write `session-seed.test.ts` using a fake session manager with `getLeafId()` and `createBranchedSession()`.
73- [x] Implement `session-seed.ts` so the default path calls `createBranchedSession(getLeafId())` and returns `{ path, warning: undefined }`.
74- [x] Add fallback warning only when whole-tree `forkFrom` is explicitly used by option.
75- [x] Run `npx vitest run extensions/ui/__tests__/session-seed.test.ts`; expect PASS.
76- [x] Commit `Add ui active branch session seed`.
78### Task 3: RPC bridge
80- [x] Write `rpc.test.ts` for JSONL parsing, request id matching, stderr capture, timeout, process exit event, and slow-start event.
81- [x] Implement `rpc.ts` with `startRpc`, `sendRpc`, `closeRpc`, `parseJsonLines`, and typed lifecycle callbacks.
82- [x] Make subprocess command resolve to `pi.cmd` on win32 and `pi` elsewhere unless `PI_UI_RPC_BIN` overrides it for tests.
83- [x] Run `npx vitest run extensions/ui/__tests__/rpc.test.ts`; expect PASS.
84- [x] Commit `Add ui rpc bridge`.
86### Task 4: Server snapshot and WebSocket stream
88- [x] Write server tests for authenticated `/api/snapshot`, authenticated WebSocket connect, replay after event id, and 401 on missing token.
89- [x] Implement `server.ts` upgrade handling and snapshot route.
90- [x] Add heartbeat ping/pong and disconnect cleanup.
91- [x] Run `npx vitest run extensions/ui/__tests__/server.test.ts`; expect PASS.
92- [x] Commit `Add ui browser event transport`.
94### Task 5: Browser shell and composer
96- [x] Add `web-smoke.test.ts` that fetches the shell and verifies it contains module script, stream root, composer, and status strip.
97- [x] Implement `web/app.html.ts`, `web/app.css.ts`, and `web/app.js.ts`.
98- [x] Browser JS must fetch snapshot first, then connect WebSocket, then render replayed stream items in id order.
99- [x] Composer submit sends `{ type: "prompt", text }` to server, disables during in-flight RPC, and appends visible pending state.
100- [x] Run `npx vitest run extensions/ui/__tests__/web-smoke.test.ts`; expect PASS.
101- [x] Commit `Add ui basic browser shell`.
103### Task 6: Runtime integration
105- [x] Extend runtime tests to start with fake seed and fake RPC bridge.
106- [x] Modify `runtime.ts` to create event store, seed session, start RPC, publish startup state, and expose snapshot/transport dependencies to server.
107- [x] Modify `index.ts` so `/ui` passes `ctx` into runtime start.
108- [x] Modify terminal widget to show web URL, RPC state, seeded session path basename, and last lifecycle error.
109- [x] Run all UI tests: `npx vitest run extensions/ui/__tests__/*.test.ts`; expect PASS.
110- [x] Commit `Wire ui rpc runtime`.
112### Task 7: Verification
114- [x] Run actual static check: `node --input-type=module -e "import {checkStatic, extDirs} from './scripts/extensions.mjs'; process.exit(checkStatic(extDirs(['ui'])));"`.
115- [x] Run `mise run install` and `mise run check -- ui`.
116- [x] On win32, run the manual smoke with zellij instead of tmux: create a zellij background session, launch `pi -e extensions/ui/index.ts`, send `/ui`, open the browser URL, send one browser prompt, then `/ui off`.
117- [x] On non-win32, tmux remains acceptable for manual smoke.
118- [x] Commit any verification fixes as `Verify ui phase 2 rpc stream`.
120## Done criteria
122- Browser page renders seeded session snapshot and live ordered RPC events.
123- Browser prompt submission reaches the RPC Pi session.
124- RPC slow startup/death are visible in browser and terminal widget.
125- Token auth protects snapshot and WebSocket.
126- UI tests, static check, `mise run install`, and `mise run check -- ui` pass.
127- Win32 manual terminal smoke uses zellij, not tmux.

docs/super/plans/2026-07-01-ui-extension-phase-3-pi-syntax-controls.md

Deleted
deleted file mode 100644

+0 / −111 text lines

1# UI Extension Phase 3 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Bring browser composer behavior close to normal Pi interaction: slash commands, references, keybindings, model/thinking controls, and extension UI requests.
6
7**Architecture:** Build on the Phase 2 RPC transport. Add browser-side parsing for Pi syntax, RPC command adapters, and a small UI-request protocol for select/confirm/input/editor/notify/status/title/widget/editor-text interactions.
8
9**Tech Stack:** Browser Web Components, WebSocket RPC events, Pi RPC commands, Vitest browser/parser tests.
11**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
13**Phase:** Phase 3: Pi Syntax, Commands, Keybindings, and Extension UI
15---
17## Scope
19Included:
21- Slash command autocomplete and execution.
22- `/skill:*` and prompt-template entries from RPC command state.
23- `@` reference parsing and visible unsupported attachment errors when Phase 3 cannot attach yet.
24- `!` and `!!` mapping to RPC `bash` with correct `excludeFromContext`.
25- Enter, Shift+Enter, Esc, Ctrl+O, Ctrl+P controls.
26- Model/thinking controls through RPC where available.
27- Extension UI request/response rendering for select, confirm, input, editor, notify, status, title, widget, editor text.
29Excluded:
31- Trusted full-JS visual widgets.
32- Telemetry digest.
33- Pierre/Shiki polish.
35## Files
37Create:
39- `extensions/ui/composer.ts` — shared parser for slash/ref/bash forms.
40- `extensions/ui/command-adapter.ts` — server-side RPC command helpers.
41- `extensions/ui/extension-ui.ts` — request/response event model.
42- `extensions/ui/web/components/composer.js.ts`.
43- `extensions/ui/web/components/dialogs.js.ts`.
44- `extensions/ui/__tests__/composer.test.ts`.
45- `extensions/ui/__tests__/command-adapter.test.ts`.
46- `extensions/ui/__tests__/extension-ui.test.ts`.
48Modify:
50- `extensions/ui/protocol.ts`.
51- `extensions/ui/rpc.ts`.
52- `extensions/ui/server.ts`.
53- `extensions/ui/web/app.js.ts`.
54- `extensions/ui/web/app.css.ts`.
56## Tasks
58### Task 1: Composer parser
60- [x] Write parser tests for plain prompts, `/command args`, `/skill:name`, `@path`, `!cmd`, and `!!cmd`.
61- [x] Implement `composer.ts` with `parseComposerInput(text)` returning `{ kind, command, args, refs, excludeFromContext }`.
62- [x] Run `npx vitest run extensions/ui/__tests__/composer.test.ts`; expect PASS.
63- [x] Commit `Add ui composer parser`.
65### Task 2: RPC command adapters
67- [x] Write adapter tests using fake RPC send calls for slash commands, model cycle, thinking cycle, compact, and bash.
68- [x] Implement `command-adapter.ts` with explicit functions: `sendPrompt`, `runSlashCommand`, `runBash`, `cycleModel`, `cycleThinking`, `abortCurrent`.
69- [x] Ensure `!!` calls RPC `bash` with `excludeFromContext: true`.
70- [x] Run adapter tests; expect PASS.
71- [x] Commit `Add ui rpc command adapters`.
73### Task 3: Browser autocomplete
75- [x] Add web tests for slash menu filtering and keyboard selection.
76- [x] Implement composer component with slash menu from snapshot commands and skills.
77- [x] Keep desktop minimal; show mobile tap targets only under phone-width CSS.
78- [x] Run web smoke tests; expect PASS.
79- [x] Commit `Add ui slash autocomplete`.
81### Task 4: Keybindings
83- [x] Add tests for Enter submit, Shift+Enter newline, Esc abort, Ctrl+O expand toggle, Ctrl+P model cycle.
84- [x] Implement keybinding dispatch in `composer.js.ts` and server RPC routes.
85- [x] Render immediate local state for abort/model/thinking actions before RPC response when safe.
86- [x] Run UI tests; expect PASS.
87- [x] Commit `Add ui browser keybindings`.
89### Task 5: Extension UI protocol
91- [x] Write tests for select/confirm/input/editor requests and responses.
92- [x] Implement `extension-ui.ts` and protocol events `ui_request`, `ui_response`, `ui_notify`, `ui_status`, `ui_title`, `ui_widget`, `ui_editor_text`.
93- [x] Wire RPC stderr/stdout UI request messages into event store.
94- [x] Render dialogs in browser and send response ids back through RPC.
95- [x] Run extension UI tests; expect PASS.
96- [x] Commit `Add ui extension request protocol`.
98### Task 6: Integration verification
100- [x] Run `npx vitest run extensions/ui/__tests__/*.test.ts`.
101- [x] Run actual static check for `ui`.
102- [x] Run `mise run install` and `mise run check -- ui`.
103- [x] On win32, run zellij manual smoke for `/`, `/skill:`, `!`, `!!`, Esc, Ctrl+O, Ctrl+P.
104- [x] Commit fixes as `Verify ui phase 3 syntax controls`.
106## Done criteria
108- Browser composer supports core Pi text syntax and keybindings.
109- Extension UI requests render and respond through the browser.
110- Unsupported terminal-only semantics show explicit stream errors, not silent failure.
111- Tests and mise checks pass.

docs/super/plans/2026-07-01-ui-extension-phase-4-trusted-visual-widgets.md

Deleted
deleted file mode 100644

+0 / −110 text lines

1# UI Extension Phase 4 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Let agents render trusted full-JS visual widgets in the browser stream with `window.pi` action bridges and visible attribution.
6
7**Architecture:** Register UI visual tools in the web RPC session. Store widget lifecycle events in the existing event stream. Mount widget documents in bounded `iframe srcdoc` containers, expose `window.pi` in the parent bridge, and audit every widget-originated action.
8
9**Tech Stack:** Pi extension tools, browser iframe `srcdoc`, postMessage, Web Components, Vitest, Playwright Chrome/Firefox probes.
11**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
13**Phase:** Phase 4: Trusted Visual Widgets and `window.pi`
15---
17## Scope
19Included:
21- Visual tools: card, table, diagram, form, mockup/prototype, raw HTML/CSS/JS, update/patch, wait-for-action.
22- Stable widget ids and lifecycle events.
23- Bounded iframe layout with height negotiation and overflow containment.
24- Parent-provided `window.pi` methods for action/result, prompt/steer/follow-up, state, events, update, local notify, and attachment request.
25- Visible attribution before widget-originated prompts/actions reach the agent/session.
26- Audit details in expanded stream metadata.
28Excluded:
30- Telemetry digest beyond widget action events.
31- Rendering polish and virtualization.
32- Any sandbox or permission wall.
34## Files
36Create:
38- `extensions/ui/visual-tools.ts`.
39- `extensions/ui/widget-state.ts`.
40- `extensions/ui/web/components/visual-block.js.ts`.
41- `extensions/ui/web/components/widget-bridge.js.ts`.
42- `extensions/ui/__tests__/visual-tools.test.ts`.
43- `extensions/ui/__tests__/widget-state.test.ts`.
44- `extensions/ui/__tests__/widget-layout.test.ts`.
45- `extensions/ui/__tests__/widget-bridge.test.ts`.
47Modify:
49- `extensions/ui/index.ts`.
50- `extensions/ui/protocol.ts`.
51- `extensions/ui/server.ts`.
52- `extensions/ui/web/app.js.ts`.
53- `extensions/ui/web/app.css.ts`.
54- `extensions/ui/errors.ts`.
56## Tasks
58### Task 1: Widget protocol and state
60- [x] Write tests for stable ids, mount/update/action/error lifecycle, and audit records.
61- [x] Implement `widget-state.ts` and protocol event types.
62- [x] Ensure every widget action has `widgetId`, `toolCallId`, `actionId`, visible label, and timestamp.
63- [x] Run widget state tests; expect PASS.
64- [x] Commit `Add ui widget lifecycle state`.
66### Task 2: Visual tools
68- [x] Write tests for each visual tool returning fallback text and appending widget events.
69- [x] Implement `visual-tools.ts` with no sibling extension imports.
70- [x] Register tools from `index.ts` only for the UI RPC session where tool registration is safe.
71- [x] Run visual tool tests; expect PASS.
72- [x] Commit `Add ui visual tools`.
74### Task 3: Iframe bridge
76- [x] Write bridge tests for `window.pi.action`, `window.pi.prompt`, `window.pi.notify`, and error reporting.
77- [x] Implement bounded `iframe srcdoc` bridge with parent postMessage routing.
78- [x] Reject silent prompts: widget-originated prompt must first append attribution event.
79- [x] Run bridge tests; expect PASS.
80- [x] Commit `Add ui widget bridge`.
82### Task 4: Layout probes
84- [x] Add Playwright tests for Chrome and Firefox iframe bridge access.
85- [x] Add mobile-width bounded-layout test with intentionally over-wide/tall content.
86- [x] Use installed Playwright Firefox; do not skip Firefox silently.
87- [x] Run layout tests; expect PASS.
88- [x] Commit `Add ui widget browser layout tests`.
90### Task 5: Stream rendering
92- [x] Render visual blocks in main stream with title, fallback, lifecycle state, expand/collapse, ids, and audit details.
93- [x] Show widget JS errors as stream errors with human action and agent fix hint.
94- [x] Add tests for fallback and error rendering.
95- [x] Run UI tests; expect PASS.
96- [x] Commit `Render ui visual widgets`.
98### Task 6: Verification
100- [x] Run all UI tests plus Chrome/Firefox widget probes.
101- [x] Run static check and `mise run check -- ui`.
102- [x] On win32, run zellij smoke asking the agent for card/form/raw widget and click a widget action.
103- [x] Commit fixes as `Verify ui phase 4 widgets`.
105## Done criteria
107- Agents can create trusted full-JS widgets in stream.
108- `window.pi` actions work and are visibly attributed.
109- Layout is bounded in Chrome and Firefox on desktop and phone widths.
110- Tests and mise checks pass.

docs/super/plans/2026-07-01-ui-extension-phase-5-telemetry-lifecycle.md

Deleted
deleted file mode 100644

+0 / −99 text lines

1# UI Extension Phase 5 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Summarize browser behavior for the next prompt and show actionable browser lifecycle errors.
6
7**Architecture:** Track raw browser interactions locally, aggregate them in a worker into a capped digest, and attach the digest exactly once to the next user prompt. Treat lifecycle changes as stream events so both human and agent can see disconnects, stale clients, and telemetry failures.
8
9**Tech Stack:** Browser Worker, WebSocket heartbeat, Page Visibility API, `pagehide`, local redaction helpers, Vitest browser tests.
11**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
13**Phase:** Phase 5: Telemetry Digest and Browser Lifecycle Errors
15---
17## Scope
19Included:
21- Track scroll dwell, clicks/taps, focus/blur, inactive time, viewport/device class, selected text, widget actions, form abandon/submit, and visible errors.
22- Redact selected/input text before digest generation.
23- Show inspectable “digest will be sent” indicator when non-empty.
24- Attach digest once to the next accepted prompt, then clear.
25- Detect visibility changes, pagehide, heartbeat loss, WebSocket close, stale clients, and likely browser crash/disconnect.
26- Render lifecycle errors with human action, agent hint, retryability, and related ids.
28Excluded:
30- Raw analytics persistence.
31- Multi-tab SharedWorker optimization.
32- Rendering polish.
34## Files
36Create:
38- `extensions/ui/telemetry.ts`.
39- `extensions/ui/lifecycle.ts`.
40- `extensions/ui/web/worker.js.ts`.
41- `extensions/ui/web/components/digest-indicator.js.ts`.
42- `extensions/ui/__tests__/telemetry.test.ts`.
43- `extensions/ui/__tests__/lifecycle.test.ts`.
45Modify:
47- `extensions/ui/protocol.ts`.
48- `extensions/ui/server.ts`.
49- `extensions/ui/command-adapter.ts`.
50- `extensions/ui/web/app.js.ts`.
51- `extensions/ui/web/app.css.ts`.
53## Tasks
55### Task 1: Telemetry aggregation
57- [x] Write tests for scroll/click/focus/pagehide/widget/form events, caps, and digest text.
58- [x] Implement `telemetry.ts` with `TelemetryAggregator.add`, `digest`, `clear`, and redaction helpers.
59- [x] Ensure raw values never cross into prompt context.
60- [x] Run telemetry tests; expect PASS.
61- [x] Commit `Add ui telemetry aggregator`.
63### Task 2: Browser worker tracking
65- [x] Write worker tests for batching and redaction messages.
66- [x] Implement `web/worker.js.ts` to batch raw events off the hot path.
67- [x] Wire `app.js.ts` event listeners for scroll, click, selection, focus, blur, pagehide, and widget actions.
68- [x] Run worker/web tests; expect PASS.
69- [x] Commit `Add ui browser telemetry worker`.
71### Task 3: Digest prompt attachment
73- [x] Write adapter tests proving digest attaches once to next prompt and then clears.
74- [x] Modify prompt send path to prepend or attach the digest in a deterministic bounded block.
75- [x] Render digest indicator near composer with inspectable details.
76- [x] Run prompt/digest tests; expect PASS.
77- [x] Commit `Attach ui telemetry digest once`.
79### Task 4: Lifecycle detection
81- [x] Write lifecycle tests for heartbeat timeout, WebSocket close, pagehide, stale client, and browser reconnect.
82- [x] Implement `lifecycle.ts` and server heartbeat state.
83- [x] Emit lifecycle stream events with action, agent hint, retryability, client id, and timestamps.
84- [x] Run lifecycle tests; expect PASS.
85- [x] Commit `Add ui browser lifecycle events`.
87### Task 5: Verification
89- [x] Run all UI tests.
90- [x] Run static check and `mise run check -- ui`.
91- [x] On win32, use zellij smoke to scroll/click/select/background/return/send next prompt and verify digest appears once.
92- [x] Commit fixes as `Verify ui phase 5 telemetry lifecycle`.
94## Done criteria
96- Digest is capped, inspectable, redacted, prompt-gated, and sent once.
97- Browser lifecycle errors are visible and actionable.
98- Telemetry failure does not break prompt submission.
99- Tests and mise checks pass.

docs/super/plans/2026-07-01-ui-extension-phase-6-nugu-polish-performance.md

Deleted
deleted file mode 100644

+0 / −100 text lines

1# UI Extension Phase 6 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Apply the accepted Nugu brutal/minimal visual direction and make long streams, diffs, code, and widgets stay fast.
6
7**Architecture:** Keep behavior unchanged. Add semantic CSS variables, lazy rendering upgrades, diff/highlight modules loaded on demand, stream batching, and virtualization thresholds behind the existing event protocol.
8
9**Tech Stack:** Nugu CSS variables, `prefers-color-scheme`, Pierre diffs, Shiki lazy import, Web Components, `content-visibility`, `requestAnimationFrame`, `MessageChannel`.
11**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
13**Phase:** Phase 6: Nugu Polish, Diffs, Highlighting, and Performance
15---
17## Scope
19Included:
21- Nugu semantic dark/light variables.
22- Stream-first layout: no sidebar by default, dominant `YOU` anchors, tiny top/status strips, brutal styling.
23- Pierre diff rendering with summary, expanded file view, anchors, copied hunks, and annotations.
24- Shiki lazy/cached highlighting with immediate plaintext fallback.
25- Long output truncation/expansion.
26- Virtualization threshold, content visibility, rAF batching, and worker parsing.
27- Responsive stream/widget containment on desktop and phone.
29Excluded:
31- New semantics or transport features.
32- SharedWorker multi-tab optimization unless measured pain proves it necessary.
34## Files
36Create:
38- `extensions/ui/web/theme.css.ts`.
39- `extensions/ui/web/components/code-block.js.ts`.
40- `extensions/ui/web/components/diff-view.js.ts`.
41- `extensions/ui/web/components/long-output.js.ts`.
42- `extensions/ui/web/components/virtual-stream.js.ts`.
43- `extensions/ui/__tests__/theme.test.ts`.
44- `extensions/ui/__tests__/rendering.test.ts`.
45- `extensions/ui/__tests__/performance.test.ts`.
47Modify:
49- `extensions/ui/package.json` and `package-lock.json` — add Pierre/Shiki deps.
50- `extensions/ui/web/app.css.ts`.
51- `extensions/ui/web/app.js.ts`.
52- `extensions/ui/web/worker.js.ts`.
53- `extensions/ui/README.md`.
55## Tasks
57### Task 1: Dependencies through mise/npm workspace
59- [x] Add Pierre and Shiki dependencies to `extensions/ui/package.json`.
60- [x] Run `npm install` to update `package-lock.json`.
61- [x] Run `mise run install` to verify `npm ci` installs them.
62- [x] Commit `Add ui rendering dependencies`.
64### Task 2: Nugu theme and layout
66- [x] Write theme tests for emitted semantic variables and dark/light media query.
67- [x] Implement `theme.css.ts` and update `app.css.ts`.
68- [x] Verify stream layout has no default sidebar and keeps top/status strips tiny.
69- [x] Run theme tests; expect PASS.
70- [x] Commit `Apply ui Nugu theme`.
72### Task 3: Code and diff rendering
74- [x] Write rendering tests for plaintext-first code, lazy Shiki upgrade, and Pierre diff summary/expanded view.
75- [x] Implement `code-block.js.ts` and `diff-view.js.ts`.
76- [x] Lazy-load Shiki only after initial plaintext is visible.
77- [x] Run rendering tests; expect PASS.
78- [x] Commit `Add ui code and diff rendering`.
80### Task 4: Long output and virtualization
82- [x] Write tests for truncation, expansion persistence, selected item preservation, and virtualized stream order.
83- [x] Implement `long-output.js.ts` and `virtual-stream.js.ts`.
84- [x] Use `content-visibility` and rAF/MessageChannel batching.
85- [x] Run performance tests; expect PASS.
86- [x] Commit `Add ui stream performance guards`.
88### Task 5: Visual verification
90- [x] Run all UI tests.
91- [x] Run static check and `mise run check -- ui`.
92- [x] On win32, run zellij smoke for dark/light desktop, phone width, long output, code, diff, and widgets.
93- [x] Commit fixes as `Verify ui phase 6 polish performance`.
95## Done criteria
97- Accepted Nugu direction is visible in dark and light mode.
98- Long streams remain responsive.
99- Code and diffs show plaintext immediately and upgrade lazily.
100- Tests and mise checks pass.

docs/super/plans/2026-07-01-ui-extension-phase-7-hardening-e2e-playbook.md

Deleted
deleted file mode 100644

+0 / −112 text lines

1# UI Extension Phase 7 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Harden `/ui` for release with packaging, docs, E2E coverage, and a reproducible manual playbook.
6
7**Architecture:** Freeze feature scope, strengthen tests around complete flows, document limitations, and make manual/browser verification explicit. Use zellij instead of tmux on win32; use tmux only on non-win32 systems where available.
8
9**Tech Stack:** Pi extension static checks, Vitest, Playwright Chrome/Firefox, zellij on win32, tmux on non-win32, mise tasks.
11**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
13**Phase:** Phase 7: Package Hardening, E2E, Manual Playbook
15---
17## Scope
19Included:
21- Finalize package metadata, README, dependencies, and no sibling-extension imports.
22- Complete unit, harness, browser component, fake-RPC E2E, and real-RPC smoke tiers.
23- Harden cleanup for subprocess, server, sockets, timers, widgets, terminal restore, and browser clients.
24- Add manual playbook with zellij on win32 and tmux on non-win32.
25- Document trusted full JS, LAN HTTP token model, terminal minimization limits, RPC unsupported semantics, and troubleshooting.
27Excluded:
29- New UI features.
30- Automatic RPC restart.
31- Old-browser support.
33## Files
35Create:
37- `extensions/ui/playwright.config.ts`.
38- `extensions/ui/__e2e__/fake-rpc.spec.ts`.
39- `extensions/ui/__e2e__/real-rpc-smoke.spec.ts`.
40- `extensions/ui/docs/manual-playbook.md`.
41- `extensions/ui/scripts/zellij-smoke.mjs`.
42- `extensions/ui/scripts/tmux-smoke.mjs`.
43- `extensions/ui/__tests__/cleanup.test.ts`.
45Modify:
47- `extensions/ui/package.json`.
48- `extensions/ui/README.md`.
49- `mise.toml` — only if a repo task is needed for UI E2E; otherwise keep using existing root tasks.
50- `docs/super/specs/2026-07-01-ui-extension-design.md` only for discovered corrections.
52## Tasks
54### Task 1: Cleanup hardening
56- [x] Write cleanup tests for `/ui off`, Esc, session shutdown, RPC death, socket close, and repeated stop.
57- [x] Fix runtime cleanup until all resources are idempotently closed.
58- [x] Run cleanup and all UI tests; expect PASS.
59- [x] Commit `Harden ui cleanup`.
61### Task 2: E2E fake-RPC tier
63- [x] Add Playwright config and fake-RPC E2E fixture.
64- [x] Test auth shell, snapshot, stream render, composer submit, tool lifecycle, widget render, telemetry digest, and shutdown.
65- [x] Add package script `test:e2e` for UI workspace.
66- [x] Run `npm --workspace extensions/ui run test:e2e`; expect PASS.
67- [x] Commit `Add ui fake rpc e2e`.
69### Task 3: Real-RPC smoke tier
71- [x] Add real-RPC smoke with long startup budget and explicit skip only when `pi` is unavailable.
72- [x] Verify active-branch seeded history, one browser prompt, command state, and shutdown.
73- [x] Keep the test small and non-flaky; fake-RPC remains the broad E2E tier.
74- [x] Run real smoke locally; expect PASS or documented environment skip.
75- [x] Commit `Add ui real rpc smoke`.
77### Task 4: Manual playbook scripts
79- [x] Implement `scripts/zellij-smoke.mjs` for win32: create zellij background session, launch Pi, send `/ui`, dump screen, extract URL, open browser, test 401, run `/ui off`, and leave attach/kill commands.
80- [x] Implement `scripts/tmux-smoke.mjs` for non-win32 with the same checkpoints.
81- [x] Ensure win32 path never invokes tmux.
82- [x] Add `docs/manual-playbook.md` with exact zellij/tmux commands and evidence checkpoints.
83- [x] Commit `Add ui manual smoke playbook`.
85### Task 5: Documentation and package review
87- [x] Update `extensions/ui/README.md` with commands, security/trust model, LAN token, zellij-on-win32 playbook, troubleshooting, and known limitations.
88- [x] Verify package metadata has no version, `private:true`, `main:index.ts`, MIT, peer deps, and required harness dev dep.
89- [x] Run `mise run readme -- ui` only if the generated style preserves required manual details; otherwise update manually.
90- [x] Commit `Document ui extension`.
92### Task 6: Release gate verification
94- [x] Run `npx vitest run extensions/ui/__tests__/*.test.ts`.
95- [x] Run UI E2E.
96- [x] Run actual static check for `ui`.
97- [x] Run `mise run install`, `mise run check -- ui`, and then `mise run ci` if unrelated dirty work does not make CI meaningless.
98- [x] Run win32 zellij manual smoke on this host.
99- [x] Commit fixes as `Verify ui release hardening`.
101## Done criteria
103- Full UI feature set is tested at unit/harness/browser/E2E levels.
104- Manual playbook is executable and uses zellij on win32.
105- README documents commands, trust, LAN HTTP, limitations, and troubleshooting.
106- Static check, mise install/check, and relevant test suites pass.
108## Execution note
110Automated verification passed for Vitest, fake-RPC E2E, static check, install, `mise run check -- ui`, and `mise run ci`.
111The win32 zellij smoke path now uses `scripts/zellij-smoke.mjs` and never invokes tmux.
112On this host, zellij background `run` panes exited immediately for `pi.cmd`, `cmd.exe /K`, and PowerShell `-NoExit`, and `dump-screen` returned blank output, so the script records evidence and leaves attach/kill commands for manual continuation.

docs/super/plans/2026-07-12-mise-task-architecture-phase-2-existing-e2e-and-aggregate.md

Deleted
deleted file mode 100644

+0 / −556 text lines

1# Mise Task Architecture Phase 2 Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Move existing diff-review and UI browser suites into extension-local mise tasks, run both in Chromium and Firefox, and replace extension-specific root commands with one aggregate `e2e` task.
6
7**Architecture:** A root Playwright base owns the shared Chromium/Firefox headless policy, while each browser-owning extension overlays suite-specific paths and timeouts and controls its local `e2e` command. Root mise installs both browser engines once, then dispatches extension-local suites sequentially through monorepo task syntax.
8
9**Tech Stack:** mise monorepo tasks, Playwright 1.61, Chromium, Firefox, npm workspaces, TypeScript.
11**Roadmap:** [`docs/super/roadmaps/2026-07-12-mise-task-architecture-roadmap.md`](../roadmaps/2026-07-12-mise-task-architecture-roadmap.md)
13**Phase:** Phase 2: Existing E2E Suites And Aggregate Command
15---
17## File Structure
19**Create:**
21- `test/playwright.base.ts`: shared Chromium, Firefox, and headless policy.
22- `extensions/diff-review/mise.toml`: diff-review E2E ownership.
23- `extensions/ui/mise.toml`: UI E2E ownership.
25**Modify:**
27- `extensions/diff-review/playwright.config.ts`: diff-review overlay on the shared browser base.
28- `extensions/ui/playwright.config.ts`: UI overlay on the shared browser base without a Windows-only executable override.
29- `extensions/diff-review/package.json`: remove duplicate `test:e2e` script ownership.
30- `extensions/ui/package.json`: remove duplicate `test:e2e` script ownership.
31- `scripts/extensions.mjs`: allow Playwright configs to import root test infrastructure without weakening production extension isolation.
32- `scripts/test_extensions_static_check.mjs`: regress the narrow Playwright-config allowance.
33- `mise.toml`: replace public browser-install and diff-review-specific tasks with aggregate `e2e`.
34- `AGENTS.md`: document the aggregate root task and qualified local tasks.
35- `extensions/diff-review/README.md`: document local and root-qualified E2E usage.
36- `extensions/ui/README.md`: document local and root-qualified E2E usage.
38**Unchanged:**
40- Existing Playwright specs remain behaviorally unchanged.
41- Root `test` remains Vitest-only.
42- Root `ci` remains lint, test, and check until Phase 4.
43- The-system and tune E2E coverage remain deferred to Phases 3 and 4.
45### Task 1: Normalize Existing Playwright Browser Matrices
47**Files:**
49- Create: `test/playwright.base.ts`
50- Modify: `extensions/diff-review/playwright.config.ts`
51- Modify: `extensions/ui/playwright.config.ts`
52- Modify: `scripts/extensions.mjs`
53- Test: `scripts/test_extensions_static_check.mjs`
55- [ ] **Step 1: Record unrelated work before editing**
57Run:
59```bash
60git status --short
61git diff -- extensions/diff-review/playwright.config.ts extensions/ui/playwright.config.ts
62```
64Expected: neither Playwright config has pre-existing worktree changes.
65Preserve every unrelated dirty path shown by status.
67- [ ] **Step 2: Verify the current single-browser behavior**
69Run:
71```bash
72npm exec --workspace extensions/diff-review -- playwright test --config playwright.config.ts --list
73npm --workspace extensions/ui exec -- node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts --list
74```
76Expected: diff-review lists Firefox tests only, and UI lists Chromium tests only.
77This is the failing baseline for the required two-browser matrix.
79- [ ] **Step 3: Create the shared browser base**
81Create `test/playwright.base.ts`:
83```ts
84import { defineConfig } from "@playwright/test";
86export default defineConfig({
87 projects: [
88 { name: "chromium", use: { browserName: "chromium" } },
89 { name: "firefox", use: { browserName: "firefox" } },
90 ],
91 use: {
92 headless: true,
93 },
94});
95```
97The root base owns only policy common to every extension suite.
99- [ ] **Step 4: Configure diff-review as a local overlay**
101Replace `extensions/diff-review/playwright.config.ts` with:
103```ts
104import { defineConfig } from "@playwright/test";
105import base from "../../test/playwright.base.ts";
107export default defineConfig(base, {
108 testDir: "__e2e__",
109 testMatch: "*.spec.ts",
110 timeout: 30_000,
111 retries: 1,
112});
113```
115Keep existing timeout and retry policy unchanged.
117- [ ] **Step 5: Configure UI as a local overlay**
119Replace `extensions/ui/playwright.config.ts` with:
121```ts
122import { defineConfig } from "@playwright/test";
124import base from "../../test/playwright.base.ts";
126export default defineConfig(base, {
127 testDir: "./__e2e__",
128 timeout: 30_000,
129 expect: { timeout: 5_000 },
130 use: {
131 viewport: { width: 900, height: 700 },
132 },
133});
134```
136Delete the `node:fs` import and hard-coded Windows Chrome path.
137Playwright’s installed Chromium must be used consistently on every platform.
139- [ ] **Step 6: Add a failing static-check regression for shared test infrastructure**
141Add a temporary extension with `playwright.config.ts` importing `../test/playwright.base.ts` to `scripts/test_extensions_static_check.mjs`, then assert `staticCheck()` returns no errors.
142Run `node scripts/test_extensions_static_check.mjs`.
143Expected: FAIL with `cross-extension relative import ../test/playwright.base.ts in playwright.config.ts`.
145- [ ] **Step 7: Allow only Playwright configs to import root test infrastructure**
147Extend `isAllowedTestImport()` in `scripts/extensions.mjs` so resolved paths must remain under root `test/`, and importers must be either inside `__tests__` or named `playwright.config.ts`.
148Run `node scripts/test_extensions_static_check.mjs`.
149Expected: PASS.
151- [ ] **Step 8: Verify both projects are discovered**
153Run:
155```bash
156npm exec --workspace extensions/diff-review -- playwright test --config playwright.config.ts --list
157npm --workspace extensions/ui exec -- node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts --list
158```
160Expected:
162- Every diff-review spec appears once under `[chromium]` and once under `[firefox]`.
163- Both UI specs appear once under `[chromium]` and once under `[firefox]`.
164- `real-rpc-smoke.spec.ts` remains listed but runtime-skipped unless explicitly enabled.
166- [ ] **Step 9: Install the two browser engines for verification**
168Run:
170```bash
171npm exec -- playwright install chromium firefox
172```
174Expected: exit 0.
175Existing cached engines may be reused.
176Do not use `--with-deps`; system-package mutation belongs to CI environment setup, not this cross-platform task.
178- [ ] **Step 10: Run both suites directly**
180Run:
182```bash
183npm exec --workspace extensions/diff-review -- playwright test --config playwright.config.ts
184npm --workspace extensions/ui exec -- node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts
185```
187Expected:
189- Diff-review passes in Chromium and Firefox.
190- UI’s fake-RPC suite passes in Chromium and Firefox.
191- UI’s real-RPC smoke is skipped by default in both projects.
192- No OS-specific browser executable is required.
194- [ ] **Step 11: Commit browser matrix normalization**
196Run:
198```bash
199git add test/playwright.base.ts extensions/diff-review/playwright.config.ts extensions/ui/playwright.config.ts scripts/extensions.mjs scripts/test_extensions_static_check.mjs
200git diff --cached --check
201git commit -m "test(e2e): cover chromium and firefox"
202```
204Expected: the shared base and two extension overlays are committed.
206### Task 2: Move E2E Command Ownership Into Extensions
208**Files:**
210- Create: `extensions/diff-review/mise.toml`
211- Create: `extensions/ui/mise.toml`
212- Modify: `extensions/diff-review/package.json`
213- Modify: `extensions/ui/package.json`
215- [ ] **Step 1: Verify qualified E2E tasks are absent**
217Run:
219```bash
220mise tasks --all --name-only
221```
223Expected: neither `//extensions/diff-review:e2e` nor `//extensions/ui:e2e` exists.
225- [ ] **Step 2: Add diff-review’s local E2E task**
227Create `extensions/diff-review/mise.toml`:
229```toml
230[tasks.e2e]
231description = "Run diff-review browser E2E tests"
232depends = ["//:install"]
233run = "npm exec -- playwright test --config playwright.config.ts"
234```
236- [ ] **Step 3: Add UI’s local E2E task**
238Create `extensions/ui/mise.toml`:
240```toml
241[tasks.e2e]
242description = "Run UI browser E2E tests"
243depends = ["//:install"]
244run = "node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts"
245```
247- [ ] **Step 4: Remove duplicate package-script ownership**
249Remove only `test:e2e` from both extension `scripts` objects.
251`extensions/diff-review/package.json` keeps:
253```json
254"scripts": {
255 "dev:smoke": "tsx scripts/dev-server.ts"
256},
257```
259`extensions/ui/package.json` keeps:
261```json
262"scripts": {
263 "test": "vitest run ./__tests__/*.test.ts"
264},
265```
267Do not change dependencies in this phase.
268Playwright remains a declared development dependency of the root and each E2E-owning workspace.
270- [ ] **Step 5: Regenerate npm lock metadata**
272Run:
274```bash
275mise run lock
276```
278Expected: exit 0.
279Package scripts normally do not alter `package-lock.json`; if the lockfile changes, inspect and include only metadata caused by these package edits.
281- [ ] **Step 6: Verify local task discovery and execution**
283Run:
285```bash
286mise tasks --all --name-only
287mise run //extensions/diff-review:e2e
288mise run //extensions/ui:e2e
289```
291Expected: both qualified tasks exist and both browser matrices pass.
293- [ ] **Step 7: Commit local E2E ownership**
295Run:
297```bash
298git add extensions/diff-review/mise.toml extensions/ui/mise.toml extensions/diff-review/package.json extensions/ui/package.json package-lock.json
299git diff --cached --check
300git commit -m "build(e2e): localize browser suites"
301```
303Expected: two local mise files and removal of duplicate package scripts are committed.
304Omit `package-lock.json` if unchanged.
306### Task 3: Replace Root E2E Tasks With One Aggregate
308**Files:**
310- Modify: `mise.toml:59-72`
312- [ ] **Step 1: Confirm the obsolete root commands**
314Run:
316```bash
317mise tasks --name-only
318```
320Expected: `//:install-e2e-browsers` and `//:e2e-diff-review` exist, while `//:e2e` does not.
322- [ ] **Step 2: Replace both obsolete task blocks**
324Delete the complete `[tasks.install-e2e-browsers]` and `[tasks.e2e-diff-review]` blocks.
325Insert this task in their place:
327```toml
328[tasks.e2e]
329description = "Run all extension browser E2E tests"
330depends = ["install"]
331run = [
332 "npm exec -- playwright install chromium firefox",
333 "mise run --jobs 1 //extensions/...:e2e",
334]
335```
337Browser installation occurs once at root.
338Extension execution is sequential to avoid browser/process contention and interleaved reports.
339Local qualified tasks assume browsers were installed through root `e2e` or an explicit Playwright install.
341- [ ] **Step 3: Verify root and all-task surfaces**
343Run:
345```bash
346mise tasks validate
347mise tasks --name-only
348mise tasks --all --name-only
349mise run --dry-run e2e
350```
352Expected:
354- Task validation exits 0.
355- Root contains `//:e2e`.
356- Root no longer contains `//:install-e2e-browsers` or `//:e2e-diff-review`.
357- All-task output contains both qualified extension E2E tasks.
358- The dry run shows one browser install followed by sequential monorepo dispatch.
360- [ ] **Step 4: Run the aggregate E2E task**
362Run:
364```bash
365mise run e2e
366```
368Expected: browser installation succeeds once, then diff-review and UI suites both pass in Chromium and Firefox.
369The two extension task headers do not overlap.
371- [ ] **Step 5: Confirm Vitest and CI remain unchanged**
373Run:
375```bash
376mise run test
377mise run --dry-run ci
378```
380Expected:
382- Vitest does not discover files under `__e2e__`.
383- CI resolves lint, test, and check only.
384- E2E remains outside CI until Phase 4.
386- [ ] **Step 6: Commit root aggregation**
388Run:
390```bash
391git add mise.toml
392git diff --cached --check
393git commit -m "build(e2e): aggregate browser suites"
394```
396Expected: the commit contains only replacement of the two legacy E2E tasks with root `e2e`.
398### Task 4: Document The Phase 2 Task Surface
400**Files:**
402- Modify: `AGENTS.md:10-35`
403- Modify: `extensions/diff-review/README.md`
404- Modify: `extensions/ui/README.md`
406- [ ] **Step 1: Replace legacy E2E rows in AGENTS.md**
408Remove:
410```markdown
411| E2E browsers | `mise run install-e2e-browsers` | Install Playwright E2E browsers |
412| E2E review | `mise run e2e-diff-review` | Run diff-review headless browser E2E |
413```
415Add after `Bench`:
417```markdown
418| E2E | `mise run e2e` | Run extension E2E in Chromium and Firefox |
419```
421Keep the Phase 2 CI description as `Release gate (lint + test + check)`.
423- [ ] **Step 2: Document diff-review E2E usage**
425Add this section near diff-review’s development/testing documentation:
427```markdown
428## E2E
430Run root `mise run e2e` first to install browsers and execute every extension suite.
431After that bootstrap, run `mise run e2e` here, or `mise //extensions/diff-review:e2e` from the repository root, to test only the browser review flow in Chromium and Firefox.
432```
434- [ ] **Step 3: Document UI E2E usage**
436Add this section near UI’s development/testing documentation:
438```markdown
439## E2E
441Run root `mise run e2e` first to install browsers and execute every extension suite.
442After that bootstrap, run `mise run e2e` here, or `mise //extensions/ui:e2e` from the repository root, to test only the browser UI in Chromium and Firefox.
443The real Pi RPC smoke remains opt-in through `UI_REAL_RPC_SMOKE=1`.
444```
446- [ ] **Step 4: Verify obsolete command references are gone from live docs**
448Run:
450```bash
451node -e "const fs=require('node:fs'); for(const p of ['AGENTS.md','extensions/diff-review/README.md','extensions/ui/README.md']) { const s=fs.readFileSync(p,'utf8'); for(const old of ['install-e2e-browsers','e2e-diff-review']) if(s.includes(old)) throw new Error(p+': '+old); }"
452```
454Expected: exit 0 with no output.
456- [ ] **Step 5: Verify changed documentation formatting**
458Run:
460```bash
461git diff --check -- AGENTS.md extensions/diff-review/README.md extensions/ui/README.md
462```
464Expected: exit 0 with no output.
465Do not run repository-wide formatting while unrelated dirty files remain.
466The final CI lint check validates Markdown formatting without mutating those files.
468- [ ] **Step 6: Commit documentation**
470Run:
472```bash
473git add AGENTS.md extensions/diff-review/README.md extensions/ui/README.md
474git diff --cached --check
475git commit -m "docs: explain aggregate browser E2E"
476```
478Expected: only E2E command documentation is committed.
480### Task 5: Verify The Phase 2 Boundary
482**Files:**
484- Verify: `mise.toml`
485- Verify: `extensions/diff-review/mise.toml`
486- Verify: `extensions/ui/mise.toml`
487- Verify: both Playwright configurations and suites
489- [ ] **Step 1: Validate final task discovery**
491Run:
493```bash
494mise tasks validate
495mise tasks --name-only
496mise tasks --all --name-only
497```
499Expected:
501- Exactly one public root E2E task exists: `//:e2e`.
502- Qualified diff-review and UI E2E tasks exist.
503- Legacy root E2E task names are absent.
504- Phase 1 benchmark tasks remain unchanged.
506- [ ] **Step 2: Run the complete browser aggregate**
508Run:
510```bash
511mise run e2e
512```
514Expected:
516- Both browser engines are available.
517- Diff-review passes in Chromium and Firefox.
518- UI fake-RPC passes in Chromium and Firefox.
519- UI real-RPC smoke is skipped by default.
521- [ ] **Step 3: Run the unchanged release gate**
523Run:
525```bash
526mise run ci
527```
529Expected: lint, all Vitest tests, typecheck, and static checks pass.
530E2E remains a separate manual gate in Phase 2.
532- [ ] **Step 4: Inspect final scope**
534Run:
536```bash
537git status --short
538git diff --stat
539git log -5 --oneline
540```
542Expected: unrelated pre-existing work remains untouched.
543No the-system or tune E2E files were added.
544No CI workflow was changed.
545No TypeScript import standardization from Phase 5 was started.
547- [ ] **Step 5: Report completion evidence**
549Report:
551- Task validation and root/all task lists.
552- Chromium and Firefox results for diff-review and UI.
553- `mise run ci` result.
554- Commits created.
555- Confirmation that E2E is not yet part of CI.
556- Confirmation that Phases 3 through 5 remain unimplemented.

docs/super/plans/2026-07-12-mise-task-architecture-phase-3-mockup-e2e.md

Modified

+0 / −1 text lines

350350Expected:
352352- Diff-review passes in Chromium and Firefox.
353- UI fake-RPC passes in Chromium and Firefox; real-RPC remains skipped.
354353- The-system mockup round trip passes in Chromium and Firefox.
356355- [ ] **Step 6: Run the unchanged release gate**

docs/super/plans/2026-07-12-mise-task-architecture-phase-4-tune-e2e-ci.md

Modified

+0 / −1 text lines

612612Expected:
614614- Diff-review passes in Chromium and Firefox.
615- UI fake-RPC passes in Chromium and Firefox; real-RPC remains skipped.
616615- The-system mockup passes in Chromium and Firefox.
617616- Tune dashboard passes in Chromium and Firefox.

docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md

Deleted
deleted file mode 100644

+0 / −358 text lines

1# UI Extension Roadmap
2
3> **For agentic workers:** Use /skill:writing-plans to create one detailed implementation plan per phase. Start with Phase 1 and proceed sequentially unless the user explicitly changes the order.
4
5**Goal:** Build `/ui`, a persistent browser Pi frontend backed by an active-branch RPC session while terminal Pi remains independent.
6
7**Design Spec:** [`docs/super/specs/2026-07-01-ui-extension-design.md`](../specs/2026-07-01-ui-extension-design.md)
8
9**Planning Strategy:** The design spans terminal extension behavior, LAN auth, RPC/session bridging, a browser frontend, trusted full-JS widgets, telemetry, rendering performance, and test hardening. Each phase leaves a usable, visually verifiable slice before adding the next subsystem.
11---
13## Phase 1: `/ui` Runtime Shell, LAN Server, Terminal Widget
15**Outcome:** `/ui` starts and stops a runtime with a token-authenticated LAN web server and minimal terminal widget.
17**Why now:** This creates the visible entry point, mobile link/QR path, and lifecycle shell every later phase uses.
19**Scope:**
21- Register `/ui`, `/ui off`, `/ui status`, `/ui open`, and `/ui qr`.
22- Start/stop one runtime per terminal session.
23- Bind LAN HTTP server with random token auth, same-origin CORS, and 401 handling.
24- Render terminal widget with OSC link, QR, host/port, session label, ESC help, `/ui off`, and connection state.
25- Restore terminal UI on `/ui off`, ESC, or session shutdown.
27**Out of scope:**
29- RPC subprocess.
30- Seeded active-branch session history.
31- Full Pi web composer.
32- Visual widgets and telemetry.
34**Key files/areas likely affected:**
36- `extensions/ui/index.ts`: extension registration and commands.
37- `extensions/ui/server.ts`: HTTP server and token auth.
38- `extensions/ui/terminal-widget.ts`: terminal minimized widget.
39- `extensions/ui/qr.ts`: QR generation.
40- `extensions/ui/errors.ts`: typed startup/shutdown errors.
41- `extensions/ui/__tests__/`: harness and server tests.
43**Dependencies:**
45- Pi extension command/widget APIs.
46- QR generation dependency decision.
48**Verification:**
50- Automated: extension loads without side effects; commands register; token auth accepts good token and rejects bad/missing token; duplicate `/ui` is idempotent; `/ui off` cleans server/timers/widget.
51- Visual: run real Pi, execute `/ui`, and visually confirm terminal collapses to one widget showing OSC link, QR, host/port, state, ESC, and `/ui off` help.
52- Visual: open browser link and bad-token URL; confirm authenticated page and precise 401 page are visibly distinct and understandable.
53- Visual: scan QR from phone on same LAN and see the same authenticated startup page.
55**Phase boundary health:** Terminal Pi still works independently; the browser page is only a shell, but start/stop/auth/restore are complete and testable.
57**Risks:**
59- Terminal APIs may not fully hide existing UI; mitigate by minimizing as far as APIs allow and documenting limitations.
60- LAN address detection may fail; mitigate with actionable stream/terminal error and `/ui status` diagnostics.
62**Context notes:** Keep startup work inside `/ui`; extension load must stay cheap and side-effect-free.
64## Phase 2: Active-Branch RPC Session and Basic Web Stream
66**Outcome:** Browser UI talks to a persistent Pi RPC session seeded from the terminal active branch and renders a basic ordered stream plus composer.
68**Why now:** This proves `/ui` is a real Pi frontend, not a companion page.
70**Scope:**
72- Extract the active terminal session branch into a persistent web session with `createBranchedSession(getLeafId())` where possible.
73- Spawn `pi --mode rpc --session <seeded-session>` with normal extensions/skills/settings.
74- Parse RPC stdout as LF-delimited JSONL and capture stderr separately.
75- Implement server event bus, snapshot, replay buffer, WebSocket stream, and RPC stdin queue.
76- Render basic browser shell: top state strip, central stream, tiny status strip, composer.
77- Send normal prompts from browser and show user/assistant/tool/error stream items.
79**Out of scope:**
81- Complete slash-command parity.
82- Rich diffs/highlighting.
83- Visual widget tools.
84- Telemetry digest.
86**Key files/areas likely affected:**
88- `extensions/ui/session-seed.ts`: fork/fallback session seeding.
89- `extensions/ui/rpc.ts`: subprocess bridge and command queue.
90- `extensions/ui/protocol.ts`: event types, snapshots, replay.
91- `extensions/ui/web/`: initial browser shell, stream, composer, worker.
92- `extensions/ui/__tests__/rpc.test.ts`: parser, queue, death, stderr.
94**Dependencies:**
96- Phase 1.
97- Verified Pi active-branch session extraction and RPC flags.
99**Verification:**
101- Automated: `createBranchedSession(getLeafId())` path selected; parent recorded; exact active branch preserved; whole-tree `forkFrom` fallback warns; JSONL parser splits LF only; event sequence monotonic; reconnect replays or snapshots; slow RPC startup and RPC death produce actionable events.
102- Visual: open `/ui` and see seeded terminal history in the central stream with dominant `YOU` blocks.
103- Visual: send a browser prompt and watch user message, assistant stream, and tool lifecycle appear in order.
104- Visual: kill RPC process and confirm browser shows a clear, actionable stream error while terminal widget updates state.
106**Phase boundary health:** `/ui` becomes minimally useful as a browser Pi session; missing advanced syntax is visible but not broken.
108**Risks:**
110- Exact active-branch extraction APIs may differ; mitigate by failing with actionable error rather than ad-hoc corrupt JSON rewriting.
111- RPC event shapes may need normalization; mitigate with typed protocol tests before UI assumptions spread.
113**Context notes:** Keep the stream deterministic and boring; defer polish until behavior is correct.
115## Phase 3: Pi Syntax, Commands, Keybindings, and Extension UI
117**Outcome:** Browser composer and controls match normal Pi interaction expectations.
119**Why now:** After the RPC path works, parity features can be layered without confusing transport failures with UI behavior.
121**Scope:**
123- Slash command autocomplete and execution.
124- `/skill:*`, prompt templates, model/thinking controls, compact/session commands where RPC supports them.
125- `@` file/image references and attachment flow.
126- `!`/`!!` bash behavior or explicit equivalent web mapping.
127- Enter, Shift+Enter, Esc abort, Ctrl+O expand/collapse, Ctrl+P model cycle.
128- Render RPC extension UI requests: select, confirm, input, editor, notify, status/title/widget/editor text.
129- Keep desktop chrome minimal; add tap targets only where mobile needs them.
131**Out of scope:**
133- Full-JS visual widgets.
134- Telemetry.
135- Pierre/Shiki polish.
137**Key files/areas likely affected:**
139- `extensions/ui/web/components/`: composer, autocomplete, dialogs, stream selection.
140- `extensions/ui/rpc.ts`: command adapters.
141- `extensions/ui/protocol.ts`: extension UI request/response events.
142- `extensions/ui/web/worker.js.ts`: batched input/event dispatch.
144**Dependencies:**
146- Phase 2.
147- RPC command availability check.
149**Verification:**
151- Automated: composer parsing for `/`, `/skill:*`, `@`, `!`, `!!`; keybindings dispatch expected RPC commands; dialogs return selected values.
152- Visual: type `/` and visually verify command autocomplete, skill entries, and prompt templates look and behave like Pi.
153- Visual: invoke select/confirm/input/editor flows and confirm dialogs appear in stream or modal form with clear action targets.
154- Visual: use Ctrl+P, Ctrl+O, Esc, Enter, Shift+Enter and see immediate visible state changes.
155- Visual: on phone width, confirm essential controls remain visible without desktop button clutter.
157**Phase boundary health:** Web UI now behaves like a normal Pi frontend for text, commands, tools, and extension UI; richer widgets remain additive.
159**Risks:**
161- Some terminal-only semantics may lack RPC equivalents; mitigate with explicit web mappings or visible unsupported errors.
162- Mobile controls can bloat desktop; mitigate by CSS/media-gated tap targets.
164**Context notes:** Preserve Pi syntax over inventing web-only controls.
166## Phase 4: Trusted Visual Widgets and `window.pi`
168**Outcome:** Agents can create, update, and receive actions from trusted full-JS visual widgets embedded in the stream.
170**Why now:** Widget actions require stable stream, composer, RPC, and extension UI foundations.
172**Scope:**
174- Register visual tool families for web RPC session: card, table, diagram, form/control, mockup/prototype, raw HTML/CSS/JS, update/patch, wait-for-action.
175- Render bounded visual blocks with stable widget ids, title, fallback text, lifecycle state, expand/collapse, and response expectation.
176- Expose `window.pi` methods for widget action/result, prompt/steer/follow-up, state, widget events, payload update, local notify, and attachment request.
177- Attribute every widget-originated action/prompt visibly in the stream.
178- Audit `window.pi` calls in details available to the agent.
179- Deliberately no sandbox or separate permission wall; full-JS widgets are trusted agent output, constrained by layout/lifecycle boundaries and visible attribution.
181**Out of scope:**
183- Telemetry digest beyond widget action events needed for actions.
184- Pierre/Shiki rendering polish.
185- Heavy virtualization.
187**Key files/areas likely affected:**
189- `extensions/ui/visual-tools.ts`: tool registration and fallback text.
190- `extensions/ui/web/components/`: visual block, widget bridge, errors.
191- `extensions/ui/protocol.ts`: widget lifecycle/action events.
192- `extensions/ui/errors.ts`: widget runtime/action errors.
194**Dependencies:**
196- Phase 3.
197- User decision: no sandbox; trust boundary is visual attribution/audit, not containment.
199**Verification:**
201- Automated: stable widget ids; fallback text returned; mount/update/action/error events; `window.pi` method routing; Chrome/Firefox iframe bridge and bounded-layout probes pass; widget errors become human+agent actionable stream errors.
202- Visual: ask agent for a visual card, form, diagram/prototype, and full HTML/CSS/JS widget; confirm all appear in the main stream, bounded and responsive.
203- Visual: click widget controls and confirm resulting action is visibly attributed to that widget before reaching agent/session.
204- Visual: trigger a widget JS error and confirm the block shows widget id/tool call id plus human action and agent fix hint.
205- Visual: inspect expanded metadata and see `full JS / trusted`, lifecycle, fallback, ids, and audit details.
207**Phase boundary health:** Visual widgets are useful and honest about trust; later telemetry/perf can improve observability and scale without changing the bridge contract.
209**Risks:**
211- Trusted full JS can leak data or impersonate actions; accepted by design, mitigated only through visible attribution, audit, and no silent widget-originated prompts.
212- CSS/layout interference can damage page usability; mitigate with document/layout boundary, containment, overflow, explicit height negotiation, and Chrome/Firefox mobile-width layout tests.
214**Context notes:** Do not reintroduce sandbox planning unless user changes the threat model.
216## Phase 5: Telemetry Digest and Browser Lifecycle Errors
218**Outcome:** Browser behavior is summarized for the agent on the next prompt, and inactive/closed/disconnected clients produce actionable state.
220**Why now:** Telemetry needs stable stream item/widget ids and working prompt submission.
222**Scope:**
224- Track scroll dwell, clicks/taps, pointer summaries, focus/blur, inactive time, viewport/device class, selected text, widget actions, form abandon/submit, and error visibility.
225- Aggregate locally into capped digest; redact obvious secrets from selected text/input fields.
226- Show inspectable “telemetry digest will be sent” when non-empty.
227- Attach digest once to next accepted user prompt, then clear.
228- Detect visibility changes, pagehide, heartbeat loss, WebSocket close, stale clients, and browser crash/disconnect symptoms.
229- Render human-facing and agent-facing lifecycle errors with retry safety.
231**Out of scope:**
233- Multi-tab single-socket optimization.
234- Advanced analytics UI.
235- Rendering polish.
237**Key files/areas likely affected:**
239- `extensions/ui/telemetry.ts`: digest aggregation and redaction.
240- `extensions/ui/web/worker.js.ts`: off-hot-path tracking.
241- `extensions/ui/server.ts`: heartbeat/client state.
242- `extensions/ui/web/components/`: digest indicator and lifecycle stream errors.
244**Dependencies:**
246- Phase 4.
248**Verification:**
250- Automated: scroll/click/focus/pagehide aggregate; digest cap/redaction; digest attaches once; heartbeat timeout states; disconnect errors include action/fix/retryability.
251- Visual: scroll, click, select text, background tab, return, and see an inspectable digest indicator near the composer/status.
252- Visual: send next prompt and confirm digest appears in/with the prompt context once, then disappears.
253- Visual: close tab, disable phone Wi-Fi, and kill browser; confirm top strip/stream errors say exactly what happened and what to do.
255**Phase boundary health:** The UI remains functional if telemetry fails; errors are visible and actionable rather than silent.
257**Risks:**
259- Telemetry can feel creepy/noisy; mitigate with digest-only, inspectable, capped, prompt-gated behavior.
260- Browser close detection is best-effort; mitigate with heartbeat timeout as source of truth.
262**Context notes:** Keep raw telemetry out of agent context; only digest crosses on user prompt.
264## Phase 6: Nugu Polish, Diffs, Highlighting, and Performance
266**Outcome:** The UI reaches accepted visual direction and handles long streams/code/diffs without blocking.
268**Why now:** Polish and scale are safest after core behavior and event contracts stabilize.
270**Scope:**
272- Apply Nugu semantic theme with `prefers-color-scheme` dark/light.
273- Strengthen terminal-like web layout: no sidebars by default, dominant user anchors, tiny top/status strips, brutal minimal styling.
274- Integrate Pierre for diffs with collapsed summary, expanded file views, anchors, copied hunks, and annotations where needed.
275- Integrate Shiki lazy/cached highlighting with plain text immediate fallback.
276- Add truncation, lazy expansion, virtualization threshold, `content-visibility`, `requestAnimationFrame` batching, `MessageChannel` chunks, and worker parsing for high-volume streams.
277- Ensure responsive widget/container behavior on desktop and phone.
279**Out of scope:**
281- New feature semantics.
282- Multi-tab SharedWorker optimization unless required by measured pain.
284**Key files/areas likely affected:**
286- `extensions/ui/web/app.css.ts`: Nugu theme and layout.
287- `extensions/ui/web/components/`: diff, code, long output, stream virtualization.
288- `extensions/ui/web/worker.js.ts`: batching and parsing.
289- `extensions/ui/package.json`: Pierre/Shiki deps.
291**Dependencies:**
293- Phase 5.
295**Verification:**
297- Automated: dark/light variables emitted; stream roles render expected classes; long outputs truncate/expand; Shiki lazy upgrade does not block startup; virtualization preserves selection/expand state.
298- Visual: compare dark and light system themes and confirm Nugu semantics, dominant `YOU` messages, tiny status, and no useless side chrome.
299- Visual: render real edit diffs and code blocks; confirm plain text appears immediately, then upgrades to Pierre/Shiki without layout jump.
300- Visual: load a long tool-output stream and confirm scrolling, expansion, and selection remain smooth.
301- Visual: verify the same stream and widgets on phone width remain bounded and readable.
303**Phase boundary health:** Behavior should not change, only visual quality and scale; tests remain green against existing contracts.
305**Risks:**
307- Highlight/diff deps can slow startup; mitigate with lazy loading and immediate plaintext fallback.
308- Virtualization can break anchors/selection; mitigate with tests around selected item and replayed stream state.
310**Context notes:** Measure before adding more complexity; keep no-framework default.
312## Phase 7: Package Hardening, E2E, Manual Playbook
314**Outcome:** The extension is packaged, documented, and verified through automated and manual real-Pi/browser flows.
316**Why now:** Final hardening should validate the whole assembled system, not unstable intermediate APIs.
318**Scope:**
320- Finalize standalone package metadata, peer/dev deps, README, and no cross-extension imports.
321- Complete unit, harness, browser component, and E2E coverage around critical flows.
322- Harden shutdown cleanup: subprocess, server, sockets, timers, widgets, terminal restore.
323- Run and maintain manual testing playbook with real terminal, tmux, desktop browser, and phone.
324- Document known limitations: terminal minimization API limits, trusted full JS, LAN HTTP not encrypted, RPC unsupported semantics.
326**Out of scope:**
328- New UI features beyond spec.
329- Automatic RPC restart.
330- Old-browser support.
332**Key files/areas likely affected:**
334- `extensions/ui/package.json`: package and scripts.
335- `extensions/ui/README.md`: usage, security/trust, troubleshooting.
336- `extensions/ui/__tests__/`: full test suite.
337- Playwright/E2E test area chosen during detailed planning.
338- `docs/super/specs/2026-07-01-ui-extension-design.md`: only if implementation discovers spec corrections.
340**Dependencies:**
342- Phase 6.
344**Verification:**
346- Automated: full unit/harness/web/E2E suite passes; extension load has no side effects; session shutdown cleans all resources; critical flows pass with fake or real RPC tiers.
347- Visual: run manual playbook end-to-end and visually confirm startup, seeded history, Pi syntax, tool rendering, widgets, telemetry, lifecycle errors, mobile QR, shutdown/restore.
348- Visual: capture or record final dark/light desktop and phone checkpoints for future regression comparison.
349- Visual: intentionally trigger failure cases and confirm each visible error has human action, agent hint, retryability, and related ids/session/log path.
351**Phase boundary health:** This is the release boundary; project should be green, documented, and manually reproducible.
353**Risks:**
355- E2E flakiness from real subprocess/browser timing; mitigate with fake-RPC tier plus smaller real-RPC smoke tests.
356- Manual playbook drift; mitigate by keeping it tied to visible checkpoints from this roadmap.
358**Context notes:** Do not expand scope during hardening; file discovered enhancements as later specs.

docs/super/roadmaps/2026-07-12-mise-task-architecture-roadmap.md

Modified

+8 / −11 text lines

6666## Phase 2: Existing E2E Suites And Aggregate Command
68**Outcome:** Diff-review and UI own consistent local E2E tasks, both suites run in Chromium and Firefox, and one root `e2e` command installs browsers once and dispatches discovered suites.
68**Outcome:** Diff-review owns a local E2E task, its suite runs in Chromium and Firefox, and one root `e2e` command installs browsers once and dispatches discovered suites.
70**Why now:** These are the existing Playwright suites and establish the minimal reusable task shape before adding coverage to untested browser servers.
70**Why now:** The existing Playwright suite establishes the minimal reusable task shape before adding coverage to untested browser servers.
7272**Scope:**
7474- Move diff-review’s root-specific E2E task into `extensions/diff-review/mise.toml`.
75- Add local mise ownership for UI’s existing E2E suite.
76- Normalize both Playwright configurations to Chromium and Firefox projects.
75- Normalize its Playwright configuration to Chromium and Firefox projects.
7776- Replace the public root `e2e-diff-review` and extension-specific browser installer with one aggregate root `e2e` workflow.
7877- Ensure browser installation occurs once per aggregate run.
7978- Keep detailed logic in Vitest and browser coverage smoke-focused.
8988- `mise.toml`: aggregate E2E entrypoint and browser setup.
9089- `extensions/diff-review/mise.toml`: local E2E task.
91- `extensions/ui/mise.toml`: local E2E task.
9290- `extensions/diff-review/playwright.config.ts`: two-browser matrix.
93- `extensions/ui/playwright.config.ts`: two-browser matrix.
9491- Existing package scripts and Playwright dependencies: remove duplicate command ownership where safe.
9693**Dependencies:**
10198**Verification:**
103- Qualified diff-review and UI E2E tasks pass in Chromium and Firefox.
104- Root `mise run e2e` installs required browsers once and runs both suites.
100- Qualified diff-review E2E passes in Chromium and Firefox.
101- Root `mise run e2e` installs required browsers once and runs the suite.
105102- Root Vitest still excludes `__e2e__`.
106103- Existing CI remains green without yet invoking E2E.
108**Phase boundary health:** All existing browser suites gain one consistent manual aggregate while the release gate remains unchanged until complete coverage exists.
105**Phase boundary health:** The existing browser suite gains one consistent manual aggregate while the release gate remains unchanged until complete coverage exists.
110107**Risks:**
112- Firefox may expose assumptions hidden by Chromium-only UI tests.
109- Firefox may expose assumptions hidden by Chromium-only tests.
113110- Browser installation and executable selection differ across Windows, macOS, Linux, and CI, so Playwright defaults should replace OS-specific executable logic unless explicitly required.
115112**Context notes:** Exercise the real extension and browser path; avoid mocks that reduce E2E to another unit test.
200197**Verification:**
202199- Tune passes in Chromium and Firefox.
203- Root `mise run e2e` runs diff-review, UI, mockup, and tune in both browsers.
200- Root `mise run e2e` runs diff-review, mockup, and tune in both browsers.
204201- Root `mise run test` runs Vitest only.
205202- Root `mise run bench` remains sequential and excluded from CI.
206203- `mise run ci` passes locally and in the Luci-parity ephemeral container.

docs/super/specs/2026-07-01-ui-extension-design.md

Deleted
deleted file mode 100644

+0 / −958 text lines

1# UI Extension Design
2
3Date: 2026-07-01
4Status: Approved
5
6## Goal
7
8Create a Pi extension named `ui`, activated with `/ui`, that opens a full web UI backed by a normal Pi RPC session. The terminal Pi session remains independent and usable. The web UI is a separate, persistent, fully fledged Pi session seeded from the terminal session branch.
9
10The web UI lets the agent communicate through rich visual surfaces: text, tools, forms, controls, prototypes, diagrams, images, annotations, and full HTML/CSS/JS widgets. It keeps normal Pi syntax and behavior: slash commands, skills, `@` file/image references, `!` bash, model/thinking controls, abort, expand/collapse, notifications, errors, status, and keybindings.
12## Non-goals
14- Do not replace Pi core.
15- Do not make the terminal and web sessions mirror each other live.
16- Do not make the web UI ephemeral by default.
17- Do not prevent parallel terminal/web use, even if both edit the same cwd.
18- Do not limit scope to a companion view; web UI must be a normal Pi frontend.
20## User decisions
22- Use RPC, not SDK in-process.
23- `/ui` minimizes the terminal Pi UI as much as extension APIs allow; `/ui off` restores it.
24- Web Pi session is independent and can run in parallel with terminal Pi.
25- Web session is persistent and normal.
26- Seed web session with full terminal active branch.
27- Seed via exact active-branch extraction where possible; whole-tree fork is allowed only if explicitly chosen.
28- Allow parallel edit races.
29- Mobile support uses LAN HTTP + random token.
30- Show QR code in terminal widget.
31- Agent-injected snippets may use full JS.
32- Full JS gets `window.pi` access by default.
33- Do not sandbox full-JS widgets; use visible attribution/audit and layout boundaries instead.
34- Include accepted mockup direction in this spec.
35- Theme must use Nugu semantics and respect system dark/light preference.
36- Prefer modern Chrome/Firefox APIs; no old-browser support.
38## Architecture
40```text
41terminal pi session
42 └─ /ui command
43 ├─ extract active terminal branch into new persistent session
44 ├─ spawn `pi --mode rpc --session <seeded-session>` subprocess
45 ├─ start LAN HTTP/WebSocket server with random token
46 ├─ show terminal widget: OSC link, QR, ESC cancel, /ui off help
47 └─ keep terminal session independent
49browser
50 ├─ GET snapshot
51 ├─ WebSocket event stream
52 ├─ Pi-capable composer
53 ├─ central stream renderer
54 ├─ full-JS visual widgets
55 └─ telemetry digest sent on next user message
56```
58### Runtime model
60`/ui` starts one web runtime per terminal Pi session unless an existing runtime is already active. The runtime contains:
62- local HTTP server bound for LAN access,
63- token-authenticated browser app,
64- WebSocket event channel,
65- spawned Pi RPC subprocess,
66- active-branch persistent session file,
67- in-memory event store and replay buffer,
68- telemetry aggregator,
69- terminal TUI minimizer state.
71`/ui off` stops the server, closes WebSocket clients, terminates the RPC subprocess, clears the terminal widget, restores footer/header/editor/working visibility where changed, and reports the saved web session path.
73### Terminal UI while active
75The terminal Pi UI is reduced to one custom widget as much as extension APIs permit. The widget shows:
77- clickable OSC 8 link,
78- QR code for mobile,
79- host/port,
80- session id/name,
81- “press ESC to cancel UI mode”,
82- “run `/ui off` to restore terminal UI”,
83- connection state: waiting, connected, inactive, disconnected, RPC dead.
85ESC in terminal while UI mode is active calls the same shutdown path as `/ui off`.
87## Session seeding
89Use Pi `SessionManager` APIs rather than ad-hoc JSON rewriting.
91Preferred exact active-branch path:
93```text
94source = terminal ctx.sessionManager.getSessionFile()
95leaf = terminal ctx.sessionManager.getLeafId()
96seededPath = terminal ctx.sessionManager.createBranchedSession(leaf)
97spawn pi --mode rpc --session seededPath
98```
100Prototype result: `SessionManager.forkFrom(source, cwd)` copies the whole session tree into the new file. That keeps LLM context clean because the active branch path is clean, but it also brings abandoned branches into `/tree`, increases history size, and may expose old branch history. Therefore use `createBranchedSession(leaf)` for the default exact active-branch seed. Whole-tree `forkFrom` is acceptable only behind an explicit option or fallback with visible warning.
102The seeded session must preserve the full active branch: user messages, assistant messages, thinking blocks, tool calls, tool results, bash execution messages, custom messages, compaction summaries, model changes, thinking-level changes, and relevant branch summaries.
104The web session header records the terminal session as parent. The web session gets a clear display name such as `ui: <terminal session name or cwd>`.
106If the terminal session is ephemeral or has no session file, create a normal persistent web session and seed by appending the active branch messages through `SessionManager` APIs. If exact branch copy is impossible, fail with an actionable terminal error.
108## RPC subprocess
110The web runtime spawns Pi in RPC mode with normal extension/skill/settings discovery enabled.
112Requirements:
114- do not pass `--no-extension`, `--no-skills`, or `--no-session`,
115- pass the seeded active-branch session via `--session`,
116- inherit cwd,
117- inherit normal environment,
118- parse stdout strictly as JSONL split on LF only,
119- capture stderr separately for diagnostics,
120- restart only by explicit user action, not automatically,
121- expose RPC startup, slow startup, and death as stream/terminal states with fix instructions.
123Prototype result: a normal RPC subprocess with full extensions can take longer than 8 seconds to answer first state requests. The browser and terminal widget must show an explicit “starting RPC” state instead of appearing frozen.
125RPC commands used by the web UI:
127- `prompt`, `steer`, `follow_up`, `abort`,
128- `get_state`, `get_messages`, `get_commands`, `get_session_stats`,
129- `set_model`, `cycle_model`, `set_thinking_level`, `cycle_thinking_level`,
130- `compact`, `new_session`, `switch_session`, `fork`, `clone`,
131- `bash`, `abort_bash`,
132- `export_html`, `set_session_name`.
134RPC extension UI requests are rendered as normal stream items or dialogs:
136- `select`, `confirm`, `input`, `editor`,
137- `notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`.
139## Web transport
141### Binding and auth
143Use LAN HTTP with random token.
145- Bind to `0.0.0.0` or selected LAN interface.
146- Prefer a stable port if configured; otherwise port `0`.
147- Generate a 32-byte base64url token.
148- URL format: `http://<lan-ip>:<port>/?token=<token>`.
149- First HTML load requires query token and sets a `SameSite=Strict` cookie.
150- API and WebSocket require `Authorization: Bearer <token>` or auth cookie.
151- Never log the token except inside the terminal widget link/QR.
152- Restrict CORS to same origin.
154This follows the diff-review token pattern, but changes binding from `127.0.0.1` to LAN for mobile.
156### Browser lifecycle awareness
158The extension must quickly learn:
160- page close,
161- tab inactive,
162- browser crash,
163- network disconnect,
164- WebSocket close,
165- stale client heartbeat.
167Mechanisms:
169- browser sends heartbeat every few seconds while visible,
170- server marks client inactive on missed heartbeats,
171- browser sends `visibilitychange` events,
172- browser uses `pagehide` and `navigator.sendBeacon()` or `fetch(..., { keepalive: true })` for best-effort close notice,
173- server times out missing clients,
174- RPC continues unless `/ui off` or explicit stop occurs.
176Human-facing connection errors must say exactly what happened and what to do. Agent-facing errors must include fix instructions, likely cause, and whether retry is safe.
178## Event and data flow
180```text
181RPC stdout JSONL
182 -> server parser
183 -> typed event bus
184 -> ordered event store
185 -> replay ring buffer
186 -> browser WebSocket
187 -> worker parse/batch
188 -> main-thread render store
189 -> stream components
191browser input
192 -> command builder
193 -> server auth
194 -> RPC stdin queue
195 -> RPC prompt/steer/follow_up/etc.
196```
198### Event model
200Every server-side event sent to browsers has:
202- `seq`: monotonically increasing number,
203- `time`: server timestamp,
204- `source`: `rpc | ui | telemetry | server`,
205- `type`: stable string,
206- `payload`: JSON payload,
207- optional `rpcId`, `messageId`, `toolCallId`, `entryId`, `widgetId`.
209Browsers request a snapshot first, then subscribe from the latest `seq`. Reconnect uses `?since=<seq>`. If replay buffer no longer contains `since`, server sends a fresh snapshot.
211### Queues
213Server queues:
215- one RPC stdin command queue to serialize writes and correlate responses,
216- one RPC stdout event queue from JSONL parser,
217- one browser replay ring buffer,
218- one telemetry digest queue per browser/client,
219- one visual-widget event queue per widget id.
221Browser queues:
223- Worker receives WebSocket messages,
224- Worker parses and batches events,
225- main thread applies batches on `requestAnimationFrame`,
226- high-volume token/tool updates coalesce by message/tool id,
227- telemetry events aggregate off the hot render path.
229Do not depend on `scheduler.postTask`; support is limited. Use `requestAnimationFrame`, `MessageChannel`, and normal microtasks.
231## Web UI shell
233The shell is deterministic, stream-first, brutal, minimal, and Nugu-themed.
235Layout:
237- tiny top strip: Pi mark, running/disconnected state, `/ui off`,
238- central stream: all important things appear here,
239- bottom status strip: model, thinking, context,
240- bottom composer: normal Pi input syntax.
242No permanent sidebars by default. Contextual inspectors may appear only when a message/tool/widget is selected.
244### Stream item types
246The central stream renders:
248- user messages,
249- assistant text/thinking,
250- tool call/update/result,
251- visual widgets,
252- extension UI dialogs,
253- notifications,
254- warnings/errors,
255- permission prompts,
256- compaction/retry/status events,
257- telemetry digest when it will affect the next user prompt.
259User messages must visually dominate as primary anchors: strong border, high contrast, distinct spacing, and clear “YOU” label.
261Tool and visual blocks support selected-item expand/collapse. Keyboard shortcut behavior should match terminal Pi where possible, especially Esc abort, Ctrl+O expand/collapse selected, Ctrl+P model cycling, and slash command flow.
263### Composer
265The composer must preserve Pi syntax and expectations:
267- `/` commands and command autocomplete,
268- `/skill:*` skill invocation,
269- prompt templates,
270- `@` file/image references,
271- `!` and `!!` bash behavior where RPC supports it or equivalent web command flow,
272- Enter to submit,
273- Shift+Enter newline,
274- Esc abort when running,
275- paste handling,
276- image/file attachment.
278The composer should not have redundant buttons for actions that are better done by keybind or command. Buttons may exist only where mobile needs tap targets, and they must not clutter desktop.
280### Status
282Persistent status is intentionally tiny:
284- selected model,
285- thinking level,
286- context usage.
288Everything else appears where it matters:
290- notifications/warnings/errors in stream,
291- permission prompts in stream/dialog,
292- queued prompts near composer only when non-empty and understandable,
293- widget expand/collapse on the widget itself,
294- connection state in top strip and stream error when broken.
296## Accepted mockup
298The accepted direction is “terminal-like web”: pure stream plus Pi-capable composer, with Nugu/system-theme refinements.
300Key review notes incorporated:
302- messages, tools, and visuals all live in the main middle stream,
303- user messages must stand out strongly,
304- avoid useless side chrome and implementation detail labels,
305- status belongs near the composer and must be meaningful,
306- normal Pi syntax must work exactly as expected,
307- redundant buttons should be removed on desktop,
308- use Nugu and system theme,
309- use modern CSS so agent HTML still flows inside deterministic layout,
310- use Pierre/Shiki for beautiful diffs/highlighting,
311- browser close/inactive/crash errors must be detected and actionable.
313Representative mockup fragment:
315```html
316<style>
317.nugu-ui {
318 --bg: #070706;
319 --panel: #11100d;
320 --text: #f3efe5;
321 --muted: #9d9486;
322 --accent: #ff6a2a;
323 --minor: #2a2722;
324 --warn: #ffd35a;
325 --focus: #fff;
326 font: 14px ui-monospace, SFMono-Regular, Menlo, monospace;
327 background: var(--bg);
328 color: var(--text);
329 border: 4px solid var(--focus);
330 min-height: 580px;
331 display: grid;
332 grid-template-rows: 34px minmax(0, 1fr) 128px;
333}
334@media (prefers-color-scheme: light) {
335 .nugu-ui {
336 --bg: #f8f5ee;
337 --panel: #eee7d8;
338 --text: #17140f;
339 --muted: #70695f;
340 --accent: #b84722;
341 --minor: #d8cfc0;
342 --warn: #9c6a00;
343 --focus: #111;
344 }
345}
346.nugu-ui .top {
347 display: flex;
348 align-items: center;
349 justify-content: space-between;
350 border-bottom: 3px solid var(--minor);
351 padding: 0 12px;
352 background: var(--panel);
353 color: var(--muted);
354}
355.nugu-ui .stream {
356 max-width: 960px;
357 margin: auto;
358}
359.nugu-ui .row {
360 display: grid;
361 grid-template-columns: 92px minmax(0, 1fr);
362 gap: 14px;
363 margin: 0 0 14px;
364}
365.nugu-ui .who {
366 color: var(--muted);
367 text-align: right;
368 padding-top: 12px;
369 font-weight: 1000;
370}
371.nugu-ui .bubble {
372 border: 3px solid var(--minor);
373 background: var(--panel);
374 padding: 13px;
375 min-width: 0;
376}
377.nugu-ui .user {
378 border: 5px solid var(--focus);
379 background: var(--focus);
380 color: var(--bg);
381 box-shadow: 8px 8px 0 var(--accent);
382 font-size: 17px;
383 font-weight: 900;
384}
385.nugu-ui .visual {
386 border: 4px solid var(--accent);
387 background: var(--panel);
388 color: var(--text);
389 box-shadow: 8px 8px 0 var(--focus);
390 padding: 18px;
391 container-type: inline-size;
392 overflow: auto;
393 contain: layout paint;
394}
395.nugu-ui .bottom {
396 border-top: 4px solid var(--focus);
397 background: var(--panel);
398}
399.nugu-ui .status {
400 display: flex;
401 align-items: center;
402 justify-content: space-between;
403 padding: 7px 12px;
404 border-bottom: 2px solid var(--minor);
405 color: var(--muted);
406}
407.nugu-ui .editor {
408 border: 4px solid var(--focus);
409 background: var(--bg);
410 min-height: 58px;
411 padding: 10px;
412 color: var(--text);
413 box-shadow: 6px 6px 0 var(--minor);
414}
415</style>
416<div class="nugu-ui">
417 <div class="top">
418 <div class="brand">π</div>
419 <div>running</div>
420 <div>/ui off</div>
421 </div>
422 <main class="mid">
423 <div class="stream">
424 <div class="row">
425 <div class="who">YOU</div>
426 <div class="bubble user">I want Nugu, modern web, all Pi syntax.</div>
427 </div>
428 <div class="row">
429 <div class="who">TOOL</div>
430 <div class="bubble">Pierre diff / Shiki code block</div>
431 </div>
432 <div class="row">
433 <div class="who">VISUAL</div>
434 <div class="visual">Constrained full-JS widget</div>
435 </div>
436 </div>
437 </main>
438 <div class="bottom">
439 <div class="status">
440 <div><strong>sonnet</strong> · medium · ctx 31%</div>
441 <div>Esc abort · Ctrl+O expand · Ctrl+P model · / · @ · !</div>
442 </div>
443 <div class="composer"><div class="editor">Message Pi…</div></div>
444 </div>
445</div>
446```
448## Visual widget system
450Agents get UI tools injected into the web RPC session. Tool names are implementation detail, but tool families are:
452- visual message/card,
453- structured data/table,
454- diagram,
455- form/control,
456- mockup/prototype,
457- raw HTML/CSS/JS widget,
458- update/patch existing widget,
459- wait for widget user action.
461Every visual has:
463- stable `widgetId`,
464- title/label,
465- fallback text for agent context and terminal export,
466- expand/collapse state,
467- lifecycle: mounted, updated, action, closed, errored,
468- whether it expects user response,
469- telemetry summary scope.
471### Full JS policy
473Full JS widgets are allowed by default. They receive `window.pi` inside their execution context.
475`window.pi` exposes controlled methods:
477- send a widget action/result,
478- request agent prompt/steer/follow-up,
479- read current widget state,
480- subscribe to widget-scoped events,
481- update the widget payload,
482- show a local notification,
483- request file/image attachment through host UI.
485Full-JS widgets are trusted agent output, not untrusted third-party apps. They may impersonate user-like actions through `window.pi` and may use browser/network capabilities available to the page. The UI must make this trust boundary visible:
487- visual blocks show “full JS / trusted” in expanded metadata,
488- widget errors identify widget id and tool call id,
489- all widget-originated prompts/actions are visibly attributed in stream,
490- `window.pi` calls are audited in details available to the agent.
492### Layout constraints for agent HTML
494Agent HTML must flow inside deterministic stream layout.
496- Mount each widget in a bounded visual block.
497- Do not use iframe sandboxing or a separate permission wall for full JS.
498- Use `iframe srcdoc`, Shadow DOM, or equivalent document/layout boundary only to keep CSS, layout, and lifecycle contained.
499- Prototype result: unsandboxed `iframe srcdoc` can call parent `window.pi` in system Chrome and Playwright Firefox.
500- Prototype result: a host-bounded iframe with intentionally over-wide/tall content can fit the stream on a 390px mobile viewport in system Chrome and Playwright Firefox when the host applies `width: 100%`, overflow containment, and capped height negotiation.
501- Container gets fixed stream width, `max-width: 100%`, overflow boundary, and resize observer.
502- Host applies a minimal reset and Nugu CSS variables.
503- Widget document receives theme variables and container dimensions.
504- Use CSS containment: `contain: layout paint`, `content-visibility` where safe.
505- Use container queries for responsive widget internals.
506- Widget cannot resize the whole page except through explicit host height negotiation.
508## Diffs and code highlighting
510Use modern high-quality rendering:
512- Pierre for file diffs, preferably SSR/preload where possible.
513- Shiki for code highlighting, lazy and cached.
514- Show plain text immediately for long code, then upgrade async.
515- Never block startup on Shiki cold init.
516- Large tool/code outputs use truncation, lazy expansion, and virtualized rendering.
517- Diffs must support collapsed summary, expanded file-level view, line anchors, copied hunks, and annotations where needed.
519## Telemetry
521The browser tracks user behavior transparently and summarizes it for the agent on the next user message.
523Tracked classes:
525- scroll position and scroll dwell by stream item,
526- click/tap positions and target ids,
527- pointer movement summaries,
528- focused/blurred tab time,
529- inactive time,
530- viewport size and device class,
531- selected text,
532- widget action events,
533- form dwell/abandon/submit,
534- error visibility and whether user saw it.
536Rules:
538- collect locally in browser/worker,
539- aggregate into digest, not raw spam,
540- show “telemetry digest will be sent” when non-empty,
541- attach digest to next user prompt as hidden or visible context according to implementation choice, but it must be inspectable by user,
542- cap digest size,
543- redact obvious secrets from selected text and input fields,
544- do not send telemetry while no user prompt is sent,
545- clear sent digest after successful prompt acceptance.
547Example digest:
549```text
550UI telemetry since last message:
551- Viewed visual widget visual-42 for 18s.
552- Clicked Approve in visual-42.
553- Scrolled bash tool result tool-17 to bottom.
554- Tab inactive for 4m12s.
555- Form requirements-form abandoned after editing field “scope”.
556```
558## Error model
560Errors are first-class stream items and must be actionable.
562Every error has:
564- `code`,
565- severity,
566- human title,
567- precise human description,
568- human action,
569- agent hint,
570- source component,
571- retryability,
572- related ids/session path/log path.
574Human error example:
576```text
577Browser disconnected
578No heartbeat from Chrome for 12s. The RPC session is still running.
579Action: reload the QR/link page, or run /ui off to stop it.
580```
582Agent error example:
584```text
585ui_widget_render_failed
586Widget visual-42 threw ReferenceError: foo is not defined.
587Fix: call ui_update_widget with corrected JS, or replace widget with fallback HTML.
588```
590Error categories:
592- server bind failure,
593- no LAN address,
594- QR generation failure,
595- RPC spawn failure,
596- RPC JSON parse failure,
597- RPC process exit,
598- WebSocket disconnect,
599- browser inactive/closed/crashed,
600- auth failure,
601- widget render/runtime failure,
602- telemetry send failure,
603- session fork failure,
604- unsupported terminal OSC.
606## Performance architecture
608Browser target: current Chrome and Firefox only.
610Use:
612- normal WebSocket, not `WebSocketStream` because it is experimental/nonstandard,
613- HTTP snapshot + WebSocket events,
614- Dedicated Worker for WS parsing and telemetry aggregation,
615- optional SharedWorker later for multi-tab single-socket behavior,
616- native `EventTarget` as in-page event bus,
617- `BroadcastChannel` for same-browser tab coordination,
618- Web Locks only if multi-tab write coordination becomes necessary,
619- Web Components for message/tool/visual cards,
620- no framework by default,
621- CSS Grid/Flex, container queries, CSS containment,
622- `content-visibility: auto` for long stream items,
623- virtualization after a configurable item threshold,
624- `requestAnimationFrame` batching for DOM updates,
625- `MessageChannel` for cooperative chunks,
626- `OffscreenCanvas` only for heavy canvas widgets/diagrams.
628Avoid:
630- React/Vue/Angular,
631- old-browser polyfills,
632- `scheduler.postTask` as required dependency,
633- WebSocketStream,
634- main-thread JSON parsing for high-volume streams,
635- unbounded DOM growth,
636- layout measurement loops.
638## Package structure
640```text
641extensions/ui/
642 package.json
643 index.ts
644 server.ts
645 rpc.ts
646 session-seed.ts
647 terminal-widget.ts
648 qr.ts
649 protocol.ts
650 errors.ts
651 telemetry.ts
652 visual-tools.ts
653 web/
654 index.html.ts
655 app.css.ts
656 app.js.ts
657 worker.js.ts
658 components/*.ts
659 __tests__/
660 harness.test.ts
661 server.test.ts
662 rpc.test.ts
663 telemetry.test.ts
664 e2e.test.ts
665 README.md
666```
668Extension package requirements:
670- standalone package,
671- peer-depend on `@earendil-works/pi-coding-agent`,
672- dev-depend on `@marcfargas/pi-test-harness`,
673- include harness test,
674- no imports from other `@bugabinga/pi-ext-*` extensions,
675- startup fast: no blocking network, subprocess, or FS scans during `session_start`.
677Runtime startup work happens in `/ui` command, not extension load.
679## Commands
681### `/ui`
683Start UI mode. If already active, show current link/QR/status.
685Optional future args:
687- `--host <ip|0.0.0.0>`
688- `--port <port>`
689- `--local`
690- `--no-open`
691- `--no-qr`
692- `--session <path>`
694Argument autocomplete is required if subcommands/options are implemented.
696### `/ui off`
698Stop UI mode and restore terminal UI.
700### `/ui status`
702Show server URL, browser count, RPC status, web session path, last error.
704### `/ui open`
706Open browser again using desktop opener.
708### `/ui qr`
710Re-render QR/link widget.
712## Testing strategy
714### Unit tests
716Server/auth:
718- token required for `/`, APIs, and WebSocket,
719- query token sets cookie,
720- Bearer auth works,
721- bad token gets 401,
722- LAN URL generation chooses expected address,
723- body size limits,
724- CORS same-origin only.
726RPC bridge:
728- JSONL parser splits LF only,
729- parse errors become actionable events,
730- command ids correlate with responses,
731- stdin command queue serializes writes,
732- stdout events keep order,
733- subprocess exit generates typed error,
734- stderr is captured without leaking token.
736Session seed:
738- `createBranchedSession(getLeafId())` selected when source session file exists,
739- exact active branch preserved,
740- whole-tree `forkFrom` fallback warns that abandoned branches are included,
741- parent session recorded,
742- display name set,
743- ephemeral source fallback behaves as specified,
744- failure gives actionable error.
746Event store:
748- monotonic sequence,
749- snapshot includes current state,
750- replay after reconnect,
751- replay miss triggers snapshot,
752- high-volume updates coalesce correctly.
754Telemetry:
756- scroll/click/focus/pagehide events aggregate,
757- digest size cap,
758- digest redaction,
759- digest attaches once to next prompt,
760- inactive/browser closed states detected.
762Visual tools:
764- widget ids stable,
765- fallback text returned to agent,
766- full-JS widget mount event emitted,
767- widget action flows to agent/web stream,
768- widget runtime error creates human+agent actionable error.
770Theme/rendering:
772- Nugu dark/light variables emitted,
773- `prefers-color-scheme` works,
774- stream item classes render expected roles,
775- user message has dominant styling.
777### Pi extension harness tests
779Use the real Pi extension runtime.
781- extension loads without side effects,
782- `/ui` command registers,
783- `/ui off/status/open/qr` commands register,
784- `/ui` starts runtime from command, not `session_start`,
785- terminal widget appears,
786- `/ui off` clears widget and restores UI state,
787- duplicate `/ui` is idempotent,
788- session_shutdown cleans subprocess/server/timers,
789- ESC terminal input cancels UI mode,
790- visual tools register only for the web RPC session as designed.
792### Web unit/component tests
794Use browser-capable tests where possible.
796- WebSocket worker batches events,
797- components render message/tool/visual/error/notice rows,
798- selected item expand/collapse,
799- keyboard shortcuts dispatch expected commands,
800- composer handles Enter/Shift+Enter/Esc,
801- command autocomplete renders slash commands and skills,
802- `@` references and `!` bash parsing match Pi expectations,
803- mobile layout hides nothing essential,
804- iframe widget bridge exposes `window.pi`,
805- iframe widget layout does not create page-level horizontal overflow in Chrome or Firefox,
806- widget height negotiation stays bounded.
808### E2E tests
810Use Playwright with real server and fake or real RPC subprocess depending on test tier.
812Critical flows:
814- run `/ui`, obtain URL/token, open browser,
815- QR URL and link route to same authenticated page,
816- initial snapshot shows exact active-branch seeded session history,
817- send prompt from web, observe RPC events stream,
818- invoke slash command,
819- invoke `/skill:*`,
820- test command autocomplete,
821- attach `@` file/image reference,
822- run `!` bash equivalent,
823- model cycle via Ctrl+P,
824- expand/collapse via Ctrl+O,
825- abort via Esc,
826- tool call start/update/end renders,
827- visual full-JS widget mounts and sends action,
828- telemetry digest appears and is attached to next prompt,
829- tab inactive/active changes state,
830- close tab triggers heartbeat lost,
831- kill RPC subprocess shows actionable error,
832- kill/restart browser reconnects through snapshot/replay,
833- `/ui off` disconnects browser and restores terminal UI.
835## Manual testing playbook
837Run this in a real terminal with tmux and a real browser, not only automated tests.
839### Setup
8411. Open tmux session.
8422. Start real `pi` in `C:/Users/okr/Workspace/dotfiles/pi-ext`.
8433. Confirm repo has visible session history.
8444. Run `/ui`.
8455. Verify terminal becomes minimal widget with OSC link, QR, ESC help, `/ui off` help, connection state.
8466. Open desktop browser link.
8477. Scan QR from phone on same LAN.
849### Startup/session
851- Verify web loads with token.
852- Verify bad/missing token gets precise 401 page.
853- Verify web session is a persistent normal Pi session.
854- Verify web session history is seeded from the terminal active branch.
855- Verify terminal and web sessions can both receive prompts independently.
856- Verify web session appears in Pi session list with clear name and parent link.
858### Pi syntax/composer
860- Type normal prompt, verify response.
861- Use `/` autocomplete.
862- Invoke a prompt template command.
863- Invoke `/skill:<name>`.
864- Use `@` file reference.
865- Attach image/file if available.
866- Run `!pwd` or equivalent user bash.
867- Verify `!!` exclude-from-context behavior if supported.
868- Paste multi-line text.
869- Use Shift+Enter newline and Enter send.
871### Keybindings/status
873- Esc aborts running agent.
874- Ctrl+P cycles model.
875- Change thinking level if key/command is available.
876- Ctrl+O expands/collapses selected tool/visual block.
877- Verify status shows model, thinking, context usage.
878- Verify warnings/errors/notifications appear as stream items.
879- Verify permission/confirm/select/input/editor extension UI requests are usable.
881### Tools and stream
883- Ask agent to run `bash`, `read`, `grep`, `find`, `ls`, `edit` on safe files.
884- Verify tool start/update/end render live.
885- Verify long tool output is collapsed and expandable.
886- Verify edit diffs render beautifully with Pierre.
887- Verify code blocks highlight with Shiki after lazy upgrade.
888- Verify compaction/retry events display clearly.
890### Visual widgets
892- Ask agent to create a visual card.
893- Ask for a form with controls.
894- Ask for a diagram/prototype/mockup.
895- Ask for full HTML/CSS/JS interactive widget.
896- Click widget buttons and verify actions reach agent/stream.
897- Verify widget can update itself through `window.pi`.
898- Intentionally create widget JS error and verify human+agent error guidance.
899- Verify widget remains bounded and responsive on desktop and phone.
901### Telemetry
903- Scroll stream and tool output.
904- Click visual widget.
905- Select text.
906- Leave tab inactive for at least 30 seconds.
907- Return and send next prompt.
908- Verify telemetry digest is shown/inspectable and attached once.
909- Verify digest does not include obvious secret-like input.
911### Browser/mobile lifecycle
913- Close browser tab; terminal/web status should detect close/heartbeat loss.
914- Reopen link; snapshot/replay restores state.
915- Put phone browser in background; inactive state detected.
916- Disable phone Wi-Fi briefly; disconnect is clear and recoverable.
917- Kill browser process; server detects stale heartbeat.
919### Failure handling
921- Start `/ui` when preferred port is busy.
922- Start `/ui` with no LAN address if possible.
923- Kill RPC subprocess.
924- Break WebSocket auth token.
925- Force malformed RPC line in fake/dev mode if available.
926- Verify every failure gives exact action for human and fix hint for agent.
928### Shutdown/restore
930- Run `/ui status`.
931- Run `/ui qr`.
932- Run `/ui open`.
933- Press ESC in terminal widget.
934- Start again, then run `/ui off`.
935- Verify server stops, browser disconnects, RPC exits, terminal UI restores, and web session persists.
937## Open implementation risks
939- Extension APIs cannot truly replace the whole terminal UI; design intentionally minimizes terminal UI instead.
940- Exact active-branch seeding should use `createBranchedSession(getLeafId())`; `forkFrom` copies the whole tree and should not be the default.
941- RPC mode does not support some interactive-only UI methods; web must emulate or degrade.
942- `!`/`!!` exact terminal semantics may need explicit web-side mapping to RPC `bash`.
943- Full JS widgets are powerful and risky; attribution/audit is mandatory.
944- Mobile LAN HTTP is token-protected but not encrypted.
946## Planning recommendation
948This is large enough for a phased roadmap, not a single implementation plan.
950Suggested phases:
9521. Extension command + terminal widget + LAN auth server + QR.
9532. Active-branch RPC subprocess + event bridge + basic web stream/composer.
9543. Pi syntax, commands, skills, keybindings, status, extension UI protocol.
9554. Visual tools and full-JS widget bridge.
9565. Telemetry digest and lifecycle detection.
9576. Nugu polish, Pierre/Shiki rendering, virtualization/perf.
9587. Complete tests and manual playbook hardening.

extensions/ui/README.md

Deleted
deleted file mode 100644

+0 / −77 text lines

1# ui
2
3Browser UI runtime shell for Pi.
4
5## Install / load
6
7Loaded through the root [pi-ext](../../README.md) package.
8
9## Commands
11- `/ui` — start LAN web shell, token URL, QR, terminal widget, seeded RPC session.
12- `/ui off` — stop server/RPC and restore terminal widget state.
13- `/ui status` — show runtime URL, clients, state, and last error.
14- `/ui open` — open current URL in desktop browser.
15- `/ui qr` — redraw QR/link widget.
17## Behavior
19`/ui` starts a token-authenticated LAN browser UI backed by a seeded Pi RPC session.
20The browser stream supports normal prompts, slash commands, bash shorthands, extension UI requests, trusted visual widgets, telemetry digest attachment, lifecycle errors, lazy code/diff rendering, and Nugu brutal/minimal styling.
22## Security and trust model
24Transport is HTTP on LAN with a random bearer token in the URL/cookie.
25There is no HTTPS.
26Treat the URL as secret.
27The browser UI is for trusted local/LAN use only.
29Agent-created visual widgets are trusted full HTML/CSS/JS.
30They are not sandboxed.
31Widget actions are audited and visibly attributed before widget-originated prompts reach the Pi session.
33## E2E
35Run root `mise run e2e` first to install browsers and execute every extension suite.
36After that bootstrap, run `mise run e2e` here, or `mise //extensions/ui:e2e` from the repository root, to test only the browser UI in Chromium and Firefox.
37The real Pi RPC smoke remains opt-in through `UI_REAL_RPC_SMOKE=1`.
39## Manual smoke
41On win32, use zellij, never tmux:
43```sh
44node extensions/ui/scripts/zellij-smoke.mjs
45```
47On non-win32, use tmux where available:
49```sh
50node extensions/ui/scripts/tmux-smoke.mjs
51```
53Full checkpoints live in [docs/manual-playbook.md](docs/manual-playbook.md).
55## Mockup parity audit
57The accepted mockup was treated as visual direction, not a finished parity checklist.
58That was wrong for user expectations.
59Implemented now: stream-first shell, Nugu theme, sticky bottom composer, token auth, RPC stream, command input, dialogs, trusted widgets, code/diff rendering, telemetry digest, and no sidebars.
60Still incomplete versus the representative mockup/spec: richer top strip with Pi mark and `/ui off`, meaningful bottom status strip for model/thinking/context, stronger `YOU` labels, selected-item inspector, clearer tool lifecycle cards, and polished mobile status/actions.
61Track these as UI polish/parity work, not transport/runtime work.
63## Troubleshooting
65- `401` means the token is missing or stale; reopen `/ui` or rescan QR.
66- Browser says disconnected: run `/ui status`, then `/ui open` or restart with `/ui off` and `/ui`.
67- RPC unavailable: verify `pi` is on `PATH` and the seeded session can start in the current repo.
68- Browser features target modern Chrome/Firefox only.
69- Parallel terminal/browser edits are allowed and can race.
71## Package invariants
73- Private package.
74- `main` is `index.ts`.
75- MIT license.
76- Pi packages are peer dependencies.
77- Tests use Vitest, Pi harness, and Playwright E2E.

extensions/ui/__e2e__/fake-rpc.spec.ts

Deleted
deleted file mode 100644

+0 / −100 text lines

1import { expect, test } from "@playwright/test";
2import { EventStore } from "../events";
3import { startUiServer, type UiServer } from "../server";
4
5let server: UiServer | undefined;
6
7test.afterEach(async () => {
8 await server?.close("e2e cleanup");
9 server = undefined;
10});
12test("auth shell, stream, composer, widget, telemetry, and shutdown", async ({
13 page,
14 request,
15}) => {
16 const pageErrors: string[] = [];
17 page.on("pageerror", (error) => pageErrors.push(error.message));
18 const events = new EventStore();
19 events.append({ type: "message", role: "assistant", text: "ready" });
20 for (let index = 0; index < 80; index += 1) {
21 events.append({
22 type: "message",
23 role: "assistant",
24 text: `history line ${index}`,
25 });
26 }
27 events.append({
28 type: "widget_mount",
29 widgetId: "widget-e2e",
30 toolCallId: "call-e2e",
31 title: "Widget",
32 fallback: "Widget fallback",
33 html: "<button onclick=\"window.pi.action('clicked')\">click</button>",
34 status: "mounted",
35 });
36 server = await startUiServer({
37 address: "127.0.0.1",
38 events,
39 commands: [{ name: "ui", description: "Browser UI" }],
40 onBrowserMessage(message) {
41 if (isPrompt(message)) {
42 const event = events.append({
43 type: "message",
44 role: "assistant",
45 text: `echo ${message.text}`,
46 });
47 server?.publish(event);
48 }
49 if (isTelemetry(message)) {
50 const event = events.append({
51 type: "log",
52 level: "info",
53 message: "browser digest will be sent",
54 });
55 server?.publish(event);
56 }
57 },
58 });
60 const unauthorized = await request.get(server.baseUrl + "/api/status");
61 expect(unauthorized.status()).toBe(401);
62 await page.goto(server.publicUrl);
63 await expect(page.locator("#ui-progress")).toHaveText(
64 /starting|connected|waiting|rpc/,
65 );
66 if (pageErrors.length) throw new Error(pageErrors.join("\n"));
67 await expect(page.locator("#ui-stream")).toContainText("ready");
68 await expect(page.locator("#ui-stream")).toContainText("history line 79");
69 await expect(page.locator("#ui-stream")).toContainText("Widget fallback");
70 await expect(page.locator("#ui-composer")).toBeInViewport();
71 expect(
72 await page.evaluate(
73 () => document.documentElement.scrollHeight <= window.innerHeight,
74 ),
75 ).toBe(true);
77 await page.locator("#ui-input").fill("hello e2e");
78 await page.locator("#ui-send").click();
79 await expect(page.locator("#ui-stream")).toContainText("echo hello e2e");
81 await page.evaluate(() => scrollTo(0, 50));
82 await page.waitForTimeout(1_100);
83 await expect(page.locator("#ui-digest")).toContainText(/digest/);
84});
86function isPrompt(value: unknown): value is { type: "prompt"; text: string } {
87 return (
88 !!value &&
89 typeof value === "object" &&
90 (value as { type?: unknown }).type === "prompt"
91 );
92}
94function isTelemetry(value: unknown): value is { type: "telemetry_batch" } {
95 return (
96 !!value &&
97 typeof value === "object" &&
98 (value as { type?: unknown }).type === "telemetry_batch"
99 );
100}

extensions/ui/__e2e__/real-rpc-smoke.spec.ts

Deleted
deleted file mode 100644

+0 / −14 text lines

1import { spawnSync } from "node:child_process";
2import { expect, test } from "@playwright/test";
3
4test("real Pi RPC smoke prerequisites", async () => {
5 test.skip(
6 process.env.UI_REAL_RPC_SMOKE !== "1",
7 "Set UI_REAL_RPC_SMOKE=1 to run the real Pi RPC/browser smoke tier.",
8 );
9 const pi = process.platform === "win32" ? "pi.cmd" : "pi";
10 const probe = spawnSync(pi, ["--version"], { encoding: "utf8" });
11 const error = probe.error as NodeJS.ErrnoException | undefined;
12 test.skip(error?.code === "ENOENT", "pi CLI is unavailable on PATH.");
13 expect(probe.status).toBe(0);
14});

extensions/ui/__tests__/cleanup.test.ts

Deleted
deleted file mode 100644

+0 / −87 text lines

1import path from "node:path";
2import { afterEach, describe, expect, it } from "vitest";
3import WebSocket from "ws";
4import { createTestSession, type TestSession } from "../../../test/harness";
5import { createUiRuntime, type UiRuntime } from "../runtime";
6
7const runtimes: Array<{ stop(reason: string): Promise<void> }> = [];
8let t: TestSession | undefined;
9
10describe("ui cleanup", () => {
11 afterEach(async () => {
12 while (runtimes.length) await runtimes.pop()?.stop("test cleanup");
13 t?.dispose();
14 t = undefined;
15 });
17 it("stops runtime idempotently after socket close", async () => {
18 const sent: unknown[] = [];
19 const runtime = await createUiRuntime({
20 sessionLabel: "ui: cleanup",
21 address: "127.0.0.1",
22 cwd: "C:/repo",
23 openBrowser: false,
24 sessionManager: fakeSessionManager(),
25 startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
26 });
27 runtimes.push(runtime);
28 const socket = await connectRuntimeSocket(runtime);
29 socket.close();
30 await new Promise((resolve) => setTimeout(resolve, 20));
32 await runtime.stop("first");
33 await runtime.stop("second");
34 expect(runtime.status().active).toBe(false);
35 expect(sent).toContainEqual({ type: "close", reason: "first" });
36 });
38 it("/ui off removes terminal widget even when inactive", async () => {
39 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
40 t = await createTestSession({ extensions: [extensionPath] });
41 const command = t.session.extensionRunner.extensions[0].commands.get("ui");
42 expect(command).toBeDefined();
44 await command?.handler(
45 "off",
46 t.session.extensionRunner.createCommandContext(),
47 );
49 expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
50 "ui",
51 undefined,
52 ]);
53 });
54});
56async function connectRuntimeSocket(runtime: UiRuntime): Promise<WebSocket> {
57 const url = new URL(runtime.status().url ?? "");
58 const response = await fetch(url);
59 const cookie = response.headers.get("set-cookie") ?? "";
60 const socketUrl = new URL("/ws", url);
61 socketUrl.protocol = "ws:";
62 const socket = new WebSocket(socketUrl, { headers: { cookie } });
63 await new Promise((resolve) => socket.once("open", resolve));
64 return socket;
65}
67function fakeSessionManager() {
68 return {
69 getLeafId: () => "leaf",
70 createBranchedSession: () => ({ path: "C:/repo/.pi/sessions/ui.json" }),
71 };
72}
74function fakeRpc(sent: unknown[], sessionPath: string) {
75 return {
76 state: () => "connected",
77 sessionPath,
78 send(request: unknown) {
79 sent.push(request);
80 return Promise.resolve({ type: "response", success: true });
81 },
82 close(reason: string) {
83 sent.push({ type: "close", reason });
84 return Promise.resolve();
85 },
86 };
87}

extensions/ui/__tests__/command-adapter.test.ts

Deleted
deleted file mode 100644

+0 / −84 text lines

1import { describe, expect, it } from "vitest";
2import {
3 abortCurrent,
4 compactSession,
5 cycleModel,
6 cycleThinking,
7 runBash,
8 runSlashCommand,
9 sendPrompt,
10} from "../command-adapter";
12describe("ui rpc command adapters", () => {
13 it("sends normal prompts", async () => {
14 const rpc = fakeRpc();
15 await sendPrompt(rpc, "hello");
16 expect(rpc.sent).toEqual([{ type: "prompt", message: "hello" }]);
17 });
19 it("attaches digest once to the next prompt", async () => {
20 const rpc = fakeRpc();
21 let digest = "Browser digest:\n- click SEND";
22 await sendPrompt(rpc, "hello", {
23 digest: () => digest,
24 clearDigest: () => {
25 digest = "";
26 },
27 });
28 await sendPrompt(rpc, "again", {
29 digest: () => digest,
30 clearDigest: () => {
31 digest = "";
32 },
33 });
34 expect(rpc.sent).toEqual([
35 {
36 type: "prompt",
37 message: "Browser digest:\n- click SEND\n\nUser prompt:\nhello",
38 },
39 { type: "prompt", message: "again" },
40 ]);
41 });
43 it("runs slash commands through prompt expansion", async () => {
44 const rpc = fakeRpc();
45 await runSlashCommand(rpc, "mode", "terse");
46 expect(rpc.sent).toEqual([{ type: "prompt", message: "/mode terse" }]);
47 });
49 it("runs bash and preserves context exclusion", async () => {
50 const rpc = fakeRpc();
51 await runBash(rpc, "git status", true);
52 expect(rpc.sent).toEqual([
53 { type: "bash", command: "git status", excludeFromContext: true },
54 ]);
55 });
57 it("cycles model and thinking", async () => {
58 const rpc = fakeRpc();
59 await cycleModel(rpc);
60 await cycleThinking(rpc);
61 expect(rpc.sent).toEqual([
62 { type: "cycle_model" },
63 { type: "cycle_thinking_level" },
64 ]);
65 });
67 it("compacts and aborts", async () => {
68 const rpc = fakeRpc();
69 await compactSession(rpc);
70 await abortCurrent(rpc);
71 expect(rpc.sent).toEqual([{ type: "compact" }, { type: "abort" }]);
72 });
73});
75function fakeRpc() {
76 const sent: unknown[] = [];
77 return {
78 sent,
79 send(request: unknown) {
80 sent.push(request);
81 return Promise.resolve({ type: "response", success: true });
82 },
83 };
84}

extensions/ui/__tests__/composer.test.ts

Deleted
deleted file mode 100644

+0 / −60 text lines

1import { describe, expect, it } from "vitest";
2import { parseComposerInput } from "../composer";
3
4describe("ui composer parser", () => {
5 it("parses plain prompts", () => {
6 expect(parseComposerInput("hello pi")).toEqual({
7 kind: "prompt",
8 text: "hello pi",
9 refs: [],
10 });
11 });
13 it("parses slash commands and arguments", () => {
14 expect(parseComposerInput("/mode terse now")).toEqual({
15 kind: "slash",
16 command: "mode",
17 args: "terse now",
18 text: "/mode terse now",
19 refs: [],
20 });
21 });
23 it("parses skill commands", () => {
24 expect(parseComposerInput("/skill:brutal make it short")).toEqual({
25 kind: "slash",
26 command: "skill:brutal",
27 args: "make it short",
28 text: "/skill:brutal make it short",
29 refs: [],
30 });
31 });
33 it("extracts at-references from prompts", () => {
34 expect(
35 parseComposerInput("read @README.md and @docs/spec.md please"),
36 ).toEqual({
37 kind: "prompt",
38 text: "read @README.md and @docs/spec.md please",
39 refs: ["README.md", "docs/spec.md"],
40 });
41 });
43 it("parses single-bang bash", () => {
44 expect(parseComposerInput("!git status --short")).toEqual({
45 kind: "bash",
46 command: "git status --short",
47 excludeFromContext: false,
48 refs: [],
49 });
50 });
52 it("parses double-bang bash as excluded from context", () => {
53 expect(parseComposerInput("!!node --version")).toEqual({
54 kind: "bash",
55 command: "node --version",
56 excludeFromContext: true,
57 refs: [],
58 });
59 });
60});

extensions/ui/__tests__/digest-indicator.test.ts

Deleted
deleted file mode 100644

+0 / −9 text lines

1import { describe, expect, it } from "vitest";
2import { digestIndicatorText } from "../web/components/digest-indicator.js";
3
4describe("ui digest indicator", () => {
5 it("describes pending digest state as a compact chip", () => {
6 expect(digestIndicatorText(0)).toBe("digest 0");
7 expect(digestIndicatorText(3)).toBe("digest 3");
8 });
9});

extensions/ui/__tests__/events.test.ts

Deleted
deleted file mode 100644

+0 / −53 text lines

1import { describe, expect, it } from "vitest";
2import { EventStore } from "../events";
3
4describe("ui event store", () => {
5 it("assigns monotonic ids and timestamps", () => {
6 const store = new EventStore({ maxEvents: 10, now: () => 1000 });
7
8 const first = store.append({ type: "state", state: "starting" });
9 const second = store.append({
10 type: "log",
11 level: "info",
12 message: "ready",
13 });
15 expect(first).toMatchObject({ id: 1, at: 1000, type: "state" });
16 expect(second).toMatchObject({ id: 2, at: 1000, type: "log" });
17 });
19 it("keeps a bounded replay buffer", () => {
20 const store = new EventStore({ maxEvents: 3, now: () => 1 });
22 for (let i = 0; i < 5; i++) {
23 store.append({ type: "log", level: "info", message: `event ${i}` });
24 }
26 expect(store.replayAfter(0).map((event) => event.id)).toEqual([3, 4, 5]);
27 expect(store.replayAfter(3).map((event) => event.id)).toEqual([4, 5]);
28 });
30 it("builds deterministic snapshots", () => {
31 const store = new EventStore({ maxEvents: 10, now: () => 7 });
32 store.append({ type: "state", state: "starting" });
33 store.append({ type: "message", role: "user", text: "hello" });
35 expect(
36 store.snapshot({
37 status: "connected",
38 sessionPath: "C:/tmp/ui.jsonl",
39 commands: [{ name: "ui", description: "browser ui" }],
40 }),
41 ).toEqual({
42 version: 1,
43 lastEventId: 2,
44 status: "connected",
45 sessionPath: "C:/tmp/ui.jsonl",
46 commands: [{ name: "ui", description: "browser ui" }],
47 events: [
48 { id: 1, at: 7, type: "state", state: "starting" },
49 { id: 2, at: 7, type: "message", role: "user", text: "hello" },
50 ],
51 });
52 });
53});

extensions/ui/__tests__/extension-ui.test.ts

Deleted
deleted file mode 100644

+0 / −110 text lines

1import { describe, expect, it } from "vitest";
2import {
3 extensionUiEventFromRequest,
4 extensionUiResponseCommand,
5 isExtensionUiRequest,
6} from "../extension-ui";
7
8describe("ui extension UI protocol", () => {
9 it("recognizes dialog requests", () => {
10 expect(
11 isExtensionUiRequest({
12 type: "extension_ui_request",
13 id: "u1",
14 method: "select",
15 title: "Pick",
16 options: ["a", "b"],
17 }),
18 ).toBe(true);
19 });
21 it("normalizes select requests into stream events", () => {
22 expect(
23 extensionUiEventFromRequest({
24 type: "extension_ui_request",
25 id: "u1",
26 method: "select",
27 title: "Pick one",
28 options: ["a", "b"],
29 }),
30 ).toEqual({
31 type: "ui_request",
32 requestId: "u1",
33 method: "select",
34 title: "Pick one",
35 message: "select: Pick one",
36 options: ["a", "b"],
37 expectsResponse: true,
38 });
39 });
41 it("normalizes fire-and-forget notify requests", () => {
42 expect(
43 extensionUiEventFromRequest({
44 type: "extension_ui_request",
45 id: "u2",
46 method: "notify",
47 message: "Blocked",
48 notifyType: "warning",
49 }),
50 ).toMatchObject({
51 type: "ui_notify",
52 requestId: "u2",
53 message: "Blocked",
54 notifyType: "warning",
55 });
56 });
58 it("preserves status request keys for the browser status strip", () => {
59 expect(
60 extensionUiEventFromRequest({
61 type: "extension_ui_request",
62 id: "s1",
63 method: "setStatus",
64 statusKey: "model-info",
65 statusText: "gpt-5 high",
66 }),
67 ).toMatchObject({
68 type: "ui_status",
69 requestId: "s1",
70 message: "gpt-5 high",
71 statusKey: "model-info",
72 statusText: "gpt-5 high",
73 });
74 });
76 it("keeps status clears empty instead of rendering setStatus", () => {
77 expect(
78 extensionUiEventFromRequest({
79 type: "extension_ui_request",
80 id: "s2",
81 method: "setStatus",
82 statusKey: "vcs",
83 statusText: undefined,
84 }),
85 ).toMatchObject({
86 type: "ui_status",
87 requestId: "s2",
88 message: "",
89 statusKey: "vcs",
90 });
91 });
93 it("creates response commands for values, confirmations, and cancellations", () => {
94 expect(extensionUiResponseCommand("u1", { value: "a" })).toEqual({
95 type: "extension_ui_response",
96 id: "u1",
97 value: "a",
98 });
99 expect(extensionUiResponseCommand("u2", { confirmed: true })).toEqual({
100 type: "extension_ui_response",
101 id: "u2",
102 confirmed: true,
103 });
104 expect(extensionUiResponseCommand("u3", { cancelled: true })).toEqual({
105 type: "extension_ui_response",
106 id: "u3",
107 cancelled: true,
108 });
109 });
110});

extensions/ui/__tests__/harness.test.ts

Deleted
deleted file mode 100644

+0 / −71 text lines

1import path from "node:path";
2import { afterEach, describe, expect, it } from "vitest";
3import { createTestSession, type TestSession } from "../../../test/harness";
4import { notifyUrl } from "../index";
5
6describe("ui notifications", () => {
7 it("omits token params from notification URLs", () => {
8 expect(notifyUrl("http://127.0.0.1:123/?token=abc")).toBe(
9 "http://127.0.0.1:123/",
10 );
11 });
12});
14describe("ui pi-test-harness", () => {
15 let t: TestSession | undefined;
17 afterEach(() => {
18 t?.dispose();
19 t = undefined;
20 });
22 it("loads in real Pi extension runtime", async () => {
23 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
24 t = await createTestSession({ extensions: [extensionPath] });
26 expect(t.session.extensionRunner.extensions).toHaveLength(1);
27 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
28 });
30 it("registers the /ui command without starting a runtime", async () => {
31 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
32 t = await createTestSession({ extensions: [extensionPath] });
33 const extension = t.session.extensionRunner.extensions[0];
35 expect([...extension.commands.keys()]).toEqual(["ui"]);
36 expect([...extension.tools.keys()]).toEqual([
37 "ui_card",
38 "ui_table",
39 "ui_diagram",
40 "ui_form",
41 "ui_mockup",
42 "ui_html",
43 "ui_update",
44 "ui_wait_action",
45 ]);
46 expect(t.events.uiCallsFor("setWidget")).toHaveLength(0);
47 });
49 it("reports an actionable seed error in an empty session", async () => {
50 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
51 t = await createTestSession({ extensions: [extensionPath] });
52 const command = t.session.extensionRunner.extensions[0].commands.get("ui");
53 expect(command).toBeDefined();
55 await command?.handler(
56 "",
57 t.session.extensionRunner.createCommandContext(),
58 );
60 expect(latestNotify(t)).toContain("Cannot seed UI session");
61 expect(latestNotify(t)).toContain("Action:");
62 expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
63 "ui",
64 undefined,
65 ]);
66 });
67});
69function latestNotify(t: TestSession): string {
70 return String(t.events.uiCallsFor("notify").at(-1)?.args[0] ?? "");
71}

extensions/ui/__tests__/lifecycle.test.ts

Deleted
deleted file mode 100644

+0 / −40 text lines

1import { describe, expect, it } from "vitest";
2import { LifecycleTracker } from "../lifecycle";
3
4describe("ui browser lifecycle", () => {
5 it("emits heartbeat timeout errors", () => {
6 const tracker = new LifecycleTracker({
7 now: () => 10_000,
8 heartbeatMs: 5_000,
9 });
10 tracker.heartbeat("client-1", 1_000);
11 expect(tracker.check()).toEqual([
12 expect.objectContaining({
13 type: "error",
14 clientId: "client-1",
15 message: "browser heartbeat lost",
16 retryable: true,
17 }),
18 ]);
19 });
21 it("emits close pagehide stale and reconnect lifecycle events", () => {
22 const tracker = new LifecycleTracker({ now: () => 20 });
23 expect(tracker.close("client-1")).toMatchObject({
24 type: "error",
25 message: "browser websocket closed",
26 });
27 expect(tracker.pagehide("client-1")).toMatchObject({
28 type: "error",
29 message: "browser page hidden/unloaded",
30 });
31 expect(tracker.stale("client-1")).toMatchObject({
32 type: "error",
33 message: "browser client stale",
34 });
35 expect(tracker.reconnect("client-1")).toMatchObject({
36 type: "log",
37 message: "browser reconnected: client-1",
38 });
39 });
40});

extensions/ui/__tests__/performance.test.ts

Deleted
deleted file mode 100644

+0 / −36 text lines

1import { describe, expect, it } from "vitest";
2import {
3 longOutputModel,
4 toggleLongOutput,
5} from "../web/components/long-output.js";
6import { virtualWindow } from "../web/components/virtual-stream.js";
7
8describe("ui stream performance guards", () => {
9 it("truncates long output and preserves expansion state", () => {
10 const text = "x".repeat(2_000);
11 expect(longOutputModel("e1", text, new Set(), 120)).toMatchObject({
12 id: "e1",
13 truncated: true,
14 text: "x".repeat(120),
15 });
16 const expanded = toggleLongOutput("e1", new Set());
17 expect(longOutputModel("e1", text, expanded, 120)).toMatchObject({
18 truncated: false,
19 text,
20 });
21 });
23 it("returns ordered virtual windows around selected item", () => {
24 const events = Array.from({ length: 100 }, (_, index) => ({
25 id: index + 1,
26 }));
27 expect(
28 virtualWindow(events, { selectedId: 50, threshold: 20, radius: 3 }).map(
29 (e) => e.id,
30 ),
31 ).toEqual([47, 48, 49, 50, 51, 52, 53]);
32 expect(
33 virtualWindow(events, { selectedId: 2, threshold: 200, radius: 3 }),
34 ).toEqual(events);
35 });
36});

extensions/ui/__tests__/rendering.test.ts

Deleted
deleted file mode 100644

+0 / −62 text lines

1import { describe, expect, it } from "vitest";
2import { renderAppJs } from "../web/app.js";
3import {
4 renderCodeBlockComponentJs,
5 renderPlainCodeBlock,
6} from "../web/components/code-block.js";
7import { diffSummary, renderDiffViewJs } from "../web/components/diff-view.js";
8
9describe("ui code and diff rendering", () => {
10 it("renders plaintext code immediately", () => {
11 expect(renderPlainCodeBlock("ts", "const x = 1;")).toContain(
12 "const x = 1;",
13 );
14 expect(renderPlainCodeBlock("ts", "const x = 1;")).toContain(
15 'data-language="ts"',
16 );
17 });
19 it("keeps Shiki lazy and optional", () => {
20 expect(renderCodeBlockComponentJs()).toContain("import('shiki')");
21 expect(renderCodeBlockComponentJs()).toContain("textContent");
22 });
24 it("summarizes diffs and emits Pierre lazy loader", () => {
25 expect(diffSummary("--- a/a.ts\n+++ b/a.ts\n+add\n-del\n context")).toEqual(
26 {
27 files: 1,
28 additions: 1,
29 deletions: 1,
30 },
31 );
32 expect(renderDiffViewJs()).toContain("import('pierre')");
33 });
35 it("coalesces streaming message updates by stream id", () => {
36 const js = renderAppJs();
37 expect(js).toContain("event.streamId");
38 expect(js).toContain("replaceWith(row)");
39 expect(js).toContain("finalizeStreamingRows()");
40 });
42 it("clears empty extension status instead of showing method names", () => {
43 const js = renderAppJs();
44 expect(js).toContain("statusItems.delete(String(key))");
45 expect(js).not.toContain("key + ': ' + 'setStatus'");
46 });
48 it("does not locally echo submitted prompts", () => {
49 const js = renderAppJs();
50 expect(js).not.toContain(
51 "Number.MAX_SAFE_INTEGER, at: Date.now(), type: 'message', role: 'user'",
52 );
53 });
55 it("keeps internal runtime chatter out of the main stream", () => {
56 const js = renderAppJs();
57 expect(js).toContain("isStreamEvent(event)");
58 expect(js).toContain("event.type === 'message'");
59 expect(js).toContain("event.type === 'ui_request'");
60 expect(js).not.toContain("JSON.stringify(event)");
61 });
62});

extensions/ui/__tests__/rpc.test.ts

Deleted
deleted file mode 100644

+0 / −112 text lines

1import { once } from "node:events";
2import { describe, expect, it } from "vitest";
3import { parseJsonLines, rpcSpawnPlan, startRpc } from "../rpc";
4
5const node = process.execPath;
6
7describe("ui rpc bridge", () => {
8 it("splits only on LF and keeps partial records", () => {
9 const parsed = parseJsonLines(
10 '{"type":"event","text":"a
b"}\r\n{"type":"partial"',
11 );
13 expect(parsed.messages).toEqual([{ type: "event", text: "a
b" }]);
14 expect(parsed.rest).toBe('{"type":"partial"');
15 });
17 it("wraps win32 cmd shims through cmd.exe", () => {
18 expect(rpcSpawnPlan("pi.cmd", ["--mode", "rpc"], "win32")).toEqual({
19 command: "cmd.exe",
20 args: ["/d", "/s", "/c", "pi.cmd", "--mode", "rpc"],
21 windowsHide: true,
22 });
23 expect(rpcSpawnPlan("pi", ["--mode", "rpc"], "linux")).toEqual({
24 command: "pi",
25 args: ["--mode", "rpc"],
26 windowsHide: false,
27 });
28 });
30 it("matches responses by id and forwards events", async () => {
31 const events: unknown[] = [];
32 const rpc = startRpc({
33 command: node,
34 args: [
35 "-e",
36 `process.stdin.on('data', chunk => {
37 for (const line of String(chunk).trim().split('\\n')) {
38 const msg = JSON.parse(line);
39 console.log(JSON.stringify({ type: 'event', seen: msg.type }));
40 console.log(JSON.stringify({ id: msg.id, type: 'response', command: msg.type, success: true, data: { ok: true } }));
41 }
42 });`,
43 ],
44 cwd: process.cwd(),
45 sessionPath: "session.jsonl",
46 onEvent: (event) => events.push(event),
47 });
49 try {
50 const response = await rpc.send({ type: "get_state" });
51 expect(response).toMatchObject({
52 type: "response",
53 command: "get_state",
54 success: true,
55 data: { ok: true },
56 });
57 expect(events).toEqual([{ type: "event", seen: "get_state" }]);
58 } finally {
59 await rpc.close("test");
60 }
61 });
63 it("captures stderr", async () => {
64 const rpc = startRpc({
65 command: node,
66 args: ["-e", "console.error('rpc stderr'); setTimeout(() => {}, 50);"],
67 cwd: process.cwd(),
68 sessionPath: "session.jsonl",
69 });
71 try {
72 await once(rpc.child.stderr, "data");
73 expect(rpc.stderr()).toContain("rpc stderr");
74 } finally {
75 await rpc.close("test");
76 }
77 });
79 it("times out unanswered requests", async () => {
80 const rpc = startRpc({
81 command: node,
82 args: ["-e", "process.stdin.resume()"],
83 cwd: process.cwd(),
84 sessionPath: "session.jsonl",
85 requestTimeoutMs: 10,
86 });
88 try {
89 await expect(rpc.send({ type: "get_state" })).rejects.toThrow(
90 /timed out/,
91 );
92 } finally {
93 await rpc.close("test");
94 }
95 });
97 it("emits slow-start and exit lifecycle states", async () => {
98 const states: string[] = [];
99 const rpc = startRpc({
100 command: node,
101 args: ["-e", "setTimeout(() => process.exit(7), 40)"],
102 cwd: process.cwd(),
103 sessionPath: "session.jsonl",
104 slowStartMs: 5,
105 onState: (state) => states.push(state),
106 });
108 await once(rpc.child, "exit");
109 expect(states).toContain("slow-start");
110 expect(states).toContain("exit");
111 });
112});

extensions/ui/__tests__/runtime.test.ts

Deleted
deleted file mode 100644

+0 / −318 text lines

1import { EventEmitter } from "node:events";
2import { mkdtemp, readFile, rm } from "node:fs/promises";
3import { tmpdir } from "node:os";
4import path from "node:path";
5import { Writable } from "node:stream";
6import { afterEach, describe, expect, it } from "vitest";
7import WebSocket from "ws";
8import { openBrowser, openerCandidates } from "../open";
9import { createUiRuntime, normalizeRpcEvent, type UiRuntime } from "../runtime";
11describe("ui browser opener", () => {
12 it("uses platform openers", () => {
13 expect(
14 openerCandidates("http://x", { platform: "win32", env: {} })[0],
15 ).toEqual({
16 command: "explorer.exe",
17 args: ["http://x"],
18 windowsHide: true,
19 });
20 expect(
21 openerCandidates("http://x", { platform: "darwin", env: {} })[0],
22 ).toEqual({
23 command: "open",
24 args: ["http://x"],
25 });
26 expect(
27 openerCandidates("http://x", { platform: "linux", env: {} })[0],
28 ).toEqual({
29 command: "xdg-open",
30 args: ["http://x"],
31 });
32 });
34 it("uses termux opener when available", () => {
35 expect(
36 openerCandidates("http://x", {
37 platform: "linux",
38 env: { TERMUX_VERSION: "1" },
39 })[0],
40 ).toEqual({
41 command: "termux-open-url",
42 args: ["http://x"],
43 });
44 });
46 it("can suppress auto-open for smoke harnesses", async () => {
47 const previous = process.env.PI_UI_NO_AUTO_OPEN;
48 process.env.PI_UI_NO_AUTO_OPEN = "1";
49 try {
50 await expect(openBrowser("http://127.0.0.1:9")).resolves.toBeUndefined();
51 } finally {
52 if (previous === undefined) delete process.env.PI_UI_NO_AUTO_OPEN;
53 else process.env.PI_UI_NO_AUTO_OPEN = previous;
54 }
55 });
56});
58const runtimes: UiRuntime[] = [];
60afterEach(async () => {
61 await Promise.all(
62 runtimes.splice(0).map((runtime) => runtime.stop("test cleanup")),
63 );
64});
66describe("ui rpc event normalization", () => {
67 it("drops unknown rpc startup chatter", () => {
68 expect(
69 normalizeRpcEvent({ type: "startup_log", message: "builtin-tools" }),
70 ).toBeUndefined();
71 });
73 it("uses accumulated assistant text for streaming updates", () => {
74 expect(
75 normalizeRpcEvent({
76 type: "message_update",
77 message: {
78 role: "assistant",
79 content: [{ type: "text", text: "Ready. What" }],
80 },
81 assistantMessageEvent: {
82 type: "text_delta",
83 contentIndex: 0,
84 delta: " What",
85 },
86 }),
87 ).toEqual({
88 type: "message",
89 role: "assistant",
90 text: "Ready. What",
91 streamId: "assistant-stream",
92 });
93 });
94});
96describe("ui runtime", () => {
97 it("starts, reports status, redraws QR, and stops", async () => {
98 const runtime = await createUiRuntime({
99 sessionLabel: "ui: test",
100 address: "127.0.0.1",
101 openBrowser: false,
102 });
103 runtimes.push(runtime);
105 expect(runtime.status().active).toBe(true);
106 expect(runtime.status().url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/?$/);
107 expect(runtime.widgetLines().join("\n")).toContain("ui: test");
109 await runtime.redrawQr();
110 expect(runtime.widgetLines().join("\n")).toContain("mobile QR: /ui qr");
112 await runtime.stop("test");
113 expect(runtime.status().active).toBe(false);
114 });
116 it("writes smoke URL handoff only when requested", async () => {
117 const dir = await mkdtemp(path.join(tmpdir(), "pi-ui-smoke-"));
118 const file = path.join(dir, "url.txt");
119 const previous = process.env.PI_UI_SMOKE_URL_FILE;
120 process.env.PI_UI_SMOKE_URL_FILE = file;
121 try {
122 const runtime = await createUiRuntime({
123 sessionLabel: "ui: test",
124 address: "127.0.0.1",
125 openBrowser: false,
126 });
127 runtimes.push(runtime);
128 const value = await readFile(file, "utf8");
129 expect(new URL(value.trim()).searchParams.has("token")).toBe(true);
130 expect(value.trim()).not.toBe(runtime.status().url);
131 } finally {
132 if (previous === undefined) delete process.env.PI_UI_SMOKE_URL_FILE;
133 else process.env.PI_UI_SMOKE_URL_FILE = previous;
134 await rm(dir, { recursive: true, force: true });
135 }
136 });
138 it("is safe to stop twice", async () => {
139 const runtime = await createUiRuntime({
140 sessionLabel: "ui: test",
141 address: "127.0.0.1",
142 openBrowser: false,
143 });
144 await runtime.stop("first");
145 await runtime.stop("second");
146 expect(runtime.status().active).toBe(false);
147 });
149 it("seeds an active branch and starts rpc when a session manager is provided", async () => {
150 const sent: unknown[] = [];
151 const runtime = await createUiRuntime({
152 sessionLabel: "ui: test",
153 address: "127.0.0.1",
154 cwd: "C:/repo",
155 openBrowser: false,
156 sessionManager: fakeSessionManager(),
157 startRpcBridge: ({ sessionPath, onState }) => {
158 onState?.("connected");
159 return fakeRpc(sent, sessionPath);
160 },
161 });
162 runtimes.push(runtime);
164 expect(runtime.status()).toMatchObject({
165 active: true,
166 rpcState: "connected",
167 sessionPath: "C:/sessions/ui-branch.jsonl",
168 });
169 expect(runtime.widgetLines().join("\n")).toContain("rpc: connected");
170 });
172 it("forwards browser prompts to rpc and publishes stream events", async () => {
173 const sent: unknown[] = [];
174 const runtime = await createUiRuntime({
175 sessionLabel: "ui: test",
176 address: "127.0.0.1",
177 cwd: "C:/repo",
178 openBrowser: false,
179 sessionManager: fakeSessionManager(),
180 startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
181 });
182 runtimes.push(runtime);
183 const socket = await connectRuntimeSocket(runtime);
184 socket.send(JSON.stringify({ type: "prompt", text: "hello" }));
185 await new Promise((resolve) => setTimeout(resolve, 20));
186 socket.close();
188 expect(sent).toContainEqual(
189 expect.objectContaining({ type: "prompt", message: "hello" }),
190 );
191 });
193 it("routes bash and browser control actions to rpc", async () => {
194 const sent: unknown[] = [];
195 const runtime = await createUiRuntime({
196 sessionLabel: "ui: test",
197 address: "127.0.0.1",
198 cwd: "C:/repo",
199 openBrowser: false,
200 sessionManager: fakeSessionManager(),
201 startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
202 });
203 runtimes.push(runtime);
204 const socket = await connectRuntimeSocket(runtime);
206 socket.send(JSON.stringify({ type: "prompt", text: "!!git status" }));
207 socket.send(JSON.stringify({ type: "cycle_model" }));
208 socket.send(JSON.stringify({ type: "abort" }));
209 await new Promise((resolve) => setTimeout(resolve, 20));
210 socket.close();
212 expect(sent).toContainEqual({
213 type: "bash",
214 command: "git status",
215 excludeFromContext: true,
216 });
217 expect(sent).toContainEqual({ type: "cycle_model" });
218 expect(sent).toContainEqual({ type: "abort" });
219 });
221 it("attaches telemetry digest once to browser prompt", async () => {
222 const sent: unknown[] = [];
223 const runtime = await createUiRuntime({
224 sessionLabel: "ui: test",
225 address: "127.0.0.1",
226 cwd: "C:/repo",
227 openBrowser: false,
228 sessionManager: fakeSessionManager(),
229 startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
230 });
231 runtimes.push(runtime);
232 const socket = await connectRuntimeSocket(runtime);
234 socket.send(
235 JSON.stringify({
236 type: "telemetry_batch",
237 events: [{ type: "click", target: "SEND" }],
238 }),
239 );
240 socket.send(JSON.stringify({ type: "prompt", text: "hello" }));
241 socket.send(JSON.stringify({ type: "prompt", text: "again" }));
242 await new Promise((resolve) => setTimeout(resolve, 20));
243 socket.close();
245 expect(sent).toContainEqual({
246 type: "prompt",
247 message: "Browser digest:\n- click SEND\n\nUser prompt:\nhello",
248 });
249 expect(sent).toContainEqual({ type: "prompt", message: "again" });
250 });
252 it("routes extension UI responses to rpc", async () => {
253 const sent: unknown[] = [];
254 const runtime = await createUiRuntime({
255 sessionLabel: "ui: test",
256 address: "127.0.0.1",
257 cwd: "C:/repo",
258 openBrowser: false,
259 sessionManager: fakeSessionManager(),
260 startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
261 });
262 runtimes.push(runtime);
263 const socket = await connectRuntimeSocket(runtime);
265 socket.send(
266 JSON.stringify({ type: "ui_response", id: "u1", value: "Allow" }),
267 );
268 await new Promise((resolve) => setTimeout(resolve, 20));
269 socket.close();
271 expect(sent).toContainEqual({
272 type: "extension_ui_response",
273 id: "u1",
274 value: "Allow",
275 });
276 });
277});
279async function connectRuntimeSocket(runtime: UiRuntime): Promise<WebSocket> {
280 const url = new URL(runtime.status().url ?? "");
281 const response = await fetch(url);
282 const cookie = response.headers.get("set-cookie") ?? "";
283 const socketUrl = new URL("/ws", url);
284 socketUrl.protocol = "ws:";
285 const socket = new WebSocket(socketUrl, { headers: { cookie } });
286 await new Promise((resolve) => socket.once("open", resolve));
287 return socket;
288}
290function fakeSessionManager() {
291 return {
292 getLeafId: () => "leaf-1",
293 getSessionFile: () => "C:/sessions/source.jsonl",
294 createBranchedSession: () => "C:/sessions/ui-branch.jsonl",
295 };
296}
298function fakeRpc(sent: unknown[], sessionPath: string) {
299 return {
300 child: Object.assign(new EventEmitter(), {
301 stdout: new EventEmitter(),
302 stderr: new EventEmitter(),
303 stdin: new Writable({
304 write(_chunk, _encoding, callback) {
305 callback();
306 },
307 }),
308 kill() {},
309 }),
310 sessionPath,
311 send(request: unknown) {
312 sent.push(request);
313 return Promise.resolve({ type: "response", success: true, data: {} });
314 },
315 stderr: () => "",
316 close: () => Promise.resolve(),
317 };
318}

extensions/ui/__tests__/server.test.ts

Deleted
deleted file mode 100644

+0 / −208 text lines

1import { once } from "node:events";
2import { describe, expect, it } from "vitest";
3import WebSocket from "ws";
4import { humanError, redactToken, uiError } from "../errors";
5import { EventStore } from "../events";
6import { chooseLanAddress, uiUrl } from "../network";
7import { startUiServer } from "../server";
8
9describe("ui network helpers", () => {
10 it("prefers non-internal IPv4 LAN addresses", () => {
11 const address = chooseLanAddress({
12 lo: [{ address: "127.0.0.1", family: "IPv4", internal: true } as never],
13 wifi: [
14 { address: "192.168.1.44", family: "IPv4", internal: false } as never,
15 ],
16 });
18 expect(address).toBe("192.168.1.44");
19 });
21 it("falls back to 127.0.0.1 when no LAN address exists", () => {
22 const address = chooseLanAddress({
23 lo: [{ address: "127.0.0.1", family: "IPv4", internal: true } as never],
24 });
26 expect(address).toBe("127.0.0.1");
27 });
29 it("builds token URLs and redacts tokens in diagnostics", () => {
30 const url = uiUrl("10.0.0.9", 54321, "abc");
32 expect(url).toBe("http://10.0.0.9:54321/?token=abc");
33 expect(redactToken(url)).toBe("http://10.0.0.9:54321/?token=<redacted>");
34 });
35});
37async function waitFor(predicate: () => boolean): Promise<void> {
38 for (let attempt = 0; attempt < 20; attempt += 1) {
39 if (predicate()) return;
40 await new Promise((resolve) => setTimeout(resolve, 10));
41 }
42}
44describe("ui errors", () => {
45 it("formats human-actionable errors", () => {
46 const err = uiError("server_bind_failed", "Could not bind LAN server", {
47 action: "Pick another port with /ui --port <port>.",
48 retryable: true,
49 });
51 expect(humanError(err)).toContain("Could not bind LAN server");
52 expect(humanError(err)).toContain("Pick another port");
53 expect(humanError(err)).toContain("Retryable: yes");
54 });
55});
57describe("ui server", () => {
58 it("serves shell at bare root and sets strict cookie", async () => {
59 const server = await startUiServer({
60 address: "127.0.0.1",
61 token: "tok",
62 preferredPort: 0,
63 });
64 try {
65 const authorized = await fetch(server.baseUrl);
66 expect(authorized.status).toBe(200);
67 expect(authorized.headers.get("set-cookie")).toContain("pi_ui_token=tok");
68 expect(authorized.headers.get("set-cookie")).toContain("SameSite=Strict");
69 const body = await authorized.text();
70 expect(body).toContain("<title>Pi UI</title>");
71 expect(body).toContain('id="ui-composer"');
72 } finally {
73 await server.close("test");
74 }
75 });
77 it("accepts cookie and bearer auth for status", async () => {
78 const server = await startUiServer({
79 address: "127.0.0.1",
80 token: "tok",
81 preferredPort: 0,
82 });
83 try {
84 const cookie = await fetch(`${server.baseUrl}/api/status`, {
85 headers: { cookie: "pi_ui_token=tok" },
86 });
87 expect(cookie.status).toBe(200);
88 expect(await cookie.json()).toMatchObject({
89 state: "waiting",
90 clients: 0,
91 });
93 const bearer = await fetch(`${server.baseUrl}/api/status`, {
94 headers: { authorization: "Bearer tok" },
95 });
96 expect(bearer.status).toBe(200);
97 } finally {
98 await server.close("test");
99 }
100 });
102 it("rejects wrong tokens", async () => {
103 const server = await startUiServer({
104 address: "127.0.0.1",
105 token: "tok",
106 preferredPort: 0,
107 });
108 try {
109 const response = await fetch(`${server.baseUrl}/api/status`, {
110 headers: { authorization: "Bearer wrong" },
111 });
112 expect(response.status).toBe(401);
113 } finally {
114 await server.close("test");
115 }
116 });
118 it("serves authenticated snapshots", async () => {
119 const events = new EventStore({ now: () => 1 });
120 events.append({ type: "state", state: "rpc-starting" });
121 const server = await startUiServer({
122 address: "127.0.0.1",
123 token: "tok",
124 preferredPort: 0,
125 events,
126 snapshotStatus: "rpc-starting",
127 });
128 try {
129 const unauthorized = await fetch(`${server.baseUrl}/api/snapshot`);
130 expect(unauthorized.status).toBe(401);
132 const response = await fetch(`${server.baseUrl}/api/snapshot`, {
133 headers: { authorization: "Bearer tok" },
134 });
135 expect(response.status).toBe(200);
136 expect(await response.json()).toMatchObject({
137 version: 1,
138 lastEventId: 1,
139 status: "rpc-starting",
140 });
141 } finally {
142 await server.close("test");
143 }
144 });
146 it("counts active websocket tabs, not html loads", async () => {
147 const server = await startUiServer({
148 address: "127.0.0.1",
149 token: "tok",
150 preferredPort: 0,
151 });
152 try {
153 const page = await fetch(`${server.baseUrl}/?token=tok`);
154 expect(page.status).toBe(200);
155 expect(server.clients()).toBe(0);
157 const ws = new WebSocket(
158 `${server.baseUrl.replace("http", "ws")}/ws?token=tok`,
159 );
160 await once(ws, "open");
161 expect(server.clients()).toBe(1);
162 ws.close();
163 await once(ws, "close");
164 await waitFor(() => server.clients() === 0);
165 expect(server.clients()).toBe(0);
166 } finally {
167 await server.close("test");
168 }
169 });
171 it("authenticates websocket replay and broadcasts events", async () => {
172 const events = new EventStore({ now: () => 2 });
173 events.append({ type: "log", level: "info", message: "old" });
174 const live = events.append({ type: "log", level: "info", message: "live" });
175 const server = await startUiServer({
176 address: "127.0.0.1",
177 token: "tok",
178 preferredPort: 0,
179 events,
180 snapshotStatus: "connected",
181 });
182 const ws = new WebSocket(
183 `${server.baseUrl.replace("http", "ws")}/ws?token=tok&after=1`,
184 );
185 try {
186 const [firstRaw] = (await once(ws, "message")) as [Buffer];
187 expect(JSON.parse(String(firstRaw))).toEqual({
188 type: "events",
189 events: [live],
190 });
192 const next = events.append({
193 type: "message",
194 role: "user",
195 text: "hello",
196 });
197 server.publish(next);
198 const [secondRaw] = (await once(ws, "message")) as [Buffer];
199 expect(JSON.parse(String(secondRaw))).toEqual({
200 type: "events",
201 events: [next],
202 });
203 } finally {
204 ws.close();
205 await server.close("test");
206 }
207 });
208});

extensions/ui/__tests__/session-seed.test.ts

Deleted
deleted file mode 100644

+0 / −59 text lines

1import { describe, expect, it } from "vitest";
2import { seedUiSession } from "../session-seed";
3
4describe("ui session seed", () => {
5 it("creates an exact active-branch session from the current leaf", () => {
6 const calls: string[] = [];
7 const result = seedUiSession({
8 cwd: "C:/repo",
9 sessionManager: {
10 getLeafId: () => "leaf-1",
11 getSessionFile: () => "C:/sessions/source.jsonl",
12 createBranchedSession: (leafId: string) => {
13 calls.push(leafId);
14 return "C:/sessions/ui-branch.jsonl";
15 },
16 },
17 });
19 expect(calls).toEqual(["leaf-1"]);
20 expect(result).toEqual({
21 path: "C:/sessions/ui-branch.jsonl",
22 method: "active-branch",
23 warning: undefined,
24 });
25 });
27 it("fails actionably when no active leaf exists", () => {
28 expect(() =>
29 seedUiSession({
30 cwd: "C:/repo",
31 sessionManager: {
32 getLeafId: () => null,
33 getSessionFile: () => "C:/sessions/source.jsonl",
34 createBranchedSession: () => "unused",
35 },
36 }),
37 ).toThrow(/active leaf/);
38 });
40 it("uses whole-tree fallback only when explicitly requested", () => {
41 const result = seedUiSession({
42 cwd: "C:/repo",
43 allowWholeTreeFallback: true,
44 sessionManager: {
45 getLeafId: () => "leaf-1",
46 getSessionFile: () => "C:/sessions/source.jsonl",
47 createBranchedSession: () => undefined,
48 },
49 forkWholeTree: (source, cwd) => `fork:${source}:${cwd}`,
50 });
52 expect(result).toEqual({
53 path: "fork:C:/sessions/source.jsonl:C:/repo",
54 method: "whole-tree",
55 warning:
56 "Whole-tree session fork includes abandoned branches; active LLM context remains branch-clean.",
57 });
58 });
59});

extensions/ui/__tests__/telemetry.test.ts

Deleted
deleted file mode 100644

+0 / −55 text lines

1import { describe, expect, it } from "vitest";
2import { redactText, TelemetryAggregator } from "../telemetry";
3
4describe("ui telemetry aggregator", () => {
5 it("redacts selected and input text", () => {
6 expect(redactText("secret text")).toBe("[redacted 11 chars]");
7 expect(redactText("")).toBe("");
8 });
9
10 it("summarizes scroll click focus pagehide widget and form events", () => {
11 const telemetry = new TelemetryAggregator({ maxEvents: 8 });
12 telemetry.add({
13 type: "viewport",
14 device: "phone",
15 width: 390,
16 height: 760,
17 });
18 telemetry.add({ type: "scroll", y: 320, dwellMs: 1200 });
19 telemetry.add({ type: "click", target: "SEND" });
20 telemetry.add({ type: "focus", target: "composer" });
21 telemetry.add({ type: "selection", text: "private selection" });
22 telemetry.add({
23 type: "widget_action",
24 widgetId: "widget-1",
25 label: "Approve",
26 });
27 telemetry.add({ type: "form", formId: "f1", state: "abandon" });
28 telemetry.add({ type: "pagehide" });
30 expect(telemetry.digest()).toBe(
31 [
32 "Browser digest:",
33 "- viewport phone 390x760",
34 "- scroll y=320 dwell=1200ms",
35 "- click SEND",
36 "- focus composer",
37 "- selection [redacted 17 chars]",
38 "- widget widget-1 action Approve",
39 "- form f1 abandon",
40 "- pagehide",
41 ].join("\n"),
42 );
43 });
45 it("caps events and clears digest", () => {
46 const telemetry = new TelemetryAggregator({ maxEvents: 2 });
47 telemetry.add({ type: "click", target: "one" });
48 telemetry.add({ type: "click", target: "two" });
49 telemetry.add({ type: "click", target: "three" });
50 expect(telemetry.digest()).toContain("three");
51 expect(telemetry.digest()).not.toContain("one");
52 telemetry.clear();
53 expect(telemetry.digest()).toBe("");
54 });
55});

extensions/ui/__tests__/terminal-widget.test.ts

Deleted
deleted file mode 100644

+0 / −61 text lines

1import { describe, expect, it } from "vitest";
2import { osc8Link, renderUiWidget } from "../terminal-widget";
3
4const OSC8_RE = /\u001b]8;;.*?\u001b\\|\u001b]8;;\u001b\\/g;
5
6function visibleLength(line: string): number {
7 return line.replace(OSC8_RE, "").length;
8}
9
10describe("ui terminal widget", () => {
11 it("renders OSC 8 links", () => {
12 expect(osc8Link("http://127.0.0.1:123/open", "open ui")).toBe(
13 "\u001b]8;;http://127.0.0.1:123/open\u001b\\open ui\u001b]8;;\u001b\\",
14 );
15 });
17 it("renders a closed bounded widget box", () => {
18 const lines = renderUiWidget({
19 url: "http://127.0.0.1:123/?token=abc",
20 qr: Array.from({ length: 30 }, (_, index) => `QR ${index}`).join("\n"),
21 state: "connected",
22 sessionLabel: "ui: pi-ext",
23 clients: 1,
24 });
26 const text = lines.join("\n");
27 const visibleText = text.replace(OSC8_RE, "");
28 expect(lines).toHaveLength(9);
29 expect(lines[0]).toMatch(/^┏━+┓$/);
30 expect(lines.at(-1)).toMatch(/^┗━+┛$/);
31 expect(lines.slice(1, -1).every((line) => /^┃.*┃$/.test(line))).toBe(true);
32 expect(new Set(lines.map((line) => visibleLength(line))).size).toBe(1);
33 expect(text).toContain("pi ui");
34 expect(visibleText).toContain("url: http://127.0.0.1:123/");
35 expect(visibleText).not.toContain("token=abc");
36 expect(text).toContain("connected");
37 expect(text).toContain("ui: pi-ext");
38 expect(text).toContain("press ESC to stop");
39 expect(text).toContain("/ui off");
40 expect(text).toContain("/ui qr");
41 expect(text).not.toContain("widget truncated");
42 expect(text).not.toContain("QR 29");
43 });
45 it("wraps long content inside the box without truncating", () => {
46 const longLabel = "ui: " + "x".repeat(90);
47 const lines = renderUiWidget({
48 url: "http://127.0.0.1:123/?token=abc",
49 qr: "QR",
50 state: "connected",
51 sessionLabel: longLabel,
52 clients: 1,
53 });
55 const text = lines.join("\n");
56 expect(text).toContain("session: ui: ");
57 expect(text.match(/x/g)).toHaveLength(90);
58 expect(text).not.toContain("…");
59 expect(new Set(lines.map((line) => visibleLength(line))).size).toBe(1);
60 });
61});

extensions/ui/__tests__/theme.test.ts

Deleted
deleted file mode 100644

+0 / −46 text lines

1import { describe, expect, it } from "vitest";
2import { renderAppCss } from "../web/app.css";
3import { renderAppHtml } from "../web/app.html";
4import { renderThemeCss } from "../web/theme.css";
5
6describe("ui Nugu theme", () => {
7 it("emits semantic brutal variables and dark/light media query", () => {
8 const css = renderThemeCss();
9 expect(css).toContain("--nugu-bg");
10 expect(css).toContain("--nugu-fg");
11 expect(css).toContain("--nugu-accent");
12 expect(css).toContain("prefers-color-scheme: light");
13 });
15 it("keeps stream-first layout without sidebar", () => {
16 const css = renderThemeCss();
17 expect(css).toContain("grid-template-rows: auto minmax(0, 1fr) auto");
18 expect(css).not.toContain("sidebar");
19 });
21 it("keeps the composer visible while only the stream scrolls", () => {
22 const css = renderAppCss();
23 expect(css).toContain(
24 "body { margin: 0; min-height: 100vh; height: 100vh; overflow: hidden;",
25 );
26 expect(css).toContain(
27 "#ui-shell { min-height: 100vh; height: 100vh; display: grid; grid-template-rows: auto minmax(0, 1fr) auto;",
28 );
29 expect(css).toContain("#ui-stream { min-height: 0;");
30 expect(css).toContain("#ui-bottom { position: sticky; bottom: 0;");
31 expect(css).toContain("#ui-input { width: 100%; max-height: 30vh;");
32 });
34 it("renders explicit progress and status regions", () => {
35 const html = renderAppHtml();
36 const css = renderAppCss();
37 expect(html).toContain('id="ui-top"');
38 expect(html).toContain('id="ui-progress"');
39 expect(html).toContain('id="ui-meta"');
40 expect(html).toContain('id="ui-digest"');
41 expect(html).not.toContain("<details");
42 expect(css).toContain("#ui-progress");
43 expect(css).toContain("#ui-meta");
44 expect(css).toContain("#ui-digest");
45 });
46});

extensions/ui/__tests__/visual-block.test.ts

Deleted
deleted file mode 100644

+0 / −43 text lines

1import { describe, expect, it } from "vitest";
2import {
3 renderVisualBlockShell,
4 visualBlockSummary,
5} from "../web/components/visual-block.js";
6
7describe("ui visual block rendering", () => {
8 it("renders widget fallback and ids", () => {
9 expect(
10 visualBlockSummary({
11 type: "widget_mount",
12 widgetId: "widget-1",
13 title: "Demo",
14 fallback: "Fallback text",
15 status: "mounted",
16 }),
17 ).toBe("Demo · widget-1 · mounted · Fallback text");
18 });
20 it("renders widget errors with a fix hint", () => {
21 expect(
22 visualBlockSummary({
23 type: "widget_error",
24 widgetId: "widget-1",
25 message: "boom",
26 status: "error",
27 }),
28 ).toBe("widget-1 · error · boom · agent: fix widget HTML/JS");
29 });
31 it("renders bounded iframe shell", () => {
32 const html = renderVisualBlockShell({
33 widgetId: "widget-1",
34 title: "Demo",
35 fallback: "Fallback",
36 srcdoc: "<p>Hi</p>",
37 });
38 expect(html).toContain("ui-visual-block");
39 expect(html).toContain("widget-1");
40 expect(html).toContain("iframe");
41 expect(html).toContain("Fallback");
42 });
43});

extensions/ui/__tests__/visual-tools.test.ts

Deleted
deleted file mode 100644

+0 / −71 text lines

1import { describe, expect, it } from "vitest";
2import { createVisualTools } from "../visual-tools";
3import { WidgetStore } from "../widget-state";
4
5describe("ui visual tools", () => {
6 it("creates the expected visual tool family", () => {
7 const tools = createVisualTools({
8 store: new WidgetStore({ now: () => 1 }),
9 });
10 expect(tools.map((tool) => tool.name)).toEqual([
11 "ui_card",
12 "ui_table",
13 "ui_diagram",
14 "ui_form",
15 "ui_mockup",
16 "ui_html",
17 "ui_update",
18 "ui_wait_action",
19 ]);
20 });
22 it("mounts raw HTML widgets with fallback text", async () => {
23 const events: unknown[] = [];
24 const [, , , , , htmlTool] = createVisualTools({
25 store: new WidgetStore({ now: () => 2 }),
26 publish: (event) => events.push(event),
27 });
29 const result = await htmlTool.execute(
30 "call-1",
31 { title: "Demo", fallback: "fallback", html: "<button>go</button>" },
32 undefined,
33 undefined,
34 {} as never,
35 );
37 expect(result.content).toEqual([{ type: "text", text: "fallback" }]);
38 expect(result.details).toMatchObject({
39 widgetId: "widget-call-1",
40 type: "widget_mount",
41 title: "Demo",
42 });
43 expect(events).toHaveLength(1);
44 });
46 it("updates existing widgets", async () => {
47 const store = new WidgetStore({ now: () => 3 });
48 store.mount({
49 toolCallId: "call-2",
50 title: "Demo",
51 fallback: "fallback",
52 html: "<p>old</p>",
53 });
54 const tools = createVisualTools({ store });
55 const updateTool = tools.find((tool) => tool.name === "ui_update");
56 expect(updateTool).toBeDefined();
58 const result = await updateTool?.execute(
59 "call-update",
60 { widgetId: "widget-call-2", html: "<p>new</p>" },
61 undefined,
62 undefined,
63 {} as never,
64 );
66 expect(result?.content).toEqual([
67 { type: "text", text: "Updated widget-call-2" },
68 ]);
69 expect(store.get("widget-call-2")?.html).toBe("<p>new</p>");
70 });
71});

extensions/ui/__tests__/web-composer.test.ts

Deleted
deleted file mode 100644

+0 / −50 text lines

1import { describe, expect, it } from "vitest";
2import {
3 composerKeyAction,
4 filterCommandItems,
5 moveMenuIndex,
6} from "../web/components/composer.js";
7
8describe("ui web composer autocomplete", () => {
9 const commands = [
10 { name: "mode", description: "Switch mode" },
11 { name: "skill:brutal", description: "Brutal style" },
12 { name: "skill:wiki", description: "Wiki research" },
13 { name: "ui", description: "Browser UI" },
14 ];
16 it("filters slash command items", () => {
17 expect(filterCommandItems(commands, "/skill:b")).toEqual([
18 { name: "skill:brutal", description: "Brutal style" },
19 ]);
20 });
22 it("returns extension, skill, and prompt command items for empty slash prefix", () => {
23 expect(filterCommandItems(commands, "/").map((item) => item.name)).toEqual([
24 "mode",
25 "skill:brutal",
26 "skill:wiki",
27 "ui",
28 ]);
29 });
31 it("wraps keyboard menu selection", () => {
32 expect(moveMenuIndex(0, 1, 3)).toBe(1);
33 expect(moveMenuIndex(2, 1, 3)).toBe(0);
34 expect(moveMenuIndex(0, -1, 3)).toBe(2);
35 expect(moveMenuIndex(0, 1, 0)).toBe(0);
36 });
38 it("maps composer keybindings", () => {
39 expect(composerKeyAction({ key: "Enter" })).toBe("submit");
40 expect(composerKeyAction({ key: "Enter", shiftKey: true })).toBe("newline");
41 expect(composerKeyAction({ key: "Escape" })).toBe("abort");
42 expect(composerKeyAction({ key: "o", ctrlKey: true })).toBe(
43 "toggle-expand",
44 );
45 expect(composerKeyAction({ key: "p", ctrlKey: true })).toBe("cycle-model");
46 expect(
47 composerKeyAction({ key: "Arrow" + "Down", menuVisible: true }),
48 ).toBe("menu-next");
49 });
50});

extensions/ui/__tests__/web-dialogs.test.ts

Deleted
deleted file mode 100644

+0 / −22 text lines

1import { describe, expect, it } from "vitest";
2import { dialogResponse } from "../web/components/dialogs.js";
3
4describe("ui web dialogs", () => {
5 it("builds extension UI responses", () => {
6 expect(dialogResponse("u1", "select", "Allow")).toEqual({
7 type: "ui_response",
8 id: "u1",
9 value: "Allow",
10 });
11 expect(dialogResponse("u2", "confirm", true)).toEqual({
12 type: "ui_response",
13 id: "u2",
14 confirmed: true,
15 });
16 expect(dialogResponse("u3", "input", undefined)).toEqual({
17 type: "ui_response",
18 id: "u3",
19 cancelled: true,
20 });
21 });
22});

extensions/ui/__tests__/web-smoke.test.ts

Deleted
deleted file mode 100644

+0 / −37 text lines

1import { describe, expect, it } from "vitest";
2import { startUiServer } from "../server";
3
4describe("ui web shell", () => {
5 it("serves a stream-first shell and static browser assets", async () => {
6 const server = await startUiServer({
7 address: "127.0.0.1",
8 token: "tok",
9 preferredPort: 0,
10 });
11 try {
12 const shell = await fetch(`${server.baseUrl}/?token=tok`);
13 expect(shell.status).toBe(200);
14 const html = await shell.text();
15 expect(html).toContain('id="ui-progress"');
16 expect(html).toContain('id="ui-meta"');
17 expect(html).toContain('id="ui-stream"');
18 expect(html).toContain('id="ui-composer"');
19 expect(html).toContain('type="module"');
20 expect(html).toContain("/assets/app.js");
22 const js = await fetch(`${server.baseUrl}/assets/app.js`, {
23 headers: { authorization: "Bearer tok" },
24 });
25 expect(js.status).toBe(200);
26 expect(await js.text()).toContain("fetchSnapshot");
28 const css = await fetch(`${server.baseUrl}/assets/app.css`, {
29 headers: { authorization: "Bearer tok" },
30 });
31 expect(css.status).toBe(200);
32 expect(await css.text()).toContain("#ui-stream");
33 } finally {
34 await server.close("test");
35 }
36 });
37});

extensions/ui/__tests__/widget-bridge.test.ts

Deleted
deleted file mode 100644

+0 / −40 text lines

1import { describe, expect, it } from "vitest";
2import {
3 attributionEventFromWidgetMessage,
4 renderWidgetBridgeScript,
5 widgetActionMessage,
6} from "../web/components/widget-bridge.js";
7
8describe("ui widget bridge", () => {
9 it("creates window.pi bridge source", () => {
10 const source = renderWidgetBridgeScript("widget-1");
11 expect(source).toContain("window.pi");
12 expect(source).toContain("action");
13 expect(source).toContain("prompt");
14 expect(source).toContain("notify");
15 });
17 it("builds widget action messages", () => {
18 expect(widgetActionMessage("widget-1", "Approve", { ok: true })).toEqual({
19 type: "widget_action",
20 widgetId: "widget-1",
21 label: "Approve",
22 payload: { ok: true },
23 });
24 });
26 it("turns widget prompts into visible attribution events", () => {
27 expect(
28 attributionEventFromWidgetMessage(
29 { type: "widget_prompt", widgetId: "widget-1", text: "continue" },
30 () => 50,
31 ),
32 ).toEqual({
33 type: "widget_action",
34 widgetId: "widget-1",
35 label: "prompt",
36 payload: { text: "continue" },
37 at: 50,
38 });
39 });
40});

extensions/ui/__tests__/widget-layout.test.ts

Deleted
deleted file mode 100644

+0 / −106 text lines

1import { existsSync } from "node:fs";
2import {
3 type BrowserType,
4 chromium,
5 firefox,
6 type Page,
7} from "@playwright/test";
8import { describe, expect, it } from "vitest";
9
10const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe";
12describe("ui widget browser layout", () => {
13 it("lets unsandboxed srcdoc widgets call parent window.pi in Chrome and Firefox", async () => {
14 for (const browser of browsers()) {
15 const result = await withBrowser(browser, async (page) => {
16 await page.setContent(bridgeProbeHtml());
17 await page.waitForFunction(() => window.calls?.length === 1);
18 return await page.evaluate(() => window.calls[0]);
19 });
20 expect(result).toEqual({ from: "srcdoc", sameOrigin: true });
21 }
22 }, 120_000);
24 it("keeps over-wide iframe content bounded at phone width in Chrome and Firefox", async () => {
25 for (const browser of browsers()) {
26 const result = await withBrowser(browser, async (page) => {
27 await page.setViewportSize({ width: 390, height: 760 });
28 await page.setContent(layoutProbeHtml());
29 await page.waitForFunction(
30 () => document.querySelector("iframe")?.clientHeight === 600,
31 );
32 return await page.evaluate(() => ({
33 viewport: document.documentElement.clientWidth,
34 scrollWidth: document.documentElement.scrollWidth,
35 iframeHeight: document
36 .querySelector("iframe")
37 ?.getBoundingClientRect().height,
38 }));
39 });
40 expect(result).toEqual({
41 viewport: 390,
42 scrollWidth: 390,
43 iframeHeight: 600,
44 });
45 }
46 }, 120_000);
47});
49function browsers(): Array<{
50 name: string;
51 type: BrowserType;
52 executablePath?: string;
53}> {
54 return [
55 ...(existsSync(chromePath)
56 ? [{ name: "chrome", type: chromium, executablePath: chromePath }]
57 : []),
58 { name: "firefox", type: firefox },
59 ];
60}
62async function withBrowser<T>(
63 browser: { name: string; type: BrowserType; executablePath?: string },
64 fn: (page: Page) => Promise<T>,
65): Promise<T> {
66 const instance = await browser.type.launch({
67 headless: true,
68 executablePath: browser.executablePath,
69 });
70 try {
71 const page = await instance.newPage();
72 return await fn(page);
73 } finally {
74 await instance.close();
75 }
76}
78function bridgeProbeHtml(): string {
79 const srcdoc =
80 "<script>parent.pi.action({from:'srcdoc',sameOrigin:!!parent.document});</" +
81 "script>";
82 const attr = srcdoc.replaceAll(String.fromCharCode(34), "&quot;");
83 return [
84 "<!doctype html>",
85 "<script>window.calls=[];window.pi={action(x){window.calls.push(x)}};</script>",
86 `<iframe srcdoc="${attr}"></iframe>`,
87 ].join("");
88}
90function layoutProbeHtml(): string {
91 const srcdoc = [
92 "<style>body{margin:0}.wide{width:2200px;height:80px}.tall{height:900px}</style>",
93 "<div class=wide>x</div><div class=tall>y</div>",
94 "<script>parent.postMessage({height:document.documentElement.scrollHeight},'*')</" +
95 "script>",
96 ].join("");
97 const attr = srcdoc
98 .replaceAll("&", "&amp;")
99 .replaceAll(String.fromCharCode(34), "&quot;");
100 return [
101 "<!doctype html>",
102 "<style>*{box-sizing:border-box}body{margin:0}.wrap{width:min(960px,100vw);overflow:auto}.visual{min-width:0;overflow:auto;contain:layout paint;padding:12px}.visual iframe{display:block;width:100%;height:120px;max-height:600px;border:0}</style>",
103 `<div class=wrap><div class=visual><iframe srcdoc="${attr}"></iframe></div></div>`,
104 "<script>addEventListener('message',e=>{document.querySelector('iframe').style.height=Math.min(e.data.height,600)+'px'})</script>",
105 ].join("");
106}

extensions/ui/__tests__/widget-state.test.ts

Deleted
deleted file mode 100644

+0 / −62 text lines

1import { describe, expect, it } from "vitest";
2import { WidgetStore } from "../widget-state";
3
4describe("ui widget state", () => {
5 it("creates stable widget ids from tool call ids", () => {
6 const store = new WidgetStore({ now: () => 100 });
7 const first = store.mount({
8 toolCallId: "call-1",
9 title: "Card",
10 fallback: "fallback",
11 html: "<p>hi</p>",
12 });
13 const second = store.mount({
14 toolCallId: "call-1",
15 title: "Card",
16 fallback: "fallback",
17 html: "<p>hi</p>",
18 });
20 expect(first.widgetId).toBe("widget-call-1");
21 expect(second.widgetId).toBe(first.widgetId);
22 expect(store.get(first.widgetId)?.status).toBe("mounted");
23 });
25 it("records mount update action and error lifecycle", () => {
26 const store = new WidgetStore({ now: () => 200 });
27 const mount = store.mount({
28 toolCallId: "call-2",
29 title: "Form",
30 fallback: "fallback",
31 html: "<button>go</button>",
32 });
33 const update = store.update(mount.widgetId, {
34 html: "<button>stop</button>",
35 });
36 const action = store.action(mount.widgetId, {
37 toolCallId: "call-2",
38 label: "Approve",
39 payload: { ok: true },
40 });
41 const error = store.error(mount.widgetId, "boom");
43 expect(update).toMatchObject({
44 type: "widget_update",
45 widgetId: mount.widgetId,
46 });
47 expect(action).toMatchObject({
48 type: "widget_action",
49 widgetId: mount.widgetId,
50 toolCallId: "call-2",
51 label: "Approve",
52 actionId: "action-1",
53 at: 200,
54 });
55 expect(error).toMatchObject({
56 type: "widget_error",
57 widgetId: mount.widgetId,
58 message: "boom",
59 });
60 expect(store.get(mount.widgetId)?.audit).toHaveLength(4);
61 });
62});

extensions/ui/__tests__/worker.test.ts

Deleted
deleted file mode 100644

+0 / −30 text lines

1import { describe, expect, it } from "vitest";
2import {
3 createTelemetryBatcher,
4 renderTelemetryWorkerJs,
5} from "../web/worker.js";
6
7describe("ui telemetry worker", () => {
8 it("batches raw events", () => {
9 const batcher = createTelemetryBatcher({ maxBatch: 2 });
10 expect(batcher.add({ type: "click", target: "SEND" })).toEqual([]);
11 expect(batcher.add({ type: "scroll", y: 20, dwellMs: 100 })).toEqual([
12 { type: "click", target: "SEND" },
13 { type: "scroll", y: 20, dwellMs: 100 },
14 ]);
15 });
17 it("redacts selection and input text before flush", () => {
18 const batcher = createTelemetryBatcher({ maxBatch: 10 });
19 batcher.add({ type: "selection", text: "private" });
20 expect(batcher.flush()).toEqual([
21 { type: "selection", text: "[redacted 7 chars]" },
22 ]);
23 });
25 it("renders browser worker source", () => {
26 const source = renderTelemetryWorkerJs();
27 expect(source).toContain("postMessage");
28 expect(source).toContain("telemetry_batch");
29 });
30});

extensions/ui/command-adapter.ts

Deleted
deleted file mode 100644

+0 / −55 text lines

1import type { RpcClient, RpcResponse } from "./rpc";
2
3export type RpcSender = Pick<RpcClient, "send">;
4
5export type PromptOptions = {
6 digest?: () => string;
7 clearDigest?: () => void;
8};
9
10export function sendPrompt(
11 rpc: RpcSender,
12 text: string,
13 options: PromptOptions = {},
14): Promise<RpcResponse> {
15 const digest = options.digest?.() ?? "";
16 if (!digest) return rpc.send({ type: "prompt", message: text });
17 options.clearDigest?.();
18 return rpc.send({
19 type: "prompt",
20 message: `${digest}\n\nUser prompt:\n${text}`,
21 });
22}
24export function runSlashCommand(
25 rpc: RpcSender,
26 command: string,
27 args = "",
28): Promise<RpcResponse> {
29 const suffix = args.trim() ? ` ${args.trim()}` : "";
30 return sendPrompt(rpc, `/${command}${suffix}`);
31}
33export function runBash(
34 rpc: RpcSender,
35 command: string,
36 excludeFromContext: boolean,
37): Promise<RpcResponse> {
38 return rpc.send({ type: "bash", command, excludeFromContext });
39}
41export function cycleModel(rpc: RpcSender): Promise<RpcResponse> {
42 return rpc.send({ type: "cycle_model" });
43}
45export function cycleThinking(rpc: RpcSender): Promise<RpcResponse> {
46 return rpc.send({ type: "cycle_thinking_level" });
47}
49export function compactSession(rpc: RpcSender): Promise<RpcResponse> {
50 return rpc.send({ type: "compact" });
51}
53export function abortCurrent(rpc: RpcSender): Promise<RpcResponse> {
54 return rpc.send({ type: "abort" });
55}

extensions/ui/composer.ts

Deleted
deleted file mode 100644

+0 / −59 text lines

1export type ComposerParseResult =
2 | {
3 kind: "prompt";
4 text: string;
5 refs: string[];
6 }
7 | {
8 kind: "slash";
9 command: string;
10 args: string;
11 text: string;
12 refs: string[];
13 }
14 | {
15 kind: "bash";
16 command: string;
17 excludeFromContext: boolean;
18 refs: string[];
19 };
21const REF_RE = /(^|\s)@([^\s]+)/g;
23export function parseComposerInput(input: string): ComposerParseResult {
24 const text = input.trim();
25 if (text.startsWith("!!")) {
26 return {
27 kind: "bash",
28 command: text.slice(2).trimStart(),
29 excludeFromContext: true,
30 refs: [],
31 };
32 }
33 if (text.startsWith("!")) {
34 return {
35 kind: "bash",
36 command: text.slice(1).trimStart(),
37 excludeFromContext: false,
38 refs: [],
39 };
40 }
41 if (text.startsWith("/") && text.length > 1) {
42 const body = text.slice(1);
43 const space = body.search(/\s/);
44 const command = space === -1 ? body : body.slice(0, space);
45 const args = space === -1 ? "" : body.slice(space).trimStart();
46 return {
47 kind: "slash",
48 command,
49 args,
50 text,
51 refs: refs(text),
52 };
53 }
54 return { kind: "prompt", text, refs: refs(text) };
55}
57function refs(text: string): string[] {
58 return [...text.matchAll(REF_RE)].map((match) => match[2]);
59}

extensions/ui/docs/manual-playbook.md

Deleted
deleted file mode 100644

+0 / −57 text lines

1# UI manual smoke playbook
2
3## Host rule
4
5Use zellij on win32.
6Do not invoke tmux on win32.
7Use tmux only on non-win32 hosts where it is installed.
8
9## win32 zellij
11```sh
12node extensions/ui/scripts/zellij-smoke.mjs
13zellij attach <printed-session>
14```
16The script creates a zellij session through a real Windows console process, launches Pi in the default zellij terminal pane, sends `/ui`, captures the exact URL through a smoke-only local handoff file, dumps the terminal screen, probes tokenless `401`, verifies the authenticated browser shell with Playwright, sends `/ui off`, and writes `.pi/tmp/ui-zellij-smoke/*.summary.json`.
17It sets `MSYS_NO_PATHCONV=1` for zellij actions so `/ui` is not rewritten to a Git-for-Windows path.
18If URL extraction still fails, the script can run `scripts/phase1-smoke.mjs` as a fallback unless `--no-fallback` is passed.
19Do not switch to tmux on win32.
21Checkpoints:
231. Run `pi -e extensions/ui/index.ts` inside the zellij pane if the script did not keep Pi running.
242. Send `/ui`.
253. Verify the terminal widget shows a token URL and QR.
264. Open the exact URL in Chrome or Firefox.
275. Verify `/api/status` without the token returns `401`.
286. Try `/`, `/skill:`, `!`, `!!`, Esc, Ctrl+O, and Ctrl+P from the browser composer.
297. Ask for card, form, and raw HTML widgets.
308. Click one widget action and verify a visible attribution row appears before any widget-originated prompt reaches the agent.
319. Scroll, click, select text, background the tab, return, and send one prompt.
3210. Verify the digest indicator appears and the digest is attached once only.
3311. Send `/ui off` in Pi.
3412. Verify browser disconnect and terminal UI restores as far as Pi exposes.
36Cleanup:
38```sh
39zellij kill-session <printed-session>
40```
42## non-win32 tmux
44```sh
45node extensions/ui/scripts/tmux-smoke.mjs
46tmux attach -t <printed-session>
47```
49Use the same checkpoints.
51## Evidence to capture
53- zellij/tmux session name.
54- `/ui` URL redacted to origin plus `token=[redacted]`.
55- 401 result for tokenless request.
56- Browser stream screenshot for widget + attribution + digest.
57- `/ui off` terminal state.

extensions/ui/errors.ts

Deleted
deleted file mode 100644

+0 / −46 text lines

1export type UiErrorCode =
2 | "server_bind_failed"
3 | "no_lan_address"
4 | "auth_failed"
5 | "runtime_not_active"
6 | "runtime_already_active"
7 | "session_seed_failed"
8 | "open_failed"
9 | "qr_failed";
11export type UiError = Error & {
12 code: UiErrorCode;
13 action: string;
14 retryable: boolean;
15 cause?: unknown;
16};
18export function uiError(
19 code: UiErrorCode,
20 message: string,
21 options: { action: string; retryable?: boolean; cause?: unknown },
22): UiError {
23 const error = new Error(message) as UiError;
24 error.name = "UiError";
25 error.code = code;
26 error.action = options.action;
27 error.retryable = options.retryable ?? false;
28 error.cause = options.cause;
29 return error;
30}
32export function humanError(error: UiError): string {
33 return [
34 `${error.code}: ${error.message}`,
35 `Action: ${error.action}`,
36 `Retryable: ${error.retryable ? "yes" : "no"}`,
37 ].join("\n");
38}
40export function errorMessage(error: unknown): string {
41 return error instanceof Error ? error.message : String(error);
42}
44export function redactToken(value: string): string {
45 return value.replace(/([?&]token=)[^&#\s]+/g, "$1<redacted>");
46}

extensions/ui/events.ts

Deleted
deleted file mode 100644

+0 / −58 text lines

1import type {
2 UiCommandInfo,
3 UiConnectionStatus,
4 UiEvent,
5 UiEventInput,
6 UiSnapshot,
7} from "./protocol";
8
9export type EventStoreOptions = {
10 maxEvents?: number;
11 now?: () => number;
12};
14export type SnapshotOptions = {
15 status: UiConnectionStatus;
16 sessionPath?: string;
17 commands?: UiCommandInfo[];
18};
20export class EventStore {
21 readonly #maxEvents: number;
22 readonly #now: () => number;
23 #nextId = 1;
24 #events: UiEvent[] = [];
26 constructor(options: EventStoreOptions = {}) {
27 this.#maxEvents = Math.max(1, options.maxEvents ?? 500);
28 this.#now = options.now ?? Date.now;
29 }
31 append(input: UiEventInput): UiEvent {
32 const event = { id: this.#nextId++, at: this.#now(), ...input } as UiEvent;
33 this.#events.push(event);
34 if (this.#events.length > this.#maxEvents) {
35 this.#events.splice(0, this.#events.length - this.#maxEvents);
36 }
37 return event;
38 }
40 replayAfter(lastEventId: number): UiEvent[] {
41 return this.#events.filter((event) => event.id > lastEventId);
42 }
44 snapshot(options: SnapshotOptions): UiSnapshot {
45 return {
46 version: 1,
47 lastEventId: this.lastEventId(),
48 status: options.status,
49 sessionPath: options.sessionPath,
50 commands: options.commands ?? [],
51 events: [...this.#events],
52 };
53 }
55 lastEventId(): number {
56 return this.#nextId - 1;
57 }
58}

extensions/ui/extension-ui.ts

Deleted
deleted file mode 100644

+0 / −135 text lines

1import type { UiEventInput } from "./protocol";
2
3export type ExtensionUiRequest = {
4 type: "extension_ui_request";
5 id: string;
6 method: string;
7 [key: string]: unknown;
8};
9
10export type ExtensionUiResponseInput =
11 | { value: string }
12 | { confirmed: boolean }
13 | { cancelled: true };
15export function isExtensionUiRequest(
16 value: unknown,
17): value is ExtensionUiRequest {
18 return (
19 !!value &&
20 typeof value === "object" &&
21 (value as { type?: unknown }).type === "extension_ui_request" &&
22 typeof (value as { id?: unknown }).id === "string" &&
23 typeof (value as { method?: unknown }).method === "string"
24 );
25}
27export function extensionUiEventFromRequest(
28 request: ExtensionUiRequest,
29): UiEventInput {
30 if (request.method === "select") {
31 return {
32 type: "ui_request",
33 requestId: request.id,
34 method: "select",
35 title: stringField(request.title),
36 message: `select: ${stringField(request.title)}`,
37 options: arrayField(request.options),
38 expectsResponse: true,
39 };
40 }
41 if (request.method === "confirm") {
42 return {
43 type: "ui_request",
44 requestId: request.id,
45 method: "confirm",
46 title: stringField(request.title),
47 message:
48 stringField(request.message) ||
49 `confirm: ${stringField(request.title)}`,
50 expectsResponse: true,
51 };
52 }
53 if (request.method === "input") {
54 return {
55 type: "ui_request",
56 requestId: request.id,
57 method: "input",
58 title: stringField(request.title),
59 message: `input: ${stringField(request.title)}`,
60 placeholder: stringField(request.placeholder),
61 expectsResponse: true,
62 };
63 }
64 if (request.method === "editor") {
65 return {
66 type: "ui_request",
67 requestId: request.id,
68 method: "editor",
69 title: stringField(request.title),
70 message: `editor: ${stringField(request.title)}`,
71 prefill: stringField(request.prefill),
72 expectsResponse: true,
73 };
74 }
75 if (request.method === "notify") {
76 return {
77 type: "ui_notify",
78 requestId: request.id,
79 message: stringField(request.message),
80 notifyType: notifyType(request.notifyType),
81 };
82 }
83 const fields: Record<string, unknown> = { ...request };
84 delete fields.type;
85 delete fields.id;
86 delete fields.method;
87 return {
88 type: extensionUiEventType(request.method),
89 requestId: request.id,
90 message: statusMessage(request.method, fields),
91 ...fields,
92 };
93}
95export function extensionUiResponseCommand(
96 id: string,
97 input: ExtensionUiResponseInput,
98): { type: "extension_ui_response"; id: string } & ExtensionUiResponseInput {
99 return { type: "extension_ui_response", id, ...input };
100}
102function stringField(value: unknown): string {
103 return typeof value === "string" ? value : "";
104}
106function arrayField(value: unknown): string[] | undefined {
107 return Array.isArray(value)
108 ? value.filter((item) => typeof item === "string")
109 : undefined;
110}
112function notifyType(value: unknown): "info" | "warning" | "error" | undefined {
113 return value === "info" || value === "warning" || value === "error"
114 ? value
115 : undefined;
116}
118function extensionUiEventType(
119 method: string,
120): "ui_status" | "ui_title" | "ui_widget" | "ui_editor_text" {
121 if (method === "setTitle") return "ui_title";
122 if (method === "setWidget") return "ui_widget";
123 if (method === "set_editor_text") return "ui_editor_text";
124 return "ui_status";
125}
127function statusMessage(
128 method: string,
129 fields: Record<string, unknown>,
130): string {
131 if (typeof fields.statusText === "string") return fields.statusText;
132 if (method === "setStatus") return "";
133 if (typeof fields.title === "string") return fields.title;
134 return method;
135}

extensions/ui/index.ts

Deleted
deleted file mode 100644

+0 / −167 text lines

1import path from "node:path";
2import type {
3 ExtensionAPI,
4 ExtensionCommandContext,
5 ExtensionContext,
6} from "@earendil-works/pi-coding-agent";
7import { matchesKey } from "@earendil-works/pi-tui";
8import { humanError, type UiError, uiError } from "./errors";
9import { createUiRuntime, type UiRuntime } from "./runtime";
10import type { UiSeedSessionManager } from "./session-seed";
11import { createVisualTools } from "./visual-tools";
13const COMMANDS = ["off", "status", "open", "qr"];
14const WIDGET_KEY = "ui";
16export default function uiExtension(pi: ExtensionAPI): void {
17 for (const tool of createVisualTools()) pi.registerTool(tool);
18 let runtime: UiRuntime | undefined;
19 let terminalUnsubscribe: (() => void) | undefined;
21 function setWidget(ctx: ExtensionContext): void {
22 if (!ctx.hasUI) return;
23 ctx.ui.setWidget(WIDGET_KEY, runtime?.widgetLines(), {
24 placement: "aboveEditor",
25 });
26 }
28 async function stop(ctx: ExtensionContext, reason: string): Promise<void> {
29 terminalUnsubscribe?.();
30 terminalUnsubscribe = undefined;
31 const current = runtime;
32 runtime = undefined;
33 if (ctx.hasUI) {
34 ctx.ui.setWidget(WIDGET_KEY, undefined);
35 ctx.ui.setWorkingVisible?.(true);
36 }
37 if (current) await current.stop(reason);
38 }
40 async function start(ctx: ExtensionCommandContext): Promise<void> {
41 if (runtime) {
42 setWidget(ctx);
43 ctx.ui.notify(
44 `ui already active: ${notifyUrl(runtime.status().url ?? "")}`,
45 "info",
46 );
47 return;
48 }
50 if (ctx.hasUI) ctx.ui.setWorkingVisible?.(false);
51 runtime = await createUiRuntime({
52 sessionLabel: sessionLabel(pi, ctx),
53 cwd: ctx.cwd,
54 sessionManager: ctx.sessionManager as unknown as UiSeedSessionManager,
55 onChange: () => setWidget(ctx),
56 });
57 terminalUnsubscribe = ctx.hasUI
58 ? ctx.ui.onTerminalInput((data) => {
59 if (!matchesKey(data, "escape")) return undefined;
60 void stop(ctx, "escape").then(() =>
61 ctx.ui.notify("ui stopped", "info"),
62 );
63 return { consume: true };
64 })
65 : undefined;
66 setWidget(ctx);
67 ctx.ui.notify(`ui open: ${notifyUrl(runtime.status().url ?? "")}`, "info");
68 }
70 pi.registerCommand("ui", {
71 description:
72 "Start or control the browser UI runtime. Usage: /ui [off|status|open|qr]",
73 getArgumentCompletions(prefix) {
74 const trimmed = prefix.trimStart();
75 return COMMANDS.filter((item) => item.startsWith(trimmed)).map(
76 (value) => ({
77 value,
78 label: value,
79 }),
80 );
81 },
82 async handler(args, ctx) {
83 const command = args.trim();
84 try {
85 if (!command) return await start(ctx);
86 if (command === "off") return await stop(ctx, "command");
87 if (command === "status") return status(ctx);
88 if (command === "open") return await open(ctx);
89 if (command === "qr") return await redrawQr(ctx);
90 throw uiError(
91 "runtime_not_active",
92 `Unknown /ui subcommand: ${command}`,
93 {
94 action: "Use /ui, /ui off, /ui status, /ui open, or /ui qr.",
95 retryable: true,
96 },
97 );
98 } catch (error) {
99 ctx.ui.notify(formatError(error), "error");
100 setWidget(ctx);
101 }
102 },
103 });
105 pi.on("session_shutdown", async (_event, ctx) => {
106 await stop(ctx, "session shutdown");
107 });
109 function status(ctx: ExtensionCommandContext): void {
110 if (!runtime) {
111 ctx.ui.notify("ui inactive", "info");
112 return;
113 }
114 const current = runtime.status();
115 ctx.ui.notify(
116 `ui ${current.state}: ${notifyUrl(current.url ?? "")}`,
117 "info",
118 );
119 setWidget(ctx);
120 }
122 async function open(ctx: ExtensionCommandContext): Promise<void> {
123 if (!runtime) throw inactiveError();
124 await runtime.open();
125 ctx.ui.notify("ui open requested", "info");
126 }
128 async function redrawQr(ctx: ExtensionCommandContext): Promise<void> {
129 if (!runtime) throw inactiveError();
130 await runtime.redrawQr();
131 setWidget(ctx);
132 }
133}
135function sessionLabel(pi: ExtensionAPI, ctx: ExtensionContext): string {
136 const name = pi.getSessionName() ?? path.basename(ctx.cwd);
137 return `ui: ${name || "session"}`;
138}
140export function notifyUrl(value: string): string {
141 if (!value) return "";
142 const url = new URL(value);
143 url.search = "";
144 url.hash = "";
145 return url.toString();
146}
148function inactiveError(): UiError {
149 return uiError("runtime_not_active", "UI runtime is not active", {
150 action: "Run /ui first.",
151 retryable: true,
152 });
153}
155function formatError(error: unknown): string {
156 if (isUiError(error)) return humanError(error);
157 return error instanceof Error ? error.message : String(error);
158}
160function isUiError(error: unknown): error is UiError {
161 return (
162 error instanceof Error &&
163 "code" in error &&
164 "action" in error &&
165 "retryable" in error
166 );
167}

extensions/ui/lifecycle.ts

Deleted
deleted file mode 100644

+0 / −69 text lines

1import type { UiEventInput } from "./protocol";
2
3export type LifecycleTrackerOptions = {
4 now?: () => number;
5 heartbeatMs?: number;
6};
7
8export class LifecycleTracker {
9 readonly #now: () => number;
10 readonly #heartbeatMs: number;
11 #clients = new Map<string, number>();
12 #reported = new Set<string>();
14 constructor(options: LifecycleTrackerOptions = {}) {
15 this.#now = options.now ?? Date.now;
16 this.#heartbeatMs = options.heartbeatMs ?? 15_000;
17 }
19 heartbeat(clientId: string, at = this.#now()): void {
20 this.#clients.set(clientId, at);
21 this.#reported.delete(clientId);
22 }
24 check(): UiEventInput[] {
25 const now = this.#now();
26 const events: UiEventInput[] = [];
27 for (const [clientId, at] of this.#clients) {
28 if (now - at <= this.#heartbeatMs || this.#reported.has(clientId))
29 continue;
30 events.push(lifecycleError(clientId, "browser heartbeat lost"));
31 this.#reported.add(clientId);
32 }
33 return events;
34 }
36 close(clientId: string): UiEventInput {
37 this.#clients.delete(clientId);
38 return lifecycleError(clientId, "browser websocket closed");
39 }
41 pagehide(clientId: string): UiEventInput {
42 return lifecycleError(clientId, "browser page hidden/unloaded");
43 }
45 stale(clientId: string): UiEventInput {
46 return lifecycleError(clientId, "browser client stale");
47 }
49 reconnect(clientId: string): UiEventInput {
50 this.heartbeat(clientId);
51 return {
52 type: "log",
53 level: "info",
54 message: `browser reconnected: ${clientId}`,
55 };
56 }
57}
59function lifecycleError(clientId: string, message: string): UiEventInput {
60 return {
61 type: "error",
62 message,
63 action: "reload /ui browser tab or run /ui open",
64 retryable: true,
65 clientId,
66 agentHint:
67 "wait for browser reconnect before relying on widget interaction",
68 };
69}

extensions/ui/mise.toml

Deleted
deleted file mode 100644

+0 / −4 text lines

1[tasks.e2e]
2description = "Run UI browser E2E tests"
3depends = ["//:install"]
4run = "node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts"

extensions/ui/network.ts

Deleted
deleted file mode 100644

+0 / −30 text lines

1import { type NetworkInterfaceInfo, networkInterfaces } from "node:os";
2
3export type InterfaceMap = Record<string, NetworkInterfaceInfo[] | undefined>;
4
5export function chooseLanAddress(
6 interfaces: InterfaceMap = networkInterfaces(),
7): string {
8 const candidates = Object.values(interfaces)
9 .flatMap((items) => items ?? [])
10 .filter((item) => item.family === "IPv4" && !item.internal)
11 .map((item) => item.address)
12 .sort((a, b) => scoreAddress(b) - scoreAddress(a));
14 return candidates[0] ?? "127.0.0.1";
15}
17export function listenHostFor(address: string): string {
18 return address === "127.0.0.1" ? "127.0.0.1" : "0.0.0.0";
19}
21export function uiUrl(address: string, port: number, token: string): string {
22 return `http://${address}:${port}/?token=${encodeURIComponent(token)}`;
23}
25function scoreAddress(address: string): number {
26 if (address.startsWith("192.168.")) return 30;
27 if (address.startsWith("10.")) return 20;
28 if (/^172\.(1[6-9]|2\d|3[01])\./.test(address)) return 10;
29 return 1;
30}

extensions/ui/open.ts

Deleted
deleted file mode 100644

+0 / −65 text lines

1import { spawn } from "node:child_process";
2import { uiError } from "./errors";
3
4export type OpenerCandidate = {
5 command: string;
6 args: string[];
7 windowsHide?: boolean;
8};
9
10export function openerCandidates(
11 url: string,
12 options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
13): OpenerCandidate[] {
14 const platform = options.platform ?? process.platform;
15 const env = options.env ?? process.env;
16 if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
17 if (platform === "darwin") return [{ command: "open", args: [url] }];
18 if (platform === "win32") {
19 return [{ command: "explorer.exe", args: [url], windowsHide: true }];
20 }
21 return [
22 { command: "xdg-open", args: [url] },
23 { command: "wslview", args: [url] },
24 { command: "gio", args: ["open", url] },
25 ];
26}
28export async function openBrowser(url: string): Promise<void> {
29 if (
30 process.env.NODE_ENV === "test" ||
31 process.env.VITEST ||
32 process.env.PI_UI_NO_AUTO_OPEN === "1"
33 )
34 return;
35 for (const candidate of openerCandidates(url)) {
36 if (await trySpawn(candidate.command, candidate.args)) return;
37 }
38 throw uiError("open_failed", "Could not open browser", {
39 action:
40 "Open the /ui link manually from the terminal widget or scan the QR code.",
41 retryable: true,
42 });
43}
45function trySpawn(command: string, args: string[]): Promise<boolean> {
46 return new Promise((resolve) => {
47 const child = spawn(command, args, {
48 detached: true,
49 stdio: "ignore",
50 windowsHide: true,
51 });
52 let settled = false;
53 const done = (ok: boolean) => {
54 if (settled) return;
55 settled = true;
56 resolve(ok);
57 };
58 child.once("error", () => done(false));
59 child.once("spawn", () => {
60 child.unref();
61 done(true);
62 });
63 setTimeout(() => done(false), 1500).unref();
64 });
65}

extensions/ui/package.json

Deleted
deleted file mode 100644

+0 / −35 text lines

1{
2 "name": "@bugabinga/pi-ext-ui",
3 "type": "module",
4 "main": "index.ts",
5 "scripts": {
6 "test": "vitest run ./__tests__/*.test.ts"
7 },
8 "dependencies": {
9 "@types/ws": "^8.18.1",
10 "pierre": "^2.1.16",
11 "qrcode": "^1.5.4",
12 "shiki": "^4.3.0",
13 "ws": "^8.21.0"
14 },
15 "peerDependencies": {
16 "@earendil-works/pi-coding-agent": "*",
17 "@earendil-works/pi-tui": "*",
18 "typebox": "*"
19 },
20 "license": "MIT",
21 "description": "Browser UI runtime shell for Pi.",
22 "keywords": [
23 "pi",
24 "pi-extension",
25 "ui"
26 ],
27 "devDependencies": {
28 "@marcfargas/pi-test-harness": "^0.6.1",
29 "@playwright/test": "^1.61.0",
30 "@types/qrcode": "^1.5.5",
31 "tsx": "^4.20.6",
32 "vitest": "^4.1.9"
33 },
34 "private": true
35}

extensions/ui/playwright.config.ts

Deleted
deleted file mode 100644

+0 / −12 text lines

1import { defineConfig } from "@playwright/test";
2
3import base from "../../test/playwright.base.ts";
4
5export default defineConfig(base, {
6 testDir: "./__e2e__",
7 timeout: 30_000,
8 expect: { timeout: 5_000 },
9 use: {
10 viewport: { width: 900, height: 700 },
11 },
12});

extensions/ui/protocol.ts

Deleted
deleted file mode 100644

+0 / −124 text lines

1export type UiConnectionStatus =
2 | "starting"
3 | "waiting"
4 | "connected"
5 | "inactive"
6 | "rpc-starting"
7 | "rpc-connected"
8 | "rpc-dead"
9 | "error"
10 | "stopped";
12export type UiEventBase = {
13 id: number;
14 at: number;
15};
17export type UiStateEvent = UiEventBase & {
18 type: "state";
19 state: UiConnectionStatus;
20 message?: string;
21};
23export type UiLogEvent = UiEventBase & {
24 type: "log";
25 level: "info" | "warning" | "error";
26 message: string;
27};
29export type UiMessageEvent = UiEventBase & {
30 type: "message";
31 role: "user" | "assistant" | "tool" | "system";
32 text: string;
33 streamId?: string;
34};
36export type UiToolEvent = UiEventBase & {
37 type: "tool";
38 phase: "start" | "update" | "end";
39 toolCallId: string;
40 name: string;
41 text?: string;
42 isError?: boolean;
43};
45export type UiErrorEvent = UiEventBase & {
46 type: "error";
47 message: string;
48 action: string;
49 retryable: boolean;
50 clientId?: string;
51 agentHint?: string;
52 relatedId?: string;
53};
55export type UiRequestEvent = UiEventBase & {
56 type: "ui_request";
57 requestId: string;
58 method: "select" | "confirm" | "input" | "editor";
59 title: string;
60 message: string;
61 options?: string[];
62 placeholder?: string;
63 prefill?: string;
64 expectsResponse: true;
65};
67export type UiNotifyEvent = UiEventBase & {
68 type: "ui_notify";
69 requestId: string;
70 message: string;
71 notifyType?: "info" | "warning" | "error";
72};
74export type UiStatusEvent = UiEventBase & {
75 type: "ui_status" | "ui_title" | "ui_widget" | "ui_editor_text";
76 requestId: string;
77 message: string;
78 [key: string]: unknown;
79};
81export type UiWidgetEvent = UiEventBase & {
82 type: "widget_mount" | "widget_update" | "widget_action" | "widget_error";
83 widgetId: string;
84 toolCallId?: string;
85 title?: string;
86 fallback?: string;
87 html?: string;
88 status?: "mounted" | "updated" | "action" | "error";
89 actionId?: string;
90 label?: string;
91 payload?: unknown;
92 message?: string;
93};
95export type UiEvent =
96 | UiStateEvent
97 | UiLogEvent
98 | UiMessageEvent
99 | UiToolEvent
100 | UiErrorEvent
101 | UiRequestEvent
102 | UiNotifyEvent
103 | UiStatusEvent
104 | UiWidgetEvent;
106export type UiEventInput = UiEvent extends infer Event
107 ? Event extends UiEventBase
108 ? Omit<Event, keyof UiEventBase>
109 : never
110 : never;
112export type UiCommandInfo = {
113 name: string;
114 description?: string;
115};
117export type UiSnapshot = {
118 version: 1;
119 lastEventId: number;
120 status: UiConnectionStatus;
121 sessionPath?: string;
122 commands: UiCommandInfo[];
123 events: UiEvent[];
124};

extensions/ui/qr.ts

Deleted
deleted file mode 100644

+0 / −18 text lines

1import QRCode from "qrcode";
2import { uiError } from "./errors";
3
4export async function renderQr(url: string): Promise<string> {
5 try {
6 return await QRCode.toString(url, {
7 type: "terminal",
8 small: true,
9 margin: 1,
10 });
11 } catch (cause) {
12 throw uiError("qr_failed", "Could not render terminal QR code", {
13 action: "Use the OSC link in the /ui widget instead.",
14 retryable: true,
15 cause,
16 });
17 }
18}

extensions/ui/rpc.ts

Deleted
deleted file mode 100644

+0 / −199 text lines

1import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2import { randomUUID } from "node:crypto";
3import { once } from "node:events";
4
5export type RpcState = "starting" | "connected" | "slow-start" | "exit";
6
7export type RpcResponse = {
8 id?: string;
9 type: "response";
10 command?: string;
11 success: boolean;
12 data?: unknown;
13 error?: string;
14};
16export type RpcRequest = Record<string, unknown> & {
17 id?: string;
18 type: string;
19};
21export type ParsedJsonLines = {
22 messages: unknown[];
23 rest: string;
24};
26export type StartRpcOptions = {
27 sessionPath: string;
28 cwd: string;
29 command?: string;
30 args?: string[];
31 env?: NodeJS.ProcessEnv;
32 requestTimeoutMs?: number;
33 slowStartMs?: number;
34 onEvent?: (event: unknown) => void;
35 onState?: (state: RpcState, details?: unknown) => void;
36};
38export type RpcClient = {
39 child: ChildProcessWithoutNullStreams;
40 send(request: RpcRequest): Promise<RpcResponse>;
41 stderr(): string;
42 close(reason: string): Promise<void>;
43};
45export type RpcSpawnPlan = {
46 command: string;
47 args: string[];
48 windowsHide?: boolean;
49};
51type Pending = {
52 resolve(response: RpcResponse): void;
53 reject(error: Error): void;
54 timer: NodeJS.Timeout;
55};
57export function parseJsonLines(input: string): ParsedJsonLines {
58 const messages: unknown[] = [];
59 const parts = input.split("\n");
60 const rest = parts.pop() ?? "";
61 for (const raw of parts) {
62 const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
63 if (!line) continue;
64 messages.push(JSON.parse(line));
65 }
66 return { messages, rest };
67}
69export function startRpc(options: StartRpcOptions): RpcClient {
70 const command =
71 options.command ?? process.env.PI_UI_RPC_BIN ?? defaultPiBin();
72 const args = options.args ?? [
73 "--mode",
74 "rpc",
75 "--session",
76 options.sessionPath,
77 ];
78 const spawnPlan = rpcSpawnPlan(command, args);
79 const child = spawn(spawnPlan.command, spawnPlan.args, {
80 cwd: options.cwd,
81 env: { ...process.env, ...options.env },
82 stdio: "pipe",
83 windowsHide: spawnPlan.windowsHide,
84 });
85 const pending = new Map<string, Pending>();
86 const stderrChunks: string[] = [];
87 let stdoutRest = "";
88 let closed = false;
89 let connected = false;
90 const timeoutMs = options.requestTimeoutMs ?? 30_000;
91 const slowTimer = setTimeout(() => {
92 if (!connected && !closed) options.onState?.("slow-start");
93 }, options.slowStartMs ?? 8_000);
95 child.stdout.on("data", (chunk) => {
96 const parsed = parseJsonLines(stdoutRest + String(chunk));
97 stdoutRest = parsed.rest;
98 for (const message of parsed.messages) handleMessage(message);
99 });
101 child.stderr.on("data", (chunk) => {
102 stderrChunks.push(String(chunk));
103 });
105 child.once("spawn", () => options.onState?.("starting"));
106 child.once("exit", (code, signal) => {
107 closed = true;
108 clearTimeout(slowTimer);
109 const error = new Error(
110 `RPC process exited: code=${code ?? "null"} signal=${signal ?? "null"}`,
111 );
112 for (const item of pending.values()) {
113 clearTimeout(item.timer);
114 item.reject(error);
115 }
116 pending.clear();
117 options.onState?.("exit", { code, signal });
118 });
120 function handleMessage(message: unknown): void {
121 connected = true;
122 options.onState?.("connected");
123 if (isResponse(message) && message.id && pending.has(message.id)) {
124 const item = pending.get(message.id);
125 if (!item) return;
126 pending.delete(message.id);
127 clearTimeout(item.timer);
128 item.resolve(message);
129 return;
130 }
131 options.onEvent?.(message);
132 }
134 return {
135 child,
136 send(request) {
137 if (closed) return Promise.reject(new Error("RPC process is closed"));
138 const id = request.id ?? randomUUID();
139 const payload = { ...request, id };
140 return new Promise((resolve, reject) => {
141 const timer = setTimeout(() => {
142 pending.delete(id);
143 reject(new Error(`RPC request timed out: ${request.type}`));
144 }, timeoutMs);
145 pending.set(id, { resolve, reject, timer });
146 child.stdin.write(`${JSON.stringify(payload)}\n`, (error) => {
147 if (!error) return;
148 pending.delete(id);
149 clearTimeout(timer);
150 reject(error);
151 });
152 });
153 },
154 stderr: () => stderrChunks.join(""),
155 async close(reason) {
156 void reason;
157 if (closed) return;
158 closed = true;
159 clearTimeout(slowTimer);
160 for (const item of pending.values()) {
161 clearTimeout(item.timer);
162 item.reject(new Error("RPC process closed"));
163 }
164 pending.clear();
165 child.kill();
166 await Promise.race([
167 once(child, "exit"),
168 new Promise((resolve) => setTimeout(resolve, 1000)),
169 ]);
170 },
171 };
172}
174function isResponse(value: unknown): value is RpcResponse {
175 return (
176 !!value &&
177 typeof value === "object" &&
178 (value as { type?: unknown }).type === "response"
179 );
180}
182export function rpcSpawnPlan(
183 command: string,
184 args: string[],
185 platform: NodeJS.Platform = process.platform,
186): RpcSpawnPlan {
187 if (platform === "win32" && command.toLowerCase().endsWith(".cmd")) {
188 return {
189 command: "cmd.exe",
190 args: ["/d", "/s", "/c", command, ...args],
191 windowsHide: true,
192 };
193 }
194 return { command, args, windowsHide: platform === "win32" };
195}
197function defaultPiBin(): string {
198 return process.platform === "win32" ? "pi.cmd" : "pi";
199}

extensions/ui/runtime.ts

Deleted
deleted file mode 100644

+0 / −444 text lines

1import { mkdirSync, writeFileSync } from "node:fs";
2import path from "node:path";
3import {
4 abortCurrent,
5 cycleModel,
6 runBash,
7 runSlashCommand,
8 sendPrompt,
9} from "./command-adapter";
10import { parseComposerInput } from "./composer";
11import { EventStore } from "./events";
12import {
13 extensionUiEventFromRequest,
14 extensionUiResponseCommand,
15 isExtensionUiRequest,
16} from "./extension-ui";
17import { LifecycleTracker } from "./lifecycle";
18import { chooseLanAddress } from "./network";
19import { openBrowser } from "./open";
20import { renderQr } from "./qr";
21import { type RpcClient, type StartRpcOptions, startRpc } from "./rpc";
22import { startUiServer, type UiServer, type UiServerState } from "./server";
23import { seedUiSession, type UiSeedSessionManager } from "./session-seed";
24import { TelemetryAggregator, type TelemetryEvent } from "./telemetry";
25import { renderUiWidget } from "./terminal-widget";
27export type UiRuntimeStatus = {
28 active: boolean;
29 url?: string;
30 state: UiServerState | "starting" | "stopped" | "error";
31 clients: number;
32 rpcState?: string;
33 sessionPath?: string;
34 lastError?: string;
35};
37export type UiRuntime = {
38 status(): UiRuntimeStatus;
39 widgetLines(): string[];
40 redrawQr(): Promise<void>;
41 open(): Promise<void>;
42 stop(reason: string): Promise<void>;
43};
45export type CreateUiRuntimeOptions = {
46 sessionLabel: string;
47 cwd?: string;
48 address?: string;
49 preferredPort?: number;
50 openBrowser?: boolean;
51 onChange?: () => void;
52 sessionManager?: UiSeedSessionManager;
53 startRpcBridge?: (options: StartRpcOptions) => RpcClient;
54 events?: EventStore;
55};
57export async function createUiRuntime(
58 options: CreateUiRuntimeOptions,
59): Promise<UiRuntime> {
60 let state: UiRuntimeStatus = { active: false, state: "starting", clients: 0 };
61 let qr = "";
62 let server: UiServer | undefined;
63 let rpc: RpcClient | undefined;
64 let sessionPath: string | undefined;
65 let rpcState: string | undefined;
66 const events = options.events ?? new EventStore();
67 const telemetry = new TelemetryAggregator();
68 const lifecycle = new LifecycleTracker();
69 const lifecycleTimer = setInterval(() => {
70 for (const event of lifecycle.check()) publish(event);
71 }, 5_000);
72 if (typeof lifecycleTimer.unref === "function") lifecycleTimer.unref();
74 const publish = (input: Parameters<EventStore["append"]>[0]) => {
75 const event = events.append(input);
76 server?.publish(event);
77 return event;
78 };
80 if (options.sessionManager) {
81 const seed = seedUiSession({
82 cwd: options.cwd ?? process.cwd(),
83 sessionManager: options.sessionManager,
84 });
85 sessionPath = seed.path;
86 if (seed.warning)
87 publish({ type: "log", level: "warning", message: seed.warning });
88 publish({ type: "state", state: "rpc-starting" });
89 rpcState = "starting";
90 rpc = (options.startRpcBridge ?? startRpc)({
91 sessionPath,
92 cwd: options.cwd ?? process.cwd(),
93 onState(next) {
94 rpcState = next;
95 publish({ type: "state", state: mapRpcState(next) });
96 state = currentStatus();
97 options.onChange?.();
98 },
99 onEvent(event) {
100 const normalized = normalizeRpcEvent(event);
101 if (normalized) publish(normalized);
102 },
103 });
104 }
106 const address = options.address ?? chooseLanAddress();
107 server = await startUiServer({
108 address,
109 preferredPort: options.preferredPort,
110 events,
111 snapshotStatus: rpcState ? mapRpcState(rpcState) : "waiting",
112 onBrowserMessage: async (message) => {
113 await handleBrowserMessage(message, rpc, publish, telemetry, lifecycle);
114 },
115 onClientState: () => {
116 state = currentStatus();
117 options.onChange?.();
118 },
119 });
120 qr = await renderQr(server.publicUrl);
121 writeSmokeUrl(server.publicUrl);
122 state = currentStatus();
123 if (options.openBrowser !== false) await openBrowser(server.baseUrl);
125 function currentStatus(): UiRuntimeStatus {
126 if (!server) return { active: false, state: "stopped", clients: 0 };
127 return {
128 active: server.state() !== "stopped",
129 url: server.baseUrl,
130 state: server.state(),
131 clients: server.clients(),
132 rpcState,
133 sessionPath,
134 };
135 }
137 return {
138 status: () => state,
139 widgetLines: () => {
140 if (!server || !state.url) return [];
141 return renderUiWidget({
142 url: state.url,
143 qr,
144 state: state.state,
145 sessionLabel: options.sessionLabel,
146 clients: state.clients,
147 rpcState: state.rpcState,
148 sessionPath: state.sessionPath
149 ? path.basename(state.sessionPath)
150 : undefined,
151 lastError: state.lastError,
152 });
153 },
154 async redrawQr() {
155 if (!server) return;
156 qr = await renderQr(server.publicUrl);
157 state = currentStatus();
158 options.onChange?.();
159 },
160 async open() {
161 if (!server) return;
162 await openBrowser(server.baseUrl);
163 },
164 async stop(reason: string) {
165 clearInterval(lifecycleTimer);
166 const currentServer = server;
167 const currentRpc = rpc;
168 server = undefined;
169 rpc = undefined;
170 state = { active: false, state: "stopped", clients: 0 };
171 options.onChange?.();
172 await currentRpc?.close(reason);
173 if (currentServer) await currentServer.close(reason);
174 },
175 };
176}
178async function handleBrowserMessage(
179 message: unknown,
180 rpc: RpcClient | undefined,
181 publish: (input: Parameters<EventStore["append"]>[0]) => unknown,
182 telemetry: TelemetryAggregator,
183 lifecycle: LifecycleTracker,
184): Promise<void> {
185 if (!rpc || !isBrowserMessage(message)) return;
186 if (message.type === "abort") {
187 await abortCurrent(rpc);
188 publish({
189 type: "state",
190 state: "rpc-connected",
191 message: "abort requested",
192 });
193 return;
194 }
195 if (message.type === "cycle_model" || message.type === "cycle-model") {
196 await cycleModel(rpc);
197 publish({
198 type: "state",
199 state: "rpc-connected",
200 message: "model cycle requested",
201 });
202 return;
203 }
204 if (message.type === "toggle-expand") {
205 publish({ type: "log", level: "info", message: "toggle expand requested" });
206 return;
207 }
208 if (message.type === "lifecycle_heartbeat") {
209 lifecycle.heartbeat(message.clientId);
210 return;
211 }
212 if (message.type === "lifecycle_reconnect") {
213 publish(lifecycle.reconnect(message.clientId));
214 return;
215 }
216 if (message.type === "lifecycle_close") {
217 publish(lifecycle.close(message.clientId));
218 return;
219 }
220 if (message.type === "lifecycle_pagehide") {
221 publish(lifecycle.pagehide(message.clientId));
222 return;
223 }
224 if (message.type === "telemetry_batch") {
225 for (const event of message.events) telemetry.add(event);
226 publish({
227 type: "log",
228 level: "info",
229 message: "browser digest will be sent",
230 });
231 return;
232 }
233 if (message.type === "ui_response") {
234 await rpc.send(
235 extensionUiResponseCommand(message.id, responseInput(message)),
236 );
237 return;
238 }
239 if (message.type === "widget_action") {
240 publish({
241 type: "widget_action",
242 widgetId: message.widgetId,
243 label: message.label,
244 payload: message.payload,
245 });
246 return;
247 }
248 if (message.type === "widget_prompt") {
249 const text = `[widget ${message.widgetId}] ${message.text}`;
250 publish({
251 type: "widget_action",
252 widgetId: message.widgetId,
253 label: "prompt",
254 payload: { text: message.text },
255 });
256 await sendPrompt(rpc, text);
257 return;
258 }
259 if (message.type === "widget_notify") {
260 publish({
261 type: "ui_notify",
262 requestId: message.widgetId,
263 message: message.message,
264 });
265 return;
266 }
267 if (message.type === "widget_error") {
268 publish({
269 type: "widget_error",
270 widgetId: message.widgetId,
271 message: message.message,
272 });
273 return;
274 }
275 const parsed = parseComposerInput(message.text);
276 if (parsed.kind === "bash") {
277 publish({ type: "message", role: "user", text: message.text });
278 await runBash(rpc, parsed.command, parsed.excludeFromContext);
279 return;
280 }
281 if (parsed.kind === "slash") {
282 publish({ type: "message", role: "user", text: parsed.text });
283 await runSlashCommand(rpc, parsed.command, parsed.args);
284 return;
285 }
286 publish({ type: "message", role: "user", text: parsed.text });
287 await sendPrompt(rpc, parsed.text, {
288 digest: () => telemetry.digest(),
289 clearDigest: () => telemetry.clear(),
290 });
291}
293type BrowserMessage =
294 | { type: "prompt"; text: string }
295 | { type: "abort" }
296 | { type: "cycle_model" }
297 | { type: "cycle-model" }
298 | { type: "toggle-expand" }
299 | { type: "telemetry_batch"; events: TelemetryEvent[] }
300 | { type: "lifecycle_heartbeat"; clientId: string }
301 | { type: "lifecycle_reconnect"; clientId: string }
302 | { type: "lifecycle_close"; clientId: string }
303 | { type: "lifecycle_pagehide"; clientId: string }
304 | ({ type: "ui_response"; id: string } & (
305 | { value: string }
306 | { confirmed: boolean }
307 | { cancelled: true }
308 ))
309 | {
310 type: "widget_action";
311 widgetId: string;
312 label: string;
313 payload?: unknown;
314 }
315 | { type: "widget_prompt"; widgetId: string; text: string }
316 | { type: "widget_notify"; widgetId: string; message: string }
317 | { type: "widget_error"; widgetId: string; message: string };
319function isBrowserMessage(value: unknown): value is BrowserMessage {
320 if (!value || typeof value !== "object") return false;
321 const type = (value as { type?: unknown }).type;
322 if (type === "prompt")
323 return typeof (value as { text?: unknown }).text === "string";
324 if (type === "telemetry_batch")
325 return Array.isArray((value as { events?: unknown }).events);
326 if (
327 type === "lifecycle_heartbeat" ||
328 type === "lifecycle_reconnect" ||
329 type === "lifecycle_close" ||
330 type === "lifecycle_pagehide"
331 )
332 return typeof (value as { clientId?: unknown }).clientId === "string";
333 if (type === "ui_response")
334 return typeof (value as { id?: unknown }).id === "string";
335 if (type === "widget_action")
336 return (
337 typeof (value as { widgetId?: unknown }).widgetId === "string" &&
338 typeof (value as { label?: unknown }).label === "string"
339 );
340 if (type === "widget_prompt")
341 return (
342 typeof (value as { widgetId?: unknown }).widgetId === "string" &&
343 typeof (value as { text?: unknown }).text === "string"
344 );
345 if (type === "widget_notify" || type === "widget_error")
346 return (
347 typeof (value as { widgetId?: unknown }).widgetId === "string" &&
348 typeof (value as { message?: unknown }).message === "string"
349 );
350 return (
351 type === "abort" ||
352 type === "cycle_model" ||
353 type === "cycle-model" ||
354 type === "toggle-expand"
355 );
356}
358function responseInput(
359 message: Extract<BrowserMessage, { type: "ui_response" }>,
360) {
361 if ("value" in message) return { value: message.value };
362 if ("confirmed" in message) return { confirmed: message.confirmed };
363 return { cancelled: true as const };
364}
366function writeSmokeUrl(url: string): void {
367 const target = process.env.PI_UI_SMOKE_URL_FILE;
368 if (!target) return;
369 mkdirSync(path.dirname(target), { recursive: true });
370 writeFileSync(target, `${url}\n`, { encoding: "utf8" });
371}
373function mapRpcState(state: string) {
374 if (state === "connected") return "rpc-connected";
375 if (state === "exit") return "rpc-dead";
376 return "rpc-starting";
377}
379export function normalizeRpcEvent(
380 event: unknown,
381): Parameters<EventStore["append"]>[0] | undefined {
382 if (isExtensionUiRequest(event)) return extensionUiEventFromRequest(event);
383 if (isRpcMessageUpdate(event)) {
384 return {
385 type: "message",
386 role: "assistant",
387 text: assistantText(event.message),
388 streamId: "assistant-stream",
389 };
390 }
391 if (isRpcToolEvent(event)) {
392 return {
393 type: "tool",
394 phase: event.type.endsWith("start")
395 ? "start"
396 : event.type.endsWith("end")
397 ? "end"
398 : "update",
399 toolCallId: event.toolCallId,
400 name: event.toolName,
401 };
402 }
403 return undefined;
404}
406function assistantText(message: unknown): string {
407 if (!message || typeof message !== "object") return "";
408 const content = (message as { content?: unknown }).content;
409 if (!Array.isArray(content)) return "";
410 return content
411 .map((item) =>
412 item &&
413 typeof item === "object" &&
414 typeof (item as { text?: unknown }).text === "string"
415 ? (item as { text: string }).text
416 : "",
417 )
418 .join("");
419}
421function isRpcMessageUpdate(
422 event: unknown,
423): event is { message: unknown; assistantMessageEvent: { delta: string } } {
424 return (
425 !!event &&
426 typeof event === "object" &&
427 (event as { type?: unknown }).type === "message_update" &&
428 typeof (event as { assistantMessageEvent?: { delta?: unknown } })
429 .assistantMessageEvent?.delta === "string"
430 );
431}
433function isRpcToolEvent(
434 event: unknown,
435): event is { type: string; toolCallId: string; toolName: string } {
436 return (
437 !!event &&
438 typeof event === "object" &&
439 typeof (event as { type?: unknown }).type === "string" &&
440 (event as { type: string }).type.startsWith("tool_execution_") &&
441 typeof (event as { toolCallId?: unknown }).toolCallId === "string" &&
442 typeof (event as { toolName?: unknown }).toolName === "string"
443 );
444}

extensions/ui/scripts/phase1-smoke.mjs

Deleted
deleted file mode 100644

+0 / −87 text lines

1#!/usr/bin/env node
2import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3import { resolve } from "node:path";
4import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
5import { chromium } from "@playwright/test";
6import { createUiRuntime } from "../runtime.js";
7
8const args = new Set(process.argv.slice(2));
9const noBrowser = args.has("--no-browser");
10const outDir = resolve(
11 process.cwd(),
12 CONFIG_DIR_NAME,
13 "tmp",
14 "ui-phase1-smoke",
15);
16const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe";
17mkdirSync(outDir, { recursive: true });
19const runtime = await createUiRuntime({
20 sessionLabel: "ui: phase1-smoke",
21 address: "127.0.0.1",
22 cwd: process.cwd(),
23 openBrowser: false,
24});
26try {
27 const status = runtime.status();
28 if (!status.url) throw new Error("UI runtime did not expose a URL");
29 const url = status.url;
30 const parsed = new URL(url);
32 const tokenless = await fetch(`${parsed.origin}/api/status`);
33 if (tokenless.status !== 401)
34 throw new Error(
35 `Expected tokenless /api/status 401, got ${tokenless.status}`,
36 );
38 const shell = await fetch(url);
39 if (!shell.ok) throw new Error(`Bare root shell failed: ${shell.status}`);
40 const cookie = shell.headers.get("set-cookie") ?? "";
41 const authorized = await fetch(`${parsed.origin}/api/status`, {
42 headers: { cookie },
43 });
44 if (!authorized.ok)
45 throw new Error(`Authorized /api/status failed: ${authorized.status}`);
47 let browserText = "skipped";
48 if (!noBrowser) browserText = await verifyBrowser(url);
50 const summary = {
51 url: redactUrl(url),
52 state: status.state,
53 tokenlessStatus: tokenless.status,
54 authorizedStatus: authorized.status,
55 browserText,
56 };
57 const summaryPath = resolve(outDir, "summary.json");
58 writeFileSync(summaryPath, `${JSON.stringify(summary, null, "\t")}\n`);
59 console.log(`url: ${summary.url}`);
60 console.log(`summary: ${summaryPath}`);
61} finally {
62 await runtime.stop("phase1 smoke complete");
63}
65async function verifyBrowser(url) {
66 const browser = await chromium.launch({
67 headless: true,
68 executablePath: existsSync(chromePath) ? chromePath : undefined,
69 });
70 try {
71 const page = await browser.newPage();
72 await page.goto(url);
73 await page.waitForSelector("#ui-shell");
74 await page.waitForSelector("#ui-composer");
75 return await page.locator("#ui-progress").innerText();
76 } finally {
77 await browser.close();
78 }
79}
81function redactUrl(value) {
82 const tokenParam = "token" + "=";
83 return value.replace(
84 new RegExp(`${tokenParam}[A-Za-z0-9_-]+`),
85 `${tokenParam}[redacted]`,
86 );
87}

extensions/ui/scripts/tmux-smoke.mjs

Deleted
deleted file mode 100644

+0 / −38 text lines

1#!/usr/bin/env node
2import { spawnSync } from "node:child_process";
3
4if (process.platform === "win32") {
5 console.error(
6 "tmux-smoke is disabled on win32. Use scripts/zellij-smoke.mjs.",
7 );
8 process.exit(2);
9}
11const tmux = process.env.TMUX_BIN ?? "tmux";
12const session = "ui-" + "smoke-" + Date.now().toString(36);
14run(tmux, ["-V"]);
15run(tmux, ["new-session", "-d", "-s", session, "pi -e extensions/ui/index.ts"]);
17console.log(`tmux session: ${session}`);
18console.log(`attach: ${tmux} attach -t ${session}`);
19console.log("manual checkpoints:");
20console.log("1. Send /ui and verify terminal widget shows URL + QR.");
21console.log(
22 "2. Open URL in browser; verify exact URL works and /api/status without token returns 401.",
23);
24console.log(
25 "3. Try /, /skill:, !, !!, Esc, Ctrl+O, Ctrl+P, card/form/raw widget, click widget action.",
26);
27console.log(
28 "4. Scroll/click/select/background/return/send next prompt; verify digest appears once.",
29);
30console.log(
31 "5. Send /ui off; verify browser disconnect and terminal UI restored as far as Pi exposes.",
32);
33console.log(`kill: ${tmux} kill-session -t ${session}`);
35function run(command, args) {
36 const result = spawnSync(command, args, { stdio: "inherit", shell: false });
37 if (result.status !== 0) process.exit(result.status ?? 1);
38}

extensions/ui/scripts/zellij-smoke.mjs

Deleted
deleted file mode 100644

+0 / −269 text lines

1#!/usr/bin/env node
2import { spawnSync } from "node:child_process";
3import {
4 existsSync,
5 mkdirSync,
6 readFileSync,
7 rmSync,
8 writeFileSync,
9} from "node:fs";
10import { resolve } from "node:path";
11import { setTimeout as sleep } from "node:timers/promises";
12import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
14if (process.platform !== "win32") {
15 console.error(
16 "zellij-smoke is the win32 smoke path. Use scripts/tmux-smoke.mjs on non-win32.",
17 );
18 process.exit(2);
19}
21const args = new Set(process.argv.slice(2));
22const noBrowser = args.has("--no-browser");
23const noFallback = args.has("--no-fallback");
24const zellij = process.env.ZELLIJ ?? "zellij";
25const pi = process.env.PI_UI_SMOKE_PI ?? "pi.cmd";
26const session =
27 process.env.PI_UI_SMOKE_SESSION ?? `ui-smoke-${Date.now().toString(36)}`;
28const cwd = process.cwd();
29const outDir = resolve(cwd, CONFIG_DIR_NAME, "tmp", "ui-zellij-smoke");
30const screenPath = resolve(outDir, `${session}.screen.txt`);
31const urlPath = resolve(outDir, `${session}.url.txt`);
32const env = {
33 ...process.env,
34 ZELLIJ_SESSION_NAME: session,
35 MSYS_NO_PATHCONV: "1",
36};
38mkdirSync(outDir, { recursive: true });
40console.log(`zellij session: ${session}`);
41console.log(`cwd: ${cwd}`);
42run(zellij, ["--version"]);
43startZellijSession();
44await waitForSession();
46const pane = "terminal_0";
47console.log(`pane: ${pane}`);
48sendLine(pane, `cd /d ${cwd}`);
49await sleep(500);
50sendLine(
51 pane,
52 `set PI_UI_NO_AUTO_OPEN=1&& set "PI_UI_SMOKE_URL_FILE=${urlPath}"&& ${pi} -e extensions/ui/index.ts`,
53);
54await waitForPiReady(pane);
56sendLine(pane, "/ui");
57await waitForUiUrl(pane, screenPath);
58const firstScreen = safeRead(screenPath);
59const url = safeRead(urlPath).trim() || extractUiUrl(firstScreen);
61if (!url) {
62 const fallback = noFallback ? { status: "skipped" } : runPhase1Fallback();
63 writeSummary({
64 session,
65 pane,
66 screenPath,
67 url: undefined,
68 status401: undefined,
69 zellijAutomation: "url-not-found",
70 fallback,
71 });
72 console.error(`No /ui URL found in ${screenPath}.`);
73 console.error(`attach: ${zellij} attach ${session}`);
74 console.error(`kill: ${zellij} kill-session ${session}`);
75 if (fallback.status === "passed") process.exit(0);
76 process.exit(1);
77}
79const status401 = await probe401(url);
80console.log(`url: ${redactUrl(url)}`);
81console.log(`tokenless /api/status: ${status401}`);
82if (status401 !== 401) {
83 console.error("Expected tokenless /api/status to return 401.");
84}
86let browserText = "skipped";
87if (!noBrowser) {
88 browserText = await verifyBrowser(url);
89 openBrowser(url);
90}
91rmSync(urlPath, { force: true });
92await sleep(2_000);
93sendLine(pane, "/ui off");
94await sleep(3_000);
95dump(pane, screenPath);
96writeSummary({
97 session,
98 pane,
99 screenPath,
100 url: redactUrl(url),
101 status401,
102 browserText,
103});
105console.log(`screen: ${screenPath}`);
106console.log(`attach: ${zellij} attach ${session}`);
107console.log(`kill: ${zellij} kill-session ${session}`);
108if (status401 !== 401) process.exit(1);
110function startZellijSession() {
111 const psCommand = [
112 "Start-Process",
113 "-FilePath",
114 quoteForPowerShell(zellij),
115 "-ArgumentList",
116 `@('attach','--create-background','${session.replaceAll("'", "''")}')`,
117 "-WindowStyle",
118 "Minimized",
119 ].join(" ");
120 run("powershell.exe", ["-NoLogo", "-NoProfile", "-Command", psCommand]);
121}
123async function waitForSession() {
124 for (let attempt = 0; attempt < 20; attempt += 1) {
125 const sessions = runCapture(zellij, ["list-sessions"], {
126 allowFailure: true,
127 });
128 if (sessions.includes(session)) return;
129 await sleep(500);
130 }
131 throw new Error(`zellij session did not start: ${session}`);
132}
134function quoteForPowerShell(value) {
135 return `'${value.replaceAll("'", "''")}'`;
136}
138async function waitForPiReady(paneId) {
139 for (let attempt = 0; attempt < 40; attempt += 1) {
140 dump(paneId, screenPath);
141 const screen = safeRead(screenPath);
142 if (screen.includes("builtin-tools") && screen.includes("gpt-")) return;
143 await sleep(1_000);
144 }
145 throw new Error("Pi did not become ready in zellij pane");
146}
148async function waitForUiUrl(paneId, path) {
149 for (let attempt = 0; attempt < 40; attempt += 1) {
150 dump(paneId, path);
151 if (safeRead(urlPath).trim() || extractUiUrl(safeRead(path))) return;
152 await sleep(1_000);
153 }
154}
156function sendLine(paneId, line) {
157 const paneArgs = paneId ? ["-p", paneId] : [];
158 run(zellij, ["action", "write-chars", ...paneArgs, line], { env });
159 run(zellij, ["action", "send-keys", ...paneArgs, "Enter"], { env });
160}
162function dump(paneId, path) {
163 const paneArgs = paneId ? ["-p", paneId] : [];
164 run(zellij, ["action", "dump-screen", ...paneArgs, "--path", path], { env });
165}
167async function probe401(uiUrl) {
168 const parsed = new URL(uiUrl);
169 const response = await fetch(`${parsed.origin}/api/status`);
170 return response.status;
171}
173async function verifyBrowser(url) {
174 const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe";
175 const { chromium } = await import("@playwright/test");
176 const browser = await chromium.launch({
177 headless: true,
178 executablePath: existsSync(chromePath) ? chromePath : undefined,
179 });
180 try {
181 const page = await browser.newPage();
182 await page.goto(url);
183 await page.waitForSelector("#ui-shell");
184 await page.waitForSelector("#ui-composer");
185 return await page.locator("#ui-progress").innerText();
186 } finally {
187 await browser.close();
188 }
189}
191function openBrowser(url) {
192 spawnSync("cmd.exe", ["/d", "/s", "/c", "start", "", url], {
193 stdio: "ignore",
194 detached: true,
195 });
196}
198function extractUiUrl(text) {
199 const tokenParam = "token" + "=";
200 return text
201 .split(/\s+/)
202 .find((part) => part.startsWith("http://") && part.includes(tokenParam));
203}
205function redactUrl(value) {
206 const tokenParam = "token" + "=";
207 return value.replace(
208 new RegExp(`${tokenParam}[A-Za-z0-9_-]+`),
209 `${tokenParam}[redacted]`,
210 );
211}
213function safeRead(path) {
214 try {
215 return readFileSync(path, "utf8");
216 } catch {
217 return "";
218 }
219}
221function runPhase1Fallback() {
222 console.error(
223 "Running Phase 1 browser smoke fallback outside zellij pane automation.",
224 );
225 const commandArgs = [
226 "--import",
227 "tsx",
228 "extensions/ui/scripts/phase1-smoke.mjs",
229 ];
230 if (noBrowser) commandArgs.push("--no-browser");
231 const result = spawnSync(process.execPath, commandArgs, {
232 stdio: "inherit",
233 shell: false,
234 timeout: 120_000,
235 });
236 return {
237 status: result.status === 0 ? "passed" : "failed",
238 exitCode: result.status,
239 };
240}
242function writeSummary(summary) {
243 const path = resolve(outDir, `${session}.summary.json`);
244 writeFileSync(path, `${JSON.stringify(summary, null, "\t")}\n`);
245 console.log(`summary: ${path}`);
246}
248function run(command, commandArgs, options = {}) {
249 const result = spawnSync(command, commandArgs, {
250 stdio: "inherit",
251 shell: false,
252 timeout: 60_000,
253 ...options,
254 });
255 if (result.status !== 0) process.exit(result.status ?? 1);
256}
258function runCapture(command, commandArgs, options = {}) {
259 const { allowFailure, ...spawnOptions } = options;
260 const result = spawnSync(command, commandArgs, {
261 encoding: "utf8",
262 stdio: ["ignore", "pipe", "inherit"],
263 shell: false,
264 timeout: 60_000,
265 ...spawnOptions,
266 });
267 if (!allowFailure && result.status !== 0) process.exit(result.status ?? 1);
268 return result.stdout ?? "";
269}

extensions/ui/server.ts

Deleted
deleted file mode 100644

+0 / −298 text lines

1import { randomBytes } from "node:crypto";
2import {
3 createServer,
4 type IncomingMessage,
5 type Server,
6 type ServerResponse,
7} from "node:http";
8import { type WebSocket, WebSocketServer } from "ws";
9import type { EventStore } from "./events";
10import { listenHostFor, uiUrl } from "./network";
11import type { UiCommandInfo, UiConnectionStatus, UiEvent } from "./protocol";
12import { renderAppCss } from "./web/app.css";
13import { renderAppHtml } from "./web/app.html";
14import { renderAppJs } from "./web/app.js";
16export type UiServerState = "waiting" | "connected" | "inactive" | "stopped";
18export type UiServer = {
19 baseUrl: string;
20 publicUrl: string;
21 port: number;
22 token: string;
23 state(): UiServerState;
24 clients(): number;
25 publish(event: UiEvent): void;
26 close(reason: string): Promise<void>;
27};
29export type StartUiServerOptions = {
30 address: string;
31 token?: string;
32 preferredPort?: number;
33 onClientState?: (state: UiServerState) => void;
34 events?: EventStore;
35 snapshotStatus?: UiConnectionStatus;
36 onBrowserMessage?: (message: unknown) => void | Promise<void>;
37 commands?: UiCommandInfo[];
38};
40const COOKIE = "pi_ui_token";
41const MAX_BODY_BYTES = 1_000_000;
43export async function startUiServer(
44 options: StartUiServerOptions,
45): Promise<UiServer> {
46 const token = options.token ?? randomBytes(32).toString("base64url");
47 const host = listenHostFor(options.address);
48 let currentState: UiServerState = "waiting";
49 let clientSeq = 0;
50 let closed = false;
51 const sockets = new Set<WebSocket>();
52 const wss = new WebSocketServer({ noServer: true });
53 const server = createServer((req, res) => {
54 void dispatch(req, res, {
55 token,
56 events: options.events,
57 snapshotStatus: options.snapshotStatus,
58 commands: options.commands,
59 state: () => currentState,
60 clients: () => sockets.size,
61 setState(next) {
62 currentState = next;
63 options.onClientState?.(next);
64 },
65 });
66 });
68 server.on("upgrade", (req, socket, head) => {
69 const url = new URL(req.url ?? "/", "http://127.0.0.1");
70 if (url.pathname !== "/ws" || !authorizedUrlOrRequest(url, req, token)) {
71 socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
72 socket.destroy();
73 return;
74 }
75 wss.handleUpgrade(req, socket, head, (ws) => {
76 const clientId = `client-${++clientSeq}`;
77 sockets.add(ws);
78 currentState = "connected";
79 options.onClientState?.("connected");
80 void options.onBrowserMessage?.({
81 type: "lifecycle_reconnect",
82 clientId,
83 });
84 const after = Number(url.searchParams.get("after") ?? 0);
85 ws.send(
86 JSON.stringify({
87 type: "events",
88 events:
89 options.events?.replayAfter(Number.isFinite(after) ? after : 0) ??
90 [],
91 }),
92 );
93 ws.on("message", (data) => {
94 try {
95 const message = JSON.parse(String(data));
96 if (
97 message &&
98 typeof message === "object" &&
99 !("clientId" in message)
100 ) {
101 message.clientId = clientId;
102 }
103 void options.onBrowserMessage?.(message);
104 } catch {
105 ws.send(JSON.stringify({ type: "error", message: "invalid json" }));
106 }
107 });
108 ws.on("close", () => {
109 sockets.delete(ws);
110 currentState = sockets.size > 0 ? "connected" : "inactive";
111 options.onClientState?.(currentState);
112 void options.onBrowserMessage?.({ type: "lifecycle_close", clientId });
113 });
114 });
115 });
117 await listen(server, host, options.preferredPort ?? 0);
118 const address = server.address();
119 if (!address || typeof address === "string")
120 throw new Error("Failed to bind UI server");
121 const baseUrl = `http://127.0.0.1:${address.port}`;
122 const publicUrl = uiUrl(options.address, address.port, token);
124 return {
125 baseUrl,
126 publicUrl,
127 port: address.port,
128 token,
129 state: () => currentState,
130 clients: () => sockets.size,
131 publish(event) {
132 const payload = JSON.stringify({ type: "events", events: [event] });
133 for (const ws of sockets) {
134 if (ws.readyState === ws.OPEN) ws.send(payload);
135 }
136 },
137 async close(reason) {
138 void reason;
139 if (closed) return;
140 closed = true;
141 currentState = "stopped";
142 options.onClientState?.("stopped");
143 for (const ws of sockets) ws.close();
144 sockets.clear();
145 wss.close();
146 await closeServer(server);
147 },
148 };
149}
151type RouteContext = {
152 token: string;
153 events?: EventStore;
154 snapshotStatus?: UiConnectionStatus;
155 commands?: UiCommandInfo[];
156 state(): UiServerState;
157 clients(): number;
158 setState(state: UiServerState): void;
159};
161async function dispatch(
162 req: IncomingMessage,
163 res: ServerResponse,
164 ctx: RouteContext,
165): Promise<void> {
166 try {
167 const url = new URL(req.url ?? "/", "http://127.0.0.1");
168 setSecurityHeaders(res);
169 if (hasOversizedBody(req)) {
170 return json(res, 413, { error: "body too large" });
171 }
172 if (req.method === "GET" && url.pathname === "/") {
173 return serveIndex(req, url, res, ctx);
174 }
175 if (!authorized(req, ctx.token)) return serveUnauthorized(res);
176 if (req.method === "GET" && url.pathname === "/assets/app.js") {
177 return text(res, 200, "text/javascript; charset=utf-8", renderAppJs());
178 }
179 if (req.method === "GET" && url.pathname === "/assets/app.css") {
180 return text(res, 200, "text/css; charset=utf-8", renderAppCss());
181 }
182 if (req.method === "GET" && url.pathname === "/api/status") {
183 return json(res, 200, { state: ctx.state(), clients: ctx.clients() });
184 }
185 if (req.method === "GET" && url.pathname === "/api/snapshot") {
186 return json(
187 res,
188 200,
189 ctx.events?.snapshot({
190 status: ctx.snapshotStatus ?? ctx.state(),
191 commands: ctx.commands,
192 }) ?? {
193 version: 1,
194 lastEventId: 0,
195 status: ctx.snapshotStatus ?? ctx.state(),
196 commands: ctx.commands ?? [],
197 events: [],
198 },
199 );
200 }
201 return json(res, 404, { error: "not found" });
202 } catch (error) {
203 return json(res, 500, {
204 error: error instanceof Error ? error.message : String(error),
205 });
206 }
207}
209function serveIndex(
210 req: IncomingMessage,
211 url: URL,
212 res: ServerResponse,
213 ctx: RouteContext,
214): void {
215 void req;
216 void url;
217 res.setHeader(
218 "Set-Cookie",
219 `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`,
220 );
221 res.setHeader("Content-Type", "text/html; charset=utf-8");
222 res.end(renderAppHtml());
223}
225function serveUnauthorized(res: ServerResponse): void {
226 res.statusCode = 401;
227 res.setHeader("Content-Type", "text/html; charset=utf-8");
228 res.end(
229 "<!doctype html><title>Unauthorized</title><h1>Unauthorized</h1><p>Open the exact /ui link or scan the current QR code again.</p>",
230 );
231}
233function authorized(req: IncomingMessage, token: string): boolean {
234 return (
235 req.headers.authorization === `Bearer ${token}` ||
236 cookieAuthorized(req, token)
237 );
238}
240function authorizedUrlOrRequest(
241 url: URL,
242 req: IncomingMessage,
243 token: string,
244): boolean {
245 return url.searchParams.get("token") === token || authorized(req, token);
246}
248function cookieAuthorized(req: IncomingMessage, token: string): boolean {
249 return (req.headers.cookie ?? "")
250 .split(/;\s*/)
251 .some((cookie) => cookie === `${COOKIE}=${token}`);
252}
254function hasOversizedBody(req: IncomingMessage): boolean {
255 const length = req.headers["content-length"];
256 return typeof length === "string" && Number(length) > MAX_BODY_BYTES;
257}
259function setSecurityHeaders(res: ServerResponse): void {
260 res.setHeader("X-Content-Type-Options", "nosniff");
261 res.setHeader("Referrer-Policy", "no-referrer");
262 res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
263}
265function json(res: ServerResponse, status: number, body: unknown): void {
266 text(res, status, "application/json; charset=utf-8", JSON.stringify(body));
267}
269function text(
270 res: ServerResponse,
271 status: number,
272 contentType: string,
273 body: string,
274): void {
275 res.statusCode = status;
276 res.setHeader("Content-Type", contentType);
277 res.end(body);
278}
280function listen(server: Server, host: string, port: number): Promise<void> {
281 return new Promise((resolve, reject) => {
282 const onError = (error: NodeJS.ErrnoException) => {
283 server.off("error", onError);
284 reject(error);
285 };
286 server.once("error", onError);
287 server.listen(port, host, () => {
288 server.off("error", onError);
289 resolve();
290 });
291 });
292}
294function closeServer(server: Server): Promise<void> {
295 return new Promise((resolve, reject) => {
296 server.close((error) => (error ? reject(error) : resolve()));
297 });
298}

extensions/ui/session-seed.ts

Deleted
deleted file mode 100644

+0 / −63 text lines

1import { uiError } from "./errors";
2
3export type UiSeedMethod = "active-branch" | "whole-tree";
4
5export type UiSeedResult = {
6 path: string;
7 method: UiSeedMethod;
8 warning?: string;
9};
11export type UiSeedSessionManager = {
12 getLeafId(): string | null;
13 getSessionFile(): string | undefined;
14 createBranchedSession(leafId: string): string | undefined;
15};
17export type UiSeedOptions = {
18 cwd: string;
19 sessionManager: UiSeedSessionManager;
20 allowWholeTreeFallback?: boolean;
21 forkWholeTree?: (sourcePath: string, cwd: string) => string | undefined;
22};
24export const WHOLE_TREE_WARNING =
25 "Whole-tree session fork includes abandoned branches; active LLM context remains branch-clean.";
27export function seedUiSession(options: UiSeedOptions): UiSeedResult {
28 const leafId = options.sessionManager.getLeafId();
29 if (!leafId) {
30 throw uiError(
31 "session_seed_failed",
32 "Cannot seed UI session: no active leaf",
33 {
34 action:
35 "Send at least one message in the terminal session, then run /ui again.",
36 retryable: true,
37 },
38 );
39 }
41 const branched = options.sessionManager.createBranchedSession(leafId);
42 if (branched) return { path: branched, method: "active-branch" };
44 if (options.allowWholeTreeFallback) {
45 const source = options.sessionManager.getSessionFile();
46 const forked = source
47 ? options.forkWholeTree?.(source, options.cwd)
48 : undefined;
49 if (forked) {
50 return {
51 path: forked,
52 method: "whole-tree",
53 warning: WHOLE_TREE_WARNING,
54 };
55 }
56 }
58 throw uiError("session_seed_failed", "Cannot seed UI session", {
59 action:
60 "Use a persistent terminal session with an active branch, then run /ui again.",
61 retryable: true,
62 });
63}

extensions/ui/telemetry.ts

Deleted
deleted file mode 100644

+0 / −65 text lines

1export type TelemetryEvent =
2 | { type: "viewport"; device: string; width: number; height: number }
3 | { type: "scroll"; y: number; dwellMs: number }
4 | { type: "click"; target: string }
5 | { type: "focus" | "blur"; target: string }
6 | { type: "selection"; text: string }
7 | { type: "widget_action"; widgetId: string; label: string }
8 | { type: "form"; formId: string; state: "submit" | "abandon" }
9 | { type: "error"; message: string }
10 | { type: "pagehide" };
12export type TelemetryAggregatorOptions = {
13 maxEvents?: number;
14};
16export class TelemetryAggregator {
17 readonly #maxEvents: number;
18 #events: TelemetryEvent[] = [];
20 constructor(options: TelemetryAggregatorOptions = {}) {
21 this.#maxEvents = options.maxEvents ?? 24;
22 }
24 add(event: TelemetryEvent): void {
25 this.#events.push(redactEvent(event));
26 while (this.#events.length > this.#maxEvents) this.#events.shift();
27 }
29 digest(): string {
30 if (this.#events.length === 0) return "";
31 return ["Browser digest:", ...this.#events.map(formatEvent)].join("\n");
32 }
34 clear(): void {
35 this.#events = [];
36 }
37}
39export function redactText(text: string): string {
40 return text ? `[redacted ${text.length} chars]` : "";
41}
43function redactEvent(event: TelemetryEvent): TelemetryEvent {
44 if (event.type === "selection")
45 return { ...event, text: redactText(event.text) };
46 if (event.type === "error")
47 return { ...event, message: redactText(event.message) };
48 return event;
49}
51function formatEvent(event: TelemetryEvent): string {
52 if (event.type === "viewport")
53 return `- viewport ${event.device} ${event.width}x${event.height}`;
54 if (event.type === "scroll")
55 return `- scroll y=${event.y} dwell=${event.dwellMs}ms`;
56 if (event.type === "click") return `- click ${event.target}`;
57 if (event.type === "focus") return `- focus ${event.target}`;
58 if (event.type === "blur") return `- blur ${event.target}`;
59 if (event.type === "selection") return `- selection ${event.text}`;
60 if (event.type === "widget_action")
61 return `- widget ${event.widgetId} action ${event.label}`;
62 if (event.type === "form") return `- form ${event.formId} ${event.state}`;
63 if (event.type === "error") return `- error ${event.message}`;
64 return "- pagehide";
65}

extensions/ui/terminal-widget.ts

Deleted
deleted file mode 100644

+0 / −77 text lines

1import path from "node:path";
2import type { UiServerState } from "./server";
3
4export type WidgetState = {
5 url: string;
6 qr: string;
7 state: UiServerState | "starting" | "error";
8 sessionLabel: string;
9 clients: number;
10 rpcState?: string;
11 sessionPath?: string;
12 lastError?: string;
13};
15const WIDTH = 64;
16const CONTENT_WIDTH = WIDTH - 4;
17const OSC8_RE = /\u001b]8;;.*?\u001b\\|\u001b]8;;\u001b\\/g;
19export function osc8Link(url: string, label: string): string {
20 return `\u001b]8;;${url}\u001b\\${label}\u001b]8;;\u001b\\`;
21}
23export function renderUiWidget(state: WidgetState): string[] {
24 const session = state.sessionPath
25 ? path.basename(state.sessionPath)
26 : "pending";
27 const rows = [
28 "pi ui",
29 osc8Link(state.url, "open browser ui"),
30 `url: ${urlWithoutParams(state.url)}`,
31 `session: ${state.sessionLabel}`,
32 `state: ${state.state} · clients: ${state.clients} · rpc: ${state.rpcState ?? "not-started"}`,
33 `file: ${session}`,
34 "press ESC to stop · /ui off · mobile QR: /ui qr",
35 ];
36 if (state.lastError) rows.push(`error: ${state.lastError}`);
38 return [top(), ...rows.flatMap(row), bottom()];
39}
41function top(): string {
42 return `┏${"━".repeat(WIDTH - 2)}┓`;
43}
45function bottom(): string {
46 return `┗${"━".repeat(WIDTH - 2)}┛`;
47}
49function row(content: string): string[] {
50 return wrap(content).map(
51 (part) =>
52 `┃ ${part}${" ".repeat(Math.max(0, CONTENT_WIDTH - visibleLength(part)))} ┃`,
53 );
54}
56function wrap(content: string): string[] {
57 if (visibleLength(content) <= CONTENT_WIDTH) return [content];
58 const parts: string[] = [];
59 let rest = content;
60 while (visibleLength(rest) > CONTENT_WIDTH) {
61 parts.push(rest.slice(0, CONTENT_WIDTH));
62 rest = rest.slice(CONTENT_WIDTH);
63 }
64 if (rest) parts.push(rest);
65 return parts;
66}
68function visibleLength(content: string): number {
69 return content.replace(OSC8_RE, "").length;
70}
72function urlWithoutParams(value: string): string {
73 const url = new URL(value);
74 url.search = "";
75 url.hash = "";
76 return url.toString();
77}

extensions/ui/visual-tools.ts

Deleted
deleted file mode 100644

+0 / −101 text lines

1import {
2 defineTool,
3 type ToolDefinition,
4} from "@earendil-works/pi-coding-agent";
5import { Type } from "typebox";
6import type { UiWidgetEvent } from "./protocol";
7import { WidgetStore } from "./widget-state";
8
9export type VisualToolsOptions = {
10 store?: WidgetStore;
11 publish?: (event: UiWidgetEvent) => void;
12};
14const mountParams = Type.Object({
15 title: Type.String(),
16 fallback: Type.String(),
17 html: Type.String(),
18});
20const updateParams = Type.Object({
21 widgetId: Type.String(),
22 html: Type.String(),
23});
25const waitParams = Type.Object({
26 widgetId: Type.String(),
27 prompt: Type.Optional(Type.String()),
28});
30export function createVisualTools(
31 options: VisualToolsOptions = {},
32): ToolDefinition[] {
33 const store = options.store ?? new WidgetStore();
34 return [
35 mountTool("ui_card", "Card", store, options.publish),
36 mountTool("ui_table", "Table", store, options.publish),
37 mountTool("ui_diagram", "Diagram", store, options.publish),
38 mountTool("ui_form", "Form", store, options.publish),
39 mountTool("ui_mockup", "Mockup", store, options.publish),
40 mountTool("ui_html", "HTML", store, options.publish),
41 defineTool({
42 name: "ui_update",
43 label: "UI Update",
44 description: "Update an existing trusted UI widget by id.",
45 parameters: updateParams,
46 async execute(_toolCallId, params) {
47 const event = store.update(params.widgetId, { html: params.html });
48 options.publish?.(event);
49 return {
50 content: [{ type: "text", text: `Updated ${params.widgetId}` }],
51 details: event,
52 };
53 },
54 }),
55 defineTool({
56 name: "ui_wait_action",
57 label: "UI Wait Action",
58 description:
59 "Declare that the agent is waiting for a visible action from a trusted UI widget.",
60 parameters: waitParams,
61 async execute(_toolCallId, params) {
62 return {
63 content: [
64 {
65 type: "text",
66 text: `Waiting for action from ${params.widgetId}${params.prompt ? `: ${params.prompt}` : ""}`,
67 },
68 ],
69 details: params,
70 };
71 },
72 }),
73 ];
74}
76function mountTool(
77 name: string,
78 label: string,
79 store: WidgetStore,
80 publish: ((event: UiWidgetEvent) => void) | undefined,
81): ToolDefinition {
82 return defineTool({
83 name,
84 label: `UI ${label}`,
85 description: `Render a trusted ${label.toLowerCase()} widget in the browser UI stream.`,
86 parameters: mountParams,
87 async execute(toolCallId, params) {
88 const event = store.mount({
89 toolCallId,
90 title: params.title,
91 fallback: params.fallback,
92 html: params.html,
93 });
94 publish?.(event);
95 return {
96 content: [{ type: "text", text: params.fallback }],
97 details: event,
98 };
99 },
100 });
101}

extensions/ui/web/app.css.ts

Deleted
deleted file mode 100644

+0 / −36 text lines

1import { renderThemeCss } from "./theme.css.js";
2
3export function renderAppCss(): string {
4 return `${renderThemeCss()}
5:root {
6 font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
7}
8#ui-stream { min-height: 0; min-width: 0; padding: 12px; overflow: auto; overscroll-behavior: contain; scroll-padding-bottom: 180px; }
9.ui-event { border: 2px solid color-mix(in srgb, var(--nugu-line) 50%, transparent); background: var(--nugu-panel); padding: 8px; margin: 0 0 8px; white-space: pre-wrap; content-visibility: auto; contain-intrinsic-size: 80px; }
10.ui-event-user { border-width: 4px; border-color: var(--nugu-user); }
11.ui-visual-block-row { overflow: auto; contain: layout paint; }
12.ui-visual-block-row header { font-weight: 800; margin-bottom: 8px; }
13.ui-visual-fallback { color: var(--nugu-muted); margin-bottom: 8px; }
14.ui-visual-block-row iframe { display: block; width: 100%; height: min(60vh, 600px); max-height: 600px; border: 2px solid var(--nugu-line); background: var(--nugu-bg); }
15.ui-visual-error-hint { margin-top: 8px; font-weight: 800; }
16.ui-code, .ui-diff pre { overflow: auto; max-height: 60vh; padding: 8px; border: 2px solid var(--nugu-line); background: var(--nugu-bg); }
17.ui-diff summary { cursor: pointer; font-weight: 800; }
18.ui-expand-output { display: block; margin-top: 8px; font: inherit; border: 2px solid var(--nugu-line); background: var(--nugu-bg); color: var(--nugu-fg); }
19#ui-bottom { position: sticky; bottom: 0; z-index: 10; border-top: 4px solid var(--nugu-accent); background: var(--nugu-panel); box-shadow: 0 -8px 0 color-mix(in srgb, var(--nugu-bg) 85%, transparent); }
20#ui-meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 6px 8px; border-bottom: 2px solid var(--nugu-line); color: var(--nugu-muted); font-size: 12px; }
21#ui-meta span { border: 1px solid color-mix(in srgb, var(--nugu-line) 45%, transparent); padding: 2px 5px; }
22#ui-digest { color: var(--nugu-muted); }
23#ui-digest[data-pending="true"] { color: var(--nugu-accent); border-color: var(--nugu-accent); }
24#ui-composer { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 8px; }
25#ui-input-wrap { position: relative; min-width: 0; }
26#ui-input { width: 100%; max-height: 30vh; min-height: 42px; resize: vertical; font: inherit; background: var(--nugu-bg); color: var(--nugu-fg); border: 2px solid var(--nugu-line); padding: 8px; }
27#ui-command-menu { position: absolute; left: 0; right: 0; bottom: 100%; border: 2px solid var(--nugu-line); background: var(--nugu-bg); max-height: 40vh; overflow: auto; }
28.ui-command-item { display: block; width: 100%; padding: 6px 8px; border: 0; border-bottom: 1px solid color-mix(in srgb, var(--nugu-line) 35%, transparent); background: var(--nugu-bg); color: var(--nugu-fg); font: inherit; text-align: left; }
29.ui-command-item.is-selected { background: var(--nugu-fg); color: var(--nugu-bg); }
30.ui-dialog-controls { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
31.ui-dialog-controls button { font: inherit; border: 2px solid var(--nugu-line); background: var(--nugu-bg); color: var(--nugu-fg); padding: 4px 8px; }
32.ui-dialog-controls textarea { min-width: min(100%, 420px); min-height: 80px; font: inherit; }
33#ui-send { font: inherit; background: var(--nugu-fg); color: var(--nugu-bg); border: 0; padding: 0 16px; }
34#ui-send:disabled { opacity: .5; }
35`;
36}

extensions/ui/web/app.html.ts

Deleted
deleted file mode 100644

+0 / −28 text lines

1export function renderAppHtml(): string {
2 return `<!doctype html>
3<html lang="en">
4<head>
5<meta charset="utf-8">
6<meta name="viewport" content="width=device-width, initial-scale=1">
7<title>Pi UI</title>
8<link rel="stylesheet" href="/assets/app.css">
9<script type="module" src="/assets/app.js"></script>
10</head>
11<body>
12<div id="ui-shell">
13<header id="ui-top"><strong>PI</strong><span id="ui-progress">starting</span><span>/ui off in terminal</span></header>
14<main id="ui-stream" aria-live="polite"></main>
15<div id="ui-bottom">
16<div id="ui-meta"><span>model —</span><span>thinking —</span><span>ctx —</span><span>Esc abort · Ctrl+O expand · Ctrl+P model · / @ !</span><span id="ui-digest" role="status" aria-live="polite" data-pending="false">digest 0</span></div>
17<form id="ui-composer">
18<div id="ui-input-wrap">
19<textarea id="ui-input" name="prompt" placeholder="Message Pi"></textarea>
20<div id="ui-command-menu" hidden></div>
21</div>
22<button id="ui-send" type="submit">SEND</button>
23</form>
24</div>
25</div>
26</body>
27</html>`;
28}

extensions/ui/web/app.js.ts

Deleted
deleted file mode 100644

+0 / −246 text lines

1import { renderCodeBlockComponentJs } from "./components/code-block.js";
2import { renderComposerComponentJs } from "./components/composer.js";
3import { renderDialogsComponentJs } from "./components/dialogs.js";
4import { renderDiffViewJs } from "./components/diff-view.js";
5import { renderDigestIndicatorJs } from "./components/digest-indicator.js";
6import { renderLongOutputJs } from "./components/long-output.js";
7import { renderVirtualStreamJs } from "./components/virtual-stream.js";
8import { renderVisualBlockComponentJs } from "./components/visual-block.js";
9import { renderTelemetryWorkerJs } from "./worker.js";
11export function renderAppJs(): string {
12 return `const status = document.querySelector('#ui-progress');
13const meta = document.querySelector('#ui-meta');
14const stream = document.querySelector('#ui-stream');
15const form = document.querySelector('#ui-composer');
16const input = document.querySelector('#ui-input');
17const send = document.querySelector('#ui-send');
18const menu = document.querySelector('#ui-command-menu');
19let commands = [];
20let visibleCommands = [];
21let selectedCommandIndex = 0;
22let telemetryWorker;
23let lastEventId = 0;
24let socket;
25const statusItems = new Map();
27${renderComposerComponentJs()}
28${renderDialogsComponentJs()}
29${renderVisualBlockComponentJs()}
30${renderDigestIndicatorJs()}
31${renderCodeBlockComponentJs()}
32${renderDiffViewJs()}
33${renderLongOutputJs()}
34${renderVirtualStreamJs()}
35const telemetryWorkerSource = ${JSON.stringify(renderTelemetryWorkerJs())};
36function startTelemetryWorker() {
37 if (!('Worker' in window)) return;
38 const url = URL.createObjectURL(new Blob([telemetryWorkerSource], { type: 'text/javascript' }));
39 telemetryWorker = new Worker(url);
40 telemetryWorker.addEventListener('message', event => {
41 if (event.data?.type === 'telemetry_batch') {
42 setDigestIndicator(telemetryEventCount + (event.data.events || []).length);
43 socket?.send(JSON.stringify(event.data));
44 }
45 });
46}
47function trackTelemetry(event) {
48 try { telemetryWorker?.postMessage({ type: 'telemetry', event }); } catch (_) {}
49}
50function deviceClass() { return innerWidth <= 520 ? 'phone' : innerWidth <= 900 ? 'tablet' : 'desktop'; }
51function targetLabel(target) { return target?.id || target?.name || target?.textContent?.trim()?.slice(0, 40) || target?.tagName || 'unknown'; }
53function authHeaders() {
54 const token = new URL(location.href).searchParams.get('token');
55 return token ? { authorization: 'Bearer ' + token } : {};
56}
58async function fetchSnapshot() {
59 const response = await fetch('/api/snapshot', { headers: authHeaders() });
60 if (!response.ok) throw new Error('snapshot failed: ' + response.status);
61 const snapshot = await response.json();
62 setProgress(snapshot.status);
63 commands = snapshot.commands || [];
64 renderEvents(snapshot.events || []);
65 lastEventId = snapshot.lastEventId || 0;
66}
68function connectSocket() {
69 const token = new URL(location.href).searchParams.get('token');
70 const url = new URL('/ws', location.href);
71 url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
72 if (token) url.searchParams.set('token', token);
73 url.searchParams.set('after', String(lastEventId));
74 socket = new WebSocket(url);
75 socket.addEventListener('message', event => {
76 const payload = JSON.parse(event.data);
77 if (payload.type === 'events') renderEvents(payload.events || []);
78 });
79 socket.addEventListener('open', () => {
80 if (status.textContent === 'starting') setProgress('connected');
81 socket.send(JSON.stringify({ type: 'lifecycle_heartbeat' }));
82 setInterval(() => socket?.readyState === WebSocket.OPEN && socket.send(JSON.stringify({ type: 'lifecycle_heartbeat' })), 5000);
83 });
84 socket.addEventListener('close', () => { setProgress('disconnected'); });
85}
87function renderEvents(events) {
88 const fragment = document.createDocumentFragment();
89 for (const event of events) {
90 const synthetic = event.id > 9_000_000_000_000_000;
91 if (!synthetic && event.id <= lastEventId) continue;
92 if (!synthetic) lastEventId = event.id;
93 applyInternalEvent(event);
94 if (event.type === 'message' && event.role === 'user') finalizeStreamingRows();
95 if (!isStreamEvent(event)) continue;
96 const row = document.createElement('article');
97 row.className = 'ui-event ui-event-' + (event.role || event.type);
98 row.dataset.eventId = String(event.id);
99 if (event.streamId) row.dataset.streamId = String(event.streamId);
100 const eventText = event.text || event.message || event.state || '';
101 applyLongOutput(row, String(event.streamId || event.id), String(eventText));
102 const fence = String.fromCharCode(96).repeat(3);
103 if (typeof eventText === 'string' && eventText.startsWith(fence)) {
104 row.textContent = '';
105 const firstNewline = eventText.indexOf('\\n');
106 const language = eventText.slice(3, firstNewline).trim() || 'text';
107 renderCodeBlock(row, language, eventText.slice(firstNewline + 1).replace(new RegExp(fence + '\\\\s*$'), ''));
108 }
109 if (typeof eventText === 'string' && eventText.includes('+++ ') && eventText.includes('--- ')) {
110 row.textContent = '';
111 renderDiffView(row, eventText);
112 }
113 if (event.type === 'ui_request') renderUiRequest(row, event);
114 if (event.type && event.type.startsWith('widget_')) renderVisualBlock(row, event);
115 const existing = event.streamId ? stream.querySelector('[data-stream-id="' + CSS.escape(String(event.streamId)) + '"]') : null;
116 if (existing) existing.replaceWith(row);
117 else fragment.append(row);
118 }
119 appendStreamRows(fragment);
120 streamBatchChannel.port2.postMessage('flush');
121 stream.scrollTop = stream.scrollHeight;
122}
124function applyInternalEvent(event) {
125 if (event.type === 'state') setProgress(event.state);
126 if (event.type === 'log' && event.level === 'error') setProgress(event.message);
127 if (event.type === 'ui_status') updateMetaStatus(event);
128}
130function setProgress(value) {
131 status.textContent = value;
132 status.dataset.state = String(value || 'unknown');
133}
135function updateMetaStatus(event) {
136 const key = event.statusKey || event.key || event.requestId;
137 const value = event.statusText || event.text || '';
138 if (!key) return;
139 if (!value) statusItems.delete(String(key));
140 else statusItems.set(String(key), String(value));
141 renderMetaStatus();
142}
144function finalizeStreamingRows() {
145 for (const row of stream.querySelectorAll('[data-stream-id]')) delete row.dataset.streamId;
146}
148function renderMetaStatus() {
149 const digest = document.querySelector('#ui-digest');
150 const rows = [...statusItems.entries()].slice(-6);
151 meta.textContent = '';
152 if (rows.length === 0) {
153 for (const label of ['model —', 'thinking —', 'ctx —', 'Esc abort · Ctrl+O expand · Ctrl+P model · / @ !']) {
154 const item = document.createElement('span');
155 item.textContent = label;
156 meta.append(item);
157 }
158 } else {
159 for (const [key, value] of rows) {
160 const item = document.createElement('span');
161 item.textContent = key + ': ' + value;
162 meta.append(item);
163 }
164 }
165 if (digest) meta.append(digest);
166}
168function isStreamEvent(event) {
169 return event.type === 'message'
170 || event.type === 'tool'
171 || event.type === 'error'
172 || event.type === 'ui_request'
173 || event.type === 'ui_notify'
174 || String(event.type || '').startsWith('widget_');
175}
177input.addEventListener('input', renderCommandMenu);
178input.addEventListener('keydown', event => {
179 const action = composerKeyAction({
180 key: event.key,
181 ctrlKey: event.ctrlKey,
182 shiftKey: event.shiftKey,
183 menuVisible: !menu.hidden,
184 });
185 if (action === 'menu-next') {
186 event.preventDefault();
187 selectedCommandIndex = moveMenuIndex(selectedCommandIndex, 1, visibleCommands.length);
188 renderCommandMenu();
189 }
190 if (action === 'menu-prev') {
191 event.preventDefault();
192 selectedCommandIndex = moveMenuIndex(selectedCommandIndex, -1, visibleCommands.length);
193 renderCommandMenu();
194 }
195 if (action === 'menu-select') {
196 event.preventDefault();
197 selectCommand(selectedCommandIndex);
198 }
199 if (action === 'abort' || action === 'cycle-model' || action === 'toggle-expand') {
200 event.preventDefault();
201 socket?.send(JSON.stringify({ type: action }));
202 status.textContent = action;
203 }
204 if (action === 'submit') {
205 event.preventDefault();
206 form.requestSubmit();
207 }
208});
210window.addEventListener('message', event => {
211 const data = event.data;
212 if (!data || typeof data !== 'object' || !String(data.type || '').startsWith('widget_')) return;
213 trackTelemetry({ type: 'widget_action', widgetId: data.widgetId, label: data.label || data.type });
214 socket?.send(JSON.stringify(data));
215 renderEvents([{ id: Number.MAX_SAFE_INTEGER - 2, at: Date.now(), type: 'widget_action', widgetId: data.widgetId, label: data.label || data.type, payload: data.payload || data.text || data.message }]);
216});
217window.addEventListener('scroll', () => trackTelemetry({ type: 'scroll', y: scrollY, dwellMs: 0 }), { passive: true });
218window.addEventListener('click', event => trackTelemetry({ type: 'click', target: targetLabel(event.target) }), { passive: true });
219window.addEventListener('focus', event => trackTelemetry({ type: 'focus', target: targetLabel(event.target) }), true);
220window.addEventListener('blur', event => trackTelemetry({ type: 'blur', target: targetLabel(event.target) }), true);
221document.addEventListener('selectionchange', () => trackTelemetry({ type: 'selection', text: String(getSelection() || '') }));
222window.addEventListener('pagehide', () => {
223 trackTelemetry({ type: 'pagehide' });
224 socket?.send(JSON.stringify({ type: 'lifecycle_pagehide' }));
225});
226form.addEventListener('submit', () => trackTelemetry({ type: 'form', formId: 'composer', state: 'submit' }));
228form.addEventListener('submit', event => {
229 event.preventDefault();
230 const text = input.value.trim();
231 if (!text || !socket || socket.readyState !== WebSocket.OPEN) return;
232 send.disabled = true;
233 socket.send(JSON.stringify({ type: 'prompt', text }));
234 input.value = '';
235 setDigestIndicator(0);
236 send.disabled = false;
237});
239startTelemetryWorker();
240trackTelemetry({ type: 'viewport', device: deviceClass(), width: innerWidth, height: innerHeight });
241fetchSnapshot().then(connectSocket).catch(error => {
242 setProgress('error');
243 renderEvents([{ id: Number.MAX_SAFE_INTEGER - 1, at: Date.now(), type: 'error', message: error.message }]);
244});
245`;
246}

extensions/ui/web/components/code-block.js.ts

Deleted
deleted file mode 100644

+0 / −42 text lines

1export function renderPlainCodeBlock(language: string, code: string): string {
2 return `<pre class="ui-code" data-language="${escapeAttr(language)}"><code>${escapeHtml(code)}</code></pre>`;
3}
4
5export function renderCodeBlockComponentJs(): string {
6 return `const highlightCache = new Map();
7function renderCodeBlock(container, language, code) {
8 const pre = document.createElement('pre');
9 pre.className = 'ui-code';
10 pre.dataset.language = language || 'text';
11 const codeNode = document.createElement('code');
12 codeNode.textContent = code;
13 pre.append(codeNode);
14 container.append(pre);
15 queueMicrotask(() => upgradeHighlight(pre, language || 'text', code));
16}
17async function upgradeHighlight(pre, language, code) {
18 try {
19 let highlighter = highlightCache.get('highlighter');
20 if (!highlighter) {
21 const shiki = await import('shiki');
22 highlighter = await shiki.createHighlighter({ themes: ['github-dark'], langs: [language, 'text'] });
23 highlightCache.set('highlighter', highlighter);
24 }
25 pre.innerHTML = highlighter.codeToHtml(code, { lang: language, theme: 'github-dark' });
26 } catch (_) {
27 /* plaintext stays visible */
28 }
29}
30`;
31}
33function escapeAttr(value: string): string {
34 return escapeHtml(value).replaceAll('"', "&quot;");
35}
37function escapeHtml(value: string): string {
38 return value
39 .replaceAll("&", "&amp;")
40 .replaceAll("<", "&lt;")
41 .replaceAll(">", "&gt;");
42}

extensions/ui/web/components/composer.js.ts

Deleted
deleted file mode 100644

+0 / −98 text lines

1import type { UiCommandInfo } from "../../protocol";
2
3export type ComposerKeyAction =
4 | "submit"
5 | "newline"
6 | "abort"
7 | "toggle-expand"
8 | "cycle-model"
9 | "menu-next"
10 | "menu-prev"
11 | "menu-select"
12 | "none";
14export type ComposerKeyInput = {
15 key: string;
16 ctrlKey?: boolean;
17 shiftKey?: boolean;
18 menuVisible?: boolean;
19};
21export function filterCommandItems(
22 commands: UiCommandInfo[],
23 input: string,
24): UiCommandInfo[] {
25 const prefix = input.startsWith("/") ? input.slice(1).toLowerCase() : "";
26 return commands.filter((item) => item.name.toLowerCase().startsWith(prefix));
27}
29export function moveMenuIndex(
30 current: number,
31 delta: number,
32 count: number,
33): number {
34 if (count <= 0) return 0;
35 return (current + delta + count) % count;
36}
38export function composerKeyAction(input: ComposerKeyInput): ComposerKeyAction {
39 const normalized = input.key.toLowerCase();
40 if (input.menuVisible && input.key === "ArrowDown") return "menu-next";
41 if (input.menuVisible && input.key === "ArrowUp") return "menu-prev";
42 if (input.menuVisible && input.key === "Tab") return "menu-select";
43 if (input.ctrlKey && normalized === "o") return "toggle-expand";
44 if (input.ctrlKey && normalized === "p") return "cycle-model";
45 if (input.key === "Escape") return "abort";
46 if (input.key === "Enter" && input.shiftKey) return "newline";
47 if (input.key === "Enter") return "submit";
48 return "none";
49}
51export function renderComposerComponentJs(): string {
52 return `function filterCommandItems(commands, input) {
53 const prefix = input.startsWith('/') ? input.slice(1).toLowerCase() : '';
54 return commands.filter(item => item.name.toLowerCase().startsWith(prefix));
55}
56function moveMenuIndex(current, delta, count) {
57 if (count <= 0) return 0;
58 return (current + delta + count) % count;
59}
60function composerKeyAction(input) {
61 const normalized = input.key.toLowerCase();
62 if (input.menuVisible && input.key === 'ArrowDown') return 'menu-next';
63 if (input.menuVisible && input.key === 'ArrowUp') return 'menu-prev';
64 if (input.menuVisible && input.key === 'Tab') return 'menu-select';
65 if (input.ctrlKey && normalized === 'o') return 'toggle-expand';
66 if (input.ctrlKey && normalized === 'p') return 'cycle-model';
67 if (input.key === 'Escape') return 'abort';
68 if (input.key === 'Enter' && input.shiftKey) return 'newline';
69 if (input.key === 'Enter') return 'submit';
70 return 'none';
71}
72function renderCommandMenu() {
73 menu.innerHTML = '';
74 if (!input.value.startsWith('/')) {
75 menu.hidden = true;
76 selectedCommandIndex = 0;
77 return;
78 }
79 visibleCommands = filterCommandItems(commands, input.value);
80 menu.hidden = visibleCommands.length === 0;
81 for (const [index, command] of visibleCommands.entries()) {
82 const item = document.createElement('button');
83 item.type = 'button';
84 item.className = 'ui-command-item' + (index === selectedCommandIndex ? ' is-selected' : '');
85 item.textContent = '/' + command.name + (command.description ? ' — ' + command.description : '');
86 item.addEventListener('click', () => selectCommand(index));
87 menu.append(item);
88 }
89}
90function selectCommand(index) {
91 const command = visibleCommands[index];
92 if (!command) return;
93 input.value = '/' + command.name + ' ';
94 input.focus();
95 menu.hidden = true;
96}
97`;
98}

extensions/ui/web/components/dialogs.js.ts

Deleted
deleted file mode 100644

+0 / −55 text lines

1export type DialogResponse =
2 | { type: "ui_response"; id: string; value: string }
3 | { type: "ui_response"; id: string; confirmed: boolean }
4 | { type: "ui_response"; id: string; cancelled: true };
5
6export function dialogResponse(
7 id: string,
8 method: string,
9 value: string | boolean | undefined,
10): DialogResponse {
11 if (value === undefined) return { type: "ui_response", id, cancelled: true };
12 if (method === "confirm")
13 return { type: "ui_response", id, confirmed: Boolean(value) };
14 return { type: "ui_response", id, value: String(value) };
15}
17export function renderDialogsComponentJs(): string {
18 return `function dialogResponse(id, method, value) {
19 if (value === undefined) return { type: 'ui_response', id, cancelled: true };
20 if (method === 'confirm') return { type: 'ui_response', id, confirmed: Boolean(value) };
21 return { type: 'ui_response', id, value: String(value) };
22}
23function renderUiRequest(row, event) {
24 const controls = document.createElement('div');
25 controls.className = 'ui-dialog-controls';
26 if (event.method === 'select') {
27 for (const option of event.options || []) {
28 const button = document.createElement('button');
29 button.type = 'button';
30 button.textContent = option;
31 button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, option))));
32 controls.append(button);
33 }
34 } else if (event.method === 'confirm') {
35 for (const item of [['YES', true], ['NO', false]]) {
36 const button = document.createElement('button');
37 button.type = 'button';
38 button.textContent = item[0];
39 button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, item[1]))));
40 controls.append(button);
41 }
42 } else {
43 const field = document.createElement('textarea');
44 field.value = event.prefill || '';
45 field.placeholder = event.placeholder || '';
46 const button = document.createElement('button');
47 button.type = 'button';
48 button.textContent = 'SEND';
49 button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, field.value))));
50 controls.append(field, button);
51 }
52 row.append(controls);
53}
54`;
55}

extensions/ui/web/components/diff-view.js.ts

Deleted
deleted file mode 100644

+0 / −45 text lines

1export type DiffSummary = {
2 files: number;
3 additions: number;
4 deletions: number;
5};
6
7export function diffSummary(diff: string): DiffSummary {
8 let files = 0;
9 let additions = 0;
10 let deletions = 0;
11 for (const line of diff.split("\n")) {
12 if (line.startsWith("+++ ")) files += 1;
13 else if (line.startsWith("+") && !line.startsWith("+++")) additions += 1;
14 else if (line.startsWith("-") && !line.startsWith("---")) deletions += 1;
15 }
16 return { files, additions, deletions };
17}
19export function renderDiffViewJs(): string {
20 return `function renderDiffView(container, diff) {
21 const summary = diffSummary(diff);
22 const details = document.createElement('details');
23 details.className = 'ui-diff';
24 const summaryNode = document.createElement('summary');
25 summaryNode.textContent = summary.files + ' files +' + summary.additions + ' -' + summary.deletions;
26 details.append(summaryNode);
27 const pre = document.createElement('pre');
28 pre.textContent = diff;
29 details.append(pre);
30 container.append(details);
31 queueMicrotask(async () => {
32 try { await import('pierre'); } catch (_) { /* plaintext diff stays visible */ }
33 });
34}
35function diffSummary(diff) {
36 let files = 0, additions = 0, deletions = 0;
37 for (const line of diff.split('\\n')) {
38 if (line.startsWith('+++ ')) files += 1;
39 else if (line.startsWith('+') && !line.startsWith('+++')) additions += 1;
40 else if (line.startsWith('-') && !line.startsWith('---')) deletions += 1;
41 }
42 return { files, additions, deletions };
43}
44`;
45}

extensions/ui/web/components/digest-indicator.js.ts

Deleted
deleted file mode 100644

+0 / −15 text lines

1export function digestIndicatorText(count: number): string {
2 return `digest ${count}`;
3}
4
5export function renderDigestIndicatorJs(): string {
6 return `let telemetryEventCount = 0;
7function setDigestIndicator(count) {
8 telemetryEventCount = count;
9 const indicator = document.querySelector('#ui-digest');
10 if (!indicator) return;
11 indicator.textContent = 'digest ' + count;
12 indicator.dataset.pending = count > 0 ? 'true' : 'false';
13}
14`;
15}

extensions/ui/web/components/long-output.js.ts

Deleted
deleted file mode 100644

+0 / −46 text lines

1export type LongOutputModel = {
2 id: string;
3 text: string;
4 truncated: boolean;
5};
6
7export function longOutputModel(
8 id: string,
9 text: string,
10 expanded: Set<string>,
11 limit = 4_000,
12): LongOutputModel {
13 if (expanded.has(id) || text.length <= limit)
14 return { id, text, truncated: false };
15 return { id, text: text.slice(0, limit), truncated: true };
16}
18export function toggleLongOutput(
19 id: string,
20 expanded: Set<string>,
21): Set<string> {
22 const next = new Set(expanded);
23 if (next.has(id)) next.delete(id);
24 else next.add(id);
25 return next;
26}
28export function renderLongOutputJs(): string {
29 return `const expandedOutputs = new Set();
30function longOutputText(id, text, limit = 4000) {
31 if (expandedOutputs.has(id) || text.length <= limit) return { text, truncated: false };
32 return { text: text.slice(0, limit), truncated: true };
33}
34function applyLongOutput(row, id, text) {
35 const model = longOutputText(id, text);
36 row.textContent = model.text;
37 if (!model.truncated) return;
38 const button = document.createElement('button');
39 button.type = 'button';
40 button.className = 'ui-expand-output';
41 button.textContent = 'expand output';
42 button.addEventListener('click', () => { expandedOutputs.add(id); row.textContent = text; });
43 row.append(button);
44}
45`;
46}

extensions/ui/web/components/virtual-stream.js.ts

Deleted
deleted file mode 100644

+0 / −31 text lines

1export type VirtualWindowOptions = {
2 selectedId: number;
3 threshold?: number;
4 radius?: number;
5};
6
7export function virtualWindow<T extends { id: number }>(
8 events: T[],
9 options: VirtualWindowOptions,
10): T[] {
11 const threshold = options.threshold ?? 200;
12 if (events.length <= threshold) return events;
13 const radius = options.radius ?? 30;
14 const index = events.findIndex((event) => event.id === options.selectedId);
15 if (index === -1) return events.slice(-threshold);
16 return events.slice(Math.max(0, index - radius), index + radius + 1);
17}
19export function renderVirtualStreamJs(): string {
20 return `function appendStreamRows(fragment) {
21 requestAnimationFrame(() => stream.append(fragment));
22}
23function maybeVirtualizeStream() {
24 const rows = [...stream.children];
25 if (rows.length <= 500) return;
26 for (const row of rows.slice(0, rows.length - 500)) row.remove();
27}
28const streamBatchChannel = new MessageChannel();
29streamBatchChannel.port1.onmessage = maybeVirtualizeStream;
30`;
31}

extensions/ui/web/components/visual-block.js.ts

Deleted
deleted file mode 100644

+0 / −71 text lines

1import type { UiWidgetEvent } from "../../protocol";
2import { renderWidgetBridgeScript } from "./widget-bridge.js";
3
4export type VisualBlockShellInput = {
5 widgetId: string;
6 title: string;
7 fallback: string;
8 srcdoc: string;
9};
11export function visualBlockSummary(event: Partial<UiWidgetEvent>): string {
12 if (event.type === "widget_error") {
13 return [event.widgetId, "error", event.message, "agent: fix widget HTML/JS"]
14 .filter(Boolean)
15 .join(" · ");
16 }
17 return [event.title, event.widgetId, event.status, event.fallback]
18 .filter(Boolean)
19 .join(" · ");
20}
22export function renderVisualBlockShell(input: VisualBlockShellInput): string {
23 return `<section class="ui-visual-block" data-widget-id="${escapeAttr(input.widgetId)}">
24<header>${escapeHtml(input.title)} <code>${escapeHtml(input.widgetId)}</code></header>
25<div class="ui-visual-fallback">${escapeHtml(input.fallback)}</div>
26<iframe title="${escapeAttr(input.title)}" srcdoc="${escapeAttr(renderWidgetBridgeScript(input.widgetId) + input.srcdoc)}"></iframe>
27</section>`;
28}
30export function renderVisualBlockComponentJs(): string {
31 return `function renderVisualBlock(row, event) {
32 row.classList.add('ui-visual-block-row');
33 row.textContent = '';
34 const header = document.createElement('header');
35 header.textContent = [event.title, event.widgetId, event.status, event.label, event.message].filter(Boolean).join(' · ');
36 row.append(header);
37 if (event.fallback) {
38 const fallback = document.createElement('div');
39 fallback.className = 'ui-visual-fallback';
40 fallback.textContent = event.fallback;
41 row.append(fallback);
42 }
43 if (event.type === 'widget_mount' || event.type === 'widget_update') {
44 const iframe = document.createElement('iframe');
45 iframe.title = event.title || event.widgetId;
46 iframe.srcdoc = widgetBridgeScript(event.widgetId) + (event.html || '');
47 row.append(iframe);
48 }
49 if (event.type === 'widget_error') {
50 const hint = document.createElement('div');
51 hint.className = 'ui-visual-error-hint';
52 hint.textContent = 'agent: fix widget HTML/JS';
53 row.append(hint);
54 }
55}
56function widgetBridgeScript(widgetId) {
57 return ${JSON.stringify(renderWidgetBridgeScript("__WIDGET_ID__"))}.replaceAll('__WIDGET_ID__', widgetId);
58}
59`;
60}
62function escapeAttr(value: string): string {
63 return escapeHtml(value).replaceAll('"', "&quot;");
64}
66function escapeHtml(value: string): string {
67 return value
68 .replaceAll("&", "&amp;")
69 .replaceAll("<", "&lt;")
70 .replaceAll(">", "&gt;");
71}

extensions/ui/web/components/widget-bridge.js.ts

Deleted
deleted file mode 100644

+0 / −81 text lines

1export type WidgetBridgeMessage =
2 | {
3 type: "widget_action";
4 widgetId: string;
5 label: string;
6 payload?: unknown;
7 }
8 | { type: "widget_prompt"; widgetId: string; text: string }
9 | { type: "widget_notify"; widgetId: string; message: string }
10 | { type: "widget_error"; widgetId: string; message: string };
12export type WidgetAttributionEvent = {
13 type: "widget_action";
14 widgetId: string;
15 label: string;
16 payload?: unknown;
17 at: number;
18};
20export function widgetActionMessage(
21 widgetId: string,
22 label: string,
23 payload?: unknown,
24): WidgetBridgeMessage {
25 return { type: "widget_action", widgetId, label, payload };
26}
28export function attributionEventFromWidgetMessage(
29 message: WidgetBridgeMessage,
30 now: () => number = Date.now,
31): WidgetAttributionEvent {
32 if (message.type === "widget_prompt") {
33 return {
34 type: "widget_action",
35 widgetId: message.widgetId,
36 label: "prompt",
37 payload: { text: message.text },
38 at: now(),
39 };
40 }
41 if (message.type === "widget_notify") {
42 return {
43 type: "widget_action",
44 widgetId: message.widgetId,
45 label: "notify",
46 payload: { message: message.message },
47 at: now(),
48 };
49 }
50 if (message.type === "widget_error") {
51 return {
52 type: "widget_action",
53 widgetId: message.widgetId,
54 label: "error",
55 payload: { message: message.message },
56 at: now(),
57 };
58 }
59 return { ...message, at: now() };
60}
62export function renderWidgetBridgeScript(widgetId: string): string {
63 return `<script>
64(() => {
65 const widgetId = ${JSON.stringify(widgetId)};
66 function send(message) { parent.postMessage({ ...message, widgetId }, '*'); }
67 window.pi = {
68 action(label, payload) { send({ type: 'widget_action', label, payload }); },
69 prompt(text) { send({ type: 'widget_prompt', text }); },
70 steer(text) { send({ type: 'widget_prompt', text }); },
71 followUp(text) { send({ type: 'widget_prompt', text }); },
72 notify(message) { send({ type: 'widget_notify', message }); },
73 state() { return { widgetId }; },
74 on() {},
75 update(payload) { send({ type: 'widget_action', label: 'update', payload }); },
76 requestAttachment() { send({ type: 'widget_action', label: 'attachment-request' }); },
77 };
78 window.addEventListener('error', event => send({ type: 'widget_error', message: event.message }));
79})();
80</script>`;
81}

extensions/ui/web/theme.css.ts

Deleted
deleted file mode 100644

+0 / −33 text lines

1export function renderThemeCss(): string {
2 return `:root {
3 color-scheme: dark light;
4 --nugu-bg: #0b0d10;
5 --nugu-fg: #f2f0e8;
6 --nugu-muted: #979183;
7 --nugu-line: #f2f0e8;
8 --nugu-accent: #ffb000;
9 --nugu-danger: #ff4d4d;
10 --nugu-panel: #14171c;
11 --nugu-user: #f2f0e8;
12 background: var(--nugu-bg);
13 color: var(--nugu-fg);
14}
15@media (prefers-color-scheme: light) {
16 :root {
17 --nugu-bg: #f2f0e8;
18 --nugu-fg: #0b0d10;
19 --nugu-muted: #5e5a52;
20 --nugu-line: #0b0d10;
21 --nugu-accent: #a85f00;
22 --nugu-danger: #b00020;
23 --nugu-panel: #ffffff;
24 --nugu-user: #0b0d10;
25 }
26}
27* { box-sizing: border-box; }
28body { margin: 0; min-height: 100vh; height: 100vh; overflow: hidden; background: var(--nugu-bg); color: var(--nugu-fg); }
29#ui-shell { min-height: 100vh; height: 100vh; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; }
30#ui-top { display: flex; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 3px solid var(--nugu-line); padding: 4px 8px; font-size: 11px; letter-spacing: .08em; text-transform: uppercase; }
31#ui-progress { color: var(--nugu-accent); }
32`;
33}

extensions/ui/web/worker.js.ts

Deleted
deleted file mode 100644

+0 / −56 text lines

1import { redactText, type TelemetryEvent } from "../telemetry";
2
3export type TelemetryBatcherOptions = {
4 maxBatch?: number;
5};
6
7export function createTelemetryBatcher(options: TelemetryBatcherOptions = {}) {
8 const maxBatch = options.maxBatch ?? 12;
9 let pending: TelemetryEvent[] = [];
10 return {
11 add(event: TelemetryEvent): TelemetryEvent[] {
12 pending.push(redactRawEvent(event));
13 if (pending.length < maxBatch) return [];
14 return flush();
15 },
16 flush,
17 };
19 function flush() {
20 const batch = pending;
21 pending = [];
22 return batch;
23 }
24}
26export function renderTelemetryWorkerJs(): string {
27 return `let pending = [];
28const maxBatch = 12;
29function redactText(text) { return text ? '[redacted ' + text.length + ' chars]' : ''; }
30function redact(event) {
31 if (event.type === 'selection') return { ...event, text: redactText(event.text || '') };
32 if (event.type === 'error') return { ...event, message: redactText(event.message || '') };
33 return event;
34}
35function flush() {
36 if (pending.length === 0) return;
37 postMessage({ type: 'telemetry_batch', events: pending });
38 pending = [];
39}
40onmessage = event => {
41 const message = event.data;
42 if (!message || message.type !== 'telemetry') return;
43 pending.push(redact(message.event));
44 if (pending.length >= maxBatch) flush();
45};
46setInterval(flush, 1000);
47`;
48}
50function redactRawEvent(event: TelemetryEvent): TelemetryEvent {
51 if (event.type === "selection")
52 return { ...event, text: redactText(event.text) };
53 if (event.type === "error")
54 return { ...event, message: redactText(event.message) };
55 return event;
56}

extensions/ui/widget-state.ts

Deleted
deleted file mode 100644

+0 / −125 text lines

1import type { UiWidgetEvent } from "./protocol";
2
3export type WidgetRecord = {
4 widgetId: string;
5 toolCallId: string;
6 title: string;
7 fallback: string;
8 html: string;
9 status: "mounted" | "updated" | "action" | "error";
10 audit: UiWidgetEvent[];
11};
13export type WidgetStoreOptions = {
14 now?: () => number;
15};
17export type MountWidgetInput = {
18 toolCallId: string;
19 title: string;
20 fallback: string;
21 html: string;
22};
24export type WidgetActionInput = {
25 toolCallId: string;
26 label: string;
27 payload?: unknown;
28};
30export class WidgetStore {
31 readonly #now: () => number;
32 #actions = 0;
33 #widgets = new Map<string, WidgetRecord>();
35 constructor(options: WidgetStoreOptions = {}) {
36 this.#now = options.now ?? Date.now;
37 }
39 mount(input: MountWidgetInput): UiWidgetEvent {
40 const widgetId = widgetIdForToolCall(input.toolCallId);
41 const event: UiWidgetEvent = {
42 id: 0,
43 at: this.#now(),
44 type: "widget_mount",
45 widgetId,
46 toolCallId: input.toolCallId,
47 title: input.title,
48 fallback: input.fallback,
49 html: input.html,
50 status: "mounted",
51 };
52 this.#widgets.set(widgetId, {
53 widgetId,
54 toolCallId: input.toolCallId,
55 title: input.title,
56 fallback: input.fallback,
57 html: input.html,
58 status: "mounted",
59 audit: [event],
60 });
61 return event;
62 }
64 update(widgetId: string, patch: { html: string }): UiWidgetEvent {
65 const record = this.#require(widgetId);
66 record.html = patch.html;
67 record.status = "updated";
68 return this.#audit(record, {
69 type: "widget_update",
70 widgetId,
71 toolCallId: record.toolCallId,
72 html: patch.html,
73 status: "updated",
74 });
75 }
77 action(widgetId: string, input: WidgetActionInput): UiWidgetEvent {
78 const record = this.#require(widgetId);
79 record.status = "action";
80 return this.#audit(record, {
81 type: "widget_action",
82 widgetId,
83 toolCallId: input.toolCallId,
84 actionId: `action-${++this.#actions}`,
85 label: input.label,
86 payload: input.payload,
87 status: "action",
88 });
89 }
91 error(widgetId: string, message: string): UiWidgetEvent {
92 const record = this.#require(widgetId);
93 record.status = "error";
94 return this.#audit(record, {
95 type: "widget_error",
96 widgetId,
97 toolCallId: record.toolCallId,
98 message,
99 status: "error",
100 });
101 }
103 get(widgetId: string): WidgetRecord | undefined {
104 return this.#widgets.get(widgetId);
105 }
107 #audit(
108 record: WidgetRecord,
109 event: Omit<UiWidgetEvent, "id" | "at">,
110 ): UiWidgetEvent {
111 const full = { id: 0, at: this.#now(), ...event };
112 record.audit.push(full);
113 return full;
114 }
116 #require(widgetId: string): WidgetRecord {
117 const record = this.#widgets.get(widgetId);
118 if (!record) throw new Error(`Unknown widget: ${widgetId}`);
119 return record;
120 }
121}
123export function widgetIdForToolCall(toolCallId: string): string {
124 return `widget-${toolCallId.replaceAll(/[^a-zA-Z0-9_-]/g, "-")}`;
125}

package-lock.json

Modified

+22 / −2506 text lines

475475 "typebox": "*"
476476 }
477477 },
478 "extensions/ui": {
479 "name": "@bugabinga/pi-ext-ui",
480 "license": "MIT",
481 "dependencies": {
482 "@types/ws": "^8.18.1",
483 "pierre": "^2.1.16",
484 "qrcode": "^1.5.4",
485 "shiki": "^4.3.0",
486 "ws": "^8.21.0"
487 },
488 "devDependencies": {
489 "@marcfargas/pi-test-harness": "^0.6.1",
490 "@playwright/test": "^1.61.0",
491 "@types/qrcode": "^1.5.5",
492 "tsx": "^4.20.6",
493 "vitest": "^4.1.9"
494 },
495 "peerDependencies": {
496 "@earendil-works/pi-coding-agent": "*",
497 "@earendil-works/pi-tui": "*",
498 "typebox": "*"
499 }
500 },
501478 "extensions/ultra": {
502479 "name": "@bugabinga/pi-ext-ultra",
503480 "license": "MIT",
13591336 "resolved": "extensions/tune",
13601337 "link": true
13611338 },
1362 "node_modules/@bugabinga/pi-ext-ui": {
1363 "resolved": "extensions/ui",
1364 "link": true
1365 },
13661339 "node_modules/@bugabinga/pi-ext-ultra": {
13671340 "resolved": "extensions/ultra",
13681341 "link": true
13831356 "resolved": "extensions/web",
13841357 "link": true
13851358 },
1386 "node_modules/@cspotcode/source-map-support": {
1387 "version": "0.8.1",
1388 "license": "MIT",
1389 "dependencies": {
1390 "@jridgewell/trace-mapping": "0.3.9"
1391 },
1392 "engines": {
1393 "node": ">=12"
1394 }
1395 },
1396 "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
1397 "version": "0.3.9",
1398 "license": "MIT",
1399 "dependencies": {
1400 "@jridgewell/resolve-uri": "^3.0.3",
1401 "@jridgewell/sourcemap-codec": "^1.4.10"
1402 }
1403 },
14041359 "node_modules/@earendil-works/pi-agent-core": {
14051360 "version": "0.80.6",
14061361 "resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-0.80.6.tgz",
34743429 "tslib": "^2.4.0"
34763431 },
3477 "node_modules/@esbuild/aix-ppc64": {
3478 "version": "0.28.1",
3479 "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
3480 "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
3481 "cpu": [
3482 "ppc64"
3483 ],
3484 "dev": true,
3485 "license": "MIT",
3486 "optional": true,
3487 "os": [
3488 "aix"
3489 ],
3490 "engines": {
3491 "node": ">=18"
3492 }
3493 },
3494 "node_modules/@esbuild/android-arm": {
3495 "version": "0.28.1",
3496 "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
3497 "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
3498 "cpu": [
3499 "arm"
3500 ],
3501 "dev": true,
3502 "license": "MIT",
3503 "optional": true,
3504 "os": [
3505 "android"
3506 ],
3507 "engines": {
3508 "node": ">=18"
3509 }
3510 },
3511 "node_modules/@esbuild/android-arm64": {
3512 "version": "0.28.1",
3513 "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
3514 "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
3515 "cpu": [
3516 "arm64"
3517 ],
3518 "dev": true,
3519 "license": "MIT",
3520 "optional": true,
3521 "os": [
3522 "android"
3523 ],
3524 "engines": {
3525 "node": ">=18"
3526 }
3527 },
3528 "node_modules/@esbuild/android-x64": {
3529 "version": "0.28.1",
3530 "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
3531 "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
3532 "cpu": [
3533 "x64"
3534 ],
3535 "dev": true,
3536 "license": "MIT",
3537 "optional": true,
3538 "os": [
3539 "android"
3540 ],
3541 "engines": {
3542 "node": ">=18"
3543 }
3544 },
3545 "node_modules/@esbuild/darwin-arm64": {
3546 "version": "0.28.1",
3547 "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
3548 "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
3549 "cpu": [
3550 "arm64"
3551 ],
3552 "dev": true,
3553 "license": "MIT",
3554 "optional": true,
3555 "os": [
3556 "darwin"
3557 ],
3558 "engines": {
3559 "node": ">=18"
3560 }
3561 },
3562 "node_modules/@esbuild/darwin-x64": {
3563 "version": "0.28.1",
3564 "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
3565 "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
3566 "cpu": [
3567 "x64"
3568 ],
3569 "dev": true,
3570 "license": "MIT",
3571 "optional": true,
3572 "os": [
3573 "darwin"
3574 ],
3575 "engines": {
3576 "node": ">=18"
3577 }
3578 },
3579 "node_modules/@esbuild/freebsd-arm64": {
3580 "version": "0.28.1",
3581 "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
3582 "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
3583 "cpu": [
3584 "arm64"
3585 ],
3586 "dev": true,
3587 "license": "MIT",
3588 "optional": true,
3589 "os": [
3590 "freebsd"
3591 ],
3592 "engines": {
3593 "node": ">=18"
3594 }
3595 },
3596 "node_modules/@esbuild/freebsd-x64": {
3597 "version": "0.28.1",
3598 "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
3599 "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
3600 "cpu": [
3601 "x64"
3602 ],
3603 "dev": true,
3604 "license": "MIT",
3605 "optional": true,
3606 "os": [
3607 "freebsd"
3608 ],
3609 "engines": {
3610 "node": ">=18"
3611 }
3612 },
3613 "node_modules/@esbuild/linux-arm": {
3614 "version": "0.28.1",
3615 "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
3616 "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
3617 "cpu": [
3618 "arm"
3619 ],
3620 "dev": true,
3621 "license": "MIT",
3622 "optional": true,
3623 "os": [
3624 "linux"
3625 ],
3626 "engines": {
3627 "node": ">=18"
3628 }
3629 },
3630 "node_modules/@esbuild/linux-arm64": {
3631 "version": "0.28.1",
3632 "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
3633 "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
3634 "cpu": [
3635 "arm64"
3636 ],
3637 "dev": true,
3638 "license": "MIT",
3639 "optional": true,
3640 "os": [
3641 "linux"
3642 ],
3643 "engines": {
3644 "node": ">=18"
3645 }
3646 },
3647 "node_modules/@esbuild/linux-ia32": {
3648 "version": "0.28.1",
3649 "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
3650 "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
3651 "cpu": [
3652 "ia32"
3653 ],
3654 "dev": true,
3655 "license": "MIT",
3656 "optional": true,
3657 "os": [
3658 "linux"
3659 ],
3660 "engines": {
3661 "node": ">=18"
3662 }
3663 },
3664 "node_modules/@esbuild/linux-loong64": {
3665 "version": "0.28.1",
3666 "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
3667 "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
3668 "cpu": [
3669 "loong64"
3670 ],
3671 "dev": true,
3672 "license": "MIT",
3673 "optional": true,
3674 "os": [
3675 "linux"
3676 ],
3677 "engines": {
3678 "node": ">=18"
3679 }
3680 },
3681 "node_modules/@esbuild/linux-mips64el": {
3682 "version": "0.28.1",
3683 "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
3684 "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
3685 "cpu": [
3686 "mips64el"
3687 ],
3688 "dev": true,
3689 "license": "MIT",
3690 "optional": true,
3691 "os": [
3692 "linux"
3693 ],
3694 "engines": {
3695 "node": ">=18"
3696 }
3697 },
3698 "node_modules/@esbuild/linux-ppc64": {
3699 "version": "0.28.1",
3700 "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
3701 "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
3702 "cpu": [
3703 "ppc64"
3704 ],
3705 "dev": true,
3706 "license": "MIT",
3707 "optional": true,
3708 "os": [
3709 "linux"
3710 ],
3711 "engines": {
3712 "node": ">=18"
3713 }
3714 },
3715 "node_modules/@esbuild/linux-riscv64": {
3716 "version": "0.28.1",
3717 "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
3718 "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
3719 "cpu": [
3720 "riscv64"
3721 ],
3722 "dev": true,
3723 "license": "MIT",
3724 "optional": true,
3725 "os": [
3726 "linux"
3727 ],
3728 "engines": {
3729 "node": ">=18"
3730 }
3731 },
3732 "node_modules/@esbuild/linux-s390x": {
3733 "version": "0.28.1",
3734 "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
3735 "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
3736 "cpu": [
3737 "s390x"
3738 ],
3739 "dev": true,
3740 "license": "MIT",
3741 "optional": true,
3742 "os": [
3743 "linux"
3744 ],
3745 "engines": {
3746 "node": ">=18"
3747 }
3748 },
3749 "node_modules/@esbuild/linux-x64": {
3750 "version": "0.28.1",
3751 "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
3752 "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
3753 "cpu": [
3754 "x64"
3755 ],
3756 "dev": true,
3757 "license": "MIT",
3758 "optional": true,
3759 "os": [
3760 "linux"
3761 ],
3762 "engines": {
3763 "node": ">=18"
3764 }
3765 },
3766 "node_modules/@esbuild/netbsd-arm64": {
3767 "version": "0.28.1",
3768 "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
3769 "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
3770 "cpu": [
3771 "arm64"
3772 ],
3773 "dev": true,
3774 "license": "MIT",
3775 "optional": true,
3776 "os": [
3777 "netbsd"
3778 ],
3779 "engines": {
3780 "node": ">=18"
3781 }
3782 },
3783 "node_modules/@esbuild/netbsd-x64": {
3784 "version": "0.28.1",
3785 "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
3786 "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
3787 "cpu": [
3788 "x64"
3789 ],
3790 "dev": true,
3791 "license": "MIT",
3792 "optional": true,
3793 "os": [
3794 "netbsd"
3795 ],
3796 "engines": {
3797 "node": ">=18"
3798 }
3799 },
3800 "node_modules/@esbuild/openbsd-arm64": {
3801 "version": "0.28.1",
3802 "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
3803 "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
3804 "cpu": [
3805 "arm64"
3806 ],
3807 "dev": true,
3808 "license": "MIT",
3809 "optional": true,
3810 "os": [
3811 "openbsd"
3812 ],
3813 "engines": {
3814 "node": ">=18"
3815 }
3816 },
3817 "node_modules/@esbuild/openbsd-x64": {
3818 "version": "0.28.1",
3819 "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
3820 "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
3821 "cpu": [
3822 "x64"
3823 ],
3824 "dev": true,
3825 "license": "MIT",
3826 "optional": true,
3827 "os": [
3828 "openbsd"
3829 ],
3830 "engines": {
3831 "node": ">=18"
3832 }
3833 },
3834 "node_modules/@esbuild/openharmony-arm64": {
3835 "version": "0.28.1",
3836 "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
3837 "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
3838 "cpu": [
3839 "arm64"
3840 ],
3841 "dev": true,
3842 "license": "MIT",
3843 "optional": true,
3844 "os": [
3845 "openharmony"
3846 ],
3847 "engines": {
3848 "node": ">=18"
3849 }
3850 },
3851 "node_modules/@esbuild/sunos-x64": {
3852 "version": "0.28.1",
3853 "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
3854 "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
3855 "cpu": [
3856 "x64"
3857 ],
3858 "dev": true,
3859 "license": "MIT",
3860 "optional": true,
3861 "os": [
3862 "sunos"
3863 ],
3864 "engines": {
3865 "node": ">=18"
3866 }
3867 },
3868 "node_modules/@esbuild/win32-arm64": {
3869 "version": "0.28.1",
3870 "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
3871 "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
3872 "cpu": [
3873 "arm64"
3874 ],
3875 "dev": true,
3876 "license": "MIT",
3877 "optional": true,
3878 "os": [
3879 "win32"
3880 ],
3881 "engines": {
3882 "node": ">=18"
3883 }
3884 },
3885 "node_modules/@esbuild/win32-ia32": {
3886 "version": "0.28.1",
3887 "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
3888 "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
3889 "cpu": [
3890 "ia32"
3891 ],
3892 "dev": true,
3893 "license": "MIT",
3894 "optional": true,
3895 "os": [
3896 "win32"
3897 ],
3898 "engines": {
3899 "node": ">=18"
3900 }
3901 },
3902 "node_modules/@esbuild/win32-x64": {
3903 "version": "0.28.1",
3904 "cpu": [
3905 "x64"
3906 ],
3907 "dev": true,
3908 "license": "MIT",
3909 "optional": true,
3910 "os": [
3911 "win32"
3912 ],
3913 "engines": {
3914 "node": ">=18"
3915 }
3916 },
3917 "node_modules/@fat/prompts": {
3918 "version": "0.0.3",
3919 "license": "MIT",
3920 "dependencies": {
3921 "kleur": "^4.0.1",
3922 "sisteransi": "^1.0.5"
3923 },
3924 "engines": {
3925 "node": ">= 14"
3926 }
3927 },
39283432 "node_modules/@google/genai": {
39293433 "version": "1.52.0",
39303434 "hasInstallScript": true,
39763480 },
39773481 "node_modules/@jridgewell/resolve-uri": {
39783482 "version": "3.1.2",
3483 "dev": true,
39793484 "license": "MIT",
39803485 "engines": {
39813486 "node": ">=6.0.0"
39833488 },
39843489 "node_modules/@jridgewell/sourcemap-codec": {
39853490 "version": "1.5.5",
3491 "dev": true,
39863492 "license": "MIT"
39873493 },
39883494 "node_modules/@jridgewell/trace-mapping": {
39943500 "@jridgewell/sourcemap-codec": "^1.4.14"
39963502 },
3997 "node_modules/@kwsites/file-exists": {
3998 "version": "1.1.1",
3999 "license": "MIT",
4000 "dependencies": {
4001 "debug": "^4.1.1"
4002 }
4003 },
4004 "node_modules/@kwsites/promise-deferred": {
4005 "version": "1.1.1",
4006 "license": "MIT"
4007 },
40083503 "node_modules/@marcfargas/pi-test-harness": {
40093504 "version": "0.6.1",
40103505 "dev": true,
40663561 "license": "MIT",
40673562 "peer": true
40683563 },
4069 "node_modules/@octokit/app": {
4070 "version": "14.1.0",
4071 "license": "MIT",
4072 "dependencies": {
4073 "@octokit/auth-app": "^6.0.0",
4074 "@octokit/auth-unauthenticated": "^5.0.0",
4075 "@octokit/core": "^5.0.0",
4076 "@octokit/oauth-app": "^6.0.0",
4077 "@octokit/plugin-paginate-rest": "^9.0.0",
4078 "@octokit/types": "^12.0.0",
4079 "@octokit/webhooks": "^12.0.4"
4080 },
4081 "engines": {
4082 "node": ">= 18"
4083 }
4084 },
4085 "node_modules/@octokit/app/node_modules/@octokit/openapi-types": {
4086 "version": "20.0.0",
4087 "license": "MIT"
4088 },
4089 "node_modules/@octokit/app/node_modules/@octokit/plugin-paginate-rest": {
4090 "version": "9.2.2",
4091 "license": "MIT",
4092 "dependencies": {
4093 "@octokit/types": "^12.6.0"
4094 },
4095 "engines": {
4096 "node": ">= 18"
4097 },
4098 "peerDependencies": {
4099 "@octokit/core": "5"
4100 }
4101 },
4102 "node_modules/@octokit/app/node_modules/@octokit/types": {
4103 "version": "12.6.0",
4104 "license": "MIT",
4105 "dependencies": {
4106 "@octokit/openapi-types": "^20.0.0"
4107 }
4108 },
4109 "node_modules/@octokit/auth-app": {
4110 "version": "6.1.4",
4111 "license": "MIT",
4112 "dependencies": {
4113 "@octokit/auth-oauth-app": "^7.1.0",
4114 "@octokit/auth-oauth-user": "^4.1.0",
4115 "@octokit/request": "^8.3.1",
4116 "@octokit/request-error": "^5.1.0",
4117 "@octokit/types": "^13.1.0",
4118 "deprecation": "^2.3.1",
4119 "lru-cache": "npm:@wolfy1339/lru-cache@^11.0.2-patch.1",
4120 "universal-github-app-jwt": "^1.1.2",
4121 "universal-user-agent": "^6.0.0"
4122 },
4123 "engines": {
4124 "node": ">= 18"
4125 }
4126 },
4127 "node_modules/@octokit/auth-app/node_modules/lru-cache": {
4128 "name": "@wolfy1339/lru-cache",
4129 "version": "11.0.2-patch.1",
4130 "license": "ISC",
4131 "engines": {
4132 "node": "18 >=18.20 || 20 || >=22"
4133 }
4134 },
4135 "node_modules/@octokit/auth-oauth-app": {
4136 "version": "7.1.0",
4137 "license": "MIT",
4138 "dependencies": {
4139 "@octokit/auth-oauth-device": "^6.1.0",
4140 "@octokit/auth-oauth-user": "^4.1.0",
4141 "@octokit/request": "^8.3.1",
4142 "@octokit/types": "^13.0.0",
4143 "@types/btoa-lite": "^1.0.0",
4144 "btoa-lite": "^1.0.0",
4145 "universal-user-agent": "^6.0.0"
4146 },
4147 "engines": {
4148 "node": ">= 18"
4149 }
4150 },
4151 "node_modules/@octokit/auth-oauth-device": {
4152 "version": "6.1.0",
4153 "license": "MIT",
4154 "dependencies": {
4155 "@octokit/oauth-methods": "^4.1.0",
4156 "@octokit/request": "^8.3.1",
4157 "@octokit/types": "^13.0.0",
4158 "universal-user-agent": "^6.0.0"
4159 },
4160 "engines": {
4161 "node": ">= 18"
4162 }
4163 },
4164 "node_modules/@octokit/auth-oauth-user": {
4165 "version": "4.1.0",
4166 "license": "MIT",
4167 "dependencies": {
4168 "@octokit/auth-oauth-device": "^6.1.0",
4169 "@octokit/oauth-methods": "^4.1.0",
4170 "@octokit/request": "^8.3.1",
4171 "@octokit/types": "^13.0.0",
4172 "btoa-lite": "^1.0.0",
4173 "universal-user-agent": "^6.0.0"
4174 },
4175 "engines": {
4176 "node": ">= 18"
4177 }
4178 },
4179 "node_modules/@octokit/auth-token": {
4180 "version": "4.0.0",
4181 "license": "MIT",
4182 "engines": {
4183 "node": ">= 18"
4184 }
4185 },
4186 "node_modules/@octokit/auth-unauthenticated": {
4187 "version": "5.0.1",
4188 "license": "MIT",
4189 "dependencies": {
4190 "@octokit/request-error": "^5.0.0",
4191 "@octokit/types": "^12.0.0"
4192 },
4193 "engines": {
4194 "node": ">= 18"
4195 }
4196 },
4197 "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/openapi-types": {
4198 "version": "20.0.0",
4199 "license": "MIT"
4200 },
4201 "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/types": {
4202 "version": "12.6.0",
4203 "license": "MIT",
4204 "dependencies": {
4205 "@octokit/openapi-types": "^20.0.0"
4206 }
4207 },
4208 "node_modules/@octokit/core": {
4209 "version": "5.2.2",
4210 "license": "MIT",
4211 "dependencies": {
4212 "@octokit/auth-token": "^4.0.0",
4213 "@octokit/graphql": "^7.1.0",
4214 "@octokit/request": "^8.4.1",
4215 "@octokit/request-error": "^5.1.1",
4216 "@octokit/types": "^13.0.0",
4217 "before-after-hook": "^2.2.0",
4218 "universal-user-agent": "^6.0.0"
4219 },
4220 "engines": {
4221 "node": ">= 18"
4222 }
4223 },
4224 "node_modules/@octokit/endpoint": {
4225 "version": "9.0.6",
4226 "license": "MIT",
4227 "dependencies": {
4228 "@octokit/types": "^13.1.0",
4229 "universal-user-agent": "^6.0.0"
4230 },
4231 "engines": {
4232 "node": ">= 18"
4233 }
4234 },
4235 "node_modules/@octokit/graphql": {
4236 "version": "7.1.1",
4237 "license": "MIT",
4238 "dependencies": {
4239 "@octokit/request": "^8.4.1",
4240 "@octokit/types": "^13.0.0",
4241 "universal-user-agent": "^6.0.0"
4242 },
4243 "engines": {
4244 "node": ">= 18"
4245 }
4246 },
4247 "node_modules/@octokit/oauth-app": {
4248 "version": "6.1.0",
4249 "license": "MIT",
4250 "dependencies": {
4251 "@octokit/auth-oauth-app": "^7.0.0",
4252 "@octokit/auth-oauth-user": "^4.0.0",
4253 "@octokit/auth-unauthenticated": "^5.0.0",
4254 "@octokit/core": "^5.0.0",
4255 "@octokit/oauth-authorization-url": "^6.0.2",
4256 "@octokit/oauth-methods": "^4.0.0",
4257 "@types/aws-lambda": "^8.10.83",
4258 "universal-user-agent": "^6.0.0"
4259 },
4260 "engines": {
4261 "node": ">= 18"
4262 }
4263 },
4264 "node_modules/@octokit/oauth-authorization-url": {
4265 "version": "6.0.2",
4266 "license": "MIT",
4267 "engines": {
4268 "node": ">= 18"
4269 }
4270 },
4271 "node_modules/@octokit/oauth-methods": {
4272 "version": "4.1.0",
4273 "license": "MIT",
4274 "dependencies": {
4275 "@octokit/oauth-authorization-url": "^6.0.2",
4276 "@octokit/request": "^8.3.1",
4277 "@octokit/request-error": "^5.1.0",
4278 "@octokit/types": "^13.0.0",
4279 "btoa-lite": "^1.0.0"
4280 },
4281 "engines": {
4282 "node": ">= 18"
4283 }
4284 },
4285 "node_modules/@octokit/openapi-types": {
4286 "version": "24.2.0",
4287 "license": "MIT"
4288 },
4289 "node_modules/@octokit/plugin-paginate-graphql": {
4290 "version": "4.0.1",
4291 "license": "MIT",
4292 "engines": {
4293 "node": ">= 18"
4294 },
4295 "peerDependencies": {
4296 "@octokit/core": ">=5"
4297 }
4298 },
4299 "node_modules/@octokit/plugin-paginate-rest": {
4300 "version": "11.4.4-cjs.2",
4301 "license": "MIT",
4302 "dependencies": {
4303 "@octokit/types": "^13.7.0"
4304 },
4305 "engines": {
4306 "node": ">= 18"
4307 },
4308 "peerDependencies": {
4309 "@octokit/core": "5"
4310 }
4311 },
4312 "node_modules/@octokit/plugin-rest-endpoint-methods": {
4313 "version": "13.3.2-cjs.1",
4314 "license": "MIT",
4315 "dependencies": {
4316 "@octokit/types": "^13.8.0"
4317 },
4318 "engines": {
4319 "node": ">= 18"
4320 },
4321 "peerDependencies": {
4322 "@octokit/core": "^5"
4323 }
4324 },
4325 "node_modules/@octokit/plugin-retry": {
4326 "version": "6.1.0",
4327 "license": "MIT",
4328 "dependencies": {
4329 "@octokit/request-error": "^5.0.0",
4330 "@octokit/types": "^13.0.0",
4331 "bottleneck": "^2.15.3"
4332 },
4333 "engines": {
4334 "node": ">= 18"
4335 },
4336 "peerDependencies": {
4337 "@octokit/core": "5"
4338 }
4339 },
4340 "node_modules/@octokit/plugin-throttling": {
4341 "version": "8.2.0",
4342 "license": "MIT",
4343 "dependencies": {
4344 "@octokit/types": "^12.2.0",
4345 "bottleneck": "^2.15.3"
4346 },
4347 "engines": {
4348 "node": ">= 18"
4349 },
4350 "peerDependencies": {
4351 "@octokit/core": "^5.0.0"
4352 }
4353 },
4354 "node_modules/@octokit/plugin-throttling/node_modules/@octokit/openapi-types": {
4355 "version": "20.0.0",
4356 "license": "MIT"
4357 },
4358 "node_modules/@octokit/plugin-throttling/node_modules/@octokit/types": {
4359 "version": "12.6.0",
4360 "license": "MIT",
4361 "dependencies": {
4362 "@octokit/openapi-types": "^20.0.0"
4363 }
4364 },
4365 "node_modules/@octokit/request": {
4366 "version": "8.4.1",
4367 "license": "MIT",
4368 "dependencies": {
4369 "@octokit/endpoint": "^9.0.6",
4370 "@octokit/request-error": "^5.1.1",
4371 "@octokit/types": "^13.1.0",
4372 "universal-user-agent": "^6.0.0"
4373 },
4374 "engines": {
4375 "node": ">= 18"
4376 }
4377 },
4378 "node_modules/@octokit/request-error": {
4379 "version": "5.1.1",
4380 "license": "MIT",
4381 "dependencies": {
4382 "@octokit/types": "^13.1.0",
4383 "deprecation": "^2.0.0",
4384 "once": "^1.4.0"
4385 },
4386 "engines": {
4387 "node": ">= 18"
4388 }
4389 },
4390 "node_modules/@octokit/types": {
4391 "version": "13.10.0",
4392 "license": "MIT",
4393 "dependencies": {
4394 "@octokit/openapi-types": "^24.2.0"
4395 }
4396 },
4397 "node_modules/@octokit/webhooks": {
4398 "version": "12.3.2",
4399 "license": "MIT",
4400 "dependencies": {
4401 "@octokit/request-error": "^5.0.0",
4402 "@octokit/webhooks-methods": "^4.1.0",
4403 "@octokit/webhooks-types": "7.6.1",
4404 "aggregate-error": "^3.1.0"
4405 },
4406 "engines": {
4407 "node": ">= 18"
4408 }
4409 },
4410 "node_modules/@octokit/webhooks-methods": {
4411 "version": "4.1.0",
4412 "license": "MIT",
4413 "engines": {
4414 "node": ">= 18"
4415 }
4416 },
4417 "node_modules/@octokit/webhooks-types": {
4418 "version": "7.6.1",
4419 "license": "MIT"
4420 },
44213564 "node_modules/@opentelemetry/api": {
44223565 "version": "1.9.0",
44233566 "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
49904133 "version": "10.0.2",
49914134 "license": "MIT"
49924135 },
4993 "node_modules/@simple-git/args-pathspec": {
4994 "version": "1.0.3",
4995 "license": "MIT"
4996 },
4997 "node_modules/@simple-git/argv-parser": {
4998 "version": "1.1.1",
4999 "license": "MIT",
5000 "dependencies": {
5001 "@simple-git/args-pathspec": "^1.0.3"
5002 }
5003 },
50044136 "node_modules/@smithy/core": {
50054137 "version": "3.24.6",
50064138 "license": "Apache-2.0",
51174249 "dev": true,
51184250 "license": "MIT"
51194251 },
5120 "node_modules/@supabase/auth-js": {
5121 "version": "2.110.1",
5122 "license": "MIT",
5123 "dependencies": {
5124 "tslib": "2.8.1"
5125 },
5126 "engines": {
5127 "node": ">=22.0.0"
5128 }
5129 },
5130 "node_modules/@supabase/functions-js": {
5131 "version": "2.110.1",
5132 "license": "MIT",
5133 "dependencies": {
5134 "tslib": "2.8.1"
5135 },
5136 "engines": {
5137 "node": ">=22.0.0"
5138 }
5139 },
5140 "node_modules/@supabase/phoenix": {
5141 "version": "0.4.4",
5142 "license": "MIT"
5143 },
5144 "node_modules/@supabase/postgrest-js": {
5145 "version": "2.110.1",
5146 "license": "MIT",
5147 "dependencies": {
5148 "tslib": "2.8.1"
5149 },
5150 "engines": {
5151 "node": ">=22.0.0"
5152 }
5153 },
5154 "node_modules/@supabase/realtime-js": {
5155 "version": "2.110.1",
5156 "license": "MIT",
5157 "dependencies": {
5158 "@supabase/phoenix": "0.4.4",
5159 "tslib": "2.8.1"
5160 },
5161 "engines": {
5162 "node": ">=22.0.0"
5163 }
5164 },
5165 "node_modules/@supabase/storage-js": {
5166 "version": "2.110.1",
5167 "license": "MIT",
5168 "dependencies": {
5169 "iceberg-js": "^0.8.1",
5170 "tslib": "2.8.1"
5171 },
5172 "engines": {
5173 "node": ">=22.0.0"
5174 }
5175 },
5176 "node_modules/@supabase/supabase-js": {
5177 "version": "2.110.1",
5178 "license": "MIT",
5179 "dependencies": {
5180 "@supabase/auth-js": "2.110.1",
5181 "@supabase/functions-js": "2.110.1",
5182 "@supabase/postgrest-js": "2.110.1",
5183 "@supabase/realtime-js": "2.110.1",
5184 "@supabase/storage-js": "2.110.1"
5185 },
5186 "engines": {
5187 "node": ">=22.0.0"
5188 }
5189 },
5190 "node_modules/@tsconfig/node10": {
5191 "version": "1.0.12",
5192 "license": "MIT"
5193 },
5194 "node_modules/@tsconfig/node12": {
5195 "version": "1.0.11",
5196 "license": "MIT"
5197 },
5198 "node_modules/@tsconfig/node14": {
5199 "version": "1.0.3",
5200 "license": "MIT"
5201 },
5202 "node_modules/@tsconfig/node16": {
5203 "version": "1.0.4",
5204 "license": "MIT"
5205 },
52064252 "node_modules/@tybys/wasm-util": {
52074253 "version": "0.10.3",
52084254 "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
52144260 "tslib": "^2.4.0"
52164262 },
5217 "node_modules/@types/aws-lambda": {
5218 "version": "8.10.162",
5219 "license": "MIT"
5220 },
5221 "node_modules/@types/btoa-lite": {
5222 "version": "1.0.2",
5223 "license": "MIT"
5224 },
52254263 "node_modules/@types/chai": {
52264264 "version": "5.2.3",
52274265 "dev": true,
52574295 "@types/unist": "*"
52594297 },
5260 "node_modules/@types/jsonwebtoken": {
5261 "version": "9.0.10",
5262 "license": "MIT",
5263 "dependencies": {
5264 "@types/ms": "*",
5265 "@types/node": "*"
5266 }
5267 },
52684298 "node_modules/@types/katex": {
52694299 "version": "0.16.8",
52704300 "resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.8.tgz",
52854315 "node_modules/@types/node": {
52864316 "version": "25.9.1",
52874317 "license": "MIT",
4318 "peer": true,
52884319 "dependencies": {
52894320 "undici-types": ">=7.24.0 <7.24.7"
52914322 },
5292 "node_modules/@types/qrcode": {
5293 "version": "1.5.6",
5294 "dev": true,
5295 "license": "MIT",
5296 "dependencies": {
5297 "@types/node": "*"
5298 }
5299 },
53004323 "node_modules/@types/retry": {
53014324 "version": "0.12.0",
53024325 "license": "MIT",
53064329 "version": "3.0.3",
53074330 "license": "MIT"
53084331 },
5309 "node_modules/@types/ws": {
5310 "version": "8.18.1",
5311 "license": "MIT",
5312 "dependencies": {
5313 "@types/node": "*"
5314 }
5315 },
53164332 "node_modules/@ungap/structured-clone": {
53174333 "version": "1.3.1",
53184334 "license": "ISC"
54394455 "url": "https://opencollective.com/vitest"
54414457 },
5442 "node_modules/acorn": {
5443 "version": "8.17.0",
5444 "license": "MIT",
5445 "bin": {
5446 "acorn": "bin/acorn"
5447 },
5448 "engines": {
5449 "node": ">=0.4.0"
5450 }
5451 },
5452 "node_modules/acorn-walk": {
5453 "version": "8.3.5",
5454 "license": "MIT",
5455 "dependencies": {
5456 "acorn": "^8.11.0"
5457 },
5458 "engines": {
5459 "node": ">=0.4.0"
5460 }
5461 },
54624458 "node_modules/agent-base": {
54634459 "version": "7.1.4",
54644460 "license": "MIT",
54674463 "node": ">= 14"
54694465 },
5470 "node_modules/aggregate-error": {
5471 "version": "3.1.0",
5472 "license": "MIT",
5473 "dependencies": {
5474 "clean-stack": "^2.0.0",
5475 "indent-string": "^4.0.0"
5476 },
5477 "engines": {
5478 "node": ">=8"
5479 }
5480 },
5481 "node_modules/ansi-regex": {
5482 "version": "5.0.1",
5483 "license": "MIT",
5484 "engines": {
5485 "node": ">=8"
5486 }
5487 },
5488 "node_modules/ansi-styles": {
5489 "version": "4.3.0",
5490 "license": "MIT",
5491 "dependencies": {
5492 "color-convert": "^2.0.1"
5493 },
5494 "engines": {
5495 "node": ">=8"
5496 },
5497 "funding": {
5498 "url": "https://github.com/chalk/ansi-styles?sponsor=1"
5499 }
5500 },
5501 "node_modules/arg": {
5502 "version": "4.1.3",
5503 "license": "MIT"
5504 },
55054466 "node_modules/assertion-error": {
55064467 "version": "2.0.1",
55074468 "dev": true,
55364497 "url": "https://feross.org/support"
55384499 ],
5539 "license": "MIT"
4500 "license": "MIT",
4501 "peer": true
55404502 },
55414503 "node_modules/baseline-browser-mapping": {
55424504 "version": "2.10.35",
55494511 "node": ">=6.0.0"
55514513 },
5552 "node_modules/before-after-hook": {
5553 "version": "2.2.3",
5554 "license": "Apache-2.0"
5555 },
5556 "node_modules/big-integer": {
5557 "version": "1.6.52",
5558 "license": "Unlicense",
5559 "engines": {
5560 "node": ">=0.6"
5561 }
5562 },
55634514 "node_modules/bignumber.js": {
55644515 "version": "9.3.1",
55654516 "license": "MIT",
55684519 "node": "*"
55704521 },
5571 "node_modules/bl": {
5572 "version": "5.1.0",
5573 "license": "MIT",
5574 "dependencies": {
5575 "buffer": "^6.0.3",
5576 "inherits": "^2.0.4",
5577 "readable-stream": "^3.4.0"
5578 }
5579 },
5580 "node_modules/bottleneck": {
5581 "version": "2.19.5",
5582 "license": "MIT"
5583 },
55844522 "node_modules/bowser": {
55854523 "version": "2.14.1",
55864524 "license": "MIT",
55874525 "peer": true
55884526 },
5589 "node_modules/bplist-parser": {
5590 "version": "0.2.0",
5591 "license": "MIT",
5592 "dependencies": {
5593 "big-integer": "^1.6.44"
5594 },
5595 "engines": {
5596 "node": ">= 5.10.0"
5597 }
5598 },
55994527 "node_modules/browserslist": {
56004528 "version": "4.28.2",
56014529 "dev": true,
56284556 "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
56304558 },
5631 "node_modules/btoa-lite": {
5632 "version": "1.0.0",
5633 "license": "MIT"
5634 },
5635 "node_modules/buffer": {
5636 "version": "6.0.3",
5637 "funding": [
5638 {
5639 "type": "github",
5640 "url": "https://github.com/sponsors/feross"
5641 },
5642 {
5643 "type": "patreon",
5644 "url": "https://www.patreon.com/feross"
5645 },
5646 {
5647 "type": "consulting",
5648 "url": "https://feross.org/support"
5649 }
5650 ],
5651 "license": "MIT",
5652 "dependencies": {
5653 "base64-js": "^1.3.1",
5654 "ieee754": "^1.2.1"
5655 }
5656 },
56574559 "node_modules/buffer-equal-constant-time": {
56584560 "version": "1.0.1",
5659 "license": "BSD-3-Clause"
5660 },
5661 "node_modules/bundle-name": {
5662 "version": "3.0.0",
5663 "license": "MIT",
5664 "dependencies": {
5665 "run-applescript": "^5.0.0"
5666 },
5667 "engines": {
5668 "node": ">=12"
5669 },
5670 "funding": {
5671 "url": "https://github.com/sponsors/sindresorhus"
5672 }
5673 },
5674 "node_modules/camel-case": {
5675 "version": "4.1.2",
5676 "license": "MIT",
5677 "dependencies": {
5678 "pascal-case": "^3.1.2",
5679 "tslib": "^2.0.3"
5680 }
5681 },
5682 "node_modules/camelcase": {
5683 "version": "5.3.1",
5684 "license": "MIT",
5685 "engines": {
5686 "node": ">=6"
5687 }
4561 "license": "BSD-3-Clause",
4562 "peer": true
56884563 },
56894564 "node_modules/caniuse-lite": {
56904565 "version": "1.0.30001797",
57054580 ],
57064581 "license": "CC-BY-4.0"
57074582 },
5708 "node_modules/capital-case": {
5709 "version": "1.0.4",
5710 "license": "MIT",
5711 "dependencies": {
5712 "no-case": "^3.0.4",
5713 "tslib": "^2.0.3",
5714 "upper-case-first": "^2.0.2"
5715 }
5716 },
57174583 "node_modules/ccount": {
57184584 "version": "2.0.1",
57194585 "license": "MIT",
57304596 "node": ">=18"
57324598 },
5733 "node_modules/chalk": {
5734 "version": "5.6.2",
5735 "license": "MIT",
5736 "engines": {
5737 "node": "^12.17.0 || ^14.13 || >=16.0.0"
5738 },
5739 "funding": {
5740 "url": "https://github.com/chalk/chalk?sponsor=1"
5741 }
5742 },
5743 "node_modules/change-case": {
5744 "version": "4.1.2",
5745 "license": "MIT",
5746 "dependencies": {
5747 "camel-case": "^4.1.2",
5748 "capital-case": "^1.0.4",
5749 "constant-case": "^3.0.4",
5750 "dot-case": "^3.0.4",
5751 "header-case": "^2.0.4",
5752 "no-case": "^3.0.4",
5753 "param-case": "^3.0.4",
5754 "pascal-case": "^3.1.2",
5755 "path-case": "^3.0.4",
5756 "sentence-case": "^3.0.4",
5757 "snake-case": "^3.0.4",
5758 "tslib": "^2.0.3"
5759 }
5760 },
57614599 "node_modules/character-entities": {
57624600 "version": "2.0.2",
57634601 "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
57844622 "url": "https://github.com/sponsors/wooorm"
57864624 },
5787 "node_modules/clean-stack": {
5788 "version": "2.2.0",
5789 "license": "MIT",
5790 "engines": {
5791 "node": ">=6"
5792 }
5793 },
5794 "node_modules/cli-cursor": {
5795 "version": "4.0.0",
5796 "license": "MIT",
5797 "dependencies": {
5798 "restore-cursor": "^4.0.0"
5799 },
5800 "engines": {
5801 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
5802 },
5803 "funding": {
5804 "url": "https://github.com/sponsors/sindresorhus"
5805 }
5806 },
5807 "node_modules/cli-spinners": {
5808 "version": "2.9.2",
5809 "license": "MIT",
5810 "engines": {
5811 "node": ">=6"
5812 },
5813 "funding": {
5814 "url": "https://github.com/sponsors/sindresorhus"
5815 }
5816 },
5817 "node_modules/cliui": {
5818 "version": "6.0.0",
5819 "license": "ISC",
5820 "dependencies": {
5821 "string-width": "^4.2.0",
5822 "strip-ansi": "^6.0.0",
5823 "wrap-ansi": "^6.2.0"
5824 }
5825 },
5826 "node_modules/color-convert": {
5827 "version": "2.0.1",
5828 "license": "MIT",
5829 "dependencies": {
5830 "color-name": "~1.1.4"
5831 },
5832 "engines": {
5833 "node": ">=7.0.0"
5834 }
5835 },
5836 "node_modules/color-name": {
5837 "version": "1.1.4",
5838 "license": "MIT"
5839 },
58404625 "node_modules/comma-separated-tokens": {
58414626 "version": "2.0.3",
58424627 "license": "MIT",
58544639 "node": ">= 12"
58564641 },
5857 "node_modules/constant-case": {
5858 "version": "3.0.4",
5859 "license": "MIT",
5860 "dependencies": {
5861 "no-case": "^3.0.4",
5862 "tslib": "^2.0.3",
5863 "upper-case": "^2.0.2"
5864 }
5865 },
58664642 "node_modules/convert-source-map": {
58674643 "version": "2.0.0",
58684644 "dev": true,
58694645 "license": "MIT"
58704646 },
5871 "node_modules/create-require": {
5872 "version": "1.1.1",
5873 "license": "MIT"
5874 },
5875 "node_modules/cross-spawn": {
5876 "version": "7.0.6",
5877 "license": "MIT",
5878 "dependencies": {
5879 "path-key": "^3.1.0",
5880 "shebang-command": "^2.0.0",
5881 "which": "^2.0.1"
5882 },
5883 "engines": {
5884 "node": ">= 8"
5885 }
5886 },
58874647 "node_modules/data-uri-to-buffer": {
58884648 "version": "4.0.1",
58894649 "license": "MIT",
4650 "peer": true,
58904651 "engines": {
58914652 "node": ">= 12"
59084669 },
5909 "node_modules/decamelize": {
5910 "version": "1.2.0",
5911 "license": "MIT",
5912 "engines": {
5913 "node": ">=0.10.0"
5914 }
5915 },
59164670 "node_modules/decode-named-character-reference": {
59174671 "version": "1.3.0",
59184672 "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
59264680 "url": "https://github.com/sponsors/wooorm"
59284682 },
5929 "node_modules/default-browser": {
5930 "version": "4.0.0",
5931 "license": "MIT",
5932 "dependencies": {
5933 "bundle-name": "^3.0.0",
5934 "default-browser-id": "^3.0.0",
5935 "execa": "^7.1.1",
5936 "titleize": "^3.0.0"
5937 },
5938 "engines": {
5939 "node": ">=14.16"
5940 },
5941 "funding": {
5942 "url": "https://github.com/sponsors/sindresorhus"
5943 }
5944 },
5945 "node_modules/default-browser-id": {
5946 "version": "3.0.0",
5947 "license": "MIT",
5948 "dependencies": {
5949 "bplist-parser": "^0.2.0",
5950 "untildify": "^4.0.0"
5951 },
5952 "engines": {
5953 "node": ">=12"
5954 },
5955 "funding": {
5956 "url": "https://github.com/sponsors/sindresorhus"
5957 }
5958 },
5959 "node_modules/default-browser/node_modules/execa": {
5960 "version": "7.2.0",
5961 "license": "MIT",
5962 "dependencies": {
5963 "cross-spawn": "^7.0.3",
5964 "get-stream": "^6.0.1",
5965 "human-signals": "^4.3.0",
5966 "is-stream": "^3.0.0",
5967 "merge-stream": "^2.0.0",
5968 "npm-run-path": "^5.1.0",
5969 "onetime": "^6.0.0",
5970 "signal-exit": "^3.0.7",
5971 "strip-final-newline": "^3.0.0"
5972 },
5973 "engines": {
5974 "node": "^14.18.0 || ^16.14.0 || >=18.0.0"
5975 },
5976 "funding": {
5977 "url": "https://github.com/sindresorhus/execa?sponsor=1"
5978 }
5979 },
5980 "node_modules/default-browser/node_modules/get-stream": {
5981 "version": "6.0.1",
5982 "license": "MIT",
5983 "engines": {
5984 "node": ">=10"
5985 },
5986 "funding": {
5987 "url": "https://github.com/sponsors/sindresorhus"
5988 }
5989 },
5990 "node_modules/default-browser/node_modules/human-signals": {
5991 "version": "4.3.1",
5992 "license": "Apache-2.0",
5993 "engines": {
5994 "node": ">=14.18.0"
5995 }
5996 },
5997 "node_modules/default-browser/node_modules/is-stream": {
5998 "version": "3.0.0",
5999 "license": "MIT",
6000 "engines": {
6001 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
6002 },
6003 "funding": {
6004 "url": "https://github.com/sponsors/sindresorhus"
6005 }
6006 },
6007 "node_modules/default-browser/node_modules/mimic-fn": {
6008 "version": "4.0.0",
6009 "license": "MIT",
6010 "engines": {
6011 "node": ">=12"
6012 },
6013 "funding": {
6014 "url": "https://github.com/sponsors/sindresorhus"
6015 }
6016 },
6017 "node_modules/default-browser/node_modules/npm-run-path": {
6018 "version": "5.3.0",
6019 "license": "MIT",
6020 "dependencies": {
6021 "path-key": "^4.0.0"
6022 },
6023 "engines": {
6024 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
6025 },
6026 "funding": {
6027 "url": "https://github.com/sponsors/sindresorhus"
6028 }
6029 },
6030 "node_modules/default-browser/node_modules/onetime": {
6031 "version": "6.0.0",
6032 "license": "MIT",
6033 "dependencies": {
6034 "mimic-fn": "^4.0.0"
6035 },
6036 "engines": {
6037 "node": ">=12"
6038 },
6039 "funding": {
6040 "url": "https://github.com/sponsors/sindresorhus"
6041 }
6042 },
6043 "node_modules/default-browser/node_modules/path-key": {
6044 "version": "4.0.0",
6045 "license": "MIT",
6046 "engines": {
6047 "node": ">=12"
6048 },
6049 "funding": {
6050 "url": "https://github.com/sponsors/sindresorhus"
6051 }
6052 },
6053 "node_modules/default-browser/node_modules/strip-final-newline": {
6054 "version": "3.0.0",
6055 "license": "MIT",
6056 "engines": {
6057 "node": ">=12"
6058 },
6059 "funding": {
6060 "url": "https://github.com/sponsors/sindresorhus"
6061 }
6062 },
6063 "node_modules/define-lazy-prop": {
6064 "version": "3.0.0",
6065 "license": "MIT",
6066 "engines": {
6067 "node": ">=12"
6068 },
6069 "funding": {
6070 "url": "https://github.com/sponsors/sindresorhus"
6071 }
6072 },
6073 "node_modules/deprecation": {
6074 "version": "2.3.1",
6075 "license": "ISC"
6076 },
60774683 "node_modules/dequal": {
60784684 "version": "2.0.3",
60794685 "license": "MIT",
61074713 "node": ">=0.3.1"
61094715 },
6110 "node_modules/dijkstrajs": {
6111 "version": "1.0.3",
6112 "license": "MIT"
6113 },
6114 "node_modules/dot-case": {
6115 "version": "3.0.4",
6116 "license": "MIT",
6117 "dependencies": {
6118 "no-case": "^3.0.4",
6119 "tslib": "^2.0.3"
6120 }
6121 },
6122 "node_modules/eastasianwidth": {
6123 "version": "0.2.0",
6124 "license": "MIT"
6125 },
61264716 "node_modules/ecdsa-sig-formatter": {
61274717 "version": "1.0.11",
61284718 "license": "Apache-2.0",
4719 "peer": true,
61294720 "dependencies": {
61304721 "safe-buffer": "^5.0.1"
61354726 "dev": true,
61364727 "license": "ISC"
61374728 },
6138 "node_modules/emoji-regex": {
6139 "version": "8.0.0",
6140 "license": "MIT"
6141 },
6142 "node_modules/end-of-stream": {
6143 "version": "1.4.5",
6144 "license": "MIT",
6145 "dependencies": {
6146 "once": "^1.4.0"
6147 }
6148 },
61494729 "node_modules/es-module-lexer": {
61504730 "version": "2.1.0",
61514731 "dev": true,
61524732 "license": "MIT"
61534733 },
6154 "node_modules/esbuild": {
6155 "version": "0.28.1",
6156 "dev": true,
6157 "hasInstallScript": true,
6158 "license": "MIT",
6159 "bin": {
6160 "esbuild": "bin/esbuild"
6161 },
6162 "engines": {
6163 "node": ">=18"
6164 },
6165 "optionalDependencies": {
6166 "@esbuild/aix-ppc64": "0.28.1",
6167 "@esbuild/android-arm": "0.28.1",
6168 "@esbuild/android-arm64": "0.28.1",
6169 "@esbuild/android-x64": "0.28.1",
6170 "@esbuild/darwin-arm64": "0.28.1",
6171 "@esbuild/darwin-x64": "0.28.1",
6172 "@esbuild/freebsd-arm64": "0.28.1",
6173 "@esbuild/freebsd-x64": "0.28.1",
6174 "@esbuild/linux-arm": "0.28.1",
6175 "@esbuild/linux-arm64": "0.28.1",
6176 "@esbuild/linux-ia32": "0.28.1",
6177 "@esbuild/linux-loong64": "0.28.1",
6178 "@esbuild/linux-mips64el": "0.28.1",
6179 "@esbuild/linux-ppc64": "0.28.1",
6180 "@esbuild/linux-riscv64": "0.28.1",
6181 "@esbuild/linux-s390x": "0.28.1",
6182 "@esbuild/linux-x64": "0.28.1",
6183 "@esbuild/netbsd-arm64": "0.28.1",
6184 "@esbuild/netbsd-x64": "0.28.1",
6185 "@esbuild/openbsd-arm64": "0.28.1",
6186 "@esbuild/openbsd-x64": "0.28.1",
6187 "@esbuild/openharmony-arm64": "0.28.1",
6188 "@esbuild/sunos-x64": "0.28.1",
6189 "@esbuild/win32-arm64": "0.28.1",
6190 "@esbuild/win32-ia32": "0.28.1",
6191 "@esbuild/win32-x64": "0.28.1"
6192 }
6193 },
61944734 "node_modules/escalade": {
61954735 "version": "3.2.0",
61964736 "dev": true,
62194759 "@types/estree": "^1.0.0"
62214761 },
6222 "node_modules/execa": {
6223 "version": "4.1.0",
6224 "license": "MIT",
6225 "dependencies": {
6226 "cross-spawn": "^7.0.0",
6227 "get-stream": "^5.0.0",
6228 "human-signals": "^1.1.1",
6229 "is-stream": "^2.0.0",
6230 "merge-stream": "^2.0.0",
6231 "npm-run-path": "^4.0.0",
6232 "onetime": "^5.1.0",
6233 "signal-exit": "^3.0.2",
6234 "strip-final-newline": "^2.0.0"
6235 },
6236 "engines": {
6237 "node": ">=10"
6238 },
6239 "funding": {
6240 "url": "https://github.com/sindresorhus/execa?sponsor=1"
6241 }
6242 },
62434762 "node_modules/expect-type": {
62444763 "version": "1.3.0",
62454764 "dev": true,
63304849 ],
63314850 "license": "MIT",
4851 "peer": true,
63324852 "dependencies": {
63334853 "node-domexception": "^1.0.0",
63344854 "web-streams-polyfill": "^3.0.3"
63374857 "node": "^12.20 || >= 14.13"
63394859 },
6340 "node_modules/find-up": {
6341 "version": "4.1.0",
6342 "license": "MIT",
6343 "dependencies": {
6344 "locate-path": "^5.0.0",
6345 "path-exists": "^4.0.0"
6346 },
6347 "engines": {
6348 "node": ">=8"
6349 }
6350 },
63514860 "node_modules/format": {
63524861 "version": "0.2.2",
63534862 "resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz",
63594868 "node_modules/formdata-polyfill": {
63604869 "version": "4.0.10",
63614870 "license": "MIT",
4871 "peer": true,
63624872 "dependencies": {
63634873 "fetch-blob": "^3.1.2"
63644874 },
64154925 "node": ">=6.9.0"
64174927 },
6418 "node_modules/get-caller-file": {
6419 "version": "2.0.5",
6420 "license": "ISC",
6421 "engines": {
6422 "node": "6.* || 8.* || >= 10.*"
6423 }
6424 },
64254928 "node_modules/get-east-asian-width": {
64264929 "version": "1.6.0",
64274930 "license": "MIT",
64334936 "url": "https://github.com/sponsors/sindresorhus"
64354938 },
6436 "node_modules/get-stream": {
6437 "version": "5.2.0",
6438 "license": "MIT",
6439 "dependencies": {
6440 "pump": "^3.0.0"
6441 },
6442 "engines": {
6443 "node": ">=8"
6444 },
6445 "funding": {
6446 "url": "https://github.com/sponsors/sindresorhus"
6447 }
6448 },
64494939 "node_modules/google-auth-library": {
64504940 "version": "10.7.0",
64514941 "license": "Apache-2.0",
66535143 "url": "https://opencollective.com/unified"
66555145 },
6656 "node_modules/header-case": {
6657 "version": "2.0.4",
6658 "license": "MIT",
6659 "dependencies": {
6660 "capital-case": "^1.0.4",
6661 "tslib": "^2.0.3"
6662 }
6663 },
66645146 "node_modules/html-escaper": {
66655147 "version": "2.0.2",
66665148 "dev": true,
66985180 "node": ">= 14"
67005182 },
6701 "node_modules/human-signals": {
6702 "version": "1.1.1",
6703 "license": "Apache-2.0",
6704 "engines": {
6705 "node": ">=8.12.0"
6706 }
6707 },
6708 "node_modules/iceberg-js": {
6709 "version": "0.8.1",
6710 "license": "MIT",
6711 "engines": {
6712 "node": ">=20.0.0"
6713 }
6714 },
6715 "node_modules/ieee754": {
6716 "version": "1.2.1",
6717 "funding": [
6718 {
6719 "type": "github",
6720 "url": "https://github.com/sponsors/feross"
6721 },
6722 {
6723 "type": "patreon",
6724 "url": "https://www.patreon.com/feross"
6725 },
6726 {
6727 "type": "consulting",
6728 "url": "https://feross.org/support"
6729 }
6730 ],
6731 "license": "BSD-3-Clause"
6732 },
67335183 "node_modules/ignore": {
67345184 "version": "7.0.5",
67355185 "license": "MIT",
67385188 "node": ">= 4"
67405190 },
6741 "node_modules/indent-string": {
6742 "version": "4.0.0",
6743 "license": "MIT",
6744 "engines": {
6745 "node": ">=8"
6746 }
6747 },
6748 "node_modules/inherits": {
6749 "version": "2.0.4",
6750 "license": "ISC"
6751 },
6752 "node_modules/is-absolute": {
6753 "version": "1.0.0",
6754 "license": "MIT",
6755 "dependencies": {
6756 "is-relative": "^1.0.0",
6757 "is-windows": "^1.0.1"
6758 },
6759 "engines": {
6760 "node": ">=0.10.0"
6761 }
6762 },
6763 "node_modules/is-docker": {
6764 "version": "3.0.0",
6765 "license": "MIT",
6766 "bin": {
6767 "is-docker": "cli.js"
6768 },
6769 "engines": {
6770 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
6771 },
6772 "funding": {
6773 "url": "https://github.com/sponsors/sindresorhus"
6774 }
6775 },
6776 "node_modules/is-fullwidth-code-point": {
6777 "version": "3.0.0",
6778 "license": "MIT",
6779 "engines": {
6780 "node": ">=8"
6781 }
6782 },
6783 "node_modules/is-git-repository": {
6784 "version": "2.0.0",
6785 "license": "MIT",
6786 "dependencies": {
6787 "execa": "^4.0.3",
6788 "is-absolute": "^1.0.0"
6789 }
6790 },
6791 "node_modules/is-inside-container": {
6792 "version": "1.0.0",
6793 "license": "MIT",
6794 "dependencies": {
6795 "is-docker": "^3.0.0"
6796 },
6797 "bin": {
6798 "is-inside-container": "cli.js"
6799 },
6800 "engines": {
6801 "node": ">=14.16"
6802 },
6803 "funding": {
6804 "url": "https://github.com/sponsors/sindresorhus"
6805 }
6806 },
6807 "node_modules/is-interactive": {
6808 "version": "2.0.0",
6809 "license": "MIT",
6810 "engines": {
6811 "node": ">=12"
6812 },
6813 "funding": {
6814 "url": "https://github.com/sponsors/sindresorhus"
6815 }
6816 },
68175191 "node_modules/is-plain-obj": {
68185192 "version": "4.1.0",
68195193 "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
68265200 "url": "https://github.com/sponsors/sindresorhus"
68285202 },
6829 "node_modules/is-relative": {
6830 "version": "1.0.0",
6831 "license": "MIT",
6832 "dependencies": {
6833 "is-unc-path": "^1.0.0"
6834 },
6835 "engines": {
6836 "node": ">=0.10.0"
6837 }
6838 },
6839 "node_modules/is-stream": {
6840 "version": "2.0.1",
6841 "license": "MIT",
6842 "engines": {
6843 "node": ">=8"
6844 },
6845 "funding": {
6846 "url": "https://github.com/sponsors/sindresorhus"
6847 }
6848 },
6849 "node_modules/is-unc-path": {
6850 "version": "1.0.0",
6851 "license": "MIT",
6852 "dependencies": {
6853 "unc-path-regex": "^0.1.2"
6854 },
6855 "engines": {
6856 "node": ">=0.10.0"
6857 }
6858 },
6859 "node_modules/is-unicode-supported": {
6860 "version": "1.3.0",
6861 "license": "MIT",
6862 "engines": {
6863 "node": ">=12"
6864 },
6865 "funding": {
6866 "url": "https://github.com/sponsors/sindresorhus"
6867 }
6868 },
6869 "node_modules/is-windows": {
6870 "version": "1.0.2",
6871 "license": "MIT",
6872 "engines": {
6873 "node": ">=0.10.0"
6874 }
6875 },
6876 "node_modules/is-wsl": {
6877 "version": "2.2.0",
6878 "license": "MIT",
6879 "dependencies": {
6880 "is-docker": "^2.0.0"
6881 },
6882 "engines": {
6883 "node": ">=8"
6884 }
6885 },
6886 "node_modules/is-wsl/node_modules/is-docker": {
6887 "version": "2.2.1",
6888 "license": "MIT",
6889 "bin": {
6890 "is-docker": "cli.js"
6891 },
6892 "engines": {
6893 "node": ">=8"
6894 },
6895 "funding": {
6896 "url": "https://github.com/sponsors/sindresorhus"
6897 }
6898 },
6899 "node_modules/isexe": {
6900 "version": "2.0.0",
6901 "license": "ISC"
6902 },
69035203 "node_modules/istanbul-lib-coverage": {
69045204 "version": "3.2.2",
69055205 "dev": true,
69805280 "node": ">=6"
69825282 },
6983 "node_modules/jsonwebtoken": {
6984 "version": "9.0.3",
6985 "license": "MIT",
6986 "dependencies": {
6987 "jws": "^4.0.1",
6988 "lodash.includes": "^4.3.0",
6989 "lodash.isboolean": "^3.0.3",
6990 "lodash.isinteger": "^4.0.4",
6991 "lodash.isnumber": "^3.0.3",
6992 "lodash.isplainobject": "^4.0.6",
6993 "lodash.isstring": "^4.0.1",
6994 "lodash.once": "^4.0.0",
6995 "ms": "^2.1.1",
6996 "semver": "^7.5.4"
6997 },
6998 "engines": {
6999 "node": ">=12",
7000 "npm": ">=6"
7001 }
7002 },
7003 "node_modules/jsonwebtoken/node_modules/semver": {
7004 "version": "7.8.5",
7005 "license": "ISC",
7006 "bin": {
7007 "semver": "bin/semver.js"
7008 },
7009 "engines": {
7010 "node": ">=10"
7011 }
7012 },
70135283 "node_modules/jwa": {
70145284 "version": "2.0.1",
70155285 "license": "MIT",
5286 "peer": true,
70165287 "dependencies": {
70175288 "buffer-equal-constant-time": "^1.0.1",
70185289 "ecdsa-sig-formatter": "1.0.11",
70225293 "node_modules/jws": {
70235294 "version": "4.0.1",
70245295 "license": "MIT",
5296 "peer": true,
70255297 "dependencies": {
70265298 "jwa": "^2.0.1",
70275299 "safe-buffer": "^5.0.1"
70435315 "katex": "cli.js"
70455317 },
7046 "node_modules/kleur": {
7047 "version": "4.1.5",
7048 "license": "MIT",
7049 "engines": {
7050 "node": ">=6"
7051 }
7052 },
70535318 "node_modules/lightningcss": {
70545319 "version": "1.32.0",
70555320 "dev": true,
73195584 "url": "https://opencollective.com/parcel"
73215586 },
7322 "node_modules/locate-path": {
7323 "version": "5.0.0",
7324 "license": "MIT",
7325 "dependencies": {
7326 "p-locate": "^4.1.0"
7327 },
7328 "engines": {
7329 "node": ">=8"
7330 }
7331 },
7332 "node_modules/lodash.debounce": {
7333 "version": "4.0.8",
7334 "license": "MIT"
7335 },
7336 "node_modules/lodash.includes": {
7337 "version": "4.3.0",
7338 "license": "MIT"
7339 },
7340 "node_modules/lodash.isboolean": {
7341 "version": "3.0.3",
7342 "license": "MIT"
7343 },
7344 "node_modules/lodash.isinteger": {
7345 "version": "4.0.4",
7346 "license": "MIT"
7347 },
7348 "node_modules/lodash.isnumber": {
7349 "version": "3.0.3",
7350 "license": "MIT"
7351 },
7352 "node_modules/lodash.isplainobject": {
7353 "version": "4.0.6",
7354 "license": "MIT"
7355 },
7356 "node_modules/lodash.isstring": {
7357 "version": "4.0.1",
7358 "license": "MIT"
7359 },
7360 "node_modules/lodash.once": {
7361 "version": "4.1.1",
7362 "license": "MIT"
7363 },
7364 "node_modules/log-symbols": {
7365 "version": "5.1.0",
7366 "license": "MIT",
7367 "dependencies": {
7368 "chalk": "^5.0.0",
7369 "is-unicode-supported": "^1.1.0"
7370 },
7371 "engines": {
7372 "node": ">=12"
7373 },
7374 "funding": {
7375 "url": "https://github.com/sponsors/sindresorhus"
7376 }
7377 },
73785587 "node_modules/long": {
73795588 "version": "5.3.2",
73805589 "license": "Apache-2.0",
73905599 "url": "https://github.com/sponsors/wooorm"
73925601 },
7393 "node_modules/lower-case": {
7394 "version": "2.0.2",
7395 "license": "MIT",
7396 "dependencies": {
7397 "tslib": "^2.0.3"
7398 }
7399 },
74005602 "node_modules/lru_map": {
74015603 "version": "0.4.1",
74025604 "license": "MIT"
74525654 "node": ">=10"
74545656 },
7455 "node_modules/make-error": {
7456 "version": "1.3.6",
7457 "license": "ISC"
7458 },
74595657 "node_modules/markdown-table": {
74605658 "version": "3.0.4",
74615659 "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
77475945 "url": "https://opencollective.com/unified"
77495947 },
7750 "node_modules/merge-stream": {
7751 "version": "2.0.0",
7752 "license": "MIT"
7753 },
77545948 "node_modules/micromark": {
77555949 "version": "4.0.2",
77565950 "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
83546548 ],
83556549 "license": "MIT"
83566550 },
8357 "node_modules/mimic-fn": {
8358 "version": "2.1.0",
8359 "license": "MIT",
8360 "engines": {
8361 "node": ">=6"
8362 }
8363 },
83646551 "node_modules/ms": {
83656552 "version": "2.1.3",
83666553 "license": "MIT"
83826569 "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
83846571 },
8385 "node_modules/no-case": {
8386 "version": "3.0.4",
8387 "license": "MIT",
8388 "dependencies": {
8389 "lower-case": "^2.0.2",
8390 "tslib": "^2.0.3"
8391 }
8392 },
83936572 "node_modules/node-domexception": {
83946573 "version": "1.0.0",
83956574 "funding": [
84046583 ],
84056584 "license": "MIT",
6585 "peer": true,
84066586 "engines": {
84076587 "node": ">=10.5.0"
84106590 "node_modules/node-fetch": {
84116591 "version": "3.3.2",
84126592 "license": "MIT",
6593 "peer": true,
84136594 "dependencies": {
84146595 "data-uri-to-buffer": "^4.0.0",
84156596 "fetch-blob": "^3.1.4",
84316612 "node": ">=18"
84336614 },
8434 "node_modules/npm-run-path": {
8435 "version": "4.0.1",
8436 "license": "MIT",
8437 "dependencies": {
8438 "path-key": "^3.0.0"
8439 },
8440 "engines": {
8441 "node": ">=8"
8442 }
8443 },
84446615 "node_modules/obug": {
84456616 "version": "2.1.2",
84466617 "dev": true,
84536624 "node": ">=12.20.0"
84556626 },
8456 "node_modules/octokit": {
8457 "version": "3.2.2",
8458 "license": "MIT",
8459 "dependencies": {
8460 "@octokit/app": "^14.0.2",
8461 "@octokit/core": "^5.0.0",
8462 "@octokit/oauth-app": "^6.0.0",
8463 "@octokit/plugin-paginate-graphql": "^4.0.0",
8464 "@octokit/plugin-paginate-rest": "11.4.4-cjs.2",
8465 "@octokit/plugin-rest-endpoint-methods": "13.3.2-cjs.1",
8466 "@octokit/plugin-retry": "^6.0.0",
8467 "@octokit/plugin-throttling": "^8.0.0",
8468 "@octokit/request-error": "^5.0.0",
8469 "@octokit/types": "^13.0.0",
8470 "@octokit/webhooks": "^12.3.1"
8471 },
8472 "engines": {
8473 "node": ">= 18"
8474 }
8475 },
8476 "node_modules/once": {
8477 "version": "1.4.0",
8478 "license": "ISC",
8479 "dependencies": {
8480 "wrappy": "1"
8481 }
8482 },
8483 "node_modules/onetime": {
8484 "version": "5.1.2",
8485 "license": "MIT",
8486 "dependencies": {
8487 "mimic-fn": "^2.1.0"
8488 },
8489 "engines": {
8490 "node": ">=6"
8491 },
8492 "funding": {
8493 "url": "https://github.com/sponsors/sindresorhus"
8494 }
8495 },
84966627 "node_modules/oniguruma-parser": {
84976628 "version": "0.12.2",
84986629 "license": "MIT"
85066637 "regex-recursion": "^6.0.2"
85086639 },
8509 "node_modules/open": {
8510 "version": "9.1.0",
8511 "license": "MIT",
8512 "dependencies": {
8513 "default-browser": "^4.0.0",
8514 "define-lazy-prop": "^3.0.0",
8515 "is-inside-container": "^1.0.0",
8516 "is-wsl": "^2.2.0"
8517 },
8518 "engines": {
8519 "node": ">=14.16"
8520 },
8521 "funding": {
8522 "url": "https://github.com/sponsors/sindresorhus"
8523 }
8524 },
85256640 "node_modules/openai": {
85266641 "version": "6.26.0",
85276642 "license": "Apache-2.0",
85446659 },
8545 "node_modules/ora": {
8546 "version": "7.0.1",
8547 "license": "MIT",
8548 "dependencies": {
8549 "chalk": "^5.3.0",
8550 "cli-cursor": "^4.0.0",
8551 "cli-spinners": "^2.9.0",
8552 "is-interactive": "^2.0.0",
8553 "is-unicode-supported": "^1.3.0",
8554 "log-symbols": "^5.1.0",
8555 "stdin-discarder": "^0.1.0",
8556 "string-width": "^6.1.0",
8557 "strip-ansi": "^7.1.0"
8558 },
8559 "engines": {
8560 "node": ">=16"
8561 },
8562 "funding": {
8563 "url": "https://github.com/sponsors/sindresorhus"
8564 }
8565 },
8566 "node_modules/ora/node_modules/ansi-regex": {
8567 "version": "6.2.2",
8568 "license": "MIT",
8569 "engines": {
8570 "node": ">=12"
8571 },
8572 "funding": {
8573 "url": "https://github.com/chalk/ansi-regex?sponsor=1"
8574 }
8575 },
8576 "node_modules/ora/node_modules/emoji-regex": {
8577 "version": "10.6.0",
8578 "license": "MIT"
8579 },
8580 "node_modules/ora/node_modules/string-width": {
8581 "version": "6.1.0",
8582 "license": "MIT",
8583 "dependencies": {
8584 "eastasianwidth": "^0.2.0",
8585 "emoji-regex": "^10.2.1",
8586 "strip-ansi": "^7.0.1"
8587 },
8588 "engines": {
8589 "node": ">=16"
8590 },
8591 "funding": {
8592 "url": "https://github.com/sponsors/sindresorhus"
8593 }
8594 },
8595 "node_modules/ora/node_modules/strip-ansi": {
8596 "version": "7.2.0",
8597 "license": "MIT",
8598 "dependencies": {
8599 "ansi-regex": "^6.2.2"
8600 },
8601 "engines": {
8602 "node": ">=12"
8603 },
8604 "funding": {
8605 "url": "https://github.com/chalk/strip-ansi?sponsor=1"
8606 }
8607 },
8608 "node_modules/p-limit": {
8609 "version": "2.3.0",
8610 "license": "MIT",
8611 "dependencies": {
8612 "p-try": "^2.0.0"
8613 },
8614 "engines": {
8615 "node": ">=6"
8616 },
8617 "funding": {
8618 "url": "https://github.com/sponsors/sindresorhus"
8619 }
8620 },
8621 "node_modules/p-locate": {
8622 "version": "4.1.0",
8623 "license": "MIT",
8624 "dependencies": {
8625 "p-limit": "^2.2.0"
8626 },
8627 "engines": {
8628 "node": ">=8"
8629 }
8630 },
86316660 "node_modules/p-retry": {
86326661 "version": "4.6.2",
86336662 "license": "MIT",
86406669 "node": ">=8"
86426671 },
8643 "node_modules/p-try": {
8644 "version": "2.2.0",
8645 "license": "MIT",
8646 "engines": {
8647 "node": ">=6"
8648 }
8649 },
8650 "node_modules/param-case": {
8651 "version": "3.0.4",
8652 "license": "MIT",
8653 "dependencies": {
8654 "dot-case": "^3.0.4",
8655 "tslib": "^2.0.3"
8656 }
8657 },
86586672 "node_modules/partial-json": {
86596673 "version": "0.1.7",
86606674 "license": "MIT",
86616675 "peer": true
86626676 },
8663 "node_modules/pascal-case": {
8664 "version": "3.1.2",
8665 "license": "MIT",
8666 "dependencies": {
8667 "no-case": "^3.0.4",
8668 "tslib": "^2.0.3"
8669 }
8670 },
8671 "node_modules/path-case": {
8672 "version": "3.0.4",
8673 "license": "MIT",
8674 "dependencies": {
8675 "dot-case": "^3.0.4",
8676 "tslib": "^2.0.3"
8677 }
8678 },
8679 "node_modules/path-exists": {
8680 "version": "4.0.0",
8681 "license": "MIT",
8682 "engines": {
8683 "node": ">=8"
8684 }
8685 },
86866677 "node_modules/path-expression-matcher": {
86876678 "version": "1.5.0",
86886679 "funding": [
86976688 "node": ">=14.0.0"
86996690 },
8700 "node_modules/path-key": {
8701 "version": "3.1.1",
8702 "license": "MIT",
8703 "engines": {
8704 "node": ">=8"
8705 }
8706 },
87076691 "node_modules/pathe": {
87086692 "version": "2.0.3",
87096693 "dev": true,
87256709 "url": "https://github.com/sponsors/jonschlinkert"
87276711 },
8728 "node_modules/pierre": {
8729 "version": "2.1.16",
8730 "license": "ISC",
8731 "dependencies": {
8732 "@fat/prompts": "^0.0.3",
8733 "@supabase/supabase-js": "^2.38.0",
8734 "change-case": "^4.1.2",
8735 "diff": "^5.1.0",
8736 "is-git-repository": "^2.0.0",
8737 "lodash.debounce": "^4.0.8",
8738 "node-fetch": "^3.3.2",
8739 "octokit": "^3.2.0",
8740 "open": "^9.1.0",
8741 "ora": "^7.0.1",
8742 "simple-git": "^3.20.0",
8743 "ts-node": "^10.9.1"
8744 },
8745 "bin": {
8746 "pier": "dist/index.js",
8747 "piere": "dist/index.js",
8748 "pierr": "dist/index.js",
8749 "pierre": "dist/index.js",
8750 "pr": "dist/index.js"
8751 }
8752 },
8753 "node_modules/pierre/node_modules/diff": {
8754 "version": "5.2.2",
8755 "license": "BSD-3-Clause",
8756 "engines": {
8757 "node": ">=0.3.1"
8758 }
8759 },
87606712 "node_modules/playwright": {
87616713 "version": "1.61.0",
87626714 "dev": true,
87856737 "node": ">=18"
87876739 },
8788 "node_modules/pngjs": {
8789 "version": "5.0.0",
8790 "license": "MIT",
8791 "engines": {
8792 "node": ">=10.13.0"
8793 }
8794 },
87956740 "node_modules/postcss": {
87966741 "version": "8.5.15",
87976742 "dev": true,
88666811 "node": ">=12.0.0"
88686813 },
8869 "node_modules/pump": {
8870 "version": "3.0.4",
8871 "license": "MIT",
8872 "dependencies": {
8873 "end-of-stream": "^1.1.0",
8874 "once": "^1.3.1"
8875 }
8876 },
8877 "node_modules/qrcode": {
8878 "version": "1.5.4",
8879 "license": "MIT",
8880 "dependencies": {
8881 "dijkstrajs": "^1.0.1",
8882 "pngjs": "^5.0.0",
8883 "yargs": "^15.3.1"
8884 },
8885 "bin": {
8886 "qrcode": "bin/qrcode"
8887 },
8888 "engines": {
8889 "node": ">=10.13.0"
8890 }
8891 },
88926814 "node_modules/react": {
88936815 "version": "19.2.7",
88946816 "license": "MIT",
89086830 "react": "^19.2.7"
89106832 },
8911 "node_modules/readable-stream": {
8912 "version": "3.6.2",
8913 "license": "MIT",
8914 "dependencies": {
8915 "inherits": "^2.0.3",
8916 "string_decoder": "^1.1.1",
8917 "util-deprecate": "^1.0.1"
8918 },
8919 "engines": {
8920 "node": ">= 6"
8921 }
8922 },
89236833 "node_modules/regex": {
89246834 "version": "6.1.0",
89256835 "license": "MIT",
90596969 "url": "https://opencollective.com/unified"
90616971 },
9062 "node_modules/require-directory": {
9063 "version": "2.1.1",
9064 "license": "MIT",
9065 "engines": {
9066 "node": ">=0.10.0"
9067 }
9068 },
9069 "node_modules/require-main-filename": {
9070 "version": "2.0.0",
9071 "license": "ISC"
9072 },
9073 "node_modules/restore-cursor": {
9074 "version": "4.0.0",
9075 "license": "MIT",
9076 "dependencies": {
9077 "onetime": "^5.1.0",
9078 "signal-exit": "^3.0.2"
9079 },
9080 "engines": {
9081 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
9082 },
9083 "funding": {
9084 "url": "https://github.com/sponsors/sindresorhus"
9085 }
9086 },
90876972 "node_modules/retry": {
90886973 "version": "0.13.1",
90896974 "license": "MIT",
91247009 "@rolldown/binding-win32-x64-msvc": "1.0.3"
91267011 },
9127 "node_modules/run-applescript": {
9128 "version": "5.0.0",
9129 "license": "MIT",
9130 "dependencies": {
9131 "execa": "^5.0.0"
9132 },
9133 "engines": {
9134 "node": ">=12"
9135 },
9136 "funding": {
9137 "url": "https://github.com/sponsors/sindresorhus"
9138 }
9139 },
9140 "node_modules/run-applescript/node_modules/execa": {
9141 "version": "5.1.1",
9142 "license": "MIT",
9143 "dependencies": {
9144 "cross-spawn": "^7.0.3",
9145 "get-stream": "^6.0.0",
9146 "human-signals": "^2.1.0",
9147 "is-stream": "^2.0.0",
9148 "merge-stream": "^2.0.0",
9149 "npm-run-path": "^4.0.1",
9150 "onetime": "^5.1.2",
9151 "signal-exit": "^3.0.3",
9152 "strip-final-newline": "^2.0.0"
9153 },
9154 "engines": {
9155 "node": ">=10"
9156 },
9157 "funding": {
9158 "url": "https://github.com/sindresorhus/execa?sponsor=1"
9159 }
9160 },
9161 "node_modules/run-applescript/node_modules/get-stream": {
9162 "version": "6.0.1",
9163 "license": "MIT",
9164 "engines": {
9165 "node": ">=10"
9166 },
9167 "funding": {
9168 "url": "https://github.com/sponsors/sindresorhus"
9169 }
9170 },
9171 "node_modules/run-applescript/node_modules/human-signals": {
9172 "version": "2.1.0",
9173 "license": "Apache-2.0",
9174 "engines": {
9175 "node": ">=10.17.0"
9176 }
9177 },
91787012 "node_modules/safe-buffer": {
91797013 "version": "5.2.1",
91807014 "funding": [
91917025 "url": "https://feross.org/support"
91937027 ],
9194 "license": "MIT"
7028 "license": "MIT",
7029 "peer": true
91957030 },
91967031 "node_modules/scheduler": {
91977032 "version": "0.27.0",
92067041 "semver": "bin/semver.js"
92087043 },
9209 "node_modules/sentence-case": {
9210 "version": "3.0.4",
9211 "license": "MIT",
9212 "dependencies": {
9213 "no-case": "^3.0.4",
9214 "tslib": "^2.0.3",
9215 "upper-case-first": "^2.0.2"
9216 }
9217 },
9218 "node_modules/set-blocking": {
9219 "version": "2.0.0",
9220 "license": "ISC"
9221 },
9222 "node_modules/shebang-command": {
9223 "version": "2.0.0",
9224 "license": "MIT",
9225 "dependencies": {
9226 "shebang-regex": "^3.0.0"
9227 },
9228 "engines": {
9229 "node": ">=8"
9230 }
9231 },
9232 "node_modules/shebang-regex": {
9233 "version": "3.0.0",
9234 "license": "MIT",
9235 "engines": {
9236 "node": ">=8"
9237 }
9238 },
92397044 "node_modules/shiki": {
92407045 "version": "4.3.0",
92417046 "license": "MIT",
92837088 "dev": true,
92847089 "license": "ISC"
92857090 },
9286 "node_modules/signal-exit": {
9287 "version": "3.0.7",
9288 "license": "ISC"
9289 },
9290 "node_modules/simple-git": {
9291 "version": "3.36.0",
9292 "license": "MIT",
9293 "dependencies": {
9294 "@kwsites/file-exists": "^1.1.1",
9295 "@kwsites/promise-deferred": "^1.1.1",
9296 "@simple-git/args-pathspec": "^1.0.3",
9297 "@simple-git/argv-parser": "^1.1.0",
9298 "debug": "^4.4.0"
9299 },
9300 "funding": {
9301 "type": "github",
9302 "url": "https://github.com/steveukx/git-js?sponsor=1"
9303 }
9304 },
9305 "node_modules/sisteransi": {
9306 "version": "1.0.5",
9307 "license": "MIT"
9308 },
9309 "node_modules/snake-case": {
9310 "version": "3.0.4",
9311 "license": "MIT",
9312 "dependencies": {
9313 "dot-case": "^3.0.4",
9314 "tslib": "^2.0.3"
9315 }
9316 },
93177091 "node_modules/source-map-js": {
93187092 "version": "1.2.1",
93197093 "dev": true,
93407114 "dev": true,
93417115 "license": "MIT"
93427116 },
9343 "node_modules/stdin-discarder": {
9344 "version": "0.1.0",
9345 "license": "MIT",
9346 "dependencies": {
9347 "bl": "^5.0.0"
9348 },
9349 "engines": {
9350 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
9351 },
9352 "funding": {
9353 "url": "https://github.com/sponsors/sindresorhus"
9354 }
9355 },
9356 "node_modules/string_decoder": {
9357 "version": "1.3.0",
9358 "license": "MIT",
9359 "dependencies": {
9360 "safe-buffer": "~5.2.0"
9361 }
9362 },
9363 "node_modules/string-width": {
9364 "version": "4.2.3",
9365 "license": "MIT",
9366 "dependencies": {
9367 "emoji-regex": "^8.0.0",
9368 "is-fullwidth-code-point": "^3.0.0",
9369 "strip-ansi": "^6.0.1"
9370 },
9371 "engines": {
9372 "node": ">=8"
9373 }
9374 },
93757117 "node_modules/stringify-entities": {
93767118 "version": "4.0.4",
93777119 "license": "MIT",
93847126 "url": "https://github.com/sponsors/wooorm"
93867128 },
9387 "node_modules/strip-ansi": {
9388 "version": "6.0.1",
9389 "license": "MIT",
9390 "dependencies": {
9391 "ansi-regex": "^5.0.1"
9392 },
9393 "engines": {
9394 "node": ">=8"
9395 }
9396 },
9397 "node_modules/strip-final-newline": {
9398 "version": "2.0.0",
9399 "license": "MIT",
9400 "engines": {
9401 "node": ">=6"
9402 }
9403 },
94047129 "node_modules/strnum": {
94057130 "version": "2.3.0",
94067131 "funding": [
94597184 "node": ">=14.0.0"
94617186 },
9462 "node_modules/titleize": {
9463 "version": "3.0.0",
9464 "license": "MIT",
9465 "engines": {
9466 "node": ">=12"
9467 },
9468 "funding": {
9469 "url": "https://github.com/sponsors/sindresorhus"
9470 }
9471 },
94727187 "node_modules/trim-lines": {
94737188 "version": "3.0.1",
94747189 "license": "MIT",
95117226 "node": ">=6.10"
95137228 },
9514 "node_modules/ts-node": {
9515 "version": "10.9.2",
9516 "license": "MIT",
9517 "dependencies": {
9518 "@cspotcode/source-map-support": "^0.8.0",
9519 "@tsconfig/node10": "^1.0.7",
9520 "@tsconfig/node12": "^1.0.7",
9521 "@tsconfig/node14": "^1.0.0",
9522 "@tsconfig/node16": "^1.0.2",
9523 "acorn": "^8.4.1",
9524 "acorn-walk": "^8.1.1",
9525 "arg": "^4.1.0",
9526 "create-require": "^1.1.0",
9527 "diff": "^4.0.1",
9528 "make-error": "^1.1.1",
9529 "v8-compile-cache-lib": "^3.0.1",
9530 "yn": "3.1.1"
9531 },
9532 "bin": {
9533 "ts-node": "dist/bin.js",
9534 "ts-node-cwd": "dist/bin-cwd.js",
9535 "ts-node-esm": "dist/bin-esm.js",
9536 "ts-node-script": "dist/bin-script.js",
9537 "ts-node-transpile-only": "dist/bin-transpile.js",
9538 "ts-script": "dist/bin-script-deprecated.js"
9539 },
9540 "peerDependencies": {
9541 "@swc/core": ">=1.2.50",
9542 "@swc/wasm": ">=1.2.50",
9543 "@types/node": "*",
9544 "typescript": ">=2.7"
9545 },
9546 "peerDependenciesMeta": {
9547 "@swc/core": {
9548 "optional": true
9549 },
9550 "@swc/wasm": {
9551 "optional": true
9552 }
9553 }
9554 },
9555 "node_modules/ts-node/node_modules/diff": {
9556 "version": "4.0.4",
9557 "license": "BSD-3-Clause",
9558 "engines": {
9559 "node": ">=0.3.1"
9560 }
9561 },
95627229 "node_modules/tslib": {
95637230 "version": "2.8.1",
95647231 "license": "0BSD"
95657232 },
9566 "node_modules/tsx": {
9567 "version": "4.22.4",
9568 "dev": true,
9569 "license": "MIT",
9570 "dependencies": {
9571 "esbuild": "~0.28.0"
9572 },
9573 "bin": {
9574 "tsx": "dist/cli.mjs"
9575 },
9576 "engines": {
9577 "node": ">=18.0.0"
9578 },
9579 "optionalDependencies": {
9580 "fsevents": "~2.3.3"
9581 }
9582 },
9583 "node_modules/tsx/node_modules/fsevents": {
9584 "version": "2.3.3",
9585 "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
9586 "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
9587 "dev": true,
9588 "hasInstallScript": true,
9589 "license": "MIT",
9590 "optional": true,
9591 "os": [
9592 "darwin"
9593 ],
9594 "engines": {
9595 "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
9596 }
9597 },
95987233 "node_modules/typebox": {
95997234 "version": "1.2.1",
96007235 "license": "MIT",
96027237 },
96037238 "node_modules/typescript": {
96047239 "version": "6.0.3",
7240 "dev": true,
96057241 "license": "Apache-2.0",
96067242 "bin": {
96077243 "tsc": "bin/tsc",
96117247 "node": ">=14.17"
96137249 },
9614 "node_modules/unc-path-regex": {
9615 "version": "0.1.2",
9616 "license": "MIT",
9617 "engines": {
9618 "node": ">=0.10.0"
9619 }
9620 },
96217250 "node_modules/undici-types": {
96227251 "version": "7.24.6",
9623 "license": "MIT"
7252 "license": "MIT",
7253 "peer": true
96247254 },
96257255 "node_modules/unified": {
96267256 "version": "11.0.5",
97407370 "url": "https://opencollective.com/unified"
97427372 },
9743 "node_modules/universal-github-app-jwt": {
9744 "version": "1.2.0",
9745 "license": "MIT",
9746 "dependencies": {
9747 "@types/jsonwebtoken": "^9.0.0",
9748 "jsonwebtoken": "^9.0.2"
9749 }
9750 },
9751 "node_modules/universal-user-agent": {
9752 "version": "6.0.1",
9753 "license": "ISC"
9754 },
9755 "node_modules/untildify": {
9756 "version": "4.0.0",
9757 "license": "MIT",
9758 "engines": {
9759 "node": ">=8"
9760 }
9761 },
97627373 "node_modules/update-browserslist-db": {
97637374 "version": "1.2.3",
97647375 "dev": true,
97887399 "browserslist": ">= 4.21.0"
97907401 },
9791 "node_modules/upper-case": {
9792 "version": "2.0.2",
9793 "license": "MIT",
9794 "dependencies": {
9795 "tslib": "^2.0.3"
9796 }
9797 },
9798 "node_modules/upper-case-first": {
9799 "version": "2.0.2",
9800 "license": "MIT",
9801 "dependencies": {
9802 "tslib": "^2.0.3"
9803 }
9804 },
9805 "node_modules/util-deprecate": {
9806 "version": "1.0.2",
9807 "license": "MIT"
9808 },
9809 "node_modules/v8-compile-cache-lib": {
9810 "version": "3.0.1",
9811 "license": "MIT"
9812 },
98137402 "node_modules/vfile": {
98147403 "version": "6.0.3",
98157404 "license": "MIT",
100167605 "node_modules/web-streams-polyfill": {
100177606 "version": "3.3.3",
100187607 "license": "MIT",
7608 "peer": true,
100197609 "engines": {
100207610 "node": ">= 8"
100227612 },
10023 "node_modules/which": {
10024 "version": "2.0.2",
10025 "license": "ISC",
10026 "dependencies": {
10027 "isexe": "^2.0.0"
10028 },
10029 "bin": {
10030 "node-which": "bin/node-which"
10031 },
10032 "engines": {
10033 "node": ">= 8"
10035 },
10036 "node_modules/which-module": {
10037 "version": "2.0.1",
10038 "license": "ISC"
10039 },
100407613 "node_modules/why-is-node-running": {
100417614 "version": "2.3.0",
100427615 "dev": true,
100527625 "node": ">=8"
100547627 },
10055 "node_modules/wrap-ansi": {
10056 "version": "6.2.0",
10057 "license": "MIT",
10058 "dependencies": {
10059 "ansi-styles": "^4.0.0",
10060 "string-width": "^4.1.0",
10061 "strip-ansi": "^6.0.0"
10062 },
10063 "engines": {
10064 "node": ">=8"
10066 },
10067 "node_modules/wrappy": {
10068 "version": "1.0.2",
10069 "license": "ISC"
10070 },
100717628 "node_modules/ws": {
100727629 "version": "8.21.0",
100737630 "license": "MIT",
7631 "peer": true,
100747632 "engines": {
100757633 "node": ">=10.0.0"
100767634 },
101017659 "node": ">=16.0.0"
101037661 },
10104 "node_modules/y18n": {
10105 "version": "4.0.3",
10106 "license": "ISC"
10107 },
101087662 "node_modules/yallist": {
101097663 "version": "3.1.1",
101107664 "dev": true,
101237677 "url": "https://github.com/sponsors/eemeli"
101257679 },
10126 "node_modules/yargs": {
10127 "version": "15.4.1",
10128 "license": "MIT",
10129 "dependencies": {
10130 "cliui": "^6.0.0",
10131 "decamelize": "^1.2.0",
10132 "find-up": "^4.1.0",
10133 "get-caller-file": "^2.0.1",
10134 "require-directory": "^2.1.1",
10135 "require-main-filename": "^2.0.0",
10136 "set-blocking": "^2.0.0",
10137 "string-width": "^4.2.0",
10138 "which-module": "^2.0.0",
10139 "y18n": "^4.0.0",
10140 "yargs-parser": "^18.1.2"
10141 },
10142 "engines": {
10143 "node": ">=8"
10145 },
10146 "node_modules/yargs-parser": {
10147 "version": "18.1.3",
10148 "license": "ISC",
10149 "dependencies": {
10150 "camelcase": "^5.0.0",
10151 "decamelize": "^1.2.0"
10152 },
10153 "engines": {
10154 "node": ">=6"
10156 },
10157 "node_modules/yn": {
10158 "version": "3.1.1",
10159 "license": "MIT",
10160 "engines": {
10161 "node": ">=6"
10163 },
101647680 "node_modules/zod": {
101657681 "version": "4.4.3",
101667682 "license": "MIT",

scripts/test_extensions_static_check.mjs

Modified

+0 / −8 text lines

182182 prompts: ["extensions/the-system/prompts"],
183183});
185for (const file of [
186 "extensions/ui/scripts/phase1-smoke.mjs",
187 "extensions/ui/scripts/zellij-smoke.mjs",
188]) {
189 const text = readFileSync(join(ROOT, file), "utf8");
190 assert(!text.includes('".pi/tmp/'), `${file}: hardcoded .pi/tmp`);
191 assert(text.includes("CONFIG_DIR_NAME"), `${file}: missing CONFIG_DIR_NAME`);
192}
193185assert.deepEqual(
194186 JSON.parse(
195187 readFileSync(join(ROOT, "extensions/the-system/package.json"), "utf8"),