@pi-chamber/web 1.0.4-rc.1 → 1.0.4-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/assets/{DiagramView-DfZMQkXY.js → DiagramView-GKGxPczP.js} +1 -1
  2. package/dist/assets/{DiffView-BjWUdbL5.js → DiffView-Cay8VAqL.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-u5L4k_5k.js → FileSaveConflictDialog-BRM9TJo0.js} +1 -1
  4. package/dist/assets/{FilesView-qP1ypN9J.js → FilesView-CEeQzjc6.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-zCKCy5OJ.js → GitHubDetailScaffold-q4YP8iyJ.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-CwxKY3lN.js → GitHubLinkPicker-B9xgIW8y.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-Ck3zllel.js → GitHubListPrimitives-XkALat1v.js} +1 -1
  8. package/dist/assets/{GitView-y2k2i4gR.js → GitView-DV3d0oSJ.js} +3 -3
  9. package/dist/assets/{IssuesSurface-HWgR87N3.js → IssuesSurface-OTyt9f3A.js} +3 -3
  10. package/dist/assets/{JsonTreeView-DSuC4naV.js → JsonTreeView-X2Auiy_q.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-CT5ln9em.js → MarkdownRendererImpl-1HameF6j.js} +12 -12
  12. package/dist/assets/{PatchDiff-DArTeWeK.js → PatchDiff-GMQAv4en.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-DQKujzLb.js → PierreDiffViewer-0X__nypk.js} +2 -2
  14. package/dist/assets/PullRequestsSurface-Dec20SIg.js +2 -0
  15. package/dist/assets/{SessionSwitcherContent-DEGJyZBl.js → SessionSwitcherContent-DEw4nz7K.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-cC9wVBH7.js → SessionSwitcherDropdown-DmLhbRzE.js} +2 -2
  17. package/dist/assets/SessionUnreadDot-CJFawQpo.js +1 -0
  18. package/dist/assets/SettingsView-CwSspvq-.js +6 -0
  19. package/dist/assets/{SettingsWindow-CZM1dmVb.js → SettingsWindow-DkPv9MaU.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-DClOSbJc.js → ToolOutputDialog-DDwbOpTO.js} +3 -3
  21. package/dist/assets/{ToolPartDiffPreview-BaFiGUDE.js → ToolPartDiffPreview-DZRP7p-Q.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-D6KbvKc6.js → VirtualizedFileDiff-CUWx7JVZ.js} +1 -1
  23. package/dist/assets/{collapsible-DhV9d4dT.js → collapsible-Ce85nuXX.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-CeMpF2xC.js → computeVirtualFileMetrics-3PpRLd5B.js} +1 -1
  25. package/dist/assets/{contextFileOpenGuard-Ck5u_kAP.js → contextFileOpenGuard-PoBklHMz.js} +1 -1
  26. package/dist/assets/{gitStatusPredicates-DEBSqUNE.js → gitStatusPredicates-BvzxqidP.js} +1 -1
  27. package/dist/assets/{githubLink-DT7i2NlH.js → githubLink-iQ51wqRa.js} +1 -1
  28. package/dist/assets/{index-eDf4LKLY.js → index-CkMnC_GK.js} +1 -1
  29. package/dist/assets/{index-6IO1AcJI.js → index-Dd2OcIUY.js} +9 -9
  30. package/dist/assets/index-DvN8zlLT.css +1 -0
  31. package/dist/assets/{main-BczEScAA.js → main-FasHq7Ck.js} +2 -2
  32. package/dist/assets/{main-CHLNMYeJ.js → main-PSCt716b.js} +8 -8
  33. package/dist/assets/{markdownCore-C4Gk5Zht.js → markdownCore-BH56o6Wu.js} +1 -1
  34. package/dist/assets/{miniChat-Do3hE87Z.js → miniChat-BzfobBDq.js} +2 -2
  35. package/dist/assets/{mobile-CTnihwfa.js → mobile-DAzZE2EL.js} +2 -2
  36. package/dist/assets/{pi-session-focus-preference-LDVCJ_YR.js → pi-session-focus-preference-D2-1HWmY.js} +3 -3
  37. package/dist/assets/{renderDiffWithHighlighter-CDsgOnkH.js → renderDiffWithHighlighter-l8hZWWBO.js} +1 -1
  38. package/dist/assets/{renderElectronMiniChatApp-DSa3gYqR.js → renderElectronMiniChatApp-DGYSIihR.js} +2 -2
  39. package/dist/assets/{renderFileWithHighlighter-TpKRyfCY.js → renderFileWithHighlighter-BvDoP7ob.js} +1 -1
  40. package/dist/assets/renderMobileApp-CwgWG0lU.js +11 -0
  41. package/dist/assets/runtimeEndpointReset-CmI6dBKM.js +62 -0
  42. package/dist/assets/{runtimeSurface-DW_Ia4q3.js → runtimeSurface-B1GRkkKC.js} +1 -1
  43. package/dist/assets/{useAppFontEffects-CG3_yteE.js → useAppFontEffects--lKKtKVo.js} +62 -62
  44. package/dist/assets/{useFilesViewSearch-C_LzYIgD.js → useFilesViewSearch-D1jsGQrN.js} +3 -3
  45. package/dist/assets/{useGitHubRemoteSearch-DsxWOzKZ.js → useGitHubRemoteSearch-zNgy2bSt.js} +1 -1
  46. package/dist/assets/{useSwitcherItems-BmoCnS9W.js → useSwitcherItems-OCRYcHeu.js} +1 -1
  47. package/dist/assets/{web-components-CH3-XV-n.js → web-components-v9fuidaX.js} +1 -1
  48. package/dist/index.html +4 -4
  49. package/dist/mini-chat.html +3 -3
  50. package/dist/mobile.html +3 -3
  51. package/package.json +2 -2
  52. package/server/lib/pi/session-daemon/DOCUMENTATION.md +21 -8
  53. package/server/lib/pi/session-daemon/builtin-extensions.js +37 -0
  54. package/server/lib/pi/session-daemon/daemon-process.js +6 -0
  55. package/server/lib/pi/session-daemon/extension-theme.js +75 -0
  56. package/server/lib/pi/session-daemon/extension-theme.test.js +47 -0
  57. package/server/lib/pi/session-daemon/prompt-operations.test.js +3 -3
  58. package/server/lib/pi/session-daemon/prompt-preflight.test.js +12 -14
  59. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +118 -2
  60. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +1 -1
  61. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +1 -1
  62. package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +638 -0
  63. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +437 -0
  64. package/server/lib/pi/session-daemon/session-daemon.js +61 -42
  65. package/server/lib/pi/session-daemon/session-daemon.test.js +53 -5
  66. package/server/lib/pi/session-daemon/session-idle-residency.test.js +1 -1
  67. package/server/lib/pi/session-daemon/session-replay.test.js +1 -1
  68. package/server/lib/pi/session-persistence-gap.test.js +2 -3
  69. package/server/lib/pi/ui-settings-store.js +1 -0
  70. package/server/lib/pi/ui-settings-store.test.js +27 -0
  71. package/dist/assets/PullRequestsSurface-Cfb1wSvC.js +0 -2
  72. package/dist/assets/SessionUnreadDot-CELKNVIM.js +0 -1
  73. package/dist/assets/SettingsView-CZvRRgJe.js +0 -6
  74. package/dist/assets/index-BAmzAlNx.css +0 -1
  75. package/dist/assets/renderMobileApp-CPE-3uMl.js +0 -11
  76. package/dist/assets/runtimeEndpointReset-CzJfovWI.js +0 -62
@@ -8,11 +8,12 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
8
8
 
9
9
  - `../extension-protocol.js` owns the bounded form descriptor and response validation shared by the private daemon bridge and public route projection, so both sides of the IPC seam accept the same field contract.
10
10
  - `extension-bridge.js` owns extension UI bindings, pending dialog lifecycle, normalized status/widget/panel/app state, snapshot projection, and extension event publication. `session-daemon.js` supplies runtime lookup, publication, redaction, and directory dependencies through its narrow factory interface.
11
+ - `builtin-extensions.js` owns the list of Pi built-in extensions PiChamber loads (`codemode`, `tool-search`, `mcp`) and the list it skips on purpose (`llama.cpp`). Pi ships these inside the SDK package and only the Pi CLI loads them by itself, so the daemon passes them through `resourceLoaderOptions.extensionFactories` with the same `builtin: true` and `replaceable: true` flags the CLI uses. They load as `builtin:<name>`. `-builtin:<name>` in the Pi `extensions` setting disables one. Pi leaves one out when an installed extension registers the same tool, command, or flag, so a third-party MCP extension that registers `/mcp` takes over and Pi does not read `mcp.json`. MCP servers come from `mcp.json` in the agent directory and `.pi/mcp.json` in a trusted project. Each resident session runtime starts its own servers on `session_start` and stops them on `session_shutdown`, which every runtime disposal path emits. The MCP extension resolves `mcp.json`, `mcp-auth.json`, and `mcp.log` through the SDK's process-wide agent directory, so `daemon-process.js` sets `PI_CODING_AGENT_DIR` to the daemon's `--agent-dir` when one is given. Code that creates a daemon in-process with a custom `agentDir` must set that variable itself. `codemode` and `tool_search` are registered inactive. The MCP extension activates `codemode` for servers with the default `codemode` exposure and `tool_search` for `deferred` servers; `defaultTools` can activate them without MCP. Tool rows follow Pi's design: a `direct` MCP tool is an ordinary row rendered by its own `renderCall` and `renderResult`, `tool_search` is an ordinary row with the default display, and a `codemode` call is one row whose rendered result lists the nested calls with their status while the script runs. Nested calls stay out of the row list because their events carry `parentToolCallId`. `/mcp` runs its non-TUI path because the bridge reports `mode: 'rpc'`: `/mcp` sends server status through `ctx.ui.notify`, and `/mcp login <server>`, `/mcp logout <server>`, and `/mcp reconnect <server>` act directly. The interactive manager needs `ctx.ui.custom()` and is not available. PiChamber has no MCP settings screen.
11
12
  - `extension-name.js` owns path-free extension display names for `extensions.list` and the `source` of runtime `extension.error` events. A single-file extension is named after its file; an `index` entry point is named after its nearest non-generic directory, or the package root for package extensions. Neither surface ever carries a server path.
12
13
  - `extension-tool-render.js` owns daemon-side rendering for Pi extension tools that define `renderCall` or `renderResult`. Built-in tools are excluded so PiChamber retains native tool card rendering. Global Pi TUI theme symbols are installed once without overriding an existing theme. Partial updates render both the collapsed and expanded result slots (the browser draws the expanded slot only when a row is expanded), are throttled at 250ms with a trailing timer and component `invalidate()` trigger, the latest live render of a running tool is kept and included in session detail so a client opening mid-run sees the working state, settled results are rendered only for messages a history page selects (never for the whole branch) and memoized per toolResult message for history replay, and rendered ANSI lines are bounded to 100 columns, ≤200 lines, and ≤2000 characters per line.
13
14
  - `session-daemon.js`
14
15
  - `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` in rpc-like mode with a daemon-owned UI bridge, so pi extensions load exactly as they do under the Pi CLI's RPC mode. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
15
- - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget` (supporting both string arrays and component factory functions rendered daemon-side with a 100-column `tuiStub` and 100ms coalesced `requestRender()` throttling, with automatic lifecycle disposal and error capture), session-scoped `extension.working` (`setWorkingMessage` / `setWorkingVisible` with control character sanitization and 200-char cap; `setHiddenThinkingLabel` and `setWorkingIndicator` remain intentional no-ops because PiChamber uses its own turn working header and full thinking presentation), session-scoped `extension.editor` (`mode: 'set' | 'paste'`, default `'set'`), and `extension.title`; extension errors publish `extension.error`; displayed custom messages publish `extension.message`, and appended `pichamber.*` custom entries without a stable `id` publish `extension.entry` and appear as one-off extension-role transcript items; any other `appendEntry` custom entry is private extension state (Pi's TUI never renders it) and is neither published nor projected into history. `pichamber.ui` entries with a stable `id` and `pichamber.app` entries are mirrored into normalized live panel/app state (`extension.ui` / `extension.app` events live; latest wins per id, `removed: true` unregisters) and are excluded from transcript messages to avoid duplicate rendering. `ctx.ui.getEditorText()` uses a lazy server-side mirror: the first call on a session marks it as tracked, emits an `extension.editor.track` event (`{ enabled: true }`), and returns the current mirror text (or `''` initially); the browser composer observes tracking through session snapshots and the event stream, immediately syncing its current draft and then debouncing subsequent draft changes by 250ms via `POST /api/pi/sessions/:id/editor-draft` with monotonically increasing revisions to reject out-of-order deliveries; prompt submission resets the mirror text to empty while preserving tracking; `setEditorText` and `pasteToEditor` update the mirror synchronously; and session close, deletion, reload, or daemon disposal clears both the mirror and the tracking flag and publishes `extension.editor.track` with `{ enabled: false }` so browsers stop syncing until a later call opts the session back in. Untracked sessions never allocate mirror state (a prompt reset only touches an existing mirror), and draft syncs refresh the session's idle-disposal timer without reactivating a disposed runtime. `ctx.ui.theme` implements the complete Pi SDK `Theme` interface (`fg`, `bg`, `bold`, `italic`, `underline`, `inverse`, `strikethrough`, `getFgAnsi`, `getBgAnsi`, `getColorMode`, `getThinkingBorderColor`, `getBashModeBorderColor`), encoding semantic colors as standard truecolor SGR escape markers (`38;2;1;1;<index>m` and `48;2;1;1;<index>m`) using canonical `THEME_COLORS` and `THEME_BG_COLORS` lists that must stay strictly synchronized with `packages/ui/src/lib/pi/ansi.ts`. Extension live state (statuses, widgets, panels, apps, titles, and working indicators) is kept in per-session maps and included in both `sessions.open` and `session.snapshot`; on session runtime creation/open, restart, or branch mutation (`sessions.navigate`, `sessions.fork`, `sessions.clone`), live panels and apps are rebuilt by replaying the active branch's persisted `pichamber.ui`/`pichamber.app` custom entries in order without publishing per-entry events. The open response must cover every extension event at or below its `lastSequence`, so first attach cannot skip one-time startup statuses before the browser stream connects; reconnect snapshots rebuild the same live panels. TUI-only `setHeader`, `setFooter`, and `custom` remain intentional no-ops because PiChamber provides web/GUI message framing and composer docks rather than terminal chrome; standard RPC editor replacement/insertion and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal, session deletion, or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
16
+ - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget` (supporting both string arrays and component factory functions rendered daemon-side with a 100-column `tuiStub` and 100ms coalesced `requestRender()` throttling, with automatic lifecycle disposal and error capture), session-scoped `extension.working` (`setWorkingMessage` / `setWorkingVisible` with control character sanitization and 200-char cap; `setHiddenThinkingLabel` and `setWorkingIndicator` remain intentional no-ops because PiChamber uses its own turn working header and full thinking presentation), session-scoped `extension.editor` (`mode: 'set' | 'paste'`, default `'set'`), and `extension.title`; extension errors publish `extension.error`; displayed custom messages publish `extension.message`, and appended `pichamber.*` custom entries without a stable `id` publish `extension.entry` and appear as one-off extension-role transcript items; any other `appendEntry` custom entry is private extension state (Pi's TUI never renders it) and is neither published nor projected into history. `pichamber.ui` entries with a stable `id` and `pichamber.app` entries are mirrored into normalized live panel/app state (`extension.ui` / `extension.app` events live; latest wins per id, `removed: true` unregisters) and are excluded from transcript messages to avoid duplicate rendering. `ctx.ui.getEditorText()` uses a lazy server-side mirror: the first call on a session marks it as tracked, emits an `extension.editor.track` event (`{ enabled: true }`), and returns the current mirror text (or `''` initially); the browser composer observes tracking through session snapshots and the event stream, immediately syncing its current draft and then debouncing subsequent draft changes by 250ms via `POST /api/pi/sessions/:id/editor-draft` with monotonically increasing revisions to reject out-of-order deliveries; prompt submission resets the mirror text to empty while preserving tracking; `setEditorText` and `pasteToEditor` update the mirror synchronously; and session close, deletion, reload, or daemon disposal clears both the mirror and the tracking flag and publishes `extension.editor.track` with `{ enabled: false }` so browsers stop syncing until a later call opts the session back in. Untracked sessions never allocate mirror state (a prompt reset only touches an existing mirror), and draft syncs refresh the session's idle-disposal timer without reactivating a disposed runtime. `ctx.ui.theme` implements the complete Pi SDK `Theme` interface (`fg`, `bg`, `bold`, `dim`, `italic`, `underline`, `inverse`, `strikethrough`, `getFgAnsi`, `getBgAnsi`, `getColorMode`, `getThinkingBorderColor`, `getBashModeBorderColor`, `appearance`, `colors`, `style`), encoding semantic colors as standard truecolor SGR escape markers (`38;2;1;1;<index>m` and `48;2;1;1;<index>m`) using canonical `THEME_COLORS` and `THEME_BG_COLORS` lists that must stay strictly synchronized with `packages/ui/src/lib/pi/ansi.ts`. `appearance` returns a fixed `'dark'` default because the daemon serves multiple clients with different themes. `colors` exposes a frozen token map. `style(text, options)` maps token names and text attributes to marker escape sequences. Extension live state (statuses, widgets, panels, apps, titles, and working indicators) is kept in per-session maps and included in both `sessions.open` and `session.snapshot`; on session runtime creation/open, restart, or branch mutation (`sessions.navigate`, `sessions.fork`, `sessions.clone`), live panels and apps are rebuilt by replaying the active branch's persisted `pichamber.ui`/`pichamber.app` custom entries in order without publishing per-entry events. The open response must cover every extension event at or below its `lastSequence`, so first attach cannot skip one-time startup statuses before the browser stream connects; reconnect snapshots rebuild the same live panels. TUI-only `setHeader`, `setFooter`, and `custom` remain intentional no-ops because PiChamber provides web/GUI message framing and composer docks rather than terminal chrome; standard RPC editor replacement/insertion and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal, session deletion, or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
16
17
  - `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs. Test seams inject `createRuntime` for resident runtimes and `createServices` (default `createAgentSessionServices`) for transient per-mutation prompt services.
17
18
  - `session-replay.js` owns the byte- and count-bounded contiguous replay suffix (`MAX_REPLAY_EVENTS`, `MAX_REPLAY_BYTES`, `createSessionReplayLog`). It caches one serialized line per event for broadcast/replay reuse and reports contiguity (`canReplay`) without trusting filtered delivery.
18
19
  - `daemon-process.js` is the detached private-process entrypoint. It reads the daemon credential from its owner-only sidecar, starts the socket, writes non-secret identity state only after readiness, persists an accepted ownership claim before acknowledging it over IPC, and removes only its own state on signal shutdown.
@@ -38,13 +39,13 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
38
39
  - The public health route deliberately whitelists its response fields (state, protocol version, capability names, and the opaque public `streamEpoch`). It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
39
40
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
40
41
  - Frames are LF-delimited JSON. One frame has a 16 MiB maximum. Complete frames are parsed before the client bounds the remaining incomplete frame. Invalid JSON reports `MALFORMED_DAEMON_RESPONSE`; an oversized response reports `DAEMON_RESPONSE_TOO_LARGE`. A malformed, oversized, unauthenticated, or invalid request closes the connection.
41
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/models.add/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.models.add` appends one model (`id` required; optional `name`, `reasoning`, `thinkingLevelMap`, `input`, `contextWindow`, and `maxTokens`) atomically without replacing the provider. The model configuration store owns normalization and validation. The daemon rejects duplicate or unavailable live models, seeds a missing file provider only from authoritative live metadata when safely representable, rejects extension registrations with an explicit `models` array, and uses the same deferred recreation as `providers.models.set`. A successful recreation publishes a provider-catalog invalidation so connected settings views load the new authoritative catalog. Provider edits preserve unexposed existing model metadata server-side while public projections remain credential-blind. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Each listed row whose runtime is resident in this daemon (including unpersisted resident sessions) carries `live: { lifecycle, sequence, retry?, runStartedAt?, serverNow }`, sampled synchronously with the current event `sequence` from the same retry/streaming/run-start state as snapshots; rows without a resident runtime carry no `live`, which clients treat as unknown rather than idle. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal of persisted sessions, and clear on explicit session deletion, confirmed ephemeral expiration (which publishes `session.deleted`), or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
42
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/models.add/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.models.add` appends one model (`id` required; optional `name`, `reasoning`, `thinkingLevelMap`, `input`, `contextWindow`, and `maxTokens`) atomically without replacing the provider. The model configuration store owns normalization and validation. The daemon rejects duplicate or unavailable live models, seeds a missing file provider only from authoritative live metadata when safely representable, rejects extension registrations with an explicit `models` array, and uses the same deferred recreation as `providers.models.set`. A successful recreation publishes a provider-catalog invalidation so connected settings views load the new authoritative catalog. Provider edits preserve unexposed existing model metadata server-side while public projections remain credential-blind. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Each listed row whose runtime is resident in this daemon (including unpersisted resident sessions) carries `live: { lifecycle, sequence, retry?, runStartedAt?, serverNow }`, sampled synchronously with the current event `sequence` from the same retry/streaming/run-start state as snapshots; rows without a resident runtime carry no `live`, which clients treat as unknown rather than idle. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Nested tool execution events carrying a non-empty `parentToolCallId` are skipped because Pi records nested calls on the parent tool result and omits them from transcript messages. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal of persisted sessions, and clear on explicit session deletion, confirmed ephemeral expiration (which publishes `session.deleted`), or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
42
43
  - Each event and reconnect snapshot has a monotonic sequence. Replay is capability-negotiated: the subscriber stamps its cursor with the `streamEpoch` it was established under, a marker-less cursor fails as `DAEMON_PROTOCOL_MISMATCH`, and a cursor from a retired epoch resyncs from a snapshot instead of replaying — even when this daemon's sequence numerically overtook the old cursor, replaying from it would silently skip the head of the new space. Every event, snapshot, and health result carries an opaque random `streamEpoch` regenerated on every daemon process start (never derived from daemon id, profile key, pid, or any private identity); `runtime.health` advertises the `events.streamEpoch` capability, session reads stamp it so clients can reject stale-epoch responses, and a snapshot published because the cursor could not be replayed is additionally stamped `resync: true` as a recovery baseline. A reconnect replays the retained contiguous suffix after its cursor when available, otherwise it receives an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions. The suffix lives in `session-replay.js` and is bounded by both count (1,024 events) and encoded wire bytes (8 MiB): eviction removes whole oldest events first and never truncates content, each event is serialized once and the cached line is reused for live broadcast and replay, and live delivery stays full-fidelity even for events too large to retain. The byte budget counts encoded wire bytes, not heap, and snapshots assign sequence numbers without replay insertion so numeric gaps from private snapshots are intentional. A single oversized event clears the retained suffix without being retained, an empty ring never replays, and a cursor beyond the latest sequence resynchronizes from a snapshot; contiguity is judged on the global suffix while delivery stays session-filtered, so a filtered client never replays through a gap. A missed suffix recovers through `session.snapshot` plus `sessions.open` hydrate, which re-reads persisted entries for tool finals and lifecycle.
43
- - Prompt, steer, and follow-up requests acknowledge acceptance only after the Pi SDK preflight signal (session.prompt with preflightResult(true)); the daemon owns the still-running turn promise and publishes any asynchronous rejection as `session.error`. A preflight rejection (preflightResult(false)) propagates as the request rejection so dedup never caches it as accepted and the operation id stays reusable. Plain text uses prompt() with expandPromptTemplates:false and source:extension plus images; slash input keeps source:rpc. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata per delivery kind (`prompt`/`steer`/`followUp`) and adds it to the matching user start. SDK `queue_update` shrink is the authoritative owner of the next user start (steering drains before followUp regardless of send order); direct starts emit no shrink and fall back to oldest-by-generation. Requested `steer`/`followUp` always travels as SDK `streamingBehavior` (ignored while idle) so an idle arrival that races another sender still queues. Retention is decided at resolution from authoritative runtime state (`isStreaming` or SDK queue non-empty, never for handled extension commands); only queued resolutions keep metadata until their per-delivery start, all other completions clean a still-pending entry (an extension command that never emits a user start). The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
44
+ - Prompt, steer, and follow-up requests acknowledge acceptance only after the Pi SDK preflight signal (`session.prompt` with `preflightResult(disposition)` where `disposition` is `'started'`, `'queued'`, or `'handled'`); the daemon owns the still-running turn promise and publishes any asynchronous rejection as `session.error`. A preflight rejection (`session.prompt` promise rejecting without calling `preflightResult`) propagates as the request rejection so dedup never caches it as accepted and the operation id stays reusable. Plain text uses prompt() with expandPromptTemplates:false and source:extension plus images; slash input keeps source:rpc. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata per delivery kind (`prompt`/`steer`/`followUp`) and adds it to the matching user start. SDK `queue_update` shrink is the authoritative owner of the next user start (steering drains before followUp regardless of send order); direct starts emit no shrink and fall back to oldest-by-generation. Requested `steer`/`followUp` always travels as SDK `streamingBehavior` (ignored while idle) so an idle arrival that races another sender still queues. Retention is decided at resolution from the SDK preflight disposition: `'queued'` keeps the metadata, `'handled'` and registered extension commands never do, and `'started'` keeps it only while the session is still streaming; only queued resolutions keep metadata until their per-delivery start, all other completions clean a still-pending entry (an extension command that never emits a user start). The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
44
45
  - Send-intent deduplication (`send-operation-registry.js`) owns the authoritative execution boundary for prompt/steer/followUp: the client labels each intent with a stable `operationId` and the health-verified `streamEpoch`, the daemon claims `kind + sessionId + operationId + streamEpoch` BEFORE Pi activation, and an identical same-epoch retry returns the original acceptance receipt (`{ accepted, messageId, deduplicated: true }`) without invoking Pi again. A concurrent duplicate of a still-pending intent shares the original outcome; the same full key with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). An intent from another daemon lifetime fails as `STALE_STREAM_EPOCH` (HTTP 409) before Pi or attachment-consumption side effects. The same id on a different kind or session is a different intent and executes independently, never a mismatch. Only acceptances are retained: request-path rejections happen before Pi runs (nothing executed, id reusable) while pending duplicates still share the original rejection, and every claim settles so pending duplicates never hang. Retention is bounded: receipts expire after `sendOperationTtlMs` (default ten minutes) and at most 1,024 accepted receipts are retained (oldest evicted to a bounded expired tombstone); pending claims are bounded separately (256 entries, never expired while active, new distinct pending past the bound fails as `SESSION_BUSY`). An expired or evicted id reports `expired` and a retry with the same id fails as `OPERATION_EXPIRED` (HTTP 410), never an automatic re-execution — callers must use a new operation id. `sessions.sendReceipt` is the exact read-only receipt lookup for an uncertain send: it requires the full `kind + sessionId + operationId + streamEpoch` identity; a missing epoch returns `unknown`, never invokes Pi, and returns `accepted` (retained receipt), `pending`, `expired` (seen but retention gone, outcome unknown, never assume success), or `unknown` (never seen in this retention window, tombstone pressure, post-restart, or rejected before Pi ran). The registry is in-memory per daemon process with bounded tombstones (`expired` degrades to `unknown` under pressure): there is no lifetime receipt guarantee, only within the retention window. A restart loses receipts, but the replacement daemon rejects the retired epoch instead of replaying the old intent. Receipt lookup and replay protection remain separate read-only contracts.
45
46
  - Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
46
47
  - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). View-only access (`sessions.open`, `sessions.messages`, `sessions.tree`, plus navigate/fork/clone/abort/model/thinking/rename settlement) arms the same lifetime through `touchIdleDisposal`, so browsing old sessions without prompting cannot grow the registry unboundedly while the UI keeps only a bounded transcript cache. Disposal never deletes Pi JSONL; when the assigned session file exists on disk, the daemon remembers the selected session file and recreates that runtime on the next private prompt or open. When the assigned JSONL is positively absent (stat reports ENOENT only, determined after dispose while the resident lease is still held and before any release), the session is ephemeral: after a successful lease release the disposal clears matching dormant state plus the same safe per-session auxiliary state as explicit deletion where applicable (messageEntryAliases for cwd/session, retry/compaction/run-start/shutdown) and publishes the existing `session.deleted` event so connected clients remove it. Publication happens only after a successful release, which closes the cross-daemon recreate race. A missing/throwing getSessionFile or a non-ENOENT stat failure cannot prove absence and never claims deletion, a failed disposal retains ownership (registry entry, lease, and global runtime) without emitting deletion, and persisted sessions keep dormant state for reopen. The touch clears first and re-arms only when the session is resident and idle-safe, so a read cannot race a pending operation and a repeated open extends the deadline. Agent and compaction starts cancel pending disposal, and prompt/compact entry clears it before activation. The timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative, while a send is in flight (`activeSessionInputs`), while a resource reload is pending or running, while a provider retry is scheduled, or while compaction is running/retrying; pending extension dialogs are instead cancelled with an authoritative dismiss event. A read or prompt that arrives during an in-flight disposal waits for it and reopens from JSONL instead of adopting a dying runtime. There is deliberately no acquisition-path eviction: capacity pressure alone never disposes entries that are actively mounting.
47
- - Ephemeral sessions: Pi's `SessionManager` defers JSONL creation until the first assistant message, so `sessions.create` alone stays ephemeral (untouched sessions vanish on restart by design). A rejected first prompt likewise persists nothing: the runtime stays resident and retryable until normal idle disposal, which reports the session as deleted when its assigned JSONL is positively absent (see above). Failed `sessions.create` cancellation and lease-acquire failures dispose without persisting and release (or never hold) the lease. Model/thinking setup failures after lease acquisition dispose first and release only after successful disposal: a disposal rejection retains `{ runtime, cwd, sessionId }` in daemon-owned pending failed-create state without releasing ownership, registering the runtime, or installing dormant state, while still throwing the original model/thinking error; `sessions.delete` retries its session entry and daemon stop retries all entries (dispose-first, release-after-success, failed retries stay pending without releasing ownership, entries removed only when still current, disposal exactly once).
48
+ - Ephemeral sessions: Pi's `SessionManager` defers JSONL creation until the entries contain a user or assistant message, so `sessions.create` alone stays ephemeral (untouched sessions vanish on restart by design). A rejected first prompt likewise persists nothing: the runtime stays resident and retryable until normal idle disposal, which reports the session as deleted when its assigned JSONL is positively absent (see above). Failed `sessions.create` cancellation and lease-acquire failures dispose without persisting and release (or never hold) the lease. Model/thinking setup failures after lease acquisition dispose first and release only after successful disposal: a disposal rejection retains `{ runtime, cwd, sessionId }` in daemon-owned pending failed-create state without releasing ownership, registering the runtime, or installing dormant state, while still throwing the original model/thinking error; `sessions.delete` retries its session entry and daemon stop retries all entries (dispose-first, release-after-success, failed retries stay pending without releasing ownership, entries removed only when still current, disposal exactly once).
48
49
  - A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
49
50
  - After a forced crash, the next health, request, or subscription probe re-runs supervised startup. Each private health probe uses the supervisor's five-second operation budget; it must not inherit the general 30-second command timeout and hold every browser request until the browser aborts. Daemon readiness has its own 15-second bounded budget, separate from the shorter probe, lock, and shutdown budget, because loading Pi settings and provider/model catalogs can legitimately exceed five seconds. The supervisor removes an existing POSIX socket only when its recorded daemon PID is dead, the endpoint is a socket, and authenticated IPC deterministically refuses or times out. An endpoint that responds, authenticates incorrectly, returns malformed protocol data, or cannot be classified remains `DAEMON_ENDPOINT_UNVERIFIED`.
50
51
  - The web server creates its supervisor after HTTP listen so the profile key uses the bound port, then warms it without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`. The bound profile key travels back over the `pichamber:ready` IPC message and into the CLI instance file; `pichamber logs` uses that key to include the matching private daemon log, while `--json` and `--quiet` serve output still carries only the port.
@@ -54,16 +55,28 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
54
55
 
55
56
  This module defines the authenticated session API boundary consumed by the Pi-native session UI. Session leases coordinate PiChamber daemons only: the standalone `pi` CLI runs its own foreground runtime and does not honor these leases, so concurrently editing the same session through PiChamber and `pi` remains unsupported until Pi provides compatible upstream locking. Resource configuration and richer attachment extraction remain owned by their dedicated workstreams. The session event stream is SSE over the existing authenticated runtime transport; WebSocket callers fall back to it, preserving direct and relay behavior without a second daemon listener. The public route emits named heartbeat events so native `EventSource` clients can detect a silent foreground connection, reconnect, and resume from their last accepted sequence.
56
57
 
57
- The Pi SDK is pinned exactly at `0.85.1`. Any Pi 0.x minor upgrade requires a deliberate SDK/release-note review and repeat of this module's disposable-runtime smoke validation.
58
+ The Pi SDK is pinned exactly at `1.0.0`. Any Pi upgrade requires a deliberate SDK/release-note review and repeat of this module's disposable-runtime smoke validation.
58
59
 
59
60
  ## SDK upgrade validation
60
61
 
61
- The 0.84.1 → 0.85.1 upgrade retains the public session runtime/services API and v3 JSONL format. No PiChamber data migration or cache deletion is required. The SDK repairs a missing trailing newline when opening an existing session; subsequent entries remain separate JSONL records. Existing settings, custom model definitions, labels, and extension entries remain intact.
62
+ The 0.85.1 to 1.0.0 upgrade keeps the public session runtime/services API and the v3 JSONL format. No PiChamber data migration or cache deletion is required. Existing settings, custom model definitions, labels, and extension entries remain intact.
62
63
 
63
- - `sdk-upgrade.test.js` exercises the installed SDK with disposable directories: cached OpenCode models, user model additions and overrides, forced HTTP refresh, ETag/304, failed refresh preserving the last catalog, restart restoration, and opening/appending a pre-upgrade v3 session.
64
+ What changed in the SDK and how PiChamber handles it:
65
+
66
+ - Prompt acceptance. `preflightResult` now receives a disposition (`'started'`, `'queued'`, or `'handled'`) and is not called for a rejected prompt. The daemon treats any callback as acceptance and a rejected prompt promise as rejection. Under 0.85.1 the callback received a boolean, so the old `=== true` check rejected every prompt on 1.0.0.
67
+ - Session file timing. The SDK writes the JSONL when the first user message is appended. 0.85.1 waited for the first assistant message. A turn that fails or is aborted after its user message now leaves a persisted session. An untouched session, and a first prompt rejected before the user message, still persist nothing.
68
+ - New entry types. `context_edit` and `usage` entries are not transcript rows. History projection reads only `message` entries with the `user` or `assistant` role and the custom entries described above.
69
+ - Nested tool calls. Calls made through `ctx.executeTool()` emit `tool_execution_*` events with `parentToolCallId`. The daemon does not publish them, which matches history.
70
+ - Model catalog. Remote catalog requests carry `types=chat,image,classifier`. PiChamber lists models through `getModels()` and `getAvailableSnapshot()`, which stay chat-only.
71
+ - Theme. The extension theme adds `appearance`, `colors`, and `style()`.
72
+ - Built-in extensions. The Pi CLI's list of built-ins is not a public export. `sdk-upgrade.test.js` reads it from the installed package and fails when Pi ships a built-in that `builtin-extensions.js` neither loads nor lists as skipped, so a new upstream built-in needs a decision at upgrade time. It also checks that each loaded entry keeps the CLI's `builtin` and `replaceable` flags.
73
+
74
+ - `sdk-upgrade.test.js` exercises the installed SDK with disposable directories: cached OpenCode models with provider query parameters (`?types=chat%2Cimage%2Cclassifier`), user model additions and overrides, forced HTTP refresh, ETag/304, failed refresh preserving the last catalog, restart restoration, and opening/appending a session with context edit or usage entries.
64
75
  - `session-daemon-extensions.e2e.test.js` exercises real extension loading, commands, dialogs, GUI projection, reload, and session disposal.
76
+ - `session-daemon-turn.e2e.test.js` runs real agent turns through the installed SDK with an offline provider registered by an extension: prompt acceptance, streamed text, an extension tool with custom renderers, a nested `ctx.executeTool()` call, the session file after the first turn, steer and follow-up queued while streaming, a first prompt rejected with no usable model, and a stored session that holds `context_edit` and `usage` entries.
77
+ - `session-daemon-mcp.e2e.test.js` runs real turns against a stdio MCP server the test writes to disk: a `direct` tool row with its rendered call and result, the `/mcp` status notification, a `codemode` script whose row shows the nested call in progress and then the script output with no separate nested row, `tool_search` loading a `deferred` tool that is then called, `-builtin:mcp` disabling the extension and its command, an installed extension that registers `/mcp` replacing the built-in, a server whose command does not exist leaving a normal prompt unaffected, and the server process exiting when the daemon stops.
65
78
  - `supervisor.test.js` covers authenticated replacement of a daemon from an older PiChamber build. Normal versioned releases must retain that replacement behavior. Same-version, same-path manual dependency replacement is not a release upgrade and requires stopping the old server/daemon before restarting.
66
79
  - The SDK CLI bin moved to `dist/bundle/cli.js`; the detached daemon already resolves `package.json`'s `bin.pi` rather than hardcoding the old location.
67
80
  - `pi-runtime-smoke.test.js` checks the pinned SDK and foreground backend in real subprocesses with disposable dirs. It checks the SDK import with pinned version parity, bundled `bin.pi --help`, credential-free `rpc get_state` to success, and a credential-free foreground `serve --foreground --api-only` that polls `/api/pi/runtime` to ready and checks parent and daemon `execPath`. It is not provider E2E. It defaults to `process.execPath` and accepts an absolute override in `PICHAMBER_TEST_RUNTIME`. See `packages/web/bin/lib/DOCUMENTATION.md` for runtime rules and CI matrix.
68
81
 
69
- The new bundled OpenCode catalog removes `deepseek-v4-flash-free`. SDK remote catalogs still merge additively with bundled models, so this upgrade fixes that stale entry, not general upstream deletion propagation. Explicit user-defined models with the same ID remain supported. Do not clear users' `models.json` or `models-store.json` to apply an upgrade.
82
+ The bundled OpenCode catalog removes `deepseek-v4-flash-free`. SDK remote catalogs still merge additively with bundled models, so this upgrade fixes that stale entry, not general upstream deletion propagation. Explicit user-defined models with the same ID remain supported. Do not clear users' `models.json` or `models-store.json` to apply an upgrade.
@@ -0,0 +1,37 @@
1
+ import * as defaultSdk from '@earendil-works/pi-coding-agent';
2
+
3
+ // Pi ships these as built-in extensions. The Pi CLI loads them itself; SDK
4
+ // hosts have to pass them to the resource loader. The names match the CLI's
5
+ // list (packages/coding-agent/src/extensions/index.ts upstream), so each one
6
+ // loads as `builtin:<name>`.
7
+ export const LOADED_BUILTIN_EXTENSIONS = Object.freeze([
8
+ Object.freeze({ name: 'codemode', create: 'createCodemodeExtension' }),
9
+ Object.freeze({ name: 'tool-search', create: 'createToolSearchExtension' }),
10
+ Object.freeze({ name: 'mcp', create: 'createMcpExtension' }),
11
+ ]);
12
+
13
+ // Built-ins the Pi CLI loads that PiChamber leaves out on purpose. The SDK
14
+ // upgrade test fails when Pi ships a built-in that is in neither list.
15
+ export const SKIPPED_BUILTIN_EXTENSIONS = Object.freeze({
16
+ 'llama.cpp': 'The SDK does not export a factory for it, and its setup screen needs the Pi TUI.',
17
+ });
18
+
19
+ /**
20
+ * Built-in extension entries for `resourceLoaderOptions.extensionFactories`.
21
+ *
22
+ * `builtin: true` makes `-builtin:<name>` in the Pi `extensions` setting
23
+ * disable an entry. `replaceable: true` makes Pi leave an entry out when an
24
+ * installed extension registers the same tool, command, or flag, for example
25
+ * a third-party MCP extension that registers `/mcp`.
26
+ *
27
+ * A factory the SDK does not provide is skipped, which keeps SDK test doubles
28
+ * working.
29
+ */
30
+ export function getBuiltinExtensionFactories(sdk = defaultSdk) {
31
+ const factories = [];
32
+ for (const { name, create } of LOADED_BUILTIN_EXTENSIONS) {
33
+ if (typeof sdk?.[create] !== 'function') continue;
34
+ factories.push({ name, factory: sdk[create](), replaceable: true, builtin: true });
35
+ }
36
+ return factories;
37
+ }
@@ -23,6 +23,12 @@ const daemonRuntime = argument('--runtime');
23
23
  const buildId = argument('--build-id');
24
24
  const startedAt = new Date().toISOString();
25
25
 
26
+ // Pi's built-in MCP extension resolves mcp.json, mcp-auth.json, and mcp.log
27
+ // through the SDK's process-wide agent directory rather than the session's.
28
+ // This process serves one profile, so point that lookup at the same directory
29
+ // the daemon uses for everything else.
30
+ if (agentDir) process.env.PI_CODING_AGENT_DIR = agentDir;
31
+
26
32
  const exitWithFailure = (code) => {
27
33
  // Do not log configuration paths, credentials, or session data from this
28
34
  // private process. The parent maps startup failure to a stable error code.
@@ -79,6 +79,19 @@ export const THEME_BG_COLORS = Object.freeze([
79
79
  const FG_INDEX_MAP = new Map(THEME_COLORS.map((name, index) => [name, index]));
80
80
  const BG_INDEX_MAP = new Map(THEME_BG_COLORS.map((name, index) => [name, index]));
81
81
 
82
+ const FROZEN_COLORS = Object.freeze(
83
+ Object.fromEntries([
84
+ ...THEME_COLORS.map((token, index) => [
85
+ token,
86
+ Object.freeze({ kind: 'rgb', r: 1, g: 1, b: index }),
87
+ ]),
88
+ ...THEME_BG_COLORS.map((token, index) => [
89
+ token,
90
+ Object.freeze({ kind: 'rgb', r: 1, g: 1, b: index }),
91
+ ]),
92
+ ]),
93
+ );
94
+
82
95
  /**
83
96
  * Creates a Theme-compatible instance implementing all public Theme members.
84
97
  */
@@ -93,6 +106,61 @@ export const createExtensionTheme = () => {
93
106
  return index !== undefined ? `\x1b[48;2;1;1;${index}m` : '';
94
107
  };
95
108
 
109
+ const resolveColorAnsi = (color, isBg) => {
110
+ if (color === undefined || color === null) return '';
111
+ if (typeof color === 'string') {
112
+ return isBg ? getBgAnsi(color) : getFgAnsi(color);
113
+ }
114
+ if (typeof color === 'object') {
115
+ if (color.kind === 'rgb' && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b)) {
116
+ const r = Math.round(color.r);
117
+ const g = Math.round(color.g);
118
+ const b = Math.round(color.b);
119
+ return `\x1b[${isBg ? 48 : 38};2;${r};${g};${b}m`;
120
+ }
121
+ if (color.kind === 'indexed' && Number.isFinite(color.index)) {
122
+ return `\x1b[${isBg ? 48 : 38};5;${Math.round(color.index)}m`;
123
+ }
124
+ }
125
+ // Other Color kinds (oklch) have no SGR form here and render unstyled.
126
+ return '';
127
+ };
128
+
129
+ const style = (text, options = {}) => {
130
+ const fgAnsi = resolveColorAnsi(options.fg, false);
131
+ const bgAnsi = resolveColorAnsi(options.bg, true);
132
+ let prefix = '';
133
+ let suffix = '';
134
+ if (fgAnsi) {
135
+ prefix += fgAnsi;
136
+ suffix = '\x1b[39m';
137
+ }
138
+ if (bgAnsi) {
139
+ prefix += bgAnsi;
140
+ suffix = `\x1b[49m${suffix}`;
141
+ }
142
+ if (options.bold) prefix += '\x1b[1m';
143
+ if (options.dim) prefix += '\x1b[2m';
144
+ if (options.bold || options.dim) suffix = `\x1b[22m${suffix}`;
145
+ if (options.italic) {
146
+ prefix += '\x1b[3m';
147
+ suffix = `\x1b[23m${suffix}`;
148
+ }
149
+ if (options.underline) {
150
+ prefix += '\x1b[4m';
151
+ suffix = `\x1b[24m${suffix}`;
152
+ }
153
+ if (options.inverse) {
154
+ prefix += '\x1b[7m';
155
+ suffix = `\x1b[27m${suffix}`;
156
+ }
157
+ if (options.strikethrough) {
158
+ prefix += '\x1b[9m';
159
+ suffix = `\x1b[29m${suffix}`;
160
+ }
161
+ return `${prefix}${text}${suffix}`;
162
+ };
163
+
96
164
  const fg = (color, text) => {
97
165
  const ansi = getFgAnsi(color);
98
166
  if (!ansi) return text;
@@ -124,8 +192,15 @@ export const createExtensionTheme = () => {
124
192
 
125
193
  const getBashModeBorderColor = () => (str) => fg('bashMode', str);
126
194
 
195
+ // The daemon serves multiple clients with different themes and has no
196
+ // single terminal appearance. Return dark as the fixed default.
197
+ const appearance = 'dark';
198
+
127
199
  return {
128
200
  name: 'pichamber',
201
+ get appearance() { return appearance; },
202
+ get colors() { return FROZEN_COLORS; },
203
+ style,
129
204
  fg,
130
205
  bg,
131
206
  bold,
@@ -107,11 +107,58 @@ describe('extension-theme', () => {
107
107
  expect(bashBorder('$$$')).toBe(`\x1b[38;2;1;1;${bashModeIndex}m$$$\x1b[39m`);
108
108
  });
109
109
 
110
+ it('implements appearance, colors, and style() for SDK 1.0.0 Theme interface', () => {
111
+ const theme = createExtensionTheme();
112
+ expect(theme.appearance).toBe('dark');
113
+
114
+ // Every ThemeToken is in theme.colors with valid Color representation
115
+ for (const color of THEME_COLORS) {
116
+ const token = theme.colors[color];
117
+ expect(token).toEqual({ kind: 'rgb', r: 1, g: 1, b: THEME_COLORS.indexOf(color) });
118
+ }
119
+ for (const bg of THEME_BG_COLORS) {
120
+ const token = theme.colors[bg];
121
+ expect(token).toEqual({ kind: 'rgb', r: 1, g: 1, b: THEME_BG_COLORS.indexOf(bg) });
122
+ }
123
+
124
+ // style() with token names
125
+ const successIndex = THEME_COLORS.indexOf('success');
126
+ const selectedBgIndex = THEME_BG_COLORS.indexOf('selectedBg');
127
+ expect(theme.style('hello', { fg: 'success', bold: true })).toBe(
128
+ `\x1b[38;2;1;1;${successIndex}m\x1b[1mhello\x1b[22m\x1b[39m`,
129
+ );
130
+ expect(theme.style('world', { bg: 'selectedBg', italic: true, underline: true })).toBe(
131
+ `\x1b[48;2;1;1;${selectedBgIndex}m\x1b[3m\x1b[4mworld\x1b[24m\x1b[23m\x1b[49m`,
132
+ );
133
+
134
+ // style() with theme.colors[token]
135
+ expect(theme.style('token fg', { fg: theme.colors.success })).toBe(
136
+ `\x1b[38;2;1;1;${successIndex}mtoken fg\x1b[39m`,
137
+ );
138
+ expect(theme.style('token bg', { bg: theme.colors.selectedBg })).toBe(
139
+ `\x1b[48;2;1;1;${selectedBgIndex}mtoken bg\x1b[49m`,
140
+ );
141
+
142
+ // style() with concrete RGB and indexed Color
143
+ expect(theme.style('custom rgb', { fg: { kind: 'rgb', r: 255, g: 128, b: 0 } })).toBe(
144
+ '\x1b[38;2;255;128;0mcustom rgb\x1b[39m',
145
+ );
146
+ expect(theme.style('indexed', { bg: { kind: 'indexed', index: 42 } })).toBe(
147
+ '\x1b[48;5;42mindexed\x1b[49m',
148
+ );
149
+
150
+ // style() with all text attributes
151
+ expect(theme.style('attrs', { dim: true, inverse: true, strikethrough: true })).toBe(
152
+ '\x1b[2m\x1b[7m\x1b[9mattrs\x1b[29m\x1b[27m\x1b[22m',
153
+ );
154
+ });
155
+
110
156
  it('handles unknown color names gracefully without throwing', () => {
111
157
  const theme = createExtensionTheme();
112
158
  expect(theme.getFgAnsi('nonExistentColor')).toBe('');
113
159
  expect(theme.getBgAnsi('nonExistentBg')).toBe('');
114
160
  expect(theme.fg('nonExistentColor', 'fallback text')).toBe('fallback text');
115
161
  expect(theme.bg('nonExistentBg', 'fallback text')).toBe('fallback text');
162
+ expect(theme.style('fallback text', { fg: 'nonExistentColor', bg: 'nonExistentBg' })).toBe('fallback text');
116
163
  });
117
164
  });
@@ -40,7 +40,7 @@ class FakeSession {
40
40
  this.listeners = new Set();
41
41
  this.reloadCount = 0;
42
42
  this.reloadError = null;
43
- this.promptImpl = async (text, options) => { options?.preflightResult?.(true); };
43
+ this.promptImpl = async (text, options) => { options?.preflightResult?.('started'); };
44
44
  }
45
45
  subscribe(l) { this.listeners.add(l); return () => this.listeners.delete(l); }
46
46
  emit(event) { for (const listener of this.listeners) listener(event); }
@@ -362,7 +362,7 @@ describe('prompt template daemon operations', () => {
362
362
  const session = new FakeSession();
363
363
  let finishPrompt;
364
364
  session.promptImpl = (text, options) => {
365
- options?.preflightResult?.(true);
365
+ options?.preflightResult?.('started');
366
366
  return new Promise((resolve) => { finishPrompt = resolve; });
367
367
  };
368
368
  const ctx = await startDaemon({ session });
@@ -387,7 +387,7 @@ describe('prompt template daemon operations', () => {
387
387
  const session = new FakeSession();
388
388
  let finishPrompt;
389
389
  session.promptImpl = (text, options) => {
390
- options?.preflightResult?.(true);
390
+ options?.preflightResult?.('started');
391
391
  return new Promise((resolve) => { finishPrompt = resolve; });
392
392
  };
393
393
  const ctx = await startDaemon({ session });
@@ -56,7 +56,7 @@ class FakeSession {
56
56
  async prompt(text, options) {
57
57
  this.promptCalls.push({ text, options });
58
58
  if (this.promptImpl) return this.promptImpl(text, options);
59
- options?.preflightResult?.(true);
59
+ options?.preflightResult?.('started');
60
60
  }
61
61
 
62
62
  async sendUserMessage(text, options) {
@@ -221,10 +221,9 @@ describe('prompt preflight acceptance', () => {
221
221
  session.promptImpl = async (text, options) => {
222
222
  calls += 1;
223
223
  if (calls === 1) {
224
- options?.preflightResult?.(false);
225
224
  throw new Error('Cannot submit a prompt while compaction is in progress.');
226
225
  }
227
- options?.preflightResult?.(true);
226
+ options?.preflightResult?.('started');
228
227
  };
229
228
 
230
229
  const payload = { sessionId: 'session-1', text: 'hello preflight', operationId: 'op-preflight-reuse' };
@@ -247,7 +246,7 @@ describe('prompt preflight acceptance', () => {
247
246
  const turnGate = new Promise((resolve) => { releaseTurn = resolve; });
248
247
  session.promptImpl = async (text, options) => {
249
248
  await preflightGate;
250
- options?.preflightResult?.(true);
249
+ options?.preflightResult?.('started');
251
250
  await turnGate;
252
251
  };
253
252
 
@@ -281,7 +280,7 @@ describe('prompt preflight acceptance', () => {
281
280
  let finishPlain;
282
281
  const plainGate = new Promise((resolve) => { finishPlain = resolve; });
283
282
  session.promptImpl = async (text, options) => {
284
- options?.preflightResult?.(true);
283
+ options?.preflightResult?.('started');
285
284
  await plainGate;
286
285
  };
287
286
 
@@ -303,7 +302,7 @@ describe('prompt preflight acceptance', () => {
303
302
  let finishSlash;
304
303
  const slashGate = new Promise((resolve) => { finishSlash = resolve; });
305
304
  session.promptImpl = async (text, options) => {
306
- options?.preflightResult?.(true);
305
+ options?.preflightResult?.('started');
307
306
  await slashGate;
308
307
  };
309
308
  // A second prompt needs a fresh generation; the first turn already settled
@@ -331,7 +330,7 @@ describe('prompt preflight acceptance', () => {
331
330
  session.promptImpl = async (text, options) => {
332
331
  // SDK queued sends resolve immediately after preflight acceptance,
333
332
  // long before the queued user message starts.
334
- options?.preflightResult?.(true);
333
+ options?.preflightResult?.('queued');
335
334
  };
336
335
 
337
336
  const response = await client.request('sessions.followUp', {
@@ -395,10 +394,9 @@ describe('prompt preflight acceptance', () => {
395
394
  session.promptImpl = async (text, options) => {
396
395
  // Faithful SDK edge: streaming without an explicit behavior rejects.
397
396
  if (session.isStreaming && !options?.streamingBehavior) {
398
- options?.preflightResult?.(false);
399
397
  throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
400
398
  }
401
- options?.preflightResult?.(true);
399
+ options?.preflightResult?.('queued');
402
400
  };
403
401
  // Arrives idle, so the early guard does not reject; it then blocks in
404
402
  // setModel while another sender starts the turn.
@@ -435,10 +433,9 @@ describe('prompt preflight acceptance', () => {
435
433
  };
436
434
  session.promptImpl = async (text, options) => {
437
435
  if (session.isStreaming && !options?.streamingBehavior) {
438
- options?.preflightResult?.(false);
439
436
  throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
440
437
  }
441
- options?.preflightResult?.(true);
438
+ options?.preflightResult?.('queued');
442
439
  };
443
440
  const pending = send('sessions.steer', {
444
441
  sessionId: 'session-1',
@@ -463,7 +460,7 @@ describe('prompt preflight acceptance', () => {
463
460
  await writeFile(steerFile, Buffer.from('steer-png-data'));
464
461
  session.isStreaming = true;
465
462
  session.promptImpl = async (text, options) => {
466
- options?.preflightResult?.(true);
463
+ options?.preflightResult?.('queued');
467
464
  };
468
465
  const followResponse = await client.request('sessions.followUp', {
469
466
  sessionId: 'session-1',
@@ -521,10 +518,11 @@ describe('prompt preflight acceptance', () => {
521
518
  let finishNext;
522
519
  const nextGate = new Promise((resolve) => { finishNext = resolve; });
523
520
  session.promptImpl = async (text, options) => {
524
- options?.preflightResult?.(true);
521
+ const isCmd = typeof text === 'string' && text.startsWith('/mycmd');
522
+ options?.preflightResult?.(isCmd ? 'handled' : 'started');
525
523
  // Handled extension commands resolve without a user start; ordinary
526
524
  // new-turn prompts stay pending until their start arrives.
527
- if (typeof text === 'string' && text.startsWith('/mycmd')) return;
525
+ if (isCmd) return;
528
526
  await nextGate;
529
527
  };
530
528
  const extResponse = await client.request('sessions.followUp', {