@pi-chamber/web 1.0.8-rc.3 → 1.0.8-rc.4

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 (102) hide show
  1. package/dist/assets/{AgentsSurface-wsW9VCRp.js → AgentsSurface-DbCBygRD.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-EwCf4Yxu.js → ChoicesArtifact-DUqhCvXh.js} +1 -1
  3. package/dist/assets/{DiagramView-BX6N99cQ.js → DiagramView-CnVOyJd2.js} +1 -1
  4. package/dist/assets/{DiffView-CI0eSnPP.js → DiffView-Db8JXsvA.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-GLj2W7VE.js → FileSaveConflictDialog-D6xyf709.js} +1 -1
  6. package/dist/assets/{FilesView-CI0tfZQL.js → FilesView-Cir0Wl9F.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-B85tZ9m7.js → GitHubDetailScaffold-US37Di_K.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-Y6AuNiGl.js → GitHubLinkPicker-k_D-sk-e.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BJHBud6i.js → GitHubListPrimitives-DuUXrJGk.js} +1 -1
  10. package/dist/assets/{GitView-DueE69kW.js → GitView-BdX_3XRr.js} +3 -3
  11. package/dist/assets/{IssuesSurface-Cg-xkdIu.js → IssuesSurface-Cw93HC0G.js} +2 -2
  12. package/dist/assets/{JsonTreeView-Cvg6lc40.js → JsonTreeView-Bze4htWt.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-DExPx-QM.js → MarkdownRendererImpl-Ch7NDkF9.js} +1 -1
  14. package/dist/assets/{PatchDiff-_c3HZ34I.js → PatchDiff-l68Yz45X.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-CZnaqO-_.js → PierreDiffViewer-BHBySiXQ.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-C9AYPiwo.js → PullRequestsSurface-CGD4_ljc.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-DOpnN-8S.js → SessionSwitcherContent-DqP8OWzB.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-CmHMPZ69.js → SessionSwitcherDropdown-BkTg-cVd.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-CZCQ4t1J.js → SessionUnreadDot-CgvC3F5e.js} +1 -1
  20. package/dist/assets/{SettingsView-D5PO5M3z.js → SettingsView-CkIxCYhs.js} +3 -3
  21. package/dist/assets/{SettingsWindow-DXV5UOE8.js → SettingsWindow-DSdhzapT.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-CO1ZiI1x.js → SubagentsArtifact-BN3aX_8M.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-GOwNLj-y.js → ToolOutputDialog-CLwm4TjA.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-BoaiZji6.js → ToolPartDiffPreview-ERAStEKA.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-Chq1X8nw.js → VirtualizedFileDiff-DwR2fZHv.js} +1 -1
  26. package/dist/assets/{VisualFrame-u7aRcX7O.js → VisualFrame-Dwp7B_st.js} +1 -1
  27. package/dist/assets/{VisualsArtifact-D9vPjihW.js → VisualsArtifact-DlOxifHd.js} +1 -1
  28. package/dist/assets/{collapsible-BjpDEohv.js → collapsible-CW-_qd6v.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmPCxbok.js → computeVirtualFileMetrics-SlBfr8LB.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-CukNcUeY.js → contextFileOpenGuard-CHoFT50j.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CDyfNPYO.js → fileTreeStatus-D0uiC1D0.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-uI7Y7L5k.js → gitStatusPredicates-Bj3pkh2e.js} +1 -1
  33. package/dist/assets/{githubLink-B9Mxac4R.js → githubLink-CheLNuP0.js} +1 -1
  34. package/dist/assets/{index-BxKPJ9uG.js → index-BFkW-BPM.js} +3 -3
  35. package/dist/assets/{index-BWq2ibCw.js → index-C8zaLvup.js} +1 -1
  36. package/dist/assets/{main-ckQ0ciIN.js → main-CUEqZRu1.js} +2 -2
  37. package/dist/assets/{main-CWfC-9xT.js → main-V66ie29o.js} +4 -4
  38. package/dist/assets/{markdownCore-p2q2Kxwo.js → markdownCore-BRedKgCo.js} +1 -1
  39. package/dist/assets/{miniChat-x2TrwRYA.js → miniChat-BXwuEQhz.js} +2 -2
  40. package/dist/assets/{mobile-B0x2G8h1.js → mobile-7s-xLDG3.js} +2 -2
  41. package/dist/assets/{nativeFileSave-D542OJlG.js → nativeFileSave-Bj-V_9ae.js} +1 -1
  42. package/dist/assets/{pi-session-focus-preference-Q_RZUCnt.js → pi-session-focus-preference-clbekCjz.js} +1 -1
  43. package/dist/assets/{renderDiffWithHighlighter-CSFGSknx.js → renderDiffWithHighlighter-g9eKWi78.js} +1 -1
  44. package/dist/assets/{renderElectronMiniChatApp-CFIdesZT.js → renderElectronMiniChatApp-B6BN8YgC.js} +2 -2
  45. package/dist/assets/{renderFileWithHighlighter-C5JE0mRX.js → renderFileWithHighlighter-DKl6vubK.js} +1 -1
  46. package/dist/assets/{renderMobileApp-B1ybjcGM.js → renderMobileApp-Bp735rW7.js} +3 -3
  47. package/dist/assets/{runtimeEndpointReset-DyZSKCYM.js → runtimeEndpointReset-CtHv_OMT.js} +7 -7
  48. package/dist/assets/{runtimeSurface-BR_dhe7_.js → runtimeSurface-DD4Vn4HC.js} +1 -1
  49. package/dist/assets/{selection-CfOpW4rA.js → selection-DDT954wY.js} +1 -1
  50. package/dist/assets/useAppFontEffects-DJCrUN2D.js +226 -0
  51. package/dist/assets/{useGitHubRemoteSearch-M1AE2YuX.js → useGitHubRemoteSearch-B77fMiwQ.js} +1 -1
  52. package/dist/assets/{useSwitcherItems-D0i2BYYP.js → useSwitcherItems-CFY3mP06.js} +1 -1
  53. package/dist/assets/{web-components-wOQkOurQ.js → web-components-XIP_3VZv.js} +1 -1
  54. package/dist/index.html +3 -3
  55. package/dist/mini-chat.html +2 -2
  56. package/dist/mobile.html +2 -2
  57. package/package.json +2 -1
  58. package/pichamber.d.ts +139 -0
  59. package/plugins/subagents/extension.js +5 -5
  60. package/plugins/subagents/package.json +3 -2
  61. package/plugins/visuals/choices.js +8 -7
  62. package/plugins/visuals/extension.js +4 -4
  63. package/plugins/visuals/package.json +1 -1
  64. package/server/lib/marketplace/DOCUMENTATION.md +2 -2
  65. package/server/lib/marketplace/npm-registry.js +1 -1
  66. package/server/lib/marketplace/npm-registry.test.js +1 -1
  67. package/server/lib/marketplace/service.test.js +4 -4
  68. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  69. package/server/lib/pi/extension-card.js +48 -0
  70. package/server/lib/pi/extension-card.test.js +35 -0
  71. package/server/lib/pi/extension-commands.js +49 -0
  72. package/server/lib/pi/extension-commands.test.js +38 -0
  73. package/server/lib/pi/extension-protocol.js +1 -2
  74. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +52 -223
  75. package/server/lib/pi/routes-extension-events.test.js +35 -48
  76. package/server/lib/pi/routes.js +44 -54
  77. package/server/lib/pi/routes.test.js +32 -0
  78. package/server/lib/pi/session-daemon/DOCUMENTATION.md +7 -7
  79. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +0 -54
  80. package/server/lib/pi/session-daemon/extension-bridge.js +39 -162
  81. package/server/lib/pi/session-daemon/extension-controls.js +12 -57
  82. package/server/lib/pi/session-daemon/extension-controls.test.js +4 -34
  83. package/server/lib/pi/session-daemon/pichamber-api.js +38 -0
  84. package/server/lib/pi/session-daemon/pichamber-api.test.js +24 -0
  85. package/server/lib/pi/session-daemon/plugin-host.js +5 -7
  86. package/server/lib/pi/session-daemon/plugin-host.test.js +2 -3
  87. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +53 -7
  88. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +5 -5
  89. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +9 -4
  90. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +28 -71
  91. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +1 -1
  92. package/server/lib/pi/session-daemon/session-daemon.js +138 -78
  93. package/server/lib/pi/session-daemon/session-daemon.test.js +68 -0
  94. package/server/lib/plugins/DOCUMENTATION.md +3 -3
  95. package/server/lib/plugins/impact.js +2 -4
  96. package/server/lib/plugins/impact.test.js +0 -1
  97. package/server/lib/plugins/manifest.js +9 -5
  98. package/server/lib/plugins/manifest.test.js +5 -4
  99. package/server/lib/plugins/store.test.js +1 -1
  100. package/server/lib/plugins/visuals-extension.test.js +16 -14
  101. package/dist/assets/useAppFontEffects-COMvkffC.js +0 -226
  102. package/server/lib/pi/session-daemon/pichamber-ui.js +0 -44
@@ -19,24 +19,24 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
19
19
  - No server path leaves the daemon. Ids are sha256 base64url over resource type, declaring scope, and the canonical path or `builtin:<name>` (packages: scope and Pi's package identity). An item the global view lists keeps the same id in the project view. Names follow `pi config`: the built-in name, `parent/file` when the parent folder is not `extensions`, else the file name. Package sources are npm and git sources as written with URL userinfo removed, and the folder name only for a local package. Error text is stripped of paths and credentials and capped at 300 characters.
20
20
  - Writes reimplement Pi's private toggle logic (`config-selector.js`) as pure functions over a settings manager: in global scope only user-scope items toggle (`+`/`-` entries, package filters in object form); in project scope each item takes `inherit`, `load`, or `unload`, inherited files are named by absolute path, built-ins by `builtin:<name>`, and a user package gets an `autoload: false` project entry that is removed again when it has no filter left. `BUILTIN_PATH_PREFIX` is a local constant pinned by a test. Recheck these functions on every SDK upgrade.
21
21
  - Every write re-resolves and rejects an unknown id (`RESOURCE_NOT_FOUND`), runs in the resource mutation queue under the shared Pi config lock, reads trust inside the lock (`PROJECT_UNTRUSTED` for project scope in an untrusted project, `INVALID_ARGUMENT` without a directory), and fails with `PI_SETTINGS_INVALID` when settings cannot be read or flushed. Removal calls only Pi's `removeAndPersist` (PiChamber deletes no path; local packages keep their files). A local package's source is passed as an absolute path, resolved against the folder its settings file is in, because `removeAndPersist` reads a relative source as typed in the daemon's working directory while settings keep it relative to the settings folder: `PACKAGE_REMOVE_FAILED` when npm or git fails, `PACKAGE_NOT_CONFIGURED` when settings had no entry, and `PI_SETTINGS_INVALID` when the files are gone but the settings write failed, which is never reported as success. After a write, resident runtimes are recreated through `scheduleRuntimeRecreation` (it recreates every resident runtime, for either scope); the answer is the fresh list plus `deferred: true` when a busy session delays that.
22
- - `plugin-host.js` owns PiChamber plugins in the daemon (the server side is `../../plugins/`). The private, server-only `plugins.configure` command (`{ plugins: [{ id, entry, replaceable?, state: { global, projects, sessions? } }] }`, enabled plugins only) replaces the configured set. The host validates the payload (`INVALID_ARGUMENT`), imports each module only from under `packages/web/plugins/` (checked with realpath), and reports `{ plugins: [{ id, loaded, error? }], enabledChanged, deferred }`. One plugin that fails to import is left out and logged; the others still load. When the loaded set changes, the daemon calls `scheduleRuntimeRecreation()`, which is all or nothing: while any session in any folder is streaming, compacting, taking an input, or running a user shell command (`!cmd`), nothing is recreated and the answer is `deferred: true`; the change applies when that work ends, so a running turn or command is never cut. Recreation then disposes every resident runtime and recreates only the active one. The other sessions reopen from their files when next opened or prompted, and until then have no extension statuses, widgets, or composer controls; open drafts are discarded; a dialog or `custom()` surface left open is cancelled, as on a daemon restart. A composer control whose command the recreated runtime no longer registers answers `CONTROL_UNAVAILABLE` and never reaches the model as a prompt. A state-only change calls the `pichamber.onStateChange` listeners of live runtimes without recreation. Each loaded plugin becomes an `extensionFactories` entry after Pi's built-ins, in `createPiSessionRuntime` (through the `pluginExtensionFactories` runtime hook) and in `createFreshPromptServices`: `{ name: 'pichamber:<id>', replaceable, factory }`, listed by Pi as `<inline:pichamber:<id>>`. The factory calls the module's default export as `(pi, pichamber)` with `pichamber = { id, ui, state(directory, sessionId?), onStateChange(listener) -> unsubscribe }` (`ui` is the same `pichamber.ui` that `globalThis.pichamber` holds); `state` resolves `{ ...global, ...projects[directory], ...sessions[sessionId] }` (a session's own values are composer switches; up to 4096 sessions per plugin), and a runtime's listeners are dropped at its `session_shutdown`. The daemon never reads plugin state or the enabled set from disk, so a sandboxed daemon needs no grant for PiChamber's data folder. Until the server configures it, the daemon loads no plugins. The server pushes before the first request to each daemon process it has not configured (keyed by `streamEpoch`; see `../../plugins/DOCUMENTATION.md`). Each plugin factory runs for every runtime, also for a plugin Pi then drops as replaced, so the wrapper hands the factory a Proxy of Pi's extension API that notes the names passed to `registerTool`, `registerCommand`, and `registerFlag` (everything else forwards untouched). `registeredNames()` returns plugin id to `['tool:x', 'command:y', 'flag:z']` and `configuredIds()` lists the configured plugins; a plugin's names are forgotten when it leaves the configured set or its entry changes.
22
+ - `plugin-host.js` owns PiChamber plugins in the daemon (the server side is `../../plugins/`). The private, server-only `plugins.configure` command (`{ plugins: [{ id, entry, replaceable?, state: { global, projects, sessions? } }] }`, enabled plugins only) replaces the configured set. The host validates the payload (`INVALID_ARGUMENT`), imports each module only from under `packages/web/plugins/` (checked with realpath), and reports `{ plugins: [{ id, loaded, error? }], enabledChanged, deferred }`. One plugin that fails to import is left out and logged; the others still load. When the loaded set changes, the daemon calls `scheduleRuntimeRecreation()`, which is all or nothing: while any session in any folder is streaming, compacting, taking an input, or running a user shell command (`!cmd`), nothing is recreated and the answer is `deferred: true`; the change applies when that work ends, so a running turn or command is never cut. Recreation then disposes every resident runtime and recreates only the active one. The other sessions reopen from their files when next opened or prompted, and until then have no extension statuses, widgets, or composer controls; open drafts are discarded; a dialog or `custom()` surface left open is cancelled, as on a daemon restart. A composer control whose command the recreated runtime no longer registers answers `CONTROL_UNAVAILABLE` and never reaches the model as a prompt. A state-only change calls the `pichamber.onStateChange` listeners of live runtimes without recreation. Each loaded plugin becomes an `extensionFactories` entry after Pi's built-ins, in `createPiSessionRuntime` (through the `pluginExtensionFactories` runtime hook) and in `createFreshPromptServices`: `{ name: 'pichamber:<id>', replaceable, factory }`, listed by Pi as `<inline:pichamber:<id>>`. The factory calls the module's default export as `(pi, pichamber)` with `plugin = { id, state(directory, sessionId?), onStateChange(listener) -> unsubscribe }` (a plugin asks and shows through `globalThis.pichamber`, like any extension); `state` resolves `{ ...global, ...projects[directory], ...sessions[sessionId] }` (a session's own values are composer switches; up to 4096 sessions per plugin), and a runtime's listeners are dropped at its `session_shutdown`. The daemon never reads plugin state or the enabled set from disk, so a sandboxed daemon needs no grant for PiChamber's data folder. Until the server configures it, the daemon loads no plugins. The server pushes before the first request to each daemon process it has not configured (keyed by `streamEpoch`; see `../../plugins/DOCUMENTATION.md`). Each plugin factory runs for every runtime, also for a plugin Pi then drops as replaced, so the wrapper hands the factory a Proxy of Pi's extension API that notes the names passed to `registerTool`, `registerCommand`, and `registerFlag` (everything else forwards untouched). `registeredNames()` returns plugin id to `['tool:x', 'command:y', 'flag:z']` and `configuredIds()` lists the configured plugins; a plugin's names are forgotten when it leaves the configured set or its entry changes.
23
23
  - `extension-replacements.js` finds what Pi left out of a live runtime. Pi drops a `replaceable` extension (PiChamber plugins and the `builtin:mcp`, `builtin:codemode`, and `builtin:tool-search` built-ins) when a non-replaceable one registers the same tool, command, or flag (`omitReplacedExtensions`), and keeps no record for plugins. A plugin counts as replaced when it is configured, its `<inline:pichamber:<id>>` path is not among the runtime's loaded extensions, and a loaded non-replaceable extension has one of the names the plugin registered (tools first, then commands, then flags); a missing plugin that shares no name is not reported, since it failed for another reason. A built-in counts as replaced when Pi's `warnings` hold an entry whose `path` is `builtin:<name>`; package and install warnings use other paths. Pi names the winner only inside that warning's text, so the optional `registers` and `by` details are parsed from it and left out when the text does not match. `extensions.config.list`, `extensions.config.set`, and `extensions.packages.install/update/remove` call it through `liveExtensionReplacements` in `session-daemon.js`, which never starts a runtime and never resolves a directory for it: it uses a non-draft runtime resident in the requested directory (the active directory when the request names none, and no other folder), and answers unknown (no `replaced`) when none is resident or when a runtime recreation is still queued, because that runtime predates the new configuration. Recheck the logic and the warning text against `omitReplacedExtensions` on every SDK upgrade.
24
24
  - `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.
25
25
  - `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. Its exported `renderComponentLines` helper carries those same bounds for message renders.
26
- - PiChamber's own dialog calls live on `pichamber.ui`, not on Pi's `ctx.ui`, so a method Pi adds later cannot be shadowed by ours (`pichamber-ui.js`). `pichamber.ui.choose(ctx, title, choices, opts)`, `.form(ctx, title, fields, opts)` and `.openUrl(ctx, url)` each take the tool or handler `ctx` first; a missing or foreign `ctx` (no PiChamber session behind it) rejects with a `TypeError`, never throws synchronously. The working implementations hang on the session's ui context under a `Symbol.for('pichamber.ui')` key, which cannot collide with a name Pi adds and survives Pi's runner copying the ui context with an object spread; `pichamber.ui.x(ctx, ...)` reads them from `ctx.ui`, so no session lookup is needed. Plugins get the same `ui` on their handle (`plugin-host.js`); ordinary extensions get `globalThis.pichamber` (`{ version, ui }`, frozen), set next to the `__PICHAMBER__` marker, which stays as released. `ctx.ui.form` and `ctx.ui.openUrl`, released in 1.0.4 and 1.0.6, are removed, and `ctx.ui.choose` never existed: `ctx.ui` holds only what Pi defines. Plain Pi has no `pichamber`, so an extension checks for it and falls back to `select`.
27
- - `pichamber.ui.choose` details: `choices` is `[{ id, label, description? }]`, at most 12, the first of each id kept; `opts` takes `message`, `allowNote`, `toolCallId`, and the usual `signal` and `timeout`. It resolves `{ id, note? }`, or `undefined` when the question is closed, times out, or is cancelled, and rejects with a `TypeError` when the title or every choice is missing (nothing is published, so the caller never waits on a question no client can see). The dialog event carries `method: 'choose'`, `choices`, `allowNote`, and `toolCallId`; a tool passes its own call id so a client can draw the question with that tool call (see the UI plugin documentation, Questions). `../extension-protocol.js` owns the limits, the projection (`projectExtensionChooseFields`) and the answer check (`validateExtensionChoiceAnswer`), shared with the public routes. A client that does not know `choose` shows the dialog with nothing to pick; it can only dismiss it.
26
+ - PiChamber's own calls are functions on `globalThis.pichamber` (`pichamber-api.js`), not on Pi's `ctx.ui`, so a method Pi adds later cannot be shadowed by ours. The object is frozen: `{ apiVersion, choose, form, openUrl, card, control }`. Every function takes the tool or handler `ctx` first and returns a promise; a missing or foreign `ctx` (no PiChamber session behind it) or bad input rejects with a `TypeError`, never throws synchronously. The working implementations hang on the session's ui context under a `Symbol.for('pichamber.api')` key (`extension-bridge.js`), which cannot collide with a name Pi adds and survives Pi's runner copying the ui context with an object spread; `pichamber.x(ctx, ...)` reads them from `ctx.ui`, so no session lookup is needed. Plugins call the same global. `globalThis.pichamber` is the documented way to detect PiChamber. `pichamber.apiVersion` and a plugin manifest's `apiVersion` are one number (1): a breaking change raises it, an added function does not, and authors test for the function. `packages/web/pichamber.d.ts` is the published type of the object; `pichamber-api.test.js` fails when the two drift. The `__PICHAMBER__` marker stays as released in 1.0.6 and is no longer documented. `ctx.ui.form` and `ctx.ui.openUrl`, released in 1.0.4 and 1.0.6, are removed: `ctx.ui` holds only what Pi defines. Plain Pi has no `pichamber`, so an extension checks for it and falls back to `select`.
27
+ - `pichamber.choose` details: `choices` is `[{ id, label, description? }]`, at most 12, the first of each id kept; `opts` takes `message`, `allowNote`, `toolCallId`, and the usual `signal` and `timeout`. It resolves `{ id, note? }`, or `undefined` when the question is closed, times out, or is cancelled, and rejects with a `TypeError` when the title or every choice is missing (nothing is published, so the caller never waits on a question no client can see). The dialog event carries `method: 'choose'`, `choices`, `allowNote`, and `toolCallId`; a tool passes its own call id so a client can draw the question with that tool call (see the UI plugin documentation, Questions). `../extension-protocol.js` owns the limits, the projection (`projectExtensionChooseFields`) and the answer check (`validateExtensionChoiceAnswer`), shared with the public routes. A client that does not know `choose` shows the dialog with nothing to pick; it can only dismiss it.
28
28
  - Partial tool results: the latest `tool_execution_update` result of each running tool is kept (`toolPartialBySession`) and returned on that tool's running part by `sessions.open` and `sessions.messages`, as `output` and `metadata`. A tool that reports once and then waits (Visuals' `render_choices` shows its options, then asks) is otherwise blank for a client that opens the session mid-call. Dropped when the tool ends, the run settles, the session closes, or the daemon stops.
29
29
  - `extension-message-render.js` owns daemon-side rendering for `pi.registerMessageRenderer(customType, renderer)`. The renderer is resolved from the owning session's `extensionRunner` (a missing lookup function or a throwing lookup means no render) and called once collapsed (`expanded: false`) and once expanded (`expanded: true`) with `outputPad: 0`, `keyText()`/`keyHint()` from `extension-keybindings.js`, and the same extension theme tool renders use; each component renders at 100 columns through the shared line bounds, and every rendered line passes through attachment redaction. Live `extension.message` events and replayed `custom_message` history entries both carry optional `render: { message, messageExpanded? }` beside `customType`/`details` (public routes re-apply the same 200-line/2000-char caps and drop malformed shapes). Replay rebuilds the `{ role: 'custom', customType, content, display, details, timestamp }` input from the persisted entry so the renderer sees identical input live and on replay; renders resolve lazily for only the history page actually returned (the same pending-render mechanism as settled tool renders) and are memoized per entry. A missing/throwing renderer, a falsy component, or an empty collapsed slot omits `render` entirely; a failing or line-identical expanded slot omits `messageExpanded`. Renderer failure never breaks publication: the message still goes out with text/details, and other messages and sessions are unaffected. Only displayable messages (`display !== false`) render.
30
30
  - `extension-palette.js` answers `extensions.palette`: what Pi's theme colour names (`accent`, `border`, `selectedBg`, ...) are for Pi-drawn lines in the browser (`ctx.ui.custom()` surfaces, tool and message renders, widgets, statuses), which carry them as marker-theme escapes. The browser sends the background, foreground and 16 colours it draws the surface screen with. With Pi's `theme` setting unset or `system`, the colours are Pi's system theme generated from that palette (`generateSystemThemeColors`); a named theme gives its own colours and export page background (as `#rrggbb`, converted from `#rgb` or `oklch()` with Pi's pi-tui), leaving out tokens it sets to `""` (terminal default) so the screen's own foreground and background apply; a `light/dark` pair picks by the palette's appearance; an unknown or invalid theme falls back to `system`, as Pi does. The setting is read from the global Pi settings only; a project's own setting is ignored so one folder cannot recolour another's surfaces. Settings that cannot be read fail with `PI_SETTINGS_INVALID` rather than answering with `system`, so the browser keeps PiChamber's colours. Pi exports none of this from its package root, so the module imports `dist/modes/interactive/theme/{theme,system-theme}.js` by path from Pi's install and checks the functions exist; if a Pi update moves them, the command fails, the browser keeps PiChamber's own tokens for Pi's names, and `extension-palette.test.js` (which runs against the installed Pi) fails. A failed load is retried on the next request. The route `/api/pi/extensions/palette` validates the input and whitelists the result.
31
31
  - `extension-ui-mode.js` resolves the `ctx.mode` each extension binding reports from the "Extension interface" setting (`extensionUi` in `<dataDir>/pi/settings.json`, written by `../settings-store.js`): `terminal` or unset is `tui`, `dialogs` is `rpc`, so extensions that branch on the mode use Pi's standard dialogs. It changes only what extensions are told; `custom()` stays hosted in both. It is read once per binding (`createSessionDaemon({ resolveExtensionMode })` injects it, tests pin it), and Pi keeps a session's mode across reload, so a change applies to sessions started afterwards. A missing or unreadable file means `tui`; the settings page reports an invalid file when it loads. The `__PICHAMBER__` marker's `mode` is the value new sessions get; a session's own `ctx.mode` is authoritative.
32
32
  - `extension-custom-host.js` owns `ctx.ui.custom()` surfaces: component lifetime, the TUI stub (`stop()`/`start()` throw), key focus, nested overlays from `tui.showOverlay`, overlay handles, render scheduling (the first change after a quiet spell draws on the next tick, later ones at most every 33 ms), and frames. Overlays are placed by pi-tui's own `resolveOverlayLayout` on a screen the size of the browser's chat pane (`screenColumns`); inline surfaces render at the composer column width (`columns`). Each session has one size, set by the client that last sent input, the Esc button, or a viewport report with `claim` (the driver; the browser claims on a tap on a surface or its dimmed pane). A new top-level surface goes to the client whose `clientId` came with the session's latest prompt, steer, follow-up, or `!command` (`openerClientFor`), at once if that client reported a size, else on its first report; a viewport report without `claim` never takes over otherwise, and a size change applies after 150 ms. Extension code never throws into a timer: an `overlayOptions` function that throws keeps its last options, any other render-time failure closes that surface, and a surface whose first render fails is removed before `custom()` rejects. A factory that resolves after its session closed or reloaded resolves `custom()` with `undefined` and shows nothing. Overlays a factory shows with `tui.showOverlay` before returning (Pi's overlay focus demo shows its panels from the constructor) become children of the surface once it opens, so ending it takes them along and keys sent to it reach the panel it focused; if the surface never opens they are removed, and `hideOverlay()` from a factory only touches its own overlays. `focus` (the browser's tab stack, `extensions.custom.focus`) does what `handle.focus()` does for a shown nested panel, makes the sender the driver, and redraws that panel's family, since extensions read `isFocused()` while rendering; it refuses top-level surfaces and hidden panels. The Esc button (`extensions.custom.close`, top-level surfaces and nested panels alike) presses Esc (`\x1b`) for the user through `handleInput`, once per press, because Pi has no host Close, `custom()` takes no cancel signal, and extensions that keep a handle to their overlay (pi-btw) only learn it closed from their own Esc handler. The Esc goes where a key typed at the surface would (an overlay it opened and focused, such as a confirmation, else the surface's component), even when the surface is non-capturing, unfocused, or hidden, and never reaches another surface or the session's turn. It does nothing a typed Esc would not: a component that closes itself ends with `done`, and one that stays open (an Esc that only stopped a running answer, a confirmation it opened, or a component that ignores Esc) stays open until the next press, as in Pi. Only a target with no `handleInput`, or whose Esc throws, is ended at once, so a surface that can never take a key cannot block the session: `custom()` resolves `undefined`, nested overlays go with it, and the dismissal is `cancelled`. `close` answers `{ closed: true }` once the Esc is delivered; the client keeps the surface until the dismissal arrives. Input requests are capped at 256 items and 65,536 characters in all (`isValidCustomInputItems`, checked by the route and here); keys stay with the surface they were sent to and its nested overlays, a non-capturing overlay takes keys only while it or an overlay it opened holds focus (as pi-tui hands keys to the focused component), and keys for an open surface that takes none right now are dropped with an accepted reply, not a not-open one. SGR mouse reports (`\x1b[<b;x;y(M|m)`, cells local to the surface) never reach `handleInput`: they become pi-tui `TuiMouseEvent`s routed as pi-tui's alt screen does (`dispatchMouseEvent`; the press target keeps the gesture, a release on the press cell adds a `click` with a 500 ms click count, `capture`, `focus` and render defaults follow pi-tui). Mouse reports also reach non-capturing overlays, and a `focus` answer gives one the keys; since PiChamber sends no extension shortcuts, a press on a non-capturing overlay whose component has `handleInput` also gives it focus. Frame lines are capped at `MAX_CUSTOM_LINE_CHARS` (16,384) by `capLine`, which never cuts inside an escape sequence or a surrogate pair. Every surface ends exactly once (`done`, the Esc button on a surface that takes no keys, render error, session close, reload, daemon stop) with a resolved promise, a disposed component, and an `extension.custom.dismiss`. Capturing top-level surfaces register with `pendingInput`, and an open surface blocks idle disposal. `extension.custom` metadata and dismissals are ordinary replayed events; `extension.custom.frame` is published with `publishTransient`, which shares the sequence and stream epoch but skips the replay log, so a subscriber that attached by replay is sent each open surface's full frame afterwards (`keyframes`), and snapshots and `sessions.open` detail carry `extensionSurfaces` with full frames. The bridge's `custom()` delegates here; the bridge reports `mode: 'tui'` by default, so extensions that check `ctx.mode === 'tui'` (Pi's `snake`, `todo`, `question` examples, the MCP manager) open surfaces. `setHeader`, `setFooter`, `setEditorComponent` and `onTerminalInput` stay no-ops.
33
- - `extension-controls.js` owns composer controls that plain Pi extensions declare by emitting `pichamber:composer` on `pi.events` (`toggle`, `cycle`, or `action`, each naming the extension's own commands; `{ id, remove: true }` takes one away). `createComposerControlsExtension` is a hidden inline factory (`<inline:pichamber:composer-controls>`, filtered out of `extensions.list`) that every runtime loads after the user's extensions; it holds emits until `session_start` names the session. `parseComposerControl` validates and cleans each payload (invalid ones are ignored like a malformed status); `createComposerControls` keeps up to 16 per session, publishes `extension.control` (`{ control }` or `{ id, removed: true }`), and resolves a click to a command, or to none when the requested value is already current. The private `extensions.control` command (`{ sessionId, id, value?, clientId? }`) checks the command is registered (`CONTROL_UNAVAILABLE` otherwise), then runs `/<command>` through `runSessionInput` as a typed extension command (steering delivery while a turn streams, so it runs at once), leaving the draft mirror alone; it answers `{ ran }` and the new value arrives as the extension's next emit. Snapshots and `sessions.open` always carry `extensionControls` as a list (empty is authoritative); session reload clears them with a removal per control and extensions declare them again at `session_start`.
33
+ - `extension-controls.js` owns composer controls that plain Pi extensions declare with `pichamber.control(ctx, control)` (`toggle`, `cycle`, or `action`, each naming the extension's own commands; `{ id, remove: true }` takes one away). Command names and arguments follow the rule every extension surface shares (`../extension-commands.js`): Pi's invocation name (a letter or digit, then letters, digits, `_`, `.`, `:` or `-`, up to 128 characters, one leading `/` allowed) and one line of arguments up to 2,000 characters. The call reaches the session through `ctx`, so it works from `session_start` on, also in a draft session, and no listener extension is loaded. `parseComposerControl` validates and cleans each payload (the call rejects an invalid one with a `TypeError`); `createComposerControls` keeps up to 16 per session, publishes `extension.control` (`{ control }` or `{ id, removed: true }`), and resolves a click to a command, or to none when the requested value is already current. The private `extensions.control` command (`{ sessionId, id, value?, clientId? }`) checks the command is registered (`CONTROL_UNAVAILABLE` otherwise), then runs `/<command>` through `runSessionInput` as a typed extension command (steering delivery while a turn streams, so it runs at once), leaving the draft mirror alone; it answers `{ ran }` and the new value arrives as the extension's next `pichamber.control` call. The private `extensions.command` command (`{ sessionId, command, args?, directory?, clientId? }`) is the same run for a card action: the name must be one the session's extensions register (`COMMAND_UNAVAILABLE` otherwise, so a typo or stale card never reaches the model as a prompt), it runs at once also mid-turn, and nothing is added to the transcript. Snapshots and `sessions.open` always carry `extensionControls` as a list (empty is authoritative); session reload clears them with a removal per control and extensions declare them again at `session_start`.
34
34
  - Draft sessions (`session-daemon.js`, `draftSessionIds`): `sessions.create` with `draft: true` (no title, parent, or `draftSessionId`) starts a session for a new-session draft before anything is sent, so its extensions can declare composer controls and run their commands. The `beforeSession` runtime hook marks its id before Pi starts it, so everything it publishes, from `session_start` on, carries a top-level `draft: true`; a draft is never the active session (`activateSession` returns its runtime without switching, so `dormantSession` never names it), never a target for unattributed Open requests, and stays out of `sessions.list` and `sessions.pendingInput`. It gets the five-minute idle lifetime at once, so an abandoned draft is disposed and reported deleted (still marked). A draft is never the general runtime `ensureRuntime` hands out for a folder (catalogs, recreation), never a target for any Open request (named or not). A model turn ends a draft: when one starts on a session still marked (a control's command calling `sendUserMessage`), Pi has already written the session file, so at `agent_start` the daemon publishes one last marked `session.lifecycle` (`state: 'busy'` without `command`, which a command-only run always carries), removes the mark, and publishes the same state unmarked. From then on it is an ordinary listed session; the drafting client lets go of it on that marked event, `sessions.discardDraft` answers `{ discarded: false }`, and a later `draftSessionId` create falls back to an ordinary create. Disposal of a draft is forceful: idle disposal and `sessions.discardDraft` cancel its dialogs, close its `custom()` surfaces, abort anything running, and wait (bounded) for a control's command to settle, so a draft waiting on a dialog nobody can see cannot live forever; ordinary sessions keep every idle guard. When every runtime is disposed (`disposeRuntime`: runtime recreation, daemon stop), each draft gets a `session.deleted` still carrying `draft: true` before its mark is dropped (on stop, clients are already gone). Create paths that fail dispose a draft before unmarking it, so what disposal publishes stays marked. `sessions.create` with `draftSessionId` adopts it when it is still a draft in the same folder and no parent is asked for: its idle timer is cleared first, adoption waits (up to 5 s) for a composer-control command still running in it, then the mark is cleared, model and thinking are set only when they differ (on failure it is marked again and its idle timer re-armed), the title is appended, and it becomes the active session with the same id and whatever its controls did. Otherwise a stale draft is discarded and the session is created as usual. `sessions.discardDraft` (`{ sessionId }` → `{ discarded }`) disposes a draft whose draft closed; it acts on drafts only and is deliberately outside the session-access guard, which would make the disposal it asks for unsafe. The server routes it as `POST /api/pi/sessions/:id/discard-draft`, passes `draft` through `projectEventFrame`, and the notification watcher ignores marked events.
35
35
  - `extension-keybindings.js` owns the `KeybindingHints` (`keyText()`, `keyHint()`) that Pi 1.5.0 passes to tool renderers and message renderers. Pi's keybindings are terminal shortcuts, and PiChamber binds none of them: rows expand on click. So `keyText()` returns an empty string and `keyHint()` returns only the description, styled `muted` as in Pi, with no leading space. A Pi hint such as `(40 more lines, ctrl+o to expand)` reads `(40 more lines, to expand)`. Neither function throws.
36
36
  - `session-daemon.js`
37
37
  - `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()` with a daemon-owned UI bridge that reports the mode `extension-ui-mode.js` resolves (`tui` by default, because the daemon hosts `ctx.ui.custom()` components); terminal chrome (`setHeader`, `setFooter`, `setEditorComponent`, `onTerminalInput`) stays a no-op. 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.
38
- - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus PiChamber's `pichamber.ui.form`, which resolves with a values object keyed by field id, and `pichamber.ui.choose`, described above) publish an `extension.dialog` event, register with the pending-input index (which publishes the canonical `session.input` event right after, so every device learns the session is blocked without opening it), 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, a signal that is already aborted when the dialog is requested resolves cancellation immediately without publishing or registering anything, matching Pi's TUI, 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; a `choose` answer travels as `value` (the choice id) with an optional `note` and is rejected unless the id is one the pending dialog offers and the note is allowed and at most 2,000 characters); fire-and-forget calls publish live-only `extension.notify` (`{ id, message, level, createdAt }`, level `'info'` unless `'warning'`/`'error'`; the server id is `notice-<sessionId>-<random UUID>`, random rather than a counter so ids stay unique across daemon restarts while clients keep earlier notices, and `createdAt` is the daemon `Date.now()` wall clock; never stored, so late devices see no notice history), `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` (with daemon-side `render.message`/`messageExpanded` when a message renderer is registered; see `extension-message-render.js`), 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, composer controls, widgets, panels, apps, titles, and working indicators) is kept in per-session maps and included in both `sessions.open` and `session.snapshot`; snapshots and details also carry daemon-owned `inputState: { pending }` from the pending-input index (`null` when authoritatively nothing is pending), as does every `sessions.list` row (with `sequence`) and the `sessions.pendingInput` command; 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` and `setFooter` remain intentional no-ops (`custom` is hosted by `extension-custom-host.js`) 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 on session deletion or daemon stop so no extension thread blocks forever; idle disposal no longer cancels them, it waits while a hosted request is pending (see below). Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
39
- - Open requests: `openUrl.publish` (private, server-only) validates an http(s) URL, attributes it with `open-request.js`, and publishes `session.openUrl` (`{ id, url, attributed, createdAt }`) on the chosen session; it responds `{ published: false }` when no session is resident. `pichamber.ui.openUrl(ctx, url)` (and its deprecated alias `ctx.ui.openUrl(url)`) runs the same `$BROWSER` handler with the exact session id. `daemon-process.js` receives the intake path as `--open-url-socket` and installs the `$BROWSER` launcher before any session starts.
38
+ - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus PiChamber's `pichamber.form`, which resolves with a values object keyed by field id, and `pichamber.choose`, described above) publish an `extension.dialog` event, register with the pending-input index (which publishes the canonical `session.input` event right after, so every device learns the session is blocked without opening it), 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, a signal that is already aborted when the dialog is requested resolves cancellation immediately without publishing or registering anything, matching Pi's TUI, 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; a `choose` answer travels as `value` (the choice id) with an optional `note` and is rejected unless the id is one the pending dialog offers and the note is allowed and at most 2,000 characters); fire-and-forget calls publish live-only `extension.notify` (`{ id, message, level, createdAt }`, level `'info'` unless `'warning'`/`'error'`; the server id is `notice-<sessionId>-<random UUID>`, random rather than a counter so ids stay unique across daemon restarts while clients keep earlier notices, and `createdAt` is the daemon `Date.now()` wall clock; never stored, so late devices see no notice history), `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` (with daemon-side `render.message`/`messageExpanded` when a message renderer is registered; see `extension-message-render.js`), and appended `pichamber.*` custom entries 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.card(ctx, card)` checks the card with `normalizeExtensionCard` (`../extension-card.js`: a known component, object props, up to 8 actions that each name a valid command; fields the browser does not read are dropped), appends a `pichamber.card` entry through `appendSessionEntry` and publishes the same event. It calls the session manager directly, not `pi.appendEntry`, so only the daemon hears about the entry; recheck `appendCustomEntry` and `getEntry` on an SDK upgrade. Two retired kinds stay out of the transcript (`isRetiredExtensionEntry`): `pichamber.ui` entries with an `id` (live panels) and `pichamber.app` entries, which 1.0.6 to 1.0.8-rc saved and no client drew. `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, composer controls, widgets, titles, and working indicators) is kept in per-session maps and included in both `sessions.open` and `session.snapshot`; snapshots and details also carry daemon-owned `inputState: { pending }` from the pending-input index (`null` when authoritatively nothing is pending), as does every `sessions.list` row (with `sequence`) and the `sessions.pendingInput` command; on session runtime creation/open, restart, or branch mutation (`sessions.navigate`, `sessions.fork`, `sessions.clone`), nothing is replayed: this state is live only and extensions set it again at `session_start`. 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. TUI-only `setHeader` and `setFooter` remain intentional no-ops (`custom` is hosted by `extension-custom-host.js`) 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 on session deletion or daemon stop so no extension thread blocks forever; idle disposal no longer cancels them, it waits while a hosted request is pending (see below). Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
39
+ - Open requests: `openUrl.publish` (private, server-only) validates an http(s) URL, attributes it with `open-request.js`, and publishes `session.openUrl` (`{ id, url, attributed, createdAt }`) on the chosen session; it responds `{ published: false }` when no session is resident. `pichamber.openUrl(ctx, url)` runs the same `$BROWSER` handler with the exact session id. `daemon-process.js` receives the intake path as `--open-url-socket` and installs the `$BROWSER` launcher before any session starts.
40
40
  - `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.
41
41
  - `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.
42
42
  - `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.
@@ -78,7 +78,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
78
78
  - 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.
79
79
  - The private core commands are `runtime.health` (its result includes `residentSessions`, the count of live and starting runtimes, which the sandbox manager reads for idle stop), `projects.list/select`, `providers.list/hosts/config.get/models.set/models.add/status/login/login.respond/login.status/logout` (`providers.hosts` returns the sorted, lowercase hosts of signed-in providers' model base URLs, skipping loopback and IP literals, for sandbox network grants; it and `providers.oauth.refresh` take an optional `exclude` list of absolute folders, use a resident runtime outside them, and never start a runtime inside one, so the main daemon does not load a sandboxed project's extensions), `settings.get/set`, `sessions.release` (`{ directories }`, 1–64 absolute folders: disposes every idle resident runtime in them now and marks each busy one to dispose at its next idle edge with no grace delay; returns `{ released, pending, streamEpoch }` as session ids, for the sandbox manager's drain; a session whose lease could not be released stays `pending` and the release is retried on the next call, so another daemon never opens it while the lease is held), `providers.oauth.refresh` (`{ minValidityMs }`, 0–24 h: for each signed-in OAuth provider, Pi's `getAuth(id, { minOAuthValidityMs })` refreshes a token that expires sooner, under Pi's own credential lock; returns `{ checked, failed }` as provider ids, never tokens), `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond/palette`, `extensions.config.list/set`, `extensions.packages.install/update/remove` (see `extension-config.js` above), `plugins.configure` (see `plugin-host.js` above), and session list/pendingInput/create/discardDraft/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. `sessions.pendingInput` takes no arguments, is never session-scoped or routed to engines, and returns `{ sessions: [{ sessionId, directory, pending }], sequence, streamEpoch }` for sessions with a non-null summary; `runtime.health` advertises it. 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 plus the requested directory's runtime (started when it is not resident); the returned catalog comes from that directory's runtime via `providers.list`. Concurrent refreshes share one task per resolved directory, never across directories; refreshes for different directories run one after another so their temporary catalog keys never interleave. 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, passing the same `getDeviceId` login option as the Pi CLI (backed by the runtime `SettingsManager.getOrCreateDeviceId()`) because flows such as Sign in with ChatGPT reject logins without a stable installation ID. A failed attempt projects Pi's error message (with its causes, URL query strings stripped so a pasted callback never echoes an authorization code, capped at 500 characters) beside the stable `PROVIDER_AUTH_REQUIRED` code; 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` returns cached or incrementally scanned header, first-prompt, and name fields. For a row whose runtime is resident, the list uses `sessionManager.getSessionName()` instead of the disk name, so unflushed renames and clears show immediately. Unpersisted resident sessions are listed too, except the fresh empty session a runtime starts with when it is started only to answer a folder's catalogs (`providers.list`, `resources.list`, `extensions.list`, runtime recreation) with no JSONL to reopen: nobody asked for it, so it stays out of listings until it holds a non-`custom` message (a user prompt, an assistant reply, or anything else that is not an extension's custom message) or a name, since what an extension adds at `session_start` lands in every such session, otherwise every folder switch would add an untitled "Awaiting first prompt" row. 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. Every Pi row additionally carries `inputState: { pending, sequence }` from the pending-input index (`pending` is `null` when authoritatively nothing is pending, stamped with the same observed sequence as `live`), so every device learns blocked sessions without opening them. 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`, `getSession`, navigate, fork, and clone project the live session's model and thinking level onto the session record, because that is what the next prompt runs on; Pi itself restores both from the branch when it reopens a chat. The last assistant `provider`/`model`/`thinkingLevel` only fills in when the live session reports none. It is not a substitute: after a revert, a failed turn, or a switch nobody has prompted on yet it names a model the session has left, and a client that compared its composer against it would skip the switch and keep sending on the old model. `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, and rename). Like the Pi CLI, the daemon never persists an auto-title: on the first conversation prompt of an unnamed session it publishes the derived title live without appending `session_info`, and lists derive the same title from the first user prompt. Renames of a resident session call Pi's `session.setSessionName`, which appends `session_info` and emits `session_info_changed` to listeners and extensions; the subscriber publishes the single `session.updated`. Non-resident renames open the file and append, as Pi's session picker does, and publish directly. `session.updated` with `title: ''` means Pi cleared the name; clients fall back to the title derived from the first prompt, and older clients ignore empty titles 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. Each thinking change publishes exactly one `session.thinking` with the effective (clamped) level: `applyThinking` publishes only when Pi will not (the level did not change, or the runtime is not yet subscribed during create). 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.
80
80
  - 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.
81
- - 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`. A registered extension command running without an agent turn (waiting on `custom()`, a dialog, or its own work) keeps the session busy, as Pi's interactive mode holds input until the command returns: the daemon publishes `session.lifecycle: busy` with `command: '/name'` when it dispatches, snapshots, `getSession`, and list live status report the same, and prompt, steer, and follow-up fail as `SESSION_BUSY` until it returns, because the SDK would start a second run beside the command (steering only queues behind a streaming turn). While the command's own agent turn streams, input behaves normally; when that turn settles and the command still runs, the busy frame with `command` is published again instead of idle, and the settled turn neither completes a requested shutdown nor re-arms idle disposal. A command that returns or throws publishes idle from its own settlement, whatever the send generation (a steer into the command's turn moves it on), unless a turn still streams, whose `agent_settled` then publishes idle. `!cmd` (`sessions.bash`) and `sessions.compact` are refused the same way. The busy check runs again after the model and attachment awaits, so two clients cannot both start beside a command. Command detection follows Pi's `_tryExecuteExtensionCommand`: the text (with appended attachment notes) must start with `/`, and the name up to the first space must match a registered `invocationName` exactly. 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.
81
+ - 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. When a registered extension command changed the model or the thinking level (a mode command such as `/balance`), that same edge publishes `session.model` with `source: 'extension'`, even when the model is unchanged, so clients replace an unsent composer pick with the extension's choice; a `model_select` event Pi tags `source: 'extension'` keeps the tag. A command that changed neither publishes nothing. A change a client asked for while the command ran (`sessions.setModel`/`setThinking`, counted per session) is that client's, so the command's comparison does not credit it to the extension. The extension choice is published when the command settles even if a steer has moved the send generation on. The sequence of the last extension choice is kept per session and sent as `session.extensionModelSequence` in session details and `extensionModelSequence` in snapshots, so a client that reconnects after missing it still replaces its unsent pick once. 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`. A registered extension command running without an agent turn (waiting on `custom()`, a dialog, or its own work) keeps the session busy, as Pi's interactive mode holds input until the command returns: the daemon publishes `session.lifecycle: busy` with `command: '/name'` when it dispatches, snapshots, `getSession`, and list live status report the same, and prompt, steer, and follow-up fail as `SESSION_BUSY` until it returns, because the SDK would start a second run beside the command (steering only queues behind a streaming turn). While the command's own agent turn streams, input behaves normally; when that turn settles and the command still runs, the busy frame with `command` is published again instead of idle, and the settled turn neither completes a requested shutdown nor re-arms idle disposal. A command that returns or throws publishes idle from its own settlement, whatever the send generation (a steer into the command's turn moves it on), unless a turn still streams, whose `agent_settled` then publishes idle. `!cmd` (`sessions.bash`) and `sessions.compact` are refused the same way. The busy check runs again after the model and attachment awaits, so two clients cannot both start beside a command. Command detection follows Pi's `_tryExecuteExtensionCommand`: the text (with appended attachment notes) must start with `/`, and the name up to the first space must match a registered `invocationName` exactly. 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.
82
82
  - 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.
83
83
  - 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.
84
84
  - A command that names a directory (`extensions.list`, `resources.list`, `providers.list`) is answered only by a runtime resident in that directory. `ensureRuntime` resolves the request through the runtime registry (`listByDirectory`), prefers the active runtime when it already serves that directory, otherwise uses a runtime already resident there, and starts one owned by it when none is; a concurrent start is shared per directory, never across directories. Answering for a directory that is not the daemon's active one stays non-active, including after idle disposal has cleared the active runtime (only a start in the active directory is adopted): it never replaces the active runtime or active directory, never replaces the remembered dormant session, reopens no dormant JSONL owned by another directory, and arms the same idle lifetime as any other view-only session, so browsing many projects cannot accumulate resident runtimes. A directory-less command keeps answering for the daemon's active directory. One project's loaded extensions, skills, prompts, and models are therefore never reported for another project.
@@ -171,57 +171,3 @@ describe('extension bridge component widget disposal', () => {
171
171
  expect(published.length).toBe(initialPublishCount + 1); // +1 from clearExtensionState's clearing widget event
172
172
  });
173
173
  });
174
-
175
- describe('extension bridge reload and tree navigation panel rebuilding', () => {
176
- it('rebuilds panels and apps from branch entries after reloadSession', async () => {
177
- const entries = [
178
- { type: 'custom', customType: 'pichamber.ui', data: { id: 'p1', title: 'Panel 1', component: 'test' } },
179
- { type: 'custom', customType: 'pichamber.app', data: { appId: 'a1', title: 'App 1', html: '<div>App</div>' } },
180
- ];
181
- let reloaded = false;
182
- const session = {
183
- sessionId: 's1',
184
- sessionManager: {
185
- getBranch: () => entries,
186
- },
187
- reload: async () => {
188
- reloaded = true;
189
- },
190
- };
191
- const { bridge, bindings } = createBridge({ session });
192
-
193
- await bindings.commandContextActions.reload();
194
- expect(reloaded).toBe(true);
195
-
196
- const snapshot = bridge.getSnapshotState('s1');
197
- expect(snapshot.panels).toEqual([
198
- { id: 'p1', title: 'Panel 1', component: 'test' },
199
- ]);
200
- expect(snapshot.apps).toEqual([
201
- { appId: 'a1', title: 'App 1', html: '<div>App</div>' },
202
- ]);
203
- });
204
-
205
- it('rebuilds panels and apps after successful navigateTree', async () => {
206
- const entries = [
207
- { type: 'custom', customType: 'pichamber.ui', data: { id: 'p2', title: 'Panel 2', component: 'test2' } },
208
- ];
209
- const session = {
210
- sessionId: 's1',
211
- sessionManager: {
212
- getBranch: () => entries,
213
- },
214
- navigateTree: async () => ({ cancelled: false }),
215
- };
216
- const { bridge, bindings } = createBridge({ session });
217
-
218
- const result = await bindings.commandContextActions.navigateTree('entry-target');
219
- expect(result).toEqual({ cancelled: false });
220
-
221
- const snapshot = bridge.getSnapshotState('s1');
222
- expect(snapshot.panels).toEqual([
223
- { id: 'p2', title: 'Panel 2', component: 'test2' },
224
- ]);
225
- });
226
- });
227
-