@pi-chamber/web 0.6.0 → 0.7.0

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 (53) hide show
  1. package/dist/assets/{CommitSection-IIhrK4u7.js → CommitSection-BL61C8nr.js} +1 -1
  2. package/dist/assets/{DiagramEditor-DmDE7OFs.js → DiagramEditor-CH_gE8Ho.js} +1 -1
  3. package/dist/assets/{DiagramView-BKKPzX5U.js → DiagramView-D5PsfvzH.js} +1 -1
  4. package/dist/assets/{DiffView-BZAyvJ3r.js → DiffView-CP49mbz0.js} +1 -1
  5. package/dist/assets/{FilesView-mwjEX08j.js → FilesView-DQ0jIXPf.js} +1 -1
  6. package/dist/assets/{GitView-C1ltD6da.js → GitView-BvIVUn8p.js} +3 -3
  7. package/dist/assets/{JsonTreeView-De-9zk3N.js → JsonTreeView-4xkZ1oUB.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-BJjIFNhO.js → MarkdownRendererImpl-BYiITelR.js} +1 -1
  9. package/dist/assets/{PatchDiff-DuR1fglg.js → PatchDiff-cYVpwvLs.js} +1 -1
  10. package/dist/assets/{PierreDiffViewer-B_1JcH3B.js → PierreDiffViewer-CxTRnaw4.js} +1 -1
  11. package/dist/assets/{SessionSwitcherContent-DoEWfM8C.js → SessionSwitcherContent-C_kE1AkY.js} +1 -1
  12. package/dist/assets/{SessionSwitcherDropdown-CJWqyz1O.js → SessionSwitcherDropdown-CCXNg-hd.js} +2 -2
  13. package/dist/assets/{SessionUnreadDot-DB-YvwMh.js → SessionUnreadDot-DcLebnEm.js} +1 -1
  14. package/dist/assets/{SettingsView-ZwPgZh-7.js → SettingsView-CfpCOseW.js} +3 -3
  15. package/dist/assets/{SettingsWindow-nCTzNqyu.js → SettingsWindow-BCfEIGLV.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-CIzj2Pxu.js → ToolOutputDialog-CG3Djpaw.js} +1 -1
  17. package/dist/assets/{ToolPartDiffPreview-BgewaN20.js → ToolPartDiffPreview-Bno_Kf_v.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-aTd42JT9.js → VirtualizedFileDiff-CtTCV9aT.js} +1 -1
  19. package/dist/assets/{WindowsWindowControls-CdHYDpHx.js → WindowsWindowControls-C1cyCACC.js} +107 -107
  20. package/dist/assets/{collapsible-IV1T6v7c.js → collapsible-Y0lXAGWU.js} +1 -1
  21. package/dist/assets/{computeVirtualFileMetrics-CcGhkiFO.js → computeVirtualFileMetrics-Ygq8IDgM.js} +1 -1
  22. package/dist/assets/{contextFileOpenGuard-DRkKhovc.js → contextFileOpenGuard-CdZD2lzt.js} +1 -1
  23. package/dist/assets/index-CiQblNLS.js +8 -0
  24. package/dist/assets/{index-DmJfzwE5.js → index-Cl-EsRzi.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-DL6dDuVG.js → isDiffPlainText-BOtu3iWK.js} +1 -1
  26. package/dist/assets/{isFilePlainText-nuUWsdc6.js → isFilePlainText-DZkgwQ85.js} +1 -1
  27. package/dist/assets/{main-DIAtlyFC.js → main-BlGDTFM8.js} +9 -9
  28. package/dist/assets/{main-Bajw-SZm.js → main-hi9Mn-Bi.js} +2 -2
  29. package/dist/assets/{markdownCore-CrfGNEFF.js → markdownCore-BnziCWjq.js} +1 -1
  30. package/dist/assets/{miniChat-Dfoj435F.js → miniChat-jlNYy4Yo.js} +2 -2
  31. package/dist/assets/{mobile-DFIt0gxE.js → mobile-B2J6RZei.js} +2 -2
  32. package/dist/assets/{renderElectronMiniChatApp-DKsf3ft3.js → renderElectronMiniChatApp-D2j7dJjx.js} +2 -2
  33. package/dist/assets/{renderMobileApp-iiD58RxE.js → renderMobileApp-DRMRL_Rc.js} +4 -4
  34. package/dist/assets/{runtimeSurface-D3p7a-uO.js → runtimeSurface-DRCRpZ4U.js} +1 -1
  35. package/dist/assets/{useInlineCommentController-5paFhtYM.js → useInlineCommentController-BafZc9gs.js} +1 -1
  36. package/dist/assets/{usePanelSlide-D7Cl581q.js → usePanelSlide-C4DKnekW.js} +16 -16
  37. package/dist/assets/{usePushVisibilityBeacon-BOPrDYSe.js → usePushVisibilityBeacon-C6yhoKax.js} +1 -1
  38. package/dist/assets/{useSwitcherItems-DP5ufRVs.js → useSwitcherItems-D4fvD6XH.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-B9y74Qvn.js → vendor-codemirror-language-data-DOlAvLSI.js} +2 -2
  40. package/dist/assets/{web-components-CD0f7QZj.js → web-components-CDndDwR4.js} +1 -1
  41. package/dist/index.html +3 -3
  42. package/dist/mini-chat.html +2 -2
  43. package/dist/mobile.html +2 -2
  44. package/package.json +1 -1
  45. package/server/lib/inherited-env.js +1 -1
  46. package/server/lib/pi/routes.js +9 -1
  47. package/server/lib/pi/routes.test.js +24 -0
  48. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -3
  49. package/server/lib/pi/session-daemon/session-daemon.js +39 -21
  50. package/server/lib/pi/session-daemon/session-daemon.test.js +78 -7
  51. package/server/lib/pi/session-daemon/session-jsonl.js +27 -7
  52. package/server/lib/pi/session-daemon/session-jsonl.test.js +31 -0
  53. package/dist/assets/index--5Zr-fSk.js +0 -8
@@ -15,7 +15,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
15
15
  - `daemon-process.js` is the detached private-process entrypoint. It reads the daemon credential from its owner-only sidecar, starts the socket, writes non-secret identity state only after readiness, and removes only its own state on signal shutdown.
16
16
  - `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
17
17
  - `runtime-registry.js` owns active runtime identities and session-local subscriptions. It rebinds the subscription after an SDK session replacement, rejects identity conflicts rather than displacing another runtime, and attempts every tracked disposal even when another disposal fails.
18
- - `session-jsonl.js` validates cwd-scoped Pi JSONL before discovery. List, create, and daemon startup require a valid session header per file; they do not read whole transcripts. `sessions.list` uses `listPiSessionJsonlDirectory` (header, first user prompt, latest rename from the file tail). Full-file validation remains on open of a specific session so a malformed body still fails that chat. Pi's SDK list is not the production list path because it scans every line of every log. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
18
+ - `session-jsonl.js` validates cwd-scoped Pi JSONL before discovery. List, create, and daemon startup require a valid session header per file; they do not read whole transcripts. `sessions.list` uses `listPiSessionJsonlDirectory` (header, first user prompt, latest rename from the file tail). Files in one directory are listed with at most eight concurrent reads; one unreadable or header-malformed file still fails that directory. Full-file validation remains on open of a specific session so a malformed body still fails that chat. Pi's SDK list is not the production list path because it scans every line of every log. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
19
19
  - `supervisor.js` resolves server-only overrides, creates the credential, serializes start/reuse/stop through an owner-only lock, validates daemon identity through `runtime.health`, forwards server-owned commands only after that identity check, and starts or stops the detached process. Reuse requires the ready-state sidecar `entrypoint` to match this checkout's `daemon-process.js`; a healthy daemon from another install (or an older daemon that never recorded an entrypoint) is stopped and replaced so local `bun run dev` cannot keep answering `getSession` without the live-turn overlay. When the parent is Electron, the child is spawned with `ELECTRON_RUN_AS_NODE=1` so packaged Windows/macOS/Linux apps run the daemon as Node instead of a hidden second Electron GUI process.
20
20
  - `../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` atomically owns shared PiChamber UI preferences at the data-root `settings.json`; it is exposed as `/api/pi/ui-settings`, not 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.
21
21
  - `*.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.
@@ -28,7 +28,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
28
28
  - 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`.
29
29
  - 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.
30
30
  - Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
31
- - 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.delete`, `extensions.list/respond`, and session list/create/open/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. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` resolves an id by Pi's `timestamp_<id>.jsonl` filename first so a missing deep link 404s without listing or fully reading every transcript in every cwd; SDK list and header scan remain the fallback for non-standard names. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
31
+ - 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.delete`, `extensions.list/respond`, and session list/create/open/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. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
32
32
  - 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.
33
33
  - Each event and reconnect snapshot has a monotonic sequence. A reconnect receives a bounded contiguous replay after its cursor when available, otherwise an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions.
34
34
  - 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`. 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`. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
@@ -41,6 +41,6 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
41
41
 
42
42
  ## Deliberate limits
43
43
 
44
- This module defines the authenticated session API boundary consumed by the Pi-native session UI. Resource configuration and richer attachment extraction remain owned by their dedicated workstreams. The session event stream is SSE over the existing authenticated runtime transport; WebSocket callers fall back to it, preserving direct and relay behavior without a second daemon listener.
44
+ This module defines the authenticated session API boundary consumed by the Pi-native session UI. Resource configuration and richer attachment extraction remain owned by their dedicated workstreams. The session event stream is SSE over the existing authenticated runtime transport; WebSocket callers fall back to it, preserving direct and relay behavior without a second daemon listener. The public route emits named heartbeat events so native `EventSource` clients can detect a silent foreground connection, reconnect, and resume from their last accepted sequence.
45
45
 
46
46
  The Pi SDK is pinned exactly at `0.84.1`. Any Pi 0.x minor upgrade requires a deliberate SDK/release-note review and repeat of this module's disposable-runtime smoke validation.
@@ -649,42 +649,60 @@ export function createSessionDaemon({
649
649
  if (typeof sessionId !== 'string' || sessionId.length === 0) {
650
650
  throw new SessionDaemonProtocolError('INVALID_SESSION', 'The Pi session does not exist.');
651
651
  }
652
- // Filename identity is enough to 404 a missing id without listing or
653
- // fully reading every transcript in every cwd. Deep-linking a stale
654
- // `?session=` used to hang here while `validatePiSessionJsonlDirectory`
655
- // scanned multi-megabyte JSONL files that cannot be the target.
656
- try {
657
- const named = await findPiSessionJsonlById({ sessionId, agentDir });
658
- if (named?.path && named.cwd) {
659
- await validatePiSessionJsonlFile(named.path);
660
- const directory = await resolveDirectory(named.cwd);
661
- knownDirectories.add(directory);
662
- return { target: { id: sessionId, path: named.path }, directory };
663
- }
664
- } catch {
665
- // Fall through to SDK list / header scan for non-standard filenames.
666
- }
667
652
  const candidateDirs = new Set();
653
+ let requestedTargetDirectory;
668
654
  if (requestedDirectory) {
669
655
  try {
670
- candidateDirs.add(await resolveDirectory(requestedDirectory));
656
+ requestedTargetDirectory = await resolveDirectory(requestedDirectory);
657
+ candidateDirs.add(requestedTargetDirectory);
671
658
  } catch {}
672
659
  }
673
660
  if (activeDirectory) candidateDirs.add(activeDirectory);
674
661
  if (cwd) candidateDirs.add(cwd);
675
662
  for (const d of knownDirectories) candidateDirs.add(d);
676
663
 
677
- for (const dir of candidateDirs) {
664
+ const findInDirectory = async (directory) => {
678
665
  try {
679
- const sessions = await listSessions({ cwd: dir, agentDir });
666
+ const sessions = await listSessions({ cwd: directory, agentDir });
680
667
  const target = Array.isArray(sessions) ? sessions.find((session) => session?.id === sessionId) : undefined;
681
668
  if (target && typeof target.path === 'string' && target.path.length > 0) {
682
669
  await validatePiSessionJsonlFile(target.path);
683
- return { target, directory: dir };
670
+ return { target, directory };
684
671
  }
685
- } catch (err) {
686
- // Continue searching other candidate directories
672
+ } catch {
673
+ // Continue through the remaining authoritative lookup paths.
674
+ }
675
+ return undefined;
676
+ };
677
+
678
+ // A caller-supplied directory is the narrowest authoritative scope. Check
679
+ // it before walking every directory in the agent store. This keeps an
680
+ // ordinary session open proportional to that project's sessions and avoids
681
+ // choosing a same-id record from another directory.
682
+ if (requestedTargetDirectory) {
683
+ const requestedTarget = await findInDirectory(requestedTargetDirectory);
684
+ if (requestedTarget) return requestedTarget;
685
+ }
686
+
687
+ // Filename identity is enough to locate a session from a directory-less
688
+ // deep link without fully reading every transcript. A stale link can still
689
+ // fall through to the bounded header scans below.
690
+ try {
691
+ const named = await findPiSessionJsonlById({ sessionId, agentDir });
692
+ if (named?.path && named.cwd) {
693
+ await validatePiSessionJsonlFile(named.path);
694
+ const directory = await resolveDirectory(named.cwd);
695
+ knownDirectories.add(directory);
696
+ return { target: { id: sessionId, path: named.path }, directory };
687
697
  }
698
+ } catch {
699
+ // Fall through to list / header scan for non-standard filenames.
700
+ }
701
+
702
+ for (const directory of candidateDirs) {
703
+ if (directory === requestedTargetDirectory) continue;
704
+ const target = await findInDirectory(directory);
705
+ if (target) return target;
688
706
  }
689
707
 
690
708
  // If not found in candidateDirs, scan all directory stores under agentDir/sessions
@@ -7,10 +7,14 @@ import { join } from 'node:path';
7
7
  import { StringDecoder } from 'node:string_decoder';
8
8
 
9
9
  import { createMessageEntryAliases } from './message-entry-aliases.js';
10
- import { createSessionDaemon, isLocalSessionDaemonEndpoint } from './session-daemon.js';
10
+ import { createSessionDaemon as createSessionDaemonImpl, isLocalSessionDaemonEndpoint } from './session-daemon.js';
11
11
 
12
12
  const credential = 'a-private-daemon-credential';
13
13
 
14
+ function createSessionDaemon(options) {
15
+ return createSessionDaemonImpl({ ...options, agentDir: options.agentDir ?? options.cwd });
16
+ }
17
+
14
18
  class FakeSession {
15
19
  constructor(sessionId = 'pi-session-1', sessionFile) {
16
20
  this.sessionId = sessionId;
@@ -317,7 +321,7 @@ describe('Pi session daemon spike', () => {
317
321
  await stale.close();
318
322
  });
319
323
 
320
- it('keeps existing and late-joining device streams independent during one turn', async () => {
324
+ it('keeps existing, late-joining, and reconnecting device streams contiguous during one turn', async () => {
321
325
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-multi-client-'));
322
326
  const endpoint = testDaemonEndpoint(root);
323
327
  const session = new FakeSession();
@@ -358,15 +362,37 @@ describe('Pi session daemon spike', () => {
358
362
  expect(firstDeltaFrame.sequence).toBe(lateDeltaFrame.sequence);
359
363
  expect(lateDeltaFrame.payload.delta).toBe(' plus the rest');
360
364
 
365
+ await late.close();
366
+ const firstEnd = first.next((frame) => frame.event === 'assistant.message.end');
367
+ session.emit({
368
+ type: 'message_end',
369
+ message: {
370
+ role: 'assistant',
371
+ content: [{ type: 'text', text: 'half plus the rest' }],
372
+ provider: 'test',
373
+ model: 'model',
374
+ timestamp: 1_000,
375
+ },
376
+ });
377
+ const firstEndFrame = await firstEnd;
378
+
379
+ const resumed = connectClient(endpoint);
380
+ await resumed.authenticate(credential, {
381
+ sessionId: 'pi-session-1',
382
+ fromSequence: lateDeltaFrame.sequence,
383
+ });
384
+ const resumedEndFrame = await resumed.next((frame) => frame.event === 'assistant.message.end');
385
+ expect(resumedEndFrame.sequence).toBe(firstEndFrame.sequence);
386
+
361
387
  const firstIdle = first.next((frame) => frame.event === 'session.lifecycle' && frame.payload?.state === 'idle');
362
- const lateIdle = late.next((frame) => frame.event === 'session.lifecycle' && frame.payload?.state === 'idle');
388
+ const resumedIdle = resumed.next((frame) => frame.event === 'session.lifecycle' && frame.payload?.state === 'idle');
363
389
  session.isStreaming = false;
364
390
  session.emit({ type: 'agent_settled' });
365
- const [firstIdleFrame, lateIdleFrame] = await Promise.all([firstIdle, lateIdle]);
366
- expect(firstIdleFrame.sequence).toBe(lateIdleFrame.sequence);
367
- expect(firstIdleFrame.sequence).toBeGreaterThan(firstDeltaFrame.sequence);
391
+ const [firstIdleFrame, resumedIdleFrame] = await Promise.all([firstIdle, resumedIdle]);
392
+ expect(firstIdleFrame.sequence).toBe(resumedIdleFrame.sequence);
393
+ expect(firstIdleFrame.sequence).toBeGreaterThan(firstEndFrame.sequence);
368
394
 
369
- await late.close();
395
+ await resumed.close();
370
396
  await first.close();
371
397
  });
372
398
 
@@ -532,6 +558,51 @@ describe('Pi session daemon spike', () => {
532
558
  await second.close();
533
559
  });
534
560
 
561
+ it('opens the requested directory before falling back to a same-id global session', async () => {
562
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-open-requested-'));
563
+ const otherRoot = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-open-other-'));
564
+ const endpoint = testDaemonEndpoint(root);
565
+ const agentDir = join(root, 'agent');
566
+ const otherSessionDir = join(agentDir, 'sessions', 'other');
567
+ await mkdir(otherSessionDir, { recursive: true });
568
+
569
+ const requestedSessionFile = join(root, 'session-1.jsonl');
570
+ const otherSessionFile = join(otherSessionDir, 'session-1.jsonl');
571
+ await writeFile(requestedSessionFile, `{"type":"session","id":"session-1","cwd":${JSON.stringify(root)}}\n`);
572
+ await writeFile(otherSessionFile, `{"type":"session","id":"session-1","cwd":${JSON.stringify(otherRoot)}}\n`);
573
+
574
+ let opened;
575
+ daemon = createSessionDaemon({
576
+ endpoint,
577
+ credential,
578
+ cwd: root,
579
+ agentDir,
580
+ listSessions: async ({ cwd }) => cwd === root ? [{
581
+ path: requestedSessionFile,
582
+ id: 'session-1',
583
+ cwd: root,
584
+ created: new Date('2026-01-01T00:00:00.000Z'),
585
+ modified: new Date('2026-01-02T00:00:00.000Z'),
586
+ }] : [],
587
+ createRuntime: async (options) => {
588
+ opened = options;
589
+ return new FakeRuntime({
590
+ cwd: options.cwd,
591
+ session: new FakeSession('session-1', options.sessionFile),
592
+ });
593
+ },
594
+ });
595
+ await daemon.start();
596
+
597
+ const client = connectClient(endpoint);
598
+ await client.authenticate();
599
+ const response = await client.request('sessions.open', { sessionId: 'session-1', directory: root });
600
+
601
+ expect(response.result.session.directory).toBe(root);
602
+ expect(opened).toMatchObject({ cwd: root, sessionFile: requestedSessionFile });
603
+ await client.close();
604
+ });
605
+
535
606
  it('does not include in-memory sessions from another directory when listing a newly selected project directory', async () => {
536
607
  const rootA = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-a-'));
537
608
  const rootB = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-b-'));
@@ -38,6 +38,25 @@ const LIST_HEAD_SCAN_BYTES = 512 * 1024;
38
38
  /** Latest `session_info` (rename) is appended; read a tail instead of the whole log. */
39
39
  const LIST_TAIL_SCAN_BYTES = 128 * 1024;
40
40
  const LIST_PREVIEW_CHARS = 500;
41
+ /** Bound in-directory JSONL listing so a large folder is not one file at a time. */
42
+ const LIST_FILE_CONCURRENCY = 8;
43
+
44
+ const mapWithConcurrency = async (values, concurrency, mapper) => {
45
+ if (values.length === 0) return [];
46
+ const safeConcurrency = Math.max(1, Math.min(concurrency, values.length));
47
+ const results = new Array(values.length);
48
+ let cursor = 0;
49
+ const worker = async () => {
50
+ while (true) {
51
+ const nextIndex = cursor;
52
+ cursor += 1;
53
+ if (nextIndex >= values.length) return;
54
+ results[nextIndex] = await mapper(values[nextIndex]);
55
+ }
56
+ };
57
+ await Promise.all(Array.from({ length: safeConcurrency }, () => worker()));
58
+ return results;
59
+ };
41
60
 
42
61
  const isSessionHeader = (entry) => (
43
62
  Boolean(entry)
@@ -266,7 +285,9 @@ async function readPiSessionJsonlListFields(filePath, fileSize) {
266
285
  /**
267
286
  * Sidebar/list metadata for one cwd. Reads a header, a bounded prefix for
268
287
  * the first user prompt, and a tail for the latest rename. It does not
269
- * load whole transcripts.
288
+ * load whole transcripts. Files in the directory are read with bounded
289
+ * concurrency; one unreadable or header-malformed file still fails the
290
+ * whole directory list.
270
291
  */
271
292
  export async function listPiSessionJsonlDirectory({
272
293
  cwd,
@@ -284,9 +305,8 @@ export async function listPiSessionJsonlDirectory({
284
305
  throw unreadable();
285
306
  }
286
307
 
287
- const sessions = [];
288
- for (const entry of entries) {
289
- if (!entry.name.endsWith('.jsonl') || entry.isDirectory()) continue;
308
+ const files = entries.filter((entry) => entry.name.endsWith('.jsonl') && !entry.isDirectory());
309
+ const sessions = await mapWithConcurrency(files, LIST_FILE_CONCURRENCY, async (entry) => {
290
310
  const filePath = join(sessionDirectory, entry.name);
291
311
  let fileStat;
292
312
  try {
@@ -303,7 +323,7 @@ export async function listPiSessionJsonlDirectory({
303
323
  ? Date.parse(fields.header.timestamp)
304
324
  : NaN;
305
325
  const created = Number.isFinite(headerTime) ? new Date(headerTime) : fileStat.mtime;
306
- sessions.push({
326
+ return {
307
327
  path: filePath,
308
328
  id: fields.header.id,
309
329
  cwd: fields.header.cwd,
@@ -312,8 +332,8 @@ export async function listPiSessionJsonlDirectory({
312
332
  created,
313
333
  modified: fileStat.mtime,
314
334
  ...(fields.firstMessage ? { firstMessage: fields.firstMessage } : {}),
315
- });
316
- }
335
+ };
336
+ });
317
337
  sessions.sort((left, right) => right.modified.getTime() - left.modified.getTime());
318
338
  return sessions;
319
339
  }
@@ -138,4 +138,35 @@ describe('Pi session JSONL validation', () => {
138
138
  ]);
139
139
  expect(listed[0].path).toContain('session-one.jsonl');
140
140
  });
141
+
142
+ it('lists every session file in a crowded directory', async () => {
143
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-jsonl-'));
144
+ const cwd = join(root, 'project');
145
+ const agentDir = join(root, 'agent');
146
+ const sessionDirectory = getPiSessionDirectory({ cwd, agentDir });
147
+ await mkdir(sessionDirectory, { recursive: true });
148
+ const ids = Array.from({ length: 24 }, (_, index) => `session-${String(index).padStart(2, '0')}`);
149
+ await Promise.all(ids.map((id) => writeFile(
150
+ join(sessionDirectory, `${id}.jsonl`),
151
+ `${JSON.stringify({ type: 'session', version: 3, id, timestamp: '2026-01-01T00:00:00.000Z', cwd })}\n${JSON.stringify({ type: 'message', message: { role: 'user', content: [{ type: 'text', text: `Prompt ${id}` }] } })}\n`,
152
+ )));
153
+
154
+ const listed = await listPiSessionJsonlDirectory({ cwd, agentDir });
155
+ expect(listed.map((session) => session.id).sort()).toEqual([...ids].sort());
156
+ expect(listed.every((session) => session.cwd === cwd && session.firstMessage?.startsWith('Prompt '))).toBe(true);
157
+ });
158
+
159
+ it('fails the directory list when one session header is malformed', async () => {
160
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-jsonl-'));
161
+ const cwd = join(root, 'project');
162
+ const agentDir = join(root, 'agent');
163
+ const sessionDirectory = getPiSessionDirectory({ cwd, agentDir });
164
+ await mkdir(sessionDirectory, { recursive: true });
165
+ await writeFile(join(sessionDirectory, 'valid.jsonl'), `${validHeader(cwd)}\n`);
166
+ await writeFile(join(sessionDirectory, 'broken.jsonl'), '{"type":"not-a-session"}\n');
167
+
168
+ await expect(listPiSessionJsonlDirectory({ cwd, agentDir })).rejects.toMatchObject({
169
+ code: 'MALFORMED_SESSION_JSONL',
170
+ });
171
+ });
141
172
  });