@pi-chamber/web 0.9.4 → 0.9.5

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 (89) hide show
  1. package/README.md +15 -0
  2. package/dist/assets/{DiagramEditor-DuGmiPZ5.js → DiagramEditor-BPDkGHsj.js} +1 -1
  3. package/dist/assets/DiagramView-D_EfDz2d.js +1 -0
  4. package/dist/assets/{DiffView-CBOrV4hS.js → DiffView-BmIVvheE.js} +2 -2
  5. package/dist/assets/FilesView-CJytSUAX.js +6 -0
  6. package/dist/assets/GitView-BNkzec7G.js +8 -0
  7. package/dist/assets/{JsonTreeView-CKWGm5MS.js → JsonTreeView-C1Kzaybf.js} +1 -1
  8. package/dist/assets/MarkdownRendererImpl-qmKiFVpO.js +12 -0
  9. package/dist/assets/PatchDiff-D9JesZL1.js +1 -0
  10. package/dist/assets/{SessionSwitcherContent-z9VYCXrT.js → SessionSwitcherContent-DplV_ApH.js} +1 -1
  11. package/dist/assets/SessionSwitcherDropdown-DdgDKT6K.js +2 -0
  12. package/dist/assets/SessionUnreadDot-BdSDgvhC.js +1 -0
  13. package/dist/assets/SettingsView-z8uf0XyM.js +2 -0
  14. package/dist/assets/SettingsWindow-CPDmgNg2.js +1 -0
  15. package/dist/assets/ToolOutputDialog-DaF1xcM0.js +8 -0
  16. package/dist/assets/ToolPartDiffPreview-Di6Uo0Dt.js +1 -0
  17. package/dist/assets/{VirtualizedFileDiff-DfaXovGB.js → VirtualizedFileDiff-wqcrY0yr.js} +3 -3
  18. package/dist/assets/collapsible-DBQnXTNm.js +1 -0
  19. package/dist/assets/computeVirtualFileMetrics-Cr3jh0d6.js +3 -0
  20. package/dist/assets/contextFileOpenGuard-C_AOTYQD.js +1 -0
  21. package/dist/assets/gitStatusPredicates-BvPOjeOy.js +134 -0
  22. package/dist/assets/index-B8Wt2aN3.js +1 -0
  23. package/dist/assets/index-DIF8b4bh.css +1 -0
  24. package/dist/assets/index-jrfQYSvP.js +8 -0
  25. package/dist/assets/isDiffPlainText-L9uvgz2F.js +1 -0
  26. package/dist/assets/isFilePlainText-C4yk5BOo.js +1 -0
  27. package/dist/assets/main-C1OSzD-E.js +135 -0
  28. package/dist/assets/{main-DG1oZ0Wj.js → main-DCK6lLCo.js} +2 -2
  29. package/dist/assets/{markdownCore-DUjQU2i0.js → markdownCore-Czb_lINQ.js} +2 -2
  30. package/dist/assets/{miniChat-BEAtOkr9.js → miniChat-CXiSlptL.js} +2 -2
  31. package/dist/assets/{mobile-DOFBBQg2.js → mobile-D0HVxiyJ.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +2 -0
  33. package/dist/assets/renderMobileApp-B5x_PWlc.js +11 -0
  34. package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +53 -0
  35. package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-vilE4xyj.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-C4JL1x7k.js → useAppFontEffects-BP07Vl6M.js} +102 -103
  37. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +7 -0
  38. package/dist/assets/usePushVisibilityBeacon-CChMvoTL.js +10 -0
  39. package/dist/assets/useSwitcherItems-_RSo3F-A.js +1 -0
  40. package/dist/assets/{vendor-base-ui-vkqQ2P9o.js → vendor-base-ui-CdaWtC7e.js} +1 -1
  41. package/dist/assets/vendor-beautiful-mermaid-D3YCkKz7.js +111 -0
  42. package/dist/assets/{vendor-codemirror-commands-DYppkHEk.js → vendor-codemirror-commands-CNlncqrr.js} +1 -1
  43. package/dist/assets/{vendor-codemirror-language-data-C493X_9w.js → vendor-codemirror-language-data-BJrrV83E.js} +2 -2
  44. package/dist/assets/{vendor-replit-codemirror-vim-CGHHNQxC.js → vendor-replit-codemirror-vim-DaSwPsXt.js} +1 -1
  45. package/dist/assets/{web-components-B2Rw__yK.js → web-components-B5sMa_kC.js} +3 -3
  46. package/dist/index.html +4 -4
  47. package/dist/mini-chat.html +3 -3
  48. package/dist/mobile.html +3 -3
  49. package/package.json +2 -2
  50. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -5
  51. package/server/lib/pi/session-daemon/prompt-operations.test.js +142 -0
  52. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -0
  53. package/server/lib/pi/session-daemon/session-daemon.js +230 -76
  54. package/server/lib/pi/session-daemon/session-idle-residency.test.js +742 -0
  55. package/server/lib/pi/session-daemon/session-replay.js +98 -0
  56. package/server/lib/pi/session-daemon/session-replay.test.js +626 -0
  57. package/server/lib/pi/ui-settings-store.js +16 -10
  58. package/server/lib/pi/ui-settings-store.test.js +91 -0
  59. package/server/lib/stt/DOCUMENTATION.md +1 -1
  60. package/server/lib/stt/local/worker-client.js +11 -3
  61. package/server/lib/stt/local/worker-client.test.js +255 -0
  62. package/dist/assets/DiagramView-CHy1Glsl.js +0 -1
  63. package/dist/assets/FilesView-CK2YVs_W.js +0 -6
  64. package/dist/assets/GitView-BEFLOv_7.js +0 -8
  65. package/dist/assets/MarkdownRendererImpl-hE_nmSqe.js +0 -12
  66. package/dist/assets/PatchDiff-BagRxMON.js +0 -1
  67. package/dist/assets/SessionSwitcherDropdown-icxJk_lT.js +0 -2
  68. package/dist/assets/SessionUnreadDot-Bv-5KguB.js +0 -1
  69. package/dist/assets/SettingsView-Ck0qxtKP.js +0 -2
  70. package/dist/assets/SettingsWindow-GQRL2CdD.js +0 -1
  71. package/dist/assets/ToolOutputDialog-CxJUXVZW.js +0 -8
  72. package/dist/assets/ToolPartDiffPreview-BXuLRWHT.js +0 -1
  73. package/dist/assets/collapsible-szfZ0Syc.js +0 -1
  74. package/dist/assets/computeVirtualFileMetrics-DG_E6iaN.js +0 -3
  75. package/dist/assets/contextFileOpenGuard-DPBE3ELv.js +0 -1
  76. package/dist/assets/gitStatusPredicates-OljV4Bb2.js +0 -134
  77. package/dist/assets/index-DNoEeZ2U.css +0 -1
  78. package/dist/assets/index-DmexVlTQ.js +0 -1
  79. package/dist/assets/index-KIdiBFJs.js +0 -8
  80. package/dist/assets/isDiffPlainText-aikgiqLb.js +0 -1
  81. package/dist/assets/isFilePlainText-D-Dl6LqX.js +0 -1
  82. package/dist/assets/main-BXdraZTZ.js +0 -135
  83. package/dist/assets/renderElectronMiniChatApp-B0K72YnS.js +0 -2
  84. package/dist/assets/renderMobileApp-Ca_BO_s4.js +0 -11
  85. package/dist/assets/runtimeEndpointReset-Cx2tsgTo.js +0 -54
  86. package/dist/assets/useFilesViewSearch-Du0DnmKs.js +0 -7
  87. package/dist/assets/usePushVisibilityBeacon-BnHxIv4r.js +0 -10
  88. package/dist/assets/useSwitcherItems-C91mwPJD.js +0 -1
  89. package/dist/assets/vendor-beautiful-mermaid-DneUawHp.js +0 -119
@@ -89,7 +89,7 @@
89
89
  }
90
90
  </style>
91
91
 
92
- <script type="module" crossorigin src="/assets/miniChat-BEAtOkr9.js"></script>
92
+ <script type="module" crossorigin src="/assets/miniChat-CXiSlptL.js"></script>
93
93
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
94
94
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
95
95
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-B5Z1Mdn3.js">
@@ -97,9 +97,9 @@
97
97
  <link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
98
98
  <link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-CPcsbTWB.js">
99
99
  <link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-Dw8P0qyA.js">
100
- <link rel="modulepreload" crossorigin href="/assets/index-KIdiBFJs.js">
100
+ <link rel="modulepreload" crossorigin href="/assets/index-jrfQYSvP.js">
101
101
  <link rel="modulepreload" crossorigin href="/assets/vendor-katex-CNckGUMB.js">
102
- <link rel="stylesheet" crossorigin href="/assets/index-DNoEeZ2U.css">
102
+ <link rel="stylesheet" crossorigin href="/assets/index-DIF8b4bh.css">
103
103
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-Cp579UoJ.css">
104
104
  </head>
105
105
  <body class="h-full bg-background text-foreground">
package/dist/mobile.html CHANGED
@@ -63,7 +63,7 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-DOFBBQg2.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-D0HVxiyJ.js"></script>
67
67
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
68
68
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-B5Z1Mdn3.js">
@@ -71,9 +71,9 @@
71
71
  <link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
72
72
  <link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-CPcsbTWB.js">
73
73
  <link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-Dw8P0qyA.js">
74
- <link rel="modulepreload" crossorigin href="/assets/index-KIdiBFJs.js">
74
+ <link rel="modulepreload" crossorigin href="/assets/index-jrfQYSvP.js">
75
75
  <link rel="modulepreload" crossorigin href="/assets/vendor-katex-CNckGUMB.js">
76
- <link rel="stylesheet" crossorigin href="/assets/index-DNoEeZ2U.css">
76
+ <link rel="stylesheet" crossorigin href="/assets/index-DIF8b4bh.css">
77
77
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-Cp579UoJ.css">
78
78
  </head>
79
79
  <body class="h-full bg-background text-foreground">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "0.9.4",
3
+ "version": "0.9.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "repository": {
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@clack/prompts": "^1.1.0",
31
- "@earendil-works/pi-coding-agent": "0.84.1",
31
+ "@earendil-works/pi-coding-agent": "0.85.1",
32
32
  "@octokit/rest": "^22.0.1",
33
33
  "@simplewebauthn/server": "13.3.1",
34
34
  "adm-zip": "^0.6.0",
@@ -11,7 +11,8 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
11
11
  - `session-daemon.js`
12
12
  - `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` in rpc-like mode with a daemon-owned UI bridge, so pi extensions load exactly as they do under the Pi CLI's RPC mode. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
13
13
  - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces; extension live state is kept in per-session maps and included in both `sessions.open` and `session.snapshot`. 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 component replacement, footers, and themes remain intentional no-ops; standard RPC editor replacement and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
14
- - `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
14
+ - `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.
15
+ - `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.
15
16
  - `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.
16
17
  - `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
17
18
  - `runtime-registry.js` owns active runtime identities and session-local subscriptions. It rebinds the subscription after an SDK session replacement, rejects identity conflicts rather than displacing another runtime, and attempts every tracked disposal even when another disposal fails.
@@ -34,11 +35,11 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
34
35
  - 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
36
  - 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
37
  - 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 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.
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.
38
+ - 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 from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.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
+ - Each event and reconnect snapshot has a monotonic sequence. 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.
39
40
  - 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.
40
41
  - 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.
41
- - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. Agent and compaction starts cancel pending disposal, and the timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative.
42
+ - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). View-only access (`sessions.open`, `sessions.messages`, `sessions.tree`, plus navigate/fork/clone/abort/model/thinking/rename settlement) arms the same lifetime through `touchIdleDisposal`, so browsing old sessions without prompting cannot grow the registry unboundedly while the UI keeps only a bounded transcript cache. Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt or open. The touch clears first and re-arms only when the session is resident and idle-safe, so a read cannot race a pending operation and a repeated open extends the deadline. Agent and compaction starts cancel pending disposal, and prompt/compact entry clears it before activation. The timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative, while a send is in flight (`activeSessionInputs`), while a resource reload is pending or running, while a provider retry is scheduled, or while compaction is running/retrying; pending extension dialogs are instead cancelled with an authoritative dismiss event. A read or prompt that arrives during an in-flight disposal waits for it and reopens from JSONL instead of adopting a dying runtime. There is deliberately no acquisition-path eviction: capacity pressure alone never disposes entries that are actively mounting.
42
43
  - A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
43
44
  - After a forced crash, the next health, request, or subscription probe re-runs supervised startup. Each private health probe uses the supervisor's five-second operation budget; it must not inherit the general 30-second command timeout and hold every browser request until the browser aborts. Daemon readiness has its own 15-second bounded budget, separate from the shorter probe, lock, and shutdown budget, because loading Pi settings and provider/model catalogs can legitimately exceed five seconds. The supervisor removes an existing POSIX socket only when its recorded daemon PID is dead, the endpoint is a socket, and authenticated IPC deterministically refuses or times out. An endpoint that responds, authenticates incorrectly, returns malformed protocol data, or cannot be classified remains `DAEMON_ENDPOINT_UNVERIFIED`.
44
45
  - The web server creates its supervisor after HTTP listen so the profile key uses the bound port, then warms it without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`. The bound profile key travels back over the `pichamber:ready` IPC message and into the CLI instance file; `pichamber logs` uses that key to include the matching private daemon log, while `--json` and `--quiet` serve output still carries only the port.
@@ -48,4 +49,15 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
48
49
 
49
50
  This module defines the authenticated session API boundary consumed by the Pi-native session UI. Session leases coordinate PiChamber daemons only: the standalone `pi` CLI runs its own foreground runtime and does not honor these leases, so concurrently editing the same session through PiChamber and `pi` remains unsupported until Pi provides compatible upstream locking. Resource configuration and richer attachment extraction remain owned by their dedicated workstreams. The session event stream is SSE over the existing authenticated runtime transport; WebSocket callers fall back to it, preserving direct and relay behavior without a second daemon listener. The public route emits named heartbeat events so native `EventSource` clients can detect a silent foreground connection, reconnect, and resume from their last accepted sequence.
50
51
 
51
- The Pi SDK is pinned exactly at `0.84.1`. Any Pi 0.x minor upgrade requires a deliberate SDK/release-note review and repeat of this module's disposable-runtime smoke validation.
52
+ The Pi SDK is pinned exactly at `0.85.1`. Any Pi 0.x minor upgrade requires a deliberate SDK/release-note review and repeat of this module's disposable-runtime smoke validation.
53
+
54
+ ## SDK upgrade validation
55
+
56
+ The 0.84.1 → 0.85.1 upgrade retains the public session runtime/services API and v3 JSONL format. No PiChamber data migration or cache deletion is required. The SDK repairs a missing trailing newline when opening an existing session; subsequent entries remain separate JSONL records. Existing settings, custom model definitions, labels, and extension entries remain intact.
57
+
58
+ - `sdk-upgrade.test.js` exercises the installed SDK with disposable directories: cached OpenCode models, user model additions and overrides, forced HTTP refresh, ETag/304, failed refresh preserving the last catalog, restart restoration, and opening/appending a pre-upgrade v3 session.
59
+ - `session-daemon-extensions.e2e.test.js` exercises real extension loading, commands, dialogs, GUI projection, reload, and session disposal.
60
+ - `supervisor.test.js` covers authenticated replacement of a daemon from an older PiChamber build. Normal versioned releases must retain that replacement behavior. Same-version, same-path manual dependency replacement is not a release upgrade and requires stopping the old server/daemon before restarting.
61
+ - The SDK CLI bin moved to `dist/bundle/cli.js`; the detached daemon already resolves `package.json`'s `bin.pi` rather than hardcoding the old location.
62
+
63
+ The new bundled OpenCode catalog removes `deepseek-v4-flash-free`. SDK remote catalogs still merge additively with bundled models, so this upgrade fixes that stale entry, not general upstream deletion propagation. Explicit user-defined models with the same ID remain supported. Do not clear users' `models.json` or `models-store.json` to apply an upgrade.
@@ -434,3 +434,145 @@ describe('prompt template daemon operations', () => {
434
434
  })).rejects.toMatchObject({ code: 'RESOURCE_NOT_FOUND' });
435
435
  });
436
436
  });
437
+
438
+ describe('transient prompt services (no servicesCache retention)', () => {
439
+ const dirs = [];
440
+ let daemon = null;
441
+ afterEach(async () => {
442
+ if (daemon) { await daemon.stop().catch(() => {}); daemon = null; }
443
+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })));
444
+ });
445
+
446
+ const startDaemonWithCountingServices = async ({ liveLoader } = {}) => {
447
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-prompt-transient-'));
448
+ dirs.push(root);
449
+ const endpoint = testDaemonEndpoint(root);
450
+ const agentDir = join(root, 'agent');
451
+ const cwd = join(root, 'project');
452
+ await mkdir(agentDir, { recursive: true });
453
+ await mkdir(cwd, { recursive: true });
454
+ const sess = new FakeSession();
455
+ // Live runtime keeps its own loader and modelRuntime; provider refresh must
456
+ // touch only this live ModelRuntime, never transient mutation services.
457
+ const liveRefresh = { count: 0 };
458
+ sess.modelRuntime = {
459
+ getProviders: () => [{ id: 'test' }],
460
+ getProvider: (id) => (id === 'test' ? { name: 'Test provider' } : undefined),
461
+ getModels: () => [{ provider: 'test', id: 'model', name: 'Test model' }],
462
+ getProviderAuthStatus: () => ({ configured: true }),
463
+ setRuntimeApiKey: async () => {},
464
+ removeRuntimeApiKey: async () => {},
465
+ refresh: async () => { liveRefresh.count += 1; return { errors: new Map() }; },
466
+ };
467
+ const runtimeState = { createCount: 0, disposeCount: 0 };
468
+ const transientStats = { createCount: 0, refreshCounts: [] };
469
+ const baseLiveLoader = liveLoader;
470
+ daemon = createSessionDaemon({
471
+ endpoint, credential, cwd, agentDir,
472
+ createRuntime: async (opts) => {
473
+ runtimeState.createCount += 1;
474
+ const dir = typeof opts?.cwd === 'string' && opts.cwd.length > 0 ? opts.cwd : cwd;
475
+ const runtimeLoader = baseLiveLoader ?? makeLoader(agentDir, () => dir);
476
+ return {
477
+ cwd: dir,
478
+ session: sess,
479
+ services: { resourceLoader: runtimeLoader },
480
+ async dispose() { runtimeState.disposeCount += 1; },
481
+ };
482
+ },
483
+ // Transient fresh services per mutation: read editable prompts from disk
484
+ // like the real SDK loader, but with a counting ModelRuntime that must
485
+ // never be refreshed by providers.refresh (no retention).
486
+ createServices: async ({ cwd: servicesCwd }) => {
487
+ transientStats.createCount += 1;
488
+ const refreshState = { count: 0 };
489
+ transientStats.refreshCounts.push(refreshState);
490
+ return {
491
+ cwd: servicesCwd,
492
+ agentDir,
493
+ modelRuntime: {
494
+ getProviders: () => [],
495
+ getProviderAuthStatus: () => ({ configured: true }),
496
+ setRuntimeApiKey: async () => {},
497
+ removeRuntimeApiKey: async () => {},
498
+ refresh: async () => { refreshState.count += 1; return { errors: new Map() }; },
499
+ },
500
+ settingsManager: {},
501
+ resourceLoader: makeLoader(agentDir, () => servicesCwd),
502
+ diagnostics: [],
503
+ };
504
+ },
505
+ });
506
+ await daemon.start();
507
+ const request = (command, payload = {}) =>
508
+ requestSessionDaemon({ endpoint, credential, command, payload });
509
+ return { root, endpoint, agentDir, cwd, session: sess, runtimeState, transientStats, liveRefresh, request };
510
+ };
511
+
512
+ it('creates fresh services per mutation without reuse or retention', async () => {
513
+ const ctx = await startDaemonWithCountingServices();
514
+ await ctx.request('resources.list', { directory: ctx.cwd });
515
+ expect(ctx.transientStats.createCount).toBe(0);
516
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
517
+
518
+ const first = await ctx.request('resources.prompts.create', {
519
+ name: 'alpha', description: 'Alpha', content: 'Body A', location: 'global', directory: ctx.cwd,
520
+ });
521
+ expect(first.prompts.some((p) => p.name === 'alpha')).toBe(true);
522
+ expect(ctx.transientStats.createCount).toBe(1);
523
+
524
+ const second = await ctx.request('resources.prompts.create', {
525
+ name: 'beta', description: 'Beta', content: 'Body B', location: 'global', directory: ctx.cwd,
526
+ });
527
+ // Freshness: the second response reflects both committed files even though
528
+ // the live runtime was never recreated.
529
+ expect(second.prompts.some((p) => p.name === 'alpha')).toBe(true);
530
+ expect(second.prompts.some((p) => p.name === 'beta')).toBe(true);
531
+ expect(ctx.transientStats.createCount).toBe(2);
532
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
533
+ });
534
+
535
+ it('merges live non-editable resources with fresh editable prompts', async () => {
536
+ const liveLoader = {
537
+ getSkills: () => ({ skills: [] }),
538
+ getPrompts: () => ({
539
+ prompts: [{
540
+ name: 'pkg', description: 'Pkg', content: 'Body', filePath: '/pkg/prompts/pkg.md',
541
+ sourceInfo: { origin: 'package', scope: 'user' },
542
+ }],
543
+ }),
544
+ getAgentsFiles: () => ({ agentsFiles: [] }),
545
+ };
546
+ const ctx = await startDaemonWithCountingServices({ liveLoader });
547
+ const created = await ctx.request('resources.prompts.create', {
548
+ name: 'local-edit', description: 'Local', content: 'Fresh body', location: 'global', directory: ctx.cwd,
549
+ });
550
+ // Active extension/package resources stay owned by the live session.
551
+ expect(created.prompts.some((p) => p.name === 'pkg')).toBe(true);
552
+ expect(created.prompts.find((p) => p.name === 'pkg').editable).not.toBe(true);
553
+ // Editable prompts reflect the committed file via transient services.
554
+ expect(created.prompts.find((p) => p.name === 'local-edit')).toMatchObject({
555
+ location: 'global',
556
+ editable: true,
557
+ });
558
+ expect(created.prompts.find((p) => p.name === 'local-edit').content).toContain('Fresh body');
559
+ });
560
+
561
+ it('refreshes providers from live runtimes only, not transient services', async () => {
562
+ const ctx = await startDaemonWithCountingServices();
563
+ await ctx.request('resources.prompts.create', {
564
+ name: 'alpha', description: 'A', content: 'Body A', location: 'global', directory: ctx.cwd,
565
+ });
566
+ await ctx.request('resources.prompts.create', {
567
+ name: 'beta', description: 'B', content: 'Body B', location: 'global', directory: ctx.cwd,
568
+ });
569
+ expect(ctx.transientStats.createCount).toBe(2);
570
+
571
+ const catalog = await ctx.request('providers.refresh', { directory: ctx.cwd });
572
+ expect(catalog.providers.some((p) => p.id === 'test')).toBe(true);
573
+ // Live runtime was refreshed exactly once; transient orphans were never
574
+ // retained and never refreshed (operation-count guard against retention).
575
+ expect(ctx.liveRefresh.count).toBe(1);
576
+ expect(ctx.transientStats.refreshCounts.map((s) => s.count)).toEqual([0, 0]);
577
+ });
578
+ });
@@ -0,0 +1,157 @@
1
+ import { createServer } from 'node:http';
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { ModelRuntime, SessionManager } from '@earendil-works/pi-coding-agent';
7
+
8
+ import { createPiSessionRuntime } from './session-daemon.js';
9
+ import { getPiSessionDirectory } from './session-jsonl.js';
10
+
11
+ // Exercise the installed SDK, not mocked catalogs or a developer's Pi home.
12
+ describe('pinned SDK upgrade compatibility', () => {
13
+ let root;
14
+ let server;
15
+ let runtime;
16
+
17
+ afterEach(async () => {
18
+ await runtime?.dispose();
19
+ runtime = undefined;
20
+ if (server) {
21
+ await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
22
+ server = undefined;
23
+ }
24
+ if (root) await rm(root, { recursive: true, force: true });
25
+ });
26
+
27
+ it('restores an existing model cache and preserves custom models across refresh, 304, and failure', async () => {
28
+ root = await mkdtemp(join(tmpdir(), 'pichamber-sdk-catalog-'));
29
+ let responseStatus = 200;
30
+ let remoteModels = [];
31
+ const requests = [];
32
+ server = createServer((request, response) => {
33
+ requests.push({ url: request.url, etag: request.headers['if-none-match'] });
34
+ response.writeHead(responseStatus, {
35
+ 'content-type': 'application/json',
36
+ etag: '"upgrade-catalog"',
37
+ 'last-modified': 'Wed, 01 Jan 2031 00:00:00 GMT',
38
+ });
39
+ response.end(responseStatus === 200 ? JSON.stringify(remoteModels) : undefined);
40
+ });
41
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
42
+ const options = {
43
+ authPath: join(root, 'auth.json'),
44
+ modelsPath: join(root, 'models.json'),
45
+ modelsStorePath: join(root, 'models-store.json'),
46
+ catalogBaseUrl: `http://127.0.0.1:${server.address().port}`,
47
+ allowModelNetwork: false,
48
+ };
49
+ const baseline = await ModelRuntime.create(options);
50
+ expect(baseline.getModel('opencode', 'deepseek-v4-flash-free')).toBeUndefined();
51
+ const flash = baseline.getModel('opencode', 'deepseek-v4-flash');
52
+ expect(flash).toBeDefined();
53
+ const cached = { ...flash, id: 'upgrade-cached-model', name: 'Cached model' };
54
+ await writeFile(options.modelsStorePath, JSON.stringify({
55
+ opencode: { models: [cached], checkedAt: Date.now(), lastModified: Date.UTC(2030, 0, 1), etag: '"old-catalog"' },
56
+ }));
57
+ const customConfig = JSON.stringify({ providers: { opencode: {
58
+ baseUrl: 'https://opencode.ai/zen/v1',
59
+ models: [{ id: 'upgrade-custom-model', name: 'My custom model', api: 'openai-completions', contextWindow: 8192, maxTokens: 1024 }],
60
+ modelOverrides: { 'deepseek-v4-flash': { name: 'My Flash override' } },
61
+ } } });
62
+ await writeFile(options.modelsPath, customConfig);
63
+ const models = await ModelRuntime.create(options);
64
+ await models.setRuntimeApiKey('opencode', 'pichamber-test-catalog-only');
65
+ expect(requests).toHaveLength(0);
66
+ expect(models.getModel('opencode', cached.id)).toEqual(cached);
67
+ expect(models.getModel('opencode', 'upgrade-custom-model')?.name).toBe('My custom model');
68
+ expect(models.getModel('opencode', flash.id)?.name).toBe('My Flash override');
69
+ expect(models.getModel('opencode', 'deepseek-v4-flash-free')).toBeUndefined();
70
+
71
+ remoteModels = [{ ...flash, id: 'upgrade-remote-model', name: 'Remote model' }];
72
+ const refresh = () => models.refresh({ providers: ['opencode'], allowNetwork: true, force: true, signal: AbortSignal.timeout(5000) });
73
+ expect((await refresh()).errors.size).toBe(0);
74
+ expect(requests).toEqual([{ url: '/api/models/providers/opencode', etag: '"old-catalog"' }]);
75
+ expect(models.getModel('opencode', cached.id)).toBeUndefined();
76
+ expect(models.getModel('opencode', remoteModels[0].id)).toBeDefined();
77
+
78
+ responseStatus = 304;
79
+ expect((await refresh()).errors.size).toBe(0);
80
+ expect(requests.at(-1).etag).toBe('"upgrade-catalog"');
81
+ // A non-retryable HTTP error makes failure deterministic without waiting for backoff.
82
+ responseStatus = 403;
83
+ expect((await refresh()).errors.has('opencode')).toBe(true);
84
+ expect(models.getModel('opencode', remoteModels[0].id)).toBeDefined();
85
+ expect(models.getModel('opencode', 'upgrade-custom-model')?.name).toBe('My custom model');
86
+ expect(models.getModel('opencode', flash.id)?.name).toBe('My Flash override');
87
+ expect(models.getModel('opencode', 'deepseek-v4-flash-free')).toBeUndefined();
88
+ expect(await readFile(options.modelsPath, 'utf8')).toBe(customConfig);
89
+ await models.removeRuntimeApiKey('opencode');
90
+
91
+ const restarted = await ModelRuntime.create(options);
92
+ expect(restarted.getModel('opencode', remoteModels[0].id)).toBeDefined();
93
+ expect(restarted.getModel('opencode', 'upgrade-custom-model')).toBeDefined();
94
+ expect(restarted.getModel('opencode', 'deepseek-v4-flash-free')).toBeUndefined();
95
+
96
+ // Removal from the bundled catalog must not blacklist an explicit user model.
97
+ const explicit = JSON.parse(customConfig);
98
+ explicit.providers.opencode.models.push({ ...explicit.providers.opencode.models[0], id: 'deepseek-v4-flash-free' });
99
+ await writeFile(options.modelsPath, JSON.stringify(explicit));
100
+ const withExplicitModel = await ModelRuntime.create(options);
101
+ expect(withExplicitModel.getModel('opencode', 'deepseek-v4-flash-free')?.name).toBe('My custom model');
102
+ }, 30_000);
103
+
104
+ it.each(['deepseek-v4-flash', 'deepseek-v4-flash-free'])('preserves a pre-upgrade v3 session and settings selecting %s', async (modelId) => {
105
+ root = await mkdtemp(join(tmpdir(), 'pichamber-sdk-session-'));
106
+ const cwd = join(root, 'project');
107
+ const agentDir = join(root, 'agent');
108
+ const sessionDir = getPiSessionDirectory({ cwd, agentDir });
109
+ await mkdir(cwd, { recursive: true });
110
+ await mkdir(sessionDir, { recursive: true });
111
+ const timestamp = '2026-08-07T12:00:00.000Z';
112
+ const sessionId = '26e6d482-9b6d-4b26-bc80-1a6b13b2b87c';
113
+ const sessionFile = join(sessionDir, `2026-08-07T12-00-00-000Z_${sessionId}.jsonl`);
114
+ // Literal v3 records preserve the old wire format independently of the new writer.
115
+ const entries = [
116
+ { type: 'session', version: 3, id: sessionId, timestamp, cwd },
117
+ { type: 'model_change', id: '00000001', parentId: null, timestamp, provider: 'opencode', modelId },
118
+ { type: 'thinking_level_change', id: '00000002', parentId: '00000001', timestamp, thinkingLevel: 'low' },
119
+ { type: 'message', id: '00000003', parentId: '00000002', timestamp, message: { role: 'user', content: 'Existing question', timestamp: Date.parse(timestamp) } },
120
+ { type: 'message', id: '00000004', parentId: '00000003', timestamp, message: {
121
+ role: 'assistant', content: [{ type: 'text', text: 'Existing answer' }], provider: 'opencode', model: modelId, api: 'openai-completions', stopReason: 'stop', timestamp: Date.parse(timestamp),
122
+ usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, totalTokens: 15, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
123
+ } },
124
+ { type: 'custom', id: '00000005', parentId: '00000004', timestamp, customType: 'upgrade-extension', data: { enabled: true } },
125
+ { type: 'label', id: '00000006', parentId: '00000005', timestamp, targetId: '00000003', label: 'Existing checkpoint' },
126
+ { type: 'session_info', id: '00000007', parentId: '00000006', timestamp, name: 'Existing chat' },
127
+ ];
128
+ // Also covers the upstream fix for a session saved without a final newline.
129
+ const original = entries.map((entry) => JSON.stringify(entry)).join('\n');
130
+ await writeFile(sessionFile, original);
131
+ const settingsFile = join(agentDir, 'settings.json');
132
+ const settings = JSON.stringify({ defaultProvider: 'opencode', defaultModel: modelId, defaultThinkingLevel: 'low', compaction: { enabled: false } });
133
+ await writeFile(settingsFile, settings);
134
+
135
+ runtime = await createPiSessionRuntime({ cwd, agentDir, sessionFile });
136
+ expect(runtime.session.sessionId).toBe(sessionId);
137
+ expect(runtime.session.model?.id).not.toBe('deepseek-v4-flash-free');
138
+ expect(runtime.session.messages.map((message) => message.content)).toEqual(['Existing question', [{ type: 'text', text: 'Existing answer' }]]);
139
+ const manager = runtime.session.sessionManager;
140
+ expect(manager.getSessionName()).toBe('Existing chat');
141
+ expect(manager.getLabel('00000003')).toBe('Existing checkpoint');
142
+ expect(manager.getEntry('00000005').data).toEqual({ enabled: true });
143
+ // The SDK repairs only the missing line delimiter when opening the file.
144
+ expect(await readFile(sessionFile, 'utf8')).toBe(`${original}\n`);
145
+ manager.appendSessionInfo('Renamed after upgrade');
146
+ await runtime.dispose();
147
+ runtime = undefined;
148
+
149
+ const saved = await readFile(sessionFile, 'utf8');
150
+ expect(saved.startsWith(`${original}\n`)).toBe(true);
151
+ const reopened = SessionManager.open(sessionFile, sessionDir, cwd);
152
+ expect(reopened.getSessionId()).toBe(sessionId);
153
+ expect(reopened.getSessionName()).toBe('Renamed after upgrade');
154
+ expect(reopened.getEntries().slice(0, entries.length - 1)).toEqual(entries.slice(1));
155
+ expect(await readFile(settingsFile, 'utf8')).toBe(settings);
156
+ }, 30_000);
157
+ });