@pi-chamber/web 1.0.2-rc.1 → 1.0.3-rc.1

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 (58) hide show
  1. package/dist/assets/{DiagramView-GUJij-1P.js → DiagramView-CXjieF51.js} +1 -1
  2. package/dist/assets/DiffView-CXg8TAtI.js +18 -0
  3. package/dist/assets/{FileSaveConflictDialog-Ci6WdSiS.js → FileSaveConflictDialog-a-HOCgyP.js} +1 -1
  4. package/dist/assets/{FilesView-DBiWEo71.js → FilesView-Dcd9ltOX.js} +1 -1
  5. package/dist/assets/{GitView-DVyhqN5s.js → GitView-DF2nsuSA.js} +3 -3
  6. package/dist/assets/{JsonTreeView-BaU7aAUq.js → JsonTreeView-BRU2mRTd.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-6NBJLtEr.js → MarkdownRendererImpl-CeYMkg1A.js} +5 -5
  8. package/dist/assets/{PatchDiff-CvptevA2.js → PatchDiff-kSTpjhu6.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-Cqp5FVCP.js → SessionSwitcherContent-BsXDFt24.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-CRVJU16x.js → SessionSwitcherDropdown-D8fSObHr.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-CsFxImPI.js → SessionUnreadDot-BpsHyrri.js} +1 -1
  12. package/dist/assets/SettingsView-OEl7QmXC.js +6 -0
  13. package/dist/assets/{SettingsWindow-geMUhnxd.js → SettingsWindow-BMBCj_L_.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-BLGl2mNt.js → ToolOutputDialog-KOVdmTqm.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-BVeL1IuE.js → ToolPartDiffPreview-B9xuVvkm.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-9kAZ96se.js → VirtualizedFileDiff-CV_Cpmqu.js} +4 -4
  17. package/dist/assets/{collapsible-BencOwkW.js → collapsible-BH1vXEAI.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-C8vH0vcM.js → computeVirtualFileMetrics-yHZbtf5H.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-B6e3cTcl.js → contextFileOpenGuard-BA2pkQY_.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-B6w5GMNU.js → gitStatusPredicates-CpGQLvMK.js} +1 -1
  21. package/dist/assets/index-5fyXnZFi.css +1 -0
  22. package/dist/assets/{index-CpSdU-d4.js → index-C-sV_9sb.js} +3 -3
  23. package/dist/assets/{index-BifnX1Mp.js → index-D_FGGnQQ.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-BepQ1JHv.js → isDiffPlainText-BNyusJZz.js} +1 -1
  25. package/dist/assets/{isFilePlainText-CA1KFaTm.js → isFilePlainText-CMAUe7qD.js} +1 -1
  26. package/dist/assets/{main-dhVDQIHu.js → main-BMLgZ5yn.js} +2 -2
  27. package/dist/assets/{main-TzeSIx1W.js → main-DNq1n9F_.js} +3 -3
  28. package/dist/assets/{markdownCore-BztwD2c9.js → markdownCore-CZWcaNr2.js} +2 -2
  29. package/dist/assets/{miniChat-smqdx0Y7.js → miniChat-B2AgUZqL.js} +2 -2
  30. package/dist/assets/{mobile-BV-WCEiE.js → mobile-BsGiRUUg.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-DKmb9oa7.js → renderElectronMiniChatApp-UV9dnnbf.js} +2 -2
  32. package/dist/assets/renderMobileApp-BMifduGA.js +11 -0
  33. package/dist/assets/runtimeEndpointReset-CkvC02dQ.js +53 -0
  34. package/dist/assets/{runtimeSurface-Bm6cRkok.js → runtimeSurface-BdndJV2m.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-Dq7xKVjh.js → useAppFontEffects-CclUs9KY.js} +98 -98
  36. package/dist/assets/{useFilesViewSearch-Bvlo7C3a.js → useFilesViewSearch-CI5Gy1cp.js} +1 -1
  37. package/dist/assets/{usePushVisibilityBeacon-BY4xtozp.js → usePushVisibilityBeacon-aDmGZrTW.js} +3 -3
  38. package/dist/assets/{useSwitcherItems-CkE242zK.js → useSwitcherItems-BZKyNjhp.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-Bv6kN79m.js → vendor-codemirror-language-data-C6LBD7qA.js} +2 -2
  40. package/dist/assets/{web-components-CCiRgoOw.js → web-components-Cdnmh4Xb.js} +4 -4
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/lib/pi/model-config-store.js +146 -20
  46. package/server/lib/pi/model-config-store.test.js +153 -21
  47. package/server/lib/pi/routes.js +42 -1
  48. package/server/lib/pi/routes.test.js +104 -2
  49. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -2
  50. package/server/lib/pi/session-daemon/session-daemon.js +322 -58
  51. package/server/lib/pi/session-daemon/session-daemon.test.js +335 -0
  52. package/server/lib/pi/session-daemon/session-failed-create-cleanup.test.js +372 -0
  53. package/server/lib/pi/session-persistence-gap.test.js +731 -0
  54. package/dist/assets/DiffView-BZ487Bhh.js +0 -18
  55. package/dist/assets/SettingsView-ppaIrPry.js +0 -2
  56. package/dist/assets/index-Dwz16owi.css +0 -1
  57. package/dist/assets/renderMobileApp-D3dtjeaE.js +0 -11
  58. package/dist/assets/runtimeEndpointReset-C1EENUlq.js +0 -53
@@ -36,12 +36,13 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
36
36
  - The public health route deliberately whitelists its response fields (state, protocol version, capability names, and the opaque public `streamEpoch`). It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
37
37
  - 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.
38
38
  - 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.
39
- - 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/sendReceipt/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.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. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
39
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/models.add/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.models.add` appends one model (`id` required; optional `name`, `reasoning`, `thinkingLevelMap`, `input`, `contextWindow`, and `maxTokens`) atomically without replacing the provider. The model configuration store owns normalization and validation. The daemon rejects duplicate or unavailable live models, seeds a missing file provider only from authoritative live metadata when safely representable, rejects extension registrations with an explicit `models` array, and uses the same deferred recreation as `providers.models.set`. A successful recreation publishes a provider-catalog invalidation so connected settings views load the new authoritative catalog. Provider edits preserve unexposed existing model metadata server-side while public projections remain credential-blind. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal of persisted sessions, and clear on explicit session deletion, confirmed ephemeral expiration (which publishes `session.deleted`), or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
40
40
  - Each event and reconnect snapshot has a monotonic sequence. Replay is capability-negotiated: the subscriber stamps its cursor with the `streamEpoch` it was established under, a marker-less cursor fails as `DAEMON_PROTOCOL_MISMATCH`, and a cursor from a retired epoch resyncs from a snapshot instead of replaying — even when this daemon's sequence numerically overtook the old cursor, replaying from it would silently skip the head of the new space. Every event, snapshot, and health result carries an opaque random `streamEpoch` regenerated on every daemon process start (never derived from daemon id, profile key, pid, or any private identity); `runtime.health` advertises the `events.streamEpoch` capability, session reads stamp it so clients can reject stale-epoch responses, and a snapshot published because the cursor could not be replayed is additionally stamped `resync: true` as a recovery baseline. A reconnect replays the retained contiguous suffix after its cursor when available, otherwise it receives an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions. The suffix lives in `session-replay.js` and is bounded by both count (1,024 events) and encoded wire bytes (8 MiB): eviction removes whole oldest events first and never truncates content, each event is serialized once and the cached line is reused for live broadcast and replay, and live delivery stays full-fidelity even for events too large to retain. The byte budget counts encoded wire bytes, not heap, and snapshots assign sequence numbers without replay insertion so numeric gaps from private snapshots are intentional. A single oversized event clears the retained suffix without being retained, an empty ring never replays, and a cursor beyond the latest sequence resynchronizes from a snapshot; contiguity is judged on the global suffix while delivery stays session-filtered, so a filtered client never replays through a gap. A missed suffix recovers through `session.snapshot` plus `sessions.open` hydrate, which re-reads persisted entries for tool finals and lifecycle.
41
41
  - Prompt, steer, and follow-up requests acknowledge acceptance only after the Pi SDK preflight signal (session.prompt with preflightResult(true)); the daemon owns the still-running turn promise and publishes any asynchronous rejection as `session.error`. A preflight rejection (preflightResult(false)) propagates as the request rejection so dedup never caches it as accepted and the operation id stays reusable. Plain text uses prompt() with expandPromptTemplates:false and source:extension plus images; slash input keeps source:rpc. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata per delivery kind (`prompt`/`steer`/`followUp`) and adds it to the matching user start. SDK `queue_update` shrink is the authoritative owner of the next user start (steering drains before followUp regardless of send order); direct starts emit no shrink and fall back to oldest-by-generation. Requested `steer`/`followUp` always travels as SDK `streamingBehavior` (ignored while idle) so an idle arrival that races another sender still queues. Retention is decided at resolution from authoritative runtime state (`isStreaming` or SDK queue non-empty, never for handled extension commands); only queued resolutions keep metadata until their per-delivery start, all other completions clean a still-pending entry (an extension command that never emits a user start). The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
42
42
  - Send-intent deduplication (`send-operation-registry.js`) owns the authoritative execution boundary for prompt/steer/followUp: the client labels each intent with a stable `operationId` and the health-verified `streamEpoch`, the daemon claims `kind + sessionId + operationId + streamEpoch` BEFORE Pi activation, and an identical same-epoch retry returns the original acceptance receipt (`{ accepted, messageId, deduplicated: true }`) without invoking Pi again. A concurrent duplicate of a still-pending intent shares the original outcome; the same full key with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). An intent from another daemon lifetime fails as `STALE_STREAM_EPOCH` (HTTP 409) before Pi or attachment-consumption side effects. The same id on a different kind or session is a different intent and executes independently, never a mismatch. Only acceptances are retained: request-path rejections happen before Pi runs (nothing executed, id reusable) while pending duplicates still share the original rejection, and every claim settles so pending duplicates never hang. Retention is bounded: receipts expire after `sendOperationTtlMs` (default ten minutes) and at most 1,024 accepted receipts are retained (oldest evicted to a bounded expired tombstone); pending claims are bounded separately (256 entries, never expired while active, new distinct pending past the bound fails as `SESSION_BUSY`). An expired or evicted id reports `expired` and a retry with the same id fails as `OPERATION_EXPIRED` (HTTP 410), never an automatic re-execution — callers must use a new operation id. `sessions.sendReceipt` is the exact read-only receipt lookup for an uncertain send: it requires the full `kind + sessionId + operationId + streamEpoch` identity; a missing epoch returns `unknown`, never invokes Pi, and returns `accepted` (retained receipt), `pending`, `expired` (seen but retention gone, outcome unknown, never assume success), or `unknown` (never seen in this retention window, tombstone pressure, post-restart, or rejected before Pi ran). The registry is in-memory per daemon process with bounded tombstones (`expired` degrades to `unknown` under pressure): there is no lifetime receipt guarantee, only within the retention window. A restart loses receipts, but the replacement daemon rejects the retired epoch instead of replaying the old intent. Receipt lookup and replay protection remain separate read-only contracts.
43
43
  - 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.
44
- - 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.
44
+ - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). View-only access (`sessions.open`, `sessions.messages`, `sessions.tree`, plus navigate/fork/clone/abort/model/thinking/rename settlement) arms the same lifetime through `touchIdleDisposal`, so browsing old sessions without prompting cannot grow the registry unboundedly while the UI keeps only a bounded transcript cache. Disposal never deletes Pi JSONL; when the assigned session file exists on disk, the daemon remembers the selected session file and recreates that runtime on the next private prompt or open. When the assigned JSONL is positively absent (stat reports ENOENT only, determined after dispose while the resident lease is still held and before any release), the session is ephemeral: after a successful lease release the disposal clears matching dormant state plus the same safe per-session auxiliary state as explicit deletion where applicable (messageEntryAliases for cwd/session, retry/compaction/run-start/shutdown) and publishes the existing `session.deleted` event so connected clients remove it. Publication happens only after a successful release, which closes the cross-daemon recreate race. A missing/throwing getSessionFile or a non-ENOENT stat failure cannot prove absence and never claims deletion, a failed disposal retains ownership (registry entry, lease, and global runtime) without emitting deletion, and persisted sessions keep dormant state for reopen. The touch clears first and re-arms only when the session is resident and idle-safe, so a read cannot race a pending operation and a repeated open extends the deadline. Agent and compaction starts cancel pending disposal, and prompt/compact entry clears it before activation. The timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative, while a send is in flight (`activeSessionInputs`), while a resource reload is pending or running, while a provider retry is scheduled, or while compaction is running/retrying; pending extension dialogs are instead cancelled with an authoritative dismiss event. A read or prompt that arrives during an in-flight disposal waits for it and reopens from JSONL instead of adopting a dying runtime. There is deliberately no acquisition-path eviction: capacity pressure alone never disposes entries that are actively mounting.
45
+ - Ephemeral sessions: Pi's `SessionManager` defers JSONL creation until the first assistant message, so `sessions.create` alone stays ephemeral (untouched sessions vanish on restart by design). A rejected first prompt likewise persists nothing: the runtime stays resident and retryable until normal idle disposal, which reports the session as deleted when its assigned JSONL is positively absent (see above). Failed `sessions.create` cancellation and lease-acquire failures dispose without persisting and release (or never hold) the lease. Model/thinking setup failures after lease acquisition dispose first and release only after successful disposal: a disposal rejection retains `{ runtime, cwd, sessionId }` in daemon-owned pending failed-create state without releasing ownership, registering the runtime, or installing dormant state, while still throwing the original model/thinking error; `sessions.delete` retries its session entry and daemon stop retries all entries (dispose-first, release-after-success, failed retries stay pending without releasing ownership, entries removed only when still current, disposal exactly once).
45
46
  - 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.
46
47
  - 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`.
47
48
  - 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.
@@ -245,12 +245,13 @@ export function createSessionDaemon({
245
245
  };
246
246
  const releaseResidentLease = async ({ cwd: leaseCwd, sessionId }) => {
247
247
  const owner = leaseOwner();
248
- if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return;
248
+ if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return { released: false };
249
249
  try {
250
- await releaseSessionLease({ agentDir, cwd: leaseCwd, sessionId, owner });
250
+ return await releaseSessionLease({ agentDir, cwd: leaseCwd, sessionId, owner });
251
251
  } catch {
252
252
  // Lease release is best-effort; a stale lease is reclaimable by the
253
253
  // next owner once this daemon pid is dead.
254
+ return { released: false };
254
255
  }
255
256
  };
256
257
  let runtimeRegistry;
@@ -337,6 +338,7 @@ export function createSessionDaemon({
337
338
  // trigger one more rebuild instead of being lost behind the first one.
338
339
  let pendingRuntimeRecreation = false;
339
340
  let runtimeRecreationRevision = 0;
341
+ let pendingProviderCatalogRevision = 0;
340
342
  let runtimeRecreationTask = null;
341
343
  // Pi emits each user message start before its persisted entry is readable.
342
344
  // Keep prompt file metadata keyed by delivery kind so a queued followUp
@@ -606,9 +608,15 @@ export function createSessionDaemon({
606
608
  const rememberRuntimeSession = () => {
607
609
  const sessionId = runtime?.session?.sessionId;
608
610
  if (typeof sessionId !== 'string' || sessionId.length === 0) return;
611
+ let sessionFile;
612
+ try {
613
+ sessionFile = runtime.session.sessionManager?.getSessionFile?.();
614
+ } catch {
615
+ sessionFile = undefined;
616
+ }
609
617
  dormantSession = {
610
618
  sessionId,
611
- sessionFile: runtime.session.sessionManager?.getSessionFile?.(),
619
+ sessionFile,
612
620
  cwd: runtime.cwd || activeDirectory || cwd,
613
621
  };
614
622
  };
@@ -671,7 +679,37 @@ export function createSessionDaemon({
671
679
 
672
680
  const idleDisposeTimers = new Map();
673
681
  const activeSessionRequests = new Map();
674
-
682
+ // Failed-create cleanup: when model/thinking setup fails after the
683
+ // resident lease is acquired and the dispose-first cleanup rejects,
684
+ // ownership stays held. One entry per session,
685
+ // `{ runtime, cwd, sessionId }`, retried by delete (per-session) or stop
686
+ // (all sessions). Disposal is attempted first and the lease is released
687
+ // only after successful disposal; a failed retry stays pending without
688
+ // releasing ownership. Entries are removed only when the drained object
689
+ // is still current, so a newer owner's record is never erased. The
690
+ // failed runtime is never registered and never installs dormant state.
691
+ const pendingFailedCreateCleanups = new Map();
692
+ const pendingFailedCreateDraining = new Set();
693
+ const drainPendingFailedCreateCleanup = async (sessionId) => {
694
+ const pending = pendingFailedCreateCleanups.get(sessionId);
695
+ if (!pending) return true;
696
+ if (pendingFailedCreateDraining.has(sessionId)) return false;
697
+ pendingFailedCreateDraining.add(sessionId);
698
+ try {
699
+ try {
700
+ await pending.runtime.dispose?.();
701
+ } catch {
702
+ return false;
703
+ }
704
+ await releaseResidentLease({ cwd: pending.cwd, sessionId: pending.sessionId });
705
+ if (pendingFailedCreateCleanups.get(sessionId) === pending) {
706
+ pendingFailedCreateCleanups.delete(sessionId);
707
+ }
708
+ return true;
709
+ } finally {
710
+ pendingFailedCreateDraining.delete(sessionId);
711
+ }
712
+ };
675
713
  const isValidIdleSessionId = (sessionId) => typeof sessionId === 'string' && sessionId.length > 0;
676
714
 
677
715
  const clearIdleDisposal = (sessionId) => {
@@ -800,8 +838,13 @@ export function createSessionDaemon({
800
838
  const revision = runtimeRecreationRevision;
801
839
  await disposeRuntime();
802
840
  if (!pendingRuntimeRecreation) break;
803
- await ensureRuntime();
841
+ const recreatedRuntime = await ensureRuntime();
804
842
  recreated = true;
843
+ if (pendingProviderCatalogRevision > 0 && pendingProviderCatalogRevision <= revision) {
844
+ const publishedRevision = pendingProviderCatalogRevision;
845
+ publish('extension.catalog', { providers: true }, recreatedRuntime?.session?.sessionId, recreatedRuntime?.cwd);
846
+ if (pendingProviderCatalogRevision === publishedRevision) pendingProviderCatalogRevision = 0;
847
+ }
805
848
  if (revision === runtimeRecreationRevision) pendingRuntimeRecreation = false;
806
849
  }
807
850
  return recreated;
@@ -813,10 +856,11 @@ export function createSessionDaemon({
813
856
  return tracked;
814
857
  };
815
858
 
816
- const scheduleRuntimeRecreation = async () => {
859
+ const scheduleRuntimeRecreation = async ({ providersChanged = false } = {}) => {
817
860
  const deferred = hasUnsafeRuntime();
818
861
  pendingRuntimeRecreation = true;
819
862
  runtimeRecreationRevision += 1;
863
+ if (providersChanged) pendingProviderCatalogRevision = runtimeRecreationRevision;
820
864
  if (deferred) {
821
865
  void flushPendingRuntimeRecreation().catch(() => {});
822
866
  return true;
@@ -921,6 +965,20 @@ export function createSessionDaemon({
921
965
  pendingResourceReloads.delete(targetRuntime);
922
966
  resourceReloadsByRuntime.delete(targetRuntime);
923
967
  const tracked = (async () => {
968
+ // Capture the assigned JSONL path before disposal. Pi's
969
+ // SessionManager defers JSONL creation until the first assistant
970
+ // message, so `sessions.create` alone (or a session whose first
971
+ // prompt was rejected before anything persisted) stays ephemeral:
972
+ // the runtime stays resident and retryable until this normal idle
973
+ // disposal, which then reports the session as deleted when its
974
+ // assigned JSONL is positively absent.
975
+ let assignedSessionFile;
976
+ try {
977
+ assignedSessionFile = targetRuntime.session?.sessionManager?.getSessionFile?.();
978
+ } catch {
979
+ assignedSessionFile = undefined;
980
+ }
981
+ const targetCwd = targetRuntime.cwd || activeDirectory || cwd;
924
982
  try {
925
983
  if (targetRuntime === runtime) rememberRuntimeSession();
926
984
  // Pending extension dialogs are cancelled with an authoritative
@@ -928,11 +986,46 @@ export function createSessionDaemon({
928
986
  // disposed runtime.
929
987
  clearExtensionState(sessionId);
930
988
  await runtimeRegistry.dispose(targetRuntime);
931
- await releaseResidentLease({ cwd: targetRuntime.cwd || activeDirectory || cwd, sessionId });
989
+ // Positively determine ephemerality while the resident lease is
990
+ // still held, before any release. A stat success means persisted;
991
+ // ENOENT means the assigned JSONL never reached disk; any other
992
+ // stat failure, a missing path, or a throwing getSessionFile
993
+ // cannot prove absence and never claims deletion. Determining
994
+ // here (after dispose, before release) keeps the check
995
+ // authoritative: no cross-daemon owner can interleave a recreate
996
+ // while this lease is held.
997
+ let ephemeral = false;
998
+ if (typeof assignedSessionFile === 'string' && assignedSessionFile.length > 0) {
999
+ try {
1000
+ await stat(assignedSessionFile);
1001
+ } catch (error) {
1002
+ if (error?.code === 'ENOENT') ephemeral = true;
1003
+ }
1004
+ }
1005
+ const releaseResult = await releaseResidentLease({ cwd: targetCwd, sessionId });
1006
+ const released = releaseResult?.released === true;
932
1007
  shutdownRequestedBySession.delete(sessionId);
933
1008
  compactionStateBySession.delete(sessionId);
934
1009
  if (targetRuntime === runtime) runtime = undefined;
1010
+ // Publish only after a successful lease release so a
1011
+ // cross-daemon recreate cannot slip between release and event.
1012
+ // Persisted sessions keep dormant state for reopen; an
1013
+ // unreleased or unknown (non-ENOENT/missing) session never claims
1014
+ // deletion. A confirmed ephemeral expiration clears the same safe
1015
+ // per-session auxiliary state as explicit deletion where
1016
+ // applicable (aliases, retry/compaction/run-start/shutdown).
1017
+ if (ephemeral && released) {
1018
+ if (dormantSession?.sessionId === sessionId) dormantSession = undefined;
1019
+ messageEntryAliases.clearSession({ cwd: targetCwd, sessionId });
1020
+ retryStateBySession.delete(sessionId);
1021
+ compactionStateBySession.delete(sessionId);
1022
+ activeRunStartedAt.delete(sessionId);
1023
+ shutdownRequestedBySession.delete(sessionId);
1024
+ publish('session.deleted', {}, sessionId, targetCwd);
1025
+ }
935
1026
  } catch {
1027
+ // A failed disposal retains ownership (registry entry, lease, and
1028
+ // global runtime are all still held) and never emits deletion.
936
1029
  publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId, targetRuntime.cwd);
937
1030
  } finally {
938
1031
  disposingSessionIds.delete(sessionId);
@@ -977,6 +1070,12 @@ export function createSessionDaemon({
977
1070
  scheduleIdleDisposal(sessionId);
978
1071
  };
979
1072
 
1073
+ // Idle re-arm must never throw: releaseSessionAccess runs in the request
1074
+ // dispatch `finally`, so a cleanup throw would mask the original error.
1075
+ const safeTouchIdleDisposal = (sessionId) => {
1076
+ try { touchIdleDisposal(sessionId); } catch {}
1077
+ };
1078
+
980
1079
  // Narrow session-access guard for request dispatch. Each in-flight
981
1080
  // session-scoped command holds one refcount while it activates and uses
982
1081
  // the runtime; the idle timer stays cleared until the last holder
@@ -999,7 +1098,7 @@ export function createSessionDaemon({
999
1098
  return;
1000
1099
  }
1001
1100
  activeSessionRequests.delete(sessionId);
1002
- touchIdleDisposal(sessionId);
1101
+ safeTouchIdleDisposal(sessionId);
1003
1102
  };
1004
1103
 
1005
1104
  const sessionIdForIdleGuard = (message) => {
@@ -1710,19 +1809,45 @@ export function createSessionDaemon({
1710
1809
  } else if (payload.title && newRuntime.session?.sessionManager?.appendSessionInfo) {
1711
1810
  newRuntime.session.sessionManager.appendSessionInfo(payload.title.trim());
1712
1811
  }
1713
- if (result?.cancelled) throw new SessionDaemonProtocolError('SESSION_CREATE_CANCELLED', 'Pi cancelled session creation.');
1812
+ if (result?.cancelled) {
1813
+ try { await newRuntime.dispose?.(); } catch { /* the cancelled create owns nothing */ }
1814
+ throw new SessionDaemonProtocolError('SESSION_CREATE_CANCELLED', 'Pi cancelled session creation.');
1815
+ }
1714
1816
  try {
1715
1817
  await acquireResidentLease({ cwd: targetCwd, sessionId: newRuntime.session.sessionId });
1716
1818
  } catch (error) {
1717
1819
  try { await newRuntime.dispose?.(); } catch { /* the failed create owns nothing */ }
1718
1820
  throw error;
1719
1821
  }
1720
- if (payload.model) {
1721
- await setSessionModel(newRuntime, payload.model);
1722
- publishSessionModel(newRuntime.session, newRuntime.session.sessionId, targetCwd);
1723
- }
1724
- if (payload.thinking !== undefined) {
1725
- applyThinking(newRuntime, payload.thinking, newRuntime.session.sessionId, targetCwd);
1822
+ try {
1823
+ if (payload.model) {
1824
+ await setSessionModel(newRuntime, payload.model);
1825
+ publishSessionModel(newRuntime.session, newRuntime.session.sessionId, targetCwd);
1826
+ }
1827
+ if (payload.thinking !== undefined) {
1828
+ applyThinking(newRuntime, payload.thinking, newRuntime.session.sessionId, targetCwd);
1829
+ }
1830
+ } catch (error) {
1831
+ const failedSessionId = newRuntime.session?.sessionId;
1832
+ const failedCwd = targetCwd;
1833
+ try {
1834
+ await newRuntime.dispose?.();
1835
+ } catch {
1836
+ // Dispose-first cleanup rejected: retain ownership for a later
1837
+ // delete/stop retry. Do not release the lease, install dormant
1838
+ // state, or register the runtime. The original model/thinking
1839
+ // error stays authoritative, not the disposal error.
1840
+ if (typeof failedSessionId === 'string' && failedSessionId.length > 0) {
1841
+ pendingFailedCreateCleanups.set(failedSessionId, {
1842
+ runtime: newRuntime,
1843
+ cwd: failedCwd,
1844
+ sessionId: failedSessionId,
1845
+ });
1846
+ }
1847
+ throw error;
1848
+ }
1849
+ await releaseResidentLease({ cwd: failedCwd, sessionId: failedSessionId });
1850
+ throw error;
1726
1851
  }
1727
1852
  runtimeRegistry.register(newRuntime, { cwd: targetCwd });
1728
1853
  runtime = newRuntime;
@@ -1888,7 +2013,109 @@ export function createSessionDaemon({
1888
2013
  }
1889
2014
  // ModelRuntime snapshots models.json at construction. Persist the new
1890
2015
  // catalog now, then recreate resident runtimes only at a safe edge.
1891
- const deferred = await scheduleRuntimeRecreation();
2016
+ const deferred = await scheduleRuntimeRecreation({ providersChanged: true });
2017
+ return { config, ...(deferred ? { deferred: true } : {}) };
2018
+ };
2019
+
2020
+ const ADD_MODEL_API_TYPES = new Set(['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai']);
2021
+
2022
+ const addProviderModel = async (payload) => {
2023
+ if (!payload || typeof payload !== 'object' || typeof payload.providerId !== 'string') {
2024
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider model request is invalid.');
2025
+ }
2026
+ const providerId = payload.providerId;
2027
+ const trimmedId = typeof payload.model?.id === 'string' ? payload.model.id.trim() : '';
2028
+ if (!trimmedId) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider model request is invalid.');
2029
+ const activeRuntime = await ensureRuntime();
2030
+ const modelRuntime = activeRuntime?.session?.modelRuntime;
2031
+ if (!modelRuntime) {
2032
+ throw new SessionDaemonProtocolError('PROVIDER_NOT_FOUND', 'The requested provider is unavailable.');
2033
+ }
2034
+ if (typeof modelRuntime.getError?.() === 'string') {
2035
+ throw new SessionDaemonProtocolError('PI_MODEL_CONFIG_INVALID', 'Pi models configuration is invalid.');
2036
+ }
2037
+ // Pi 0.85.1 composeModelProvider layers models.json over native/base
2038
+ // providers, so manual additions remain effective there. Extension
2039
+ // registrations without an explicit `models` array do not hide the file
2040
+ // entry either. Reject only when an extension defines its own `models`
2041
+ // array, which would replace/hide the models.json addition.
2042
+ if (typeof modelRuntime.getRegisteredProviderConfig === 'function') {
2043
+ const extensionConfig = modelRuntime.getRegisteredProviderConfig(providerId);
2044
+ if (extensionConfig && Array.isArray(extensionConfig.models)) {
2045
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Extension-registered providers with explicit models cannot be extended with manual models.');
2046
+ }
2047
+ }
2048
+ const liveProvider = typeof modelRuntime.getProvider === 'function' ? modelRuntime.getProvider(providerId) : undefined;
2049
+ if (!liveProvider) {
2050
+ throw new SessionDaemonProtocolError('PROVIDER_NOT_FOUND', 'The requested provider is unavailable.');
2051
+ }
2052
+ // Duplicate trimmed IDs would shadow the authoritative catalog entry.
2053
+ // Check live first (Pi ModelRuntime.getModel is exact), then the file.
2054
+ // Live lookup failures propagate instead of masquerading as empty success.
2055
+ if (typeof modelRuntime.getModel === 'function' && modelRuntime.getModel(providerId, trimmedId)) {
2056
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The model already exists for this provider.');
2057
+ }
2058
+ const listed = typeof modelRuntime.getModels === 'function' ? modelRuntime.getModels(providerId) : [];
2059
+ const liveModels = Array.isArray(listed) ? listed.filter((entry) => entry && entry.provider === providerId) : [];
2060
+ if (liveModels.some((entry) => typeof entry.id === 'string' && entry.id.trim() === trimmedId)) {
2061
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The model already exists for this provider.');
2062
+ }
2063
+ let existingConfig = null;
2064
+ try {
2065
+ existingConfig = await modelConfigStore.get(providerId);
2066
+ } catch (error) {
2067
+ if (error?.code === 'PI_MODEL_CONFIG_INVALID') {
2068
+ throw new SessionDaemonProtocolError('PI_MODEL_CONFIG_INVALID', 'Pi models configuration is invalid.');
2069
+ }
2070
+ throw error;
2071
+ }
2072
+ if (existingConfig && Array.isArray(existingConfig.models)
2073
+ && existingConfig.models.some((entry) => entry && typeof entry.id === 'string' && entry.id.trim() === trimmedId)) {
2074
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The model already exists for this provider.');
2075
+ }
2076
+ let seed;
2077
+ if (!existingConfig) {
2078
+ // Seed a missing models.json provider only from authoritative live
2079
+ // runtime metadata (Pi Model/Provider shapes) when every live model
2080
+ // agrees on one https baseUrl and one safely representable api.
2081
+ if (liveModels.length === 0) {
2082
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider cannot be seeded from live runtime metadata.');
2083
+ }
2084
+ const apis = new Set(liveModels.map((entry) => entry.api));
2085
+ const baseUrls = new Set(liveModels.map((entry) => entry.baseUrl));
2086
+ if (typeof liveProvider.baseUrl === 'string' && liveProvider.baseUrl.length > 0) baseUrls.add(liveProvider.baseUrl);
2087
+ if (apis.size !== 1 || baseUrls.size !== 1) {
2088
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider cannot be seeded from live runtime metadata.');
2089
+ }
2090
+ const [api] = [...apis];
2091
+ const [baseUrl] = [...baseUrls];
2092
+ const label = typeof liveProvider.name === 'string' ? liveProvider.name.trim() : '';
2093
+ if (typeof api !== 'string' || !ADD_MODEL_API_TYPES.has(api)
2094
+ || typeof baseUrl !== 'string' || !/^https?:\/\//.test(baseUrl) || baseUrl.length > 8_192
2095
+ || label.length === 0 || label.length > 256) {
2096
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider cannot be seeded from live runtime metadata.');
2097
+ }
2098
+ seed = { label, baseUrl: baseUrl.trim(), api };
2099
+ }
2100
+ let config;
2101
+ try {
2102
+ config = await modelConfigStore.addModel({
2103
+ providerId,
2104
+ model: payload.model,
2105
+ ...(seed ? { seed } : {}),
2106
+ });
2107
+ } catch (error) {
2108
+ if (error?.code === 'PI_MODEL_DUPLICATE') {
2109
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The model already exists for this provider.');
2110
+ }
2111
+ if (error?.code === 'PI_MODEL_CONFIG_INVALID') {
2112
+ throw new SessionDaemonProtocolError('PI_MODEL_CONFIG_INVALID', 'Pi models configuration is invalid.');
2113
+ }
2114
+ throw error;
2115
+ }
2116
+ // Same deferred recreation as models.set: ModelRuntime snapshots
2117
+ // models.json at construction, so busy runtimes rehydrate at idle.
2118
+ const deferred = await scheduleRuntimeRecreation({ providersChanged: true });
1892
2119
  return { config, ...(deferred ? { deferred: true } : {}) };
1893
2120
  };
1894
2121
 
@@ -2815,6 +3042,14 @@ export function createSessionDaemon({
2815
3042
  }
2816
3043
  };
2817
3044
 
3045
+ // Ephemeral sessions: Pi's SessionManager defers JSONL creation until the
3046
+ // first assistant message, so `sessions.create` alone stays ephemeral
3047
+ // (untouched sessions vanish on restart by design). A rejected first
3048
+ // prompt likewise persists nothing: the runtime stays resident and
3049
+ // retryable until normal idle disposal, which reports the session as
3050
+ // deleted when its assigned JSONL is positively absent (see
3051
+ // disposeIdleSessionRuntime).
3052
+
2818
3053
  const runSessionInput = async (payload, delivery) => {
2819
3054
  if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
2820
3055
  || typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
@@ -3024,15 +3259,18 @@ export function createSessionDaemon({
3024
3259
  // extension commands that resolve without starting an agent turn
3025
3260
  // (no agent_settled follows) as well as ordinary turn completion.
3026
3261
  if (!shutdownRequestedBySession.has(payload.sessionId)) {
3027
- touchIdleDisposal(payload.sessionId);
3262
+ safeTouchIdleDisposal(payload.sessionId);
3028
3263
  }
3029
- });
3264
+ }).catch(() => {});
3030
3265
  void flushPendingRuntimeRecreation().catch(() => {});
3031
3266
  });
3032
3267
  return { accepted: true, messageId };
3033
3268
  } catch (error) {
3034
3269
  endSessionInput(activeRuntime);
3035
- void flushPendingResourceReload(activeRuntime);
3270
+ // A rejected prompt persists nothing: the runtime stays resident and
3271
+ // retryable until normal idle disposal. The original error propagates
3272
+ // unchanged.
3273
+ void flushPendingResourceReload(activeRuntime).catch(() => {});
3036
3274
  void flushPendingRuntimeRecreation().catch(() => {});
3037
3275
  throw error;
3038
3276
  }
@@ -3059,46 +3297,59 @@ export function createSessionDaemon({
3059
3297
  const deleteSession = async (sessionId, requestedDirectory) => {
3060
3298
  // Idle protection is owned by the request-dispatch guard. The release
3061
3299
  // touch is a no-op once the runtime is gone, so deletion never re-arms.
3062
- const active = runtimeRegistry?.findBySessionId(sessionId);
3063
- let targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
3064
- const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
3065
- if (active) {
3066
- if (active.session?.isStreaming) await active.session.abort();
3067
- await runtimeRegistry?.dispose(active);
3068
- if (runtime === active) runtime = undefined;
3069
- }
3070
- if (active && typeof activeSessionFile === 'string' && activeSessionFile.length > 0) {
3071
- await rm(activeSessionFile, { force: true });
3072
- } else if (!active) {
3073
- const { target, directory } = await findPersistedSession(sessionId, targetDir);
3074
- targetDir = directory;
3075
- await acquireResidentLease({ cwd: targetDir, sessionId });
3076
- try {
3077
- await rm(target.path, { force: false });
3078
- } catch (error) {
3079
- await releaseResidentLease({ cwd: targetDir, sessionId });
3080
- throw error;
3300
+ try {
3301
+ // Retry a failed-create cleanup for this session before touching
3302
+ // persisted state: dispose first, release only after success. A
3303
+ // failed retry stays pending without releasing ownership, so delete
3304
+ // must not proceed to its own acquire/release while disposal fails.
3305
+ const failedCreateDrained = await drainPendingFailedCreateCleanup(sessionId);
3306
+ if (!failedCreateDrained) {
3307
+ throw new SessionDaemonProtocolError('RUNTIME_DISPOSAL_FAILED', 'The Pi session runtime could not be disposed.');
3308
+ }
3309
+ const active = runtimeRegistry?.findBySessionId(sessionId);
3310
+ let targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
3311
+ const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
3312
+ if (active) {
3313
+ if (active.session?.isStreaming) await active.session.abort();
3314
+ await runtimeRegistry?.dispose(active);
3315
+ if (runtime === active) runtime = undefined;
3081
3316
  }
3317
+ if (active && typeof activeSessionFile === 'string' && activeSessionFile.length > 0) {
3318
+ await rm(activeSessionFile, { force: true });
3319
+ } else if (!active) {
3320
+ const { target, directory } = await findPersistedSession(sessionId, targetDir);
3321
+ targetDir = directory;
3322
+ await acquireResidentLease({ cwd: targetDir, sessionId });
3323
+ try {
3324
+ await rm(target.path, { force: false });
3325
+ } catch (error) {
3326
+ await releaseResidentLease({ cwd: targetDir, sessionId });
3327
+ throw error;
3328
+ }
3329
+ }
3330
+ messageEntryAliases.clearSession({ cwd: active?.cwd || targetDir, sessionId });
3331
+ await releaseResidentLease({ cwd: active?.cwd || targetDir, sessionId });
3332
+ retryStateBySession.delete(sessionId);
3333
+ compactionStateBySession.delete(sessionId);
3334
+ activeRunStartedAt.delete(sessionId);
3335
+ shutdownRequestedBySession.delete(sessionId);
3336
+ sendGenerationBySession.delete(sessionId);
3337
+ settledSendGenerationBySession.delete(sessionId);
3338
+ pendingUserStartsBySession.delete(sessionId);
3339
+ queueSizesBySession.delete(sessionId);
3340
+ queueShrinkBySession.delete(sessionId);
3341
+ latestUserMessageIds.delete(sessionId);
3342
+ latestAssistantMessageIds.delete(sessionId);
3343
+ toolInputBySession.delete(sessionId);
3344
+ clearToolTimingsForSession(sessionId);
3345
+ // Explicit typed deletion: every connected and replaying client drops
3346
+ // catalog, transcript, activity, and caches. Archive and directory moves
3347
+ // keep the session id and never publish this event.
3348
+ publish('session.deleted', {}, sessionId, targetDir);
3349
+ } finally {
3350
+ // Deletion never re-arms idle lifetime.
3351
+ clearIdleDisposal(sessionId);
3082
3352
  }
3083
- messageEntryAliases.clearSession({ cwd: active?.cwd || targetDir, sessionId });
3084
- await releaseResidentLease({ cwd: active?.cwd || targetDir, sessionId });
3085
- retryStateBySession.delete(sessionId);
3086
- compactionStateBySession.delete(sessionId);
3087
- activeRunStartedAt.delete(sessionId);
3088
- shutdownRequestedBySession.delete(sessionId);
3089
- sendGenerationBySession.delete(sessionId);
3090
- settledSendGenerationBySession.delete(sessionId);
3091
- pendingUserStartsBySession.delete(sessionId);
3092
- queueSizesBySession.delete(sessionId);
3093
- queueShrinkBySession.delete(sessionId);
3094
- latestUserMessageIds.delete(sessionId);
3095
- latestAssistantMessageIds.delete(sessionId);
3096
- toolInputBySession.delete(sessionId);
3097
- clearToolTimingsForSession(sessionId);
3098
- // Explicit typed deletion: every connected and replaying client drops
3099
- // catalog, transcript, activity, and caches. Archive and directory moves
3100
- // keep the session id and never publish this event.
3101
- publish('session.deleted', {}, sessionId, targetDir);
3102
3353
  };
3103
3354
 
3104
3355
  const publishSessionEvent = (sessionId, event, directory = activeDirectory || cwd) => {
@@ -3472,7 +3723,7 @@ export function createSessionDaemon({
3472
3723
  'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
3473
3724
  'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
3474
3725
  'sessions.steer', 'sessions.followUp', 'sessions.sendReceipt', 'sessions.abort', 'sessions.setModel',
3475
- 'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
3726
+ 'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.models.add', 'providers.status', 'providers.login',
3476
3727
  'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
3477
3728
  'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
3478
3729
  'extensions.list', 'extensions.respond',
@@ -3577,6 +3828,11 @@ export function createSessionDaemon({
3577
3828
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
3578
3829
  return;
3579
3830
  }
3831
+ case 'providers.models.add': {
3832
+ const result = await addProviderModel(message.payload);
3833
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
3834
+ return;
3835
+ }
3580
3836
  case 'providers.status': {
3581
3837
  const result = await providerStatus(message.payload?.providerId);
3582
3838
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
@@ -4074,7 +4330,15 @@ export function createSessionDaemon({
4074
4330
  disposingSessionIds.clear();
4075
4331
  pendingRuntimeRecreation = false;
4076
4332
  runtimeRecreationRevision += 1;
4333
+ pendingProviderCatalogRevision = 0;
4077
4334
  await disposeRuntime();
4335
+ // Retry failed-create cleanups at the existing ownership-release
4336
+ // phase: dispose first, release only after success. A failed retry
4337
+ // stays pending without releasing ownership. Each entry is removed
4338
+ // only when still current so a newer owner's record is never erased.
4339
+ for (const pendingFailedCreate of [...pendingFailedCreateCleanups.values()]) {
4340
+ await drainPendingFailedCreateCleanup(pendingFailedCreate.sessionId).catch(() => false);
4341
+ }
4078
4342
  server = undefined;
4079
4343
  started = false;
4080
4344
  if (platform !== 'win32') await rm(endpoint, { force: true });