@pi-chamber/web 0.9.5 → 0.9.7

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 (104) hide show
  1. package/dist/assets/DiagramView-BvrCkm_z.js +1 -0
  2. package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
  3. package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
  4. package/dist/assets/FilesView-CNHu4RnC.js +6 -0
  5. package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
  6. package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
  8. package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-CDRZswx-.js} +1 -1
  12. package/dist/assets/SettingsView-hyAGp836.js +2 -0
  13. package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
  14. package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
  15. package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
  17. package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-D_31YElh.js} +1 -1
  21. package/dist/assets/index-BXgR2dKM.css +1 -0
  22. package/dist/assets/index-BZpvAhrX.js +8 -0
  23. package/dist/assets/{index-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
  25. package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
  26. package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
  27. package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
  28. package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
  29. package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
  30. package/dist/assets/{mobile-D0HVxiyJ.js → mobile-BmSlVuhn.js} +2 -2
  31. package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
  32. package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
  33. package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
  34. package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
  36. package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
  37. package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
  38. package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
  39. package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
  40. package/dist/assets/{web-components-B5sMa_kC.js → web-components-CYngz9Ml.js} +1 -1
  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/index.js +17 -3
  46. package/server/lib/client-auth/DOCUMENTATION.md +184 -0
  47. package/server/lib/client-auth/live-revocation.test.js +567 -0
  48. package/server/lib/client-auth/principal-tracker.js +383 -0
  49. package/server/lib/client-auth/principal-tracker.test.js +321 -0
  50. package/server/lib/client-auth/remote-clients.js +31 -0
  51. package/server/lib/client-auth/remote-clients.test.js +44 -0
  52. package/server/lib/fs/DOCUMENTATION.md +15 -3
  53. package/server/lib/fs/routes.js +369 -51
  54. package/server/lib/fs/routes.test.js +565 -3
  55. package/server/lib/fs/search.js +74 -29
  56. package/server/lib/pi/event-stream.js +269 -0
  57. package/server/lib/pi/event-stream.test.js +776 -0
  58. package/server/lib/pi/routes.js +132 -28
  59. package/server/lib/pi/routes.test.js +213 -4
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -4
  61. package/server/lib/pi/session-daemon/ipc-client.js +19 -15
  62. package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
  63. package/server/lib/pi/session-daemon/prompt-operations.test.js +9 -3
  64. package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
  65. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
  66. package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
  67. package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
  68. package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
  69. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
  70. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
  71. package/server/lib/pi/session-daemon/session-daemon.js +339 -37
  72. package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
  73. package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
  74. package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
  75. package/server/lib/pi/session-daemon/supervisor.js +30 -5
  76. package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
  77. package/server/lib/pi/ui-settings-store.js +1 -1
  78. package/server/lib/pi/ui-settings-store.test.js +3 -1
  79. package/server/lib/server/core-routes.js +11 -1
  80. package/server/lib/server/cors.js +6 -0
  81. package/server/lib/server/cors.test.js +3 -0
  82. package/server/lib/stt/DOCUMENTATION.md +2 -0
  83. package/server/lib/stt/runtime.js +39 -2
  84. package/server/lib/stt/runtime.test.js +53 -0
  85. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  86. package/server/lib/terminal/runtime.js +48 -2
  87. package/server/lib/terminal/runtime.test.js +35 -0
  88. package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
  89. package/server/lib/ui-auth/ui-auth.js +98 -0
  90. package/server/lib/ui-auth/ui-auth.test.js +249 -0
  91. package/server/lib/workspace/host.js +9 -3
  92. package/server/lib/workspace/host.test.js +15 -0
  93. package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
  94. package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
  95. package/dist/assets/FilesView-CJytSUAX.js +0 -6
  96. package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
  97. package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
  98. package/dist/assets/index-DIF8b4bh.css +0 -1
  99. package/dist/assets/index-jrfQYSvP.js +0 -8
  100. package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
  101. package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
  102. package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
  103. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
  104. package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
@@ -22,6 +22,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
22
22
  - `../server/cross-process-lock.js` serializes critical sections across servers sharing one data directory (exclusive create, owner nonce, dead-pid steal, bounded wait). It backs the daemon operation lock pattern and every shared read-modify-write store below.
23
23
  - `session-lease.js` owns exclusive cross-daemon residency of one Pi session, keyed by canonical agent directory, cwd, and session id under `<agentDir>/.pichamber/locks/sessions/`. The lease is acquired before a resident `AgentSessionRuntime` is created and released after idle disposal, deletion, replacement, or daemon shutdown. Opening or deleting a session leased by another live daemon returns `SESSION_IN_USE` (HTTP 409) while the session stays visible in listings; different sessions remain fully concurrent. Lease files from different `PICHAMBER_DATA_DIR` values still coordinate because they live under the shared agent directory.
24
24
  - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` owns portable PiChamber preferences at data-root `settings.json` and host, device, and secret-bearing values at `runtime-state.json`. `/api/pi/ui-settings` merges both views for existing clients and splits writes through explicit field allowlists. It migrates an unscoped flat file once; after the portable scope marker exists, local fields found in `settings.json` are ignored rather than applied to the host. The route is not available through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
25
+ - `../event-stream.js` owns the `/api/pi/events` SSE connection lifecycle so `../routes.js` stays a thin adapter. Per connection it installs cleanup before `subscribe` is awaited (a client that leaves during the opening window cannot leak a daemon subscription; a late subscription is closed exactly once), funnels client disconnect, subscription error, and server shutdown through one idempotent cleanup, hands an `AbortSignal` through the supervisor to the private IPC subscriber, never writes a named heartbeat or a late frame to a dead response, and byte-bounds the response socket buffer (`res.writableLength`, default 8 MiB, aligned with the daemon replay budget) with the bound enforced BEFORE each write so no single frame overshoots it. A client that stops reading is disconnected recoverably — the stream ends and the client reconnects from its last accepted sequence for replay or an authoritative snapshot, so no event is silently removed from an otherwise contiguous stream, but frames still buffered when the disconnect fires are not promised as delivered; the reconnect replay is the delivery guarantee — while a healthy client's connection stays independent of the slow one. Every teardown is bounded: a `write()` that returns false starts a drain deadline (default 5s) that ends even a quiet never-draining client, and after `res.end()` a terminate deadline (default 5s) destroys the response, because `end()` alone only queues the FIN behind unflushed data and would otherwise leave a stalled socket open forever and hang server shutdown/close. The response `'error'` guard stays attached for the response's lifetime (idempotent; cleanup can complete while data is still in flight and a late unhandled `'error'` would crash the process). The registry tracks live connections so `registerPiRuntimeRoutes` can expose `closeEventStreams()` for server shutdown, ending active and still-opening streams (and their daemon subscriptions) before the HTTP server closes. The IPC subscriber removes its abort listener and destroys the opening or active daemon socket on cancellation.
25
26
  - `*.test.js` uses temporary cwd, agent, data, and runtime directories; it never loads a developer's Pi home, credentials, or sessions. On Windows the private endpoint is a named pipe, not a `.sock` file, and POSIX mode-bit assertions are skipped.
26
27
 
27
28
  ## Protocol and security invariants
@@ -32,12 +33,13 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
32
33
  - The daemon credential and non-secret state sidecars are mode `0600`; their per-profile parent directory and the operation lock serialize start/reuse/stop. Exclusive lock create writes the owner pid in the same step. A leftover empty or malformed lock, a dead owner pid, or Windows `EPERM`/`EACCES` on exclusive create is retried and stolen after a short freshness window instead of failing as `DAEMON_LOCK_UNAVAILABLE`. Sidecar `chmod` failures on Windows are ignored after the file exists so readiness is still recorded. Health identity includes the daemon PID, profile key, and daemon id, and all three must match the state sidecar before the supervisor reuses a process. Reuse also requires the ready-state `entrypoint` to equal this host's `daemon-process.js`; a missing or different path is not identity-compatible and is replaced after a claim.
33
34
  - Ownership transfers through authenticated `runtime.claim` only after the previous server PID is no longer live. The daemon persists the new `serverInstanceId` and `serverPid` to its state sidecar before acknowledging the claim, so its in-memory owner and discoverable owner cannot split. Shutdown goes through authenticated `runtime.shutdown` (profile, daemon id, and current owner instance must all match) before any signal; a stale server whose daemon was claimed receives `DAEMON_OWNERSHIP_MISMATCH` and terminates nothing. A direct signal is used only after authenticated health and ownership checks prove that the sidecar PID is this profile's daemon (or for a child the supervisor just spawned during failed startup).
34
35
  - Shared writable state is coordinated, not merely namespaced. Pi prompt, context, settings, and model writes serialize through `<agentDir>/.pichamber/locks/pi-config.lock`; `models.json` additionally serializes in its store. PiChamber data-root stores (`pi/settings.json`, `pi/snippets.json`, `pi/session-archive.json`, `pi/session-folders.json`, root `settings.json` and `runtime-state.json`, STT config, remote-client and pairing stores) serialize read-modify-write through per-file locks with atomic replace; `session-folders.json` additionally rejects a stale `updatedAt` snapshot as `SESSION_FOLDERS_STALE` (HTTP 409) instead of silently overwriting newer folders. Passkeys, the JWT secret (exclusive create with re-read), the tunnel token, and git identities use atomic replace. Cross-daemon config staleness is bounded by idle runtime disposal (five minutes), which recreates runtimes from disk; there is no cross-daemon live-reload generation yet.
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`.
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`.
36
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.
37
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.
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.
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.
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.
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
+ - 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
+ - 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`, the daemon claims `kind + sessionId + operationId` BEFORE Pi activation, and an identical 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 `kind + sessionId + operationId` with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). 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` identity, 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 at-most-once guarantee, only within the retention window; a restart loses receipts (documented crash window, replay re-executes). Send-receipt lookup and replay protection remain separate contracts. The stream epoch guards event cursors across daemon restarts; send/config locking remains session-scoped.
41
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.
42
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.
43
45
  - 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.
@@ -94,27 +94,35 @@ export const requestSessionDaemon = ({ endpoint, credential, command, payload, t
94
94
  * Open an authenticated server-only event subscription. The caller owns the
95
95
  * returned close function and must relay only projected frames to browsers.
96
96
  */
97
- export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSequence, onEvent, onError, timeoutMs = 30_000 }) => {
97
+ export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSequence, streamEpoch, onEvent, onError, signal, timeoutMs = 30_000 }) => {
98
98
  const decoder = new StringDecoder('utf8');
99
99
  let buffer = '';
100
100
  let authenticated = false;
101
101
  let closed = false;
102
102
  const socket = createConnection({ path: endpoint });
103
- const timer = setTimeout(() => fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE')), timeoutMs);
104
- const finish = () => {
103
+ let timer;
104
+ function finish() {
105
105
  clearTimeout(timer);
106
- if (!closed) socket.destroy();
107
- };
108
- const fail = (error) => {
106
+ signal?.removeEventListener('abort', abort);
107
+ socket.destroy();
108
+ }
109
+ function fail(error) {
109
110
  if (closed) return;
110
111
  closed = true;
111
- clearTimeout(timer);
112
- socket.destroy();
112
+ finish();
113
113
  onError?.(error);
114
- };
114
+ }
115
+ function abort() {
116
+ if (closed) return;
117
+ closed = true;
118
+ finish();
119
+ }
120
+ timer = setTimeout(() => fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE')), timeoutMs);
121
+ if (signal?.aborted) abort();
122
+ else signal?.addEventListener('abort', abort, { once: true });
115
123
  socket.once('error', () => fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE')));
116
124
  socket.on('connect', () => {
117
- socket.write(`${JSON.stringify({ kind: 'authenticate', credential, ...(sessionId ? { sessionId } : {}), ...(Number.isSafeInteger(fromSequence) && fromSequence >= 0 ? { fromSequence } : {}) })}\n`);
125
+ socket.write(`${JSON.stringify({ kind: 'authenticate', credential, ...(sessionId ? { sessionId } : {}), ...(Number.isSafeInteger(fromSequence) && fromSequence >= 0 ? { fromSequence } : {}), ...(typeof streamEpoch === 'string' && streamEpoch.length > 0 ? { streamEpoch } : {}) })}\n`);
118
126
  });
119
127
  socket.on('data', (chunk) => {
120
128
  buffer += decoder.write(chunk);
@@ -147,9 +155,5 @@ export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSe
147
155
  socket.on('close', () => {
148
156
  if (!closed) fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE'));
149
157
  });
150
- return () => {
151
- if (closed) return;
152
- closed = true;
153
- finish();
154
- };
158
+ return abort;
155
159
  };
@@ -5,7 +5,7 @@ import { createHash } from 'node:crypto';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
 
8
- import { requestSessionDaemon } from './ipc-client.js';
8
+ import { requestSessionDaemon, subscribeSessionDaemon } from './ipc-client.js';
9
9
  import { SESSION_DAEMON_MAX_FRAME_BYTES } from './ipc-protocol.js';
10
10
 
11
11
  const credential = 'test-private-credential';
@@ -85,4 +85,116 @@ describe('session daemon IPC client framing', () => {
85
85
  await expect(requestSessionDaemon({ endpoint, credential, command: 'runtime.health' }))
86
86
  .resolves.toEqual({ ok: true });
87
87
  });
88
+
89
+ it('stamps the subscribe authenticate frame with the cursor streamEpoch', async () => {
90
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ipc-client-'));
91
+ roots.push(root);
92
+ const endpoint = endpointFor(root);
93
+ let seenAuthenticate;
94
+ const peers = new Set();
95
+ const server = createServer((socket) => {
96
+ peers.add(socket);
97
+ socket.on('error', () => {});
98
+ socket.on('close', () => peers.delete(socket));
99
+ let buffer = '';
100
+ socket.on('data', (chunk) => {
101
+ buffer += chunk.toString('utf8');
102
+ while (buffer.includes('\n')) {
103
+ const newline = buffer.indexOf('\n');
104
+ const line = buffer.slice(0, newline);
105
+ buffer = buffer.slice(newline + 1);
106
+ if (!line) continue;
107
+ const frame = JSON.parse(line);
108
+ if (frame.kind === 'authenticate') {
109
+ seenAuthenticate = frame;
110
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'authenticated' })}\n`);
111
+ socket.write(`${JSON.stringify({
112
+ protocolVersion: 1,
113
+ kind: 'event',
114
+ event: 'session.snapshot',
115
+ sequence: 0,
116
+ streamEpoch: 'epoch-abc123',
117
+ })}\n`);
118
+ }
119
+ }
120
+ });
121
+ });
122
+ servers.push(server);
123
+ await new Promise((resolve, reject) => {
124
+ server.once('error', reject);
125
+ server.listen({ path: endpoint }, resolve);
126
+ });
127
+
128
+ const events = [];
129
+ let closeCalled = false;
130
+ const close = subscribeSessionDaemon({
131
+ endpoint,
132
+ credential,
133
+ sessionId: 'pi-session-1',
134
+ fromSequence: 7,
135
+ streamEpoch: 'epoch-abc123',
136
+ onEvent: (event) => events.push(event),
137
+ onError: () => {},
138
+ });
139
+ try {
140
+ for (let attempt = 0; attempt < 50 && events.length === 0; attempt += 1) {
141
+ await new Promise((resolve) => setTimeout(resolve, 20));
142
+ }
143
+ expect(seenAuthenticate).toMatchObject({
144
+ credential,
145
+ sessionId: 'pi-session-1',
146
+ fromSequence: 7,
147
+ streamEpoch: 'epoch-abc123',
148
+ });
149
+ expect(events[0]).toMatchObject({ kind: 'event', streamEpoch: 'epoch-abc123' });
150
+ close();
151
+ closeCalled = true;
152
+ for (let attempt = 0; attempt < 50 && peers.size > 0; attempt += 1) {
153
+ await new Promise((resolve) => setTimeout(resolve, 10));
154
+ }
155
+ expect(peers.size).toBe(0);
156
+ } finally {
157
+ if (!closeCalled) close();
158
+ for (const peer of peers) peer.destroy();
159
+ }
160
+ }, 20_000);
161
+
162
+ it('aborts an opening subscription without reporting a transport error', async () => {
163
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ipc-client-'));
164
+ roots.push(root);
165
+ const endpoint = endpointFor(root);
166
+ const peers = new Set();
167
+ const server = createServer((socket) => {
168
+ peers.add(socket);
169
+ socket.on('error', () => {});
170
+ socket.on('close', () => peers.delete(socket));
171
+ socket.resume();
172
+ // Deliberately never authenticate. The AbortSignal must close this
173
+ // opening socket instead of waiting for the 30-second setup timeout.
174
+ });
175
+ servers.push(server);
176
+ await new Promise((resolve, reject) => {
177
+ server.once('error', reject);
178
+ server.listen({ path: endpoint }, resolve);
179
+ });
180
+
181
+ const controller = new AbortController();
182
+ const errors = [];
183
+ subscribeSessionDaemon({
184
+ endpoint,
185
+ credential,
186
+ signal: controller.signal,
187
+ onError: (error) => errors.push(error),
188
+ });
189
+ for (let attempt = 0; attempt < 50 && peers.size === 0; attempt += 1) {
190
+ await new Promise((resolve) => setTimeout(resolve, 10));
191
+ }
192
+ expect(peers.size).toBe(1);
193
+ controller.abort();
194
+ for (let attempt = 0; attempt < 50 && peers.size > 0; attempt += 1) {
195
+ await new Promise((resolve) => setTimeout(resolve, 10));
196
+ }
197
+ expect(peers.size).toBe(0);
198
+ expect(errors).toEqual([]);
199
+ });
88
200
  });
@@ -40,7 +40,7 @@ class FakeSession {
40
40
  this.listeners = new Set();
41
41
  this.reloadCount = 0;
42
42
  this.reloadError = null;
43
- this.promptImpl = async () => {};
43
+ this.promptImpl = async (text, options) => { options?.preflightResult?.(true); };
44
44
  }
45
45
  subscribe(l) { this.listeners.add(l); return () => this.listeners.delete(l); }
46
46
  emit(event) { for (const listener of this.listeners) listener(event); }
@@ -361,7 +361,10 @@ describe('prompt template daemon operations', () => {
361
361
  it('waits for an accepted prompt to finish before recreating the runtime', async () => {
362
362
  const session = new FakeSession();
363
363
  let finishPrompt;
364
- session.promptImpl = () => new Promise((resolve) => { finishPrompt = resolve; });
364
+ session.promptImpl = (text, options) => {
365
+ options?.preflightResult?.(true);
366
+ return new Promise((resolve) => { finishPrompt = resolve; });
367
+ };
365
368
  const ctx = await startDaemon({ session });
366
369
  await ctx.request('resources.list', { directory: ctx.cwd });
367
370
  await expect(ctx.request('sessions.prompt', { sessionId: session.sessionId, text: '/hold', directory: ctx.cwd })).resolves.toMatchObject({ accepted: true });
@@ -383,7 +386,10 @@ describe('prompt template daemon operations', () => {
383
386
  it('defers reload while a non-streaming slash command is still executing', async () => {
384
387
  const session = new FakeSession();
385
388
  let finishPrompt;
386
- session.promptImpl = () => new Promise((resolve) => { finishPrompt = resolve; });
389
+ session.promptImpl = (text, options) => {
390
+ options?.preflightResult?.(true);
391
+ return new Promise((resolve) => { finishPrompt = resolve; });
392
+ };
387
393
  const ctx = await startDaemon({ session });
388
394
  await ctx.request('resources.list', { directory: ctx.cwd });
389
395
  await ctx.request('sessions.prompt', { sessionId: session.sessionId, text: '/hold', directory: ctx.cwd });