@pi-chamber/web 0.9.3 → 0.9.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 (47) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramView-CV-iReyY.js → DiagramView-CHy1Glsl.js} +1 -1
  3. package/dist/assets/{DiffView-DVd1MLPB.js → DiffView-CBOrV4hS.js} +1 -1
  4. package/dist/assets/{FilesView-CPnW4I90.js → FilesView-CK2YVs_W.js} +1 -1
  5. package/dist/assets/{GitView-Dj_7hgX_.js → GitView-BEFLOv_7.js} +3 -3
  6. package/dist/assets/{JsonTreeView-Cyy0lEZR.js → JsonTreeView-CKWGm5MS.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-BXN78Wu_.js → MarkdownRendererImpl-hE_nmSqe.js} +1 -1
  8. package/dist/assets/{PatchDiff-C7dA3U29.js → PatchDiff-BagRxMON.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-dr3g9DR7.js → SessionSwitcherContent-z9VYCXrT.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-C3zdd82V.js → SessionSwitcherDropdown-icxJk_lT.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-qeik5qtT.js → SessionUnreadDot-Bv-5KguB.js} +1 -1
  12. package/dist/assets/SettingsView-Ck0qxtKP.js +2 -0
  13. package/dist/assets/{SettingsWindow-Bbay2W76.js → SettingsWindow-GQRL2CdD.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-CRTiN1CH.js → ToolOutputDialog-CxJUXVZW.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-CqnNcLPk.js → ToolPartDiffPreview-BXuLRWHT.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-iqwryMNU.js → VirtualizedFileDiff-DfaXovGB.js} +1 -1
  17. package/dist/assets/{computeVirtualFileMetrics-Bbugxxtp.js → computeVirtualFileMetrics-DG_E6iaN.js} +1 -1
  18. package/dist/assets/{contextFileOpenGuard-BC3ie230.js → contextFileOpenGuard-DPBE3ELv.js} +1 -1
  19. package/dist/assets/{gitStatusPredicates-DbThKVSf.js → gitStatusPredicates-OljV4Bb2.js} +1 -1
  20. package/dist/assets/{index-v6K3L94m.js → index-DmexVlTQ.js} +1 -1
  21. package/dist/assets/{isDiffPlainText-Dl0RBjPZ.js → isDiffPlainText-aikgiqLb.js} +1 -1
  22. package/dist/assets/{isFilePlainText-CbrmvrM6.js → isFilePlainText-D-Dl6LqX.js} +1 -1
  23. package/dist/assets/{main-4PkIvzf4.js → main-BXdraZTZ.js} +3 -3
  24. package/dist/assets/{main-DMyWi0qs.js → main-DG1oZ0Wj.js} +2 -2
  25. package/dist/assets/{markdownCore-BD5WkOKU.js → markdownCore-DUjQU2i0.js} +1 -1
  26. package/dist/assets/{miniChat-CLMNhna4.js → miniChat-BEAtOkr9.js} +2 -2
  27. package/dist/assets/{mobile-rWMDwhtQ.js → mobile-DOFBBQg2.js} +2 -2
  28. package/dist/assets/{renderElectronMiniChatApp-BRhGNRJ8.js → renderElectronMiniChatApp-B0K72YnS.js} +2 -2
  29. package/dist/assets/{renderMobileApp-DLy2YoQg.js → renderMobileApp-Ca_BO_s4.js} +3 -3
  30. package/dist/assets/{runtimeEndpointReset-Z9YtcHxZ.js → runtimeEndpointReset-Cx2tsgTo.js} +3 -3
  31. package/dist/assets/{useAppFontEffects-DfuJVB15.js → useAppFontEffects-C4JL1x7k.js} +84 -84
  32. package/dist/assets/{useFilesViewSearch-BZBHrZ90.js → useFilesViewSearch-Du0DnmKs.js} +1 -1
  33. package/dist/assets/{usePushVisibilityBeacon-BxTkEajM.js → usePushVisibilityBeacon-BnHxIv4r.js} +1 -1
  34. package/dist/assets/{useSwitcherItems-jITqE8PV.js → useSwitcherItems-C91mwPJD.js} +1 -1
  35. package/dist/assets/{vendor-codemirror-language-data-CDdfwzlS.js → vendor-codemirror-language-data-C493X_9w.js} +2 -2
  36. package/dist/assets/{web-components-C9wXMuCp.js → web-components-B2Rw__yK.js} +1 -1
  37. package/dist/index.html +1 -1
  38. package/dist/mini-chat.html +1 -1
  39. package/dist/mobile.html +1 -1
  40. package/package.json +1 -1
  41. package/server/lib/pi/routes.js +13 -3
  42. package/server/lib/pi/routes.test.js +55 -1
  43. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -2
  44. package/server/lib/pi/session-daemon/prompt-operations.test.js +51 -0
  45. package/server/lib/pi/session-daemon/session-daemon.js +189 -54
  46. package/server/lib/pi/session-daemon/session-daemon.test.js +186 -0
  47. package/dist/assets/SettingsView-C57uV1YS.js +0 -2
@@ -258,6 +258,59 @@ describe('Pi runtime route', () => {
258
258
  ]);
259
259
  });
260
260
 
261
+ it('preserves deferred status for accepted Pi mutations', async () => {
262
+ const runtime = {
263
+ request: async (command) => {
264
+ if (command === 'settings.set') return { global: {}, project: { trusted: false }, deferred: true };
265
+ if (command === 'resources.update') return { skills: [], prompts: [], agents: [], deferred: true };
266
+ if (command === 'providers.models.set') return {
267
+ config: {
268
+ providerId: 'custom',
269
+ label: 'Custom',
270
+ baseUrl: 'https://api.example.test/v1',
271
+ api: 'openai-completions',
272
+ models: [],
273
+ },
274
+ deferred: true,
275
+ };
276
+ throw new Error(`Unexpected command ${command}`);
277
+ },
278
+ };
279
+ const app = express();
280
+ app.use(express.json());
281
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
282
+ server = await listen(app);
283
+ const base = `http://127.0.0.1:${server.address().port}/api/pi`;
284
+
285
+ await expect((await fetch(`${base}/settings/pi`, {
286
+ method: 'PUT',
287
+ headers: { 'Content-Type': 'application/json' },
288
+ body: JSON.stringify({ scope: 'global', defaultThinking: 'high' }),
289
+ })).json()).resolves.toEqual({
290
+ pi: { global: {}, project: { trusted: false } },
291
+ deferred: true,
292
+ });
293
+ await expect((await fetch(`${base}/resources/resource-1`, {
294
+ method: 'PUT',
295
+ headers: { 'Content-Type': 'application/json' },
296
+ body: JSON.stringify({ content: 'Updated' }),
297
+ })).json()).resolves.toEqual({ skills: [], prompts: [], agents: [], deferred: true });
298
+ await expect((await fetch(`${base}/providers/custom/models`, {
299
+ method: 'PUT',
300
+ headers: { 'Content-Type': 'application/json' },
301
+ body: JSON.stringify({ label: 'Custom', baseUrl: 'https://api.example.test/v1', models: [] }),
302
+ })).json()).resolves.toEqual({
303
+ config: {
304
+ providerId: 'custom',
305
+ label: 'Custom',
306
+ baseUrl: 'https://api.example.test/v1',
307
+ api: 'openai-completions',
308
+ models: [],
309
+ },
310
+ deferred: true,
311
+ });
312
+ });
313
+
261
314
  it('forwards provider login without returning API keys and projects only interactive login state', async () => {
262
315
  const calls = [];
263
316
  const runtime = {
@@ -789,7 +842,7 @@ describe('Pi runtime route', () => {
789
842
  onEvent({ protocolVersion: 1, kind: 'event', event: 'assistant.message.end', sequence: 6, payload: { sessionId: 'pi-session-5', directory: '/workspace', messageId: 'assistant-1', durationMs: 42, continuing: true, error: { code: 'ASSISTANT_ERROR', message: 'provider request timed out' } } });
790
843
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.lifecycle', sequence: 7, payload: { sessionId: 'pi-session-5', directory: '/workspace', state: 'retry', attempt: 2, next: 8_000, message: 'provider request timed out' } });
791
844
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.error', sequence: 8, payload: { sessionId: 'pi-session-5', directory: '/workspace', code: 'ASSISTANT_ERROR', message: 'provider request timed out' } });
792
- onEvent({ protocolVersion: 1, kind: 'event', event: 'session.tool.start', sequence: 9, payload: { sessionId: 'pi-session-5', directory: '/workspace', toolCallId: 'skill-read', partId: 'assistant-1:tool:skill-read', messageId: 'assistant-1', name: 'read', state: 'running', metadata: { pichamber: { skill: { name: 'review' } } }, privatePath: '/private/skill/SKILL.md' } });
845
+ onEvent({ protocolVersion: 1, kind: 'event', event: 'session.tool.start', sequence: 9, payload: { sessionId: 'pi-session-5', directory: '/workspace', toolCallId: 'skill-read', partId: 'assistant-1:tool:skill-read', messageId: 'assistant-1', name: 'read', state: 'running', metadata: { pichamber: { skill: { name: 'review' } } }, startedAt: 2_000, serverNow: 3_000, privatePath: '/private/skill/SKILL.md' } });
793
846
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.compaction', sequence: 10, payload: { sessionId: 'pi-session-5', directory: '/workspace', phase: 'completed', reason: 'overflow', startedAt: 3_000, completedAt: 9_000, tokensBefore: 120_000, estimatedTokensAfter: 24_000, willRetry: true, privateResult: 'hidden' } });
794
847
  return () => {};
795
848
  },
@@ -817,6 +870,7 @@ describe('Pi runtime route', () => {
817
870
  expect(text).toContain('"state":"retry","attempt":2,"next":8000,"message":"provider request timed out"');
818
871
  expect(text).toContain('"message":"provider request timed out"');
819
872
  expect(text).toContain('"metadata":{"pichamber":{"skill":{"name":"review"}}}');
873
+ expect(text).toContain('"startedAt":2000,"serverNow":3000');
820
874
  expect(text).toContain('"phase":"completed","reason":"overflow","startedAt":3000,"completedAt":9000,"tokensBefore":120000,"estimatedTokensAfter":24000,"willRetry":true');
821
875
  expect(text).not.toContain('privatePath');
822
876
  expect(text).not.toContain('privateResult');
@@ -34,8 +34,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
34
34
  - The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
35
35
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
36
36
  - 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.
37
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes remain rejected while the active session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. 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.
38
- - 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, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
37
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
39
38
  - Each event and reconnect snapshot has a monotonic sequence. A reconnect receives a bounded contiguous replay after its cursor when available, otherwise an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions.
40
39
  - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. 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 and adds it to the matching user start in send order. The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
41
40
  - 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.
@@ -310,6 +310,7 @@ describe('prompt template daemon operations', () => {
310
310
  name: 'during-run', description: 'During run', content: 'x', location: 'global', directory: ctx.cwd,
311
311
  });
312
312
  expect(created.prompts.some((prompt) => prompt.name === 'during-run')).toBe(true);
313
+ expect(created.deferred).toBe(true);
313
314
  expect(session.reloadCount).toBe(0);
314
315
  expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
315
316
 
@@ -329,6 +330,56 @@ describe('prompt template daemon operations', () => {
329
330
  expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
330
331
  });
331
332
 
333
+ it('commits generic resource changes while streaming and refreshes after settlement', async () => {
334
+ const session = new FakeSession();
335
+ const ctx = await startDaemon({ session });
336
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
337
+ const agents = listed.agents.find((agent) => agent.location === 'global');
338
+ expect(agents).toBeDefined();
339
+
340
+ session.isStreaming = true;
341
+ const updated = await ctx.request('resources.update', {
342
+ resourceId: agents.id,
343
+ content: '# Updated while running\\n',
344
+ directory: ctx.cwd,
345
+ });
346
+
347
+ expect(updated.deferred).toBe(true);
348
+ expect(updated.agents.find((agent) => agent.id === agents.id)).toMatchObject({
349
+ id: agents.id,
350
+ content: '# Updated while running\\n',
351
+ });
352
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
353
+ await expect(readFile(join(ctx.agentDir, 'AGENTS.md'), 'utf8')).resolves.toBe('# Updated while running\\n');
354
+
355
+ session.isStreaming = false;
356
+ session.emit({ type: 'agent_settled' });
357
+ await expect.poll(() => ctx.runtimeState.disposeCount).toBe(1);
358
+ expect(ctx.runtimeState.createCount).toBe(2);
359
+ });
360
+
361
+ it('waits for an accepted prompt to finish before recreating the runtime', async () => {
362
+ const session = new FakeSession();
363
+ let finishPrompt;
364
+ session.promptImpl = () => new Promise((resolve) => { finishPrompt = resolve; });
365
+ const ctx = await startDaemon({ session });
366
+ await ctx.request('resources.list', { directory: ctx.cwd });
367
+ await expect(ctx.request('sessions.prompt', { sessionId: session.sessionId, text: '/hold', directory: ctx.cwd })).resolves.toMatchObject({ accepted: true });
368
+
369
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
370
+ const agents = listed.agents.find((agent) => agent.location === 'global');
371
+ const updated = await ctx.request('resources.update', {
372
+ resourceId: agents.id,
373
+ content: '# Updated after prompt acceptance\\n',
374
+ directory: ctx.cwd,
375
+ });
376
+ expect(updated.deferred).toBe(true);
377
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
378
+
379
+ finishPrompt();
380
+ await expect.poll(() => ctx.runtimeState.disposeCount).toBe(1);
381
+ });
382
+
332
383
  it('defers reload while a non-streaming slash command is still executing', async () => {
333
384
  const session = new FakeSession();
334
385
  let finishPrompt;