@pi-chamber/web 0.9.0 → 0.9.3
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.
- package/README.md +24 -8
- package/bin/cli.js +11 -1
- package/bin/cli.test.js +18 -0
- package/bin/lib/DOCUMENTATION.md +3 -3
- package/bin/lib/cli-args.js +7 -3
- package/bin/lib/cli-lifecycle.js +3 -0
- package/bin/lib/cli-paths.js +28 -6
- package/bin/lib/cli-process.js +1 -0
- package/bin/lib/cli-tunnel-profiles.js +15 -10
- package/bin/lib/commands-connect-url.js +9 -1
- package/bin/lib/commands-logs.js +22 -4
- package/bin/lib/commands-serve.js +10 -2
- package/bin/lib/commands-tunnel.js +14 -0
- package/bin/lib/commands-update.js +18 -14
- package/bin/lib/commands-update.test.js +2 -1
- package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DuGmiPZ5.js} +1 -1
- package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-CV-iReyY.js} +1 -1
- package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-DVd1MLPB.js} +6 -6
- package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CPnW4I90.js} +1 -1
- package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Dj_7hgX_.js} +3 -3
- package/dist/assets/JsonTreeView-Cyy0lEZR.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
- package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-C7dA3U29.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
- package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-qeik5qtT.js} +1 -1
- package/dist/assets/SettingsView-C57uV1YS.js +2 -0
- package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Bbay2W76.js} +1 -1
- package/dist/assets/ToolOutputDialog-CRTiN1CH.js +8 -0
- package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-iqwryMNU.js} +3 -3
- package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-szfZ0Syc.js} +1 -1
- package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +3 -0
- package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-BC3ie230.js} +1 -1
- package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-DbThKVSf.js} +1 -1
- package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
- package/dist/assets/{index-yWgKW2Fx.js → index-KIdiBFJs.js} +4 -4
- package/dist/assets/{index-D1IaU-Q7.js → index-v6K3L94m.js} +1 -1
- package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
- package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CbrmvrM6.js} +1 -1
- package/dist/assets/{main-DcAMXRSi.js → main-4PkIvzf4.js} +7 -7
- package/dist/assets/{main-DhvLreEl.js → main-DMyWi0qs.js} +2 -2
- package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-BD5WkOKU.js} +1 -1
- package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-CLMNhna4.js} +2 -2
- package/dist/assets/{mobile-C-IN49xX.js → mobile-rWMDwhtQ.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +2 -0
- package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DLy2YoQg.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
- package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-CySRuLbN.js} +1 -1
- package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-DfuJVB15.js} +102 -102
- package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
- package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +10 -0
- package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-jITqE8PV.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
- package/dist/assets/{web-components-DAkBDXRk.js → web-components-C9wXMuCp.js} +2 -2
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +3 -3
- package/server/index.js +26 -7
- package/server/lib/client-auth/pairing.js +13 -2
- package/server/lib/client-auth/remote-clients.js +13 -2
- package/server/lib/fs/DOCUMENTATION.md +3 -1
- package/server/lib/fs/routes.test.js +74 -0
- package/server/lib/git/DOCUMENTATION.md +1 -1
- package/server/lib/git/identity-storage.js +10 -1
- package/server/lib/package-manager.js +1 -1
- package/server/lib/package-manager.test.js +11 -0
- package/server/lib/pi/archive-store.js +3 -2
- package/server/lib/pi/model-config-store.js +6 -2
- package/server/lib/pi/routes.js +46 -3
- package/server/lib/pi/routes.test.js +53 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +15 -9
- package/server/lib/pi/session-daemon/daemon-process.js +48 -13
- package/server/lib/pi/session-daemon/ipc-client.js +20 -9
- package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
- package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
- package/server/lib/pi/session-daemon/session-daemon.js +353 -66
- package/server/lib/pi/session-daemon/session-daemon.test.js +348 -0
- package/server/lib/pi/session-daemon/session-lease.js +151 -0
- package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
- package/server/lib/pi/session-daemon/supervisor.js +244 -54
- package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
- package/server/lib/pi/session-folders-store.js +20 -2
- package/server/lib/pi/session-folders-store.test.js +17 -0
- package/server/lib/pi/settings-store.js +3 -2
- package/server/lib/pi/snippets-store.js +4 -1
- package/server/lib/pi/ui-settings-store.js +130 -24
- package/server/lib/pi/ui-settings-store.test.js +58 -7
- package/server/lib/server/cross-process-lock.js +112 -0
- package/server/lib/server/cross-process-lock.test.js +70 -0
- package/server/lib/server/server-profile.js +110 -0
- package/server/lib/server/server-profile.test.js +58 -0
- package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
- package/server/lib/server/tunnel-service.js +8 -1
- package/server/lib/stt/config-store.js +3 -2
- package/server/lib/terminal/DOCUMENTATION.md +1 -1
- package/server/lib/tunnels/DOCUMENTATION.md +38 -18
- package/server/lib/ui-auth/ui-auth.js +9 -2
- package/server/lib/ui-auth/ui-passkeys.js +9 -1
- package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
- package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
- package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
- package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
- package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
- package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
|
@@ -12,23 +12,29 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
12
12
|
- `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` in rpc-like mode with a daemon-owned UI bridge, so pi extensions load exactly as they do under the Pi CLI's RPC mode. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
|
|
13
13
|
- Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces; extension live state is kept in per-session maps and included in both `sessions.open` and `session.snapshot`. The open response must cover every extension event at or below its `lastSequence`, so first attach cannot skip one-time startup statuses before the browser stream connects; reconnect snapshots rebuild the same live panels. TUI-only component replacement, footers, and themes remain intentional no-ops; standard RPC editor replacement and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
|
|
14
14
|
- `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
|
|
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.
|
|
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, persists an accepted ownership claim before acknowledging it over IPC, 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
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
|
-
- `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
|
|
20
|
-
- `../
|
|
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 same-profile daemon with a different entrypoint is claimed and then shut down through authenticated IPC 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
|
+
- `../server/server-profile.js` derives one stable daemon profile per server: installed web is `web-p<port>`, development web is `web-dev-p<port>`, installed desktop is `desktop`, and development desktop is `desktop-dev`. `PICHAMBER_SERVER_PROFILE` overrides the derivation with a hashed `custom-<hash>` key so raw input never becomes a path, while preserving whether the launcher is a development build for stale-code replacement. The profile key is stable across restarts; the server instance id is a fresh UUID per launch. Development launchers (`scripts/dev-web-hmr.mjs`, `scripts/dev-web-full.mjs`, `cross-env` in the `dev:server` scripts, `PICHAMBER_ELECTRON_DEV`) explicitly mark themselves so stopping development can never terminate the installed daemon.
|
|
21
|
+
- `../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.
|
|
22
|
+
- `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.
|
|
23
|
+
- `../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.
|
|
21
24
|
- `*.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.
|
|
22
25
|
|
|
23
26
|
## Protocol and security invariants
|
|
24
27
|
|
|
25
|
-
-
|
|
28
|
+
- Each profile owns its daemon artifacts: `<dataDir>/pi/daemons/<profileKey>/` holds the credential, `daemon-state.json`, and `operation.lock`; the endpoint is `<runtimeDir>/pi-daemons/<profileKey>/daemon.sock` (or `$XDG_RUNTIME_DIR` equivalent); per-profile logs append to `<dataDir>/logs/pi-daemon-<profileKey>.log`. The state sidecar records `profileKey`, `serverInstanceId`, `serverPid`, `daemonId`, `runtime`, and `buildId` alongside pid, endpoint, and entrypoint. A pre-profile legacy daemon is never adopted, unlinked, or signaled; only its dead pid record is best-effort removed.
|
|
29
|
+
- The endpoint is a Unix domain socket on POSIX or a Windows named pipe. TCP endpoints are rejected. Listeners and clients connect with IPC `path` options so Windows `\\.\pipe\pichamber-pi-session-daemon-<owner-key>-<profileKey>` works the same as a POSIX socket path. `PICHAMBER_PI_SESSION_DAEMON_ENDPOINT` still overrides the socket path, but the credential, state, and lock stay per-profile: a profile never adopts, unlinks, or signals an endpoint it cannot authenticate and identify as its own, and the conflict surfaces as `DAEMON_ENDPOINT_UNVERIFIED`.
|
|
26
30
|
- POSIX socket parent directories are mode `0700`; the socket is created mode `0600`. An existing endpoint fails startup rather than being unlinked without daemon-identity verification. Windows named-pipe ACLs are not yet equivalent owner-only OS permissions; credential authentication remains mandatory.
|
|
27
|
-
- The daemon credential and non-secret state sidecars are mode `0600`; their
|
|
31
|
+
- 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.
|
|
32
|
+
- 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).
|
|
33
|
+
- 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.
|
|
28
34
|
- The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
|
|
29
35
|
- A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
|
|
30
|
-
- Frames are LF-delimited JSON.
|
|
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.update/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. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes remain rejected while the active session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. 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.
|
|
36
|
+
- Frames are LF-delimited JSON. One frame has a 16 MiB maximum. Complete frames are parsed before the client bounds the remaining incomplete frame. Invalid JSON reports `MALFORMED_DAEMON_RESPONSE`; an oversized response reports `DAEMON_RESPONSE_TOO_LARGE`. A malformed, oversized, unauthenticated, or invalid request closes the connection.
|
|
37
|
+
- The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes remain rejected while the active session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
|
|
32
38
|
- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
|
|
33
39
|
- 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
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.
|
|
@@ -36,11 +42,11 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
36
42
|
- After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. Agent and compaction starts cancel pending disposal, and the timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative.
|
|
37
43
|
- A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
|
|
38
44
|
- After a forced crash, the next health, request, or subscription probe re-runs supervised startup. Each private health probe uses the supervisor's five-second operation budget; it must not inherit the general 30-second command timeout and hold every browser request until the browser aborts. Daemon readiness has its own 15-second bounded budget, separate from the shorter probe, lock, and shutdown budget, because loading Pi settings and provider/model catalogs can legitimately exceed five seconds. The supervisor removes an existing POSIX socket only when its recorded daemon PID is dead, the endpoint is a socket, and authenticated IPC deterministically refuses or times out. An endpoint that responds, authenticates incorrectly, returns malformed protocol data, or cannot be classified remains `DAEMON_ENDPOINT_UNVERIFIED`.
|
|
39
|
-
- The web server
|
|
45
|
+
- The web server creates its supervisor after HTTP listen so the profile key uses the bound port, then warms it without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`. The bound profile key travels back over the `pichamber:ready` IPC message and into the CLI instance file; `pichamber logs` uses that key to include the matching private daemon log, while `--json` and `--quiet` serve output still carries only the port.
|
|
40
46
|
- The daemon owns the runtime after clients disconnect. Disconnecting the web-server client cannot stop active Pi work.
|
|
41
47
|
|
|
42
48
|
## Deliberate limits
|
|
43
49
|
|
|
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.
|
|
50
|
+
This module defines the authenticated session API boundary consumed by the Pi-native session UI. Session leases coordinate PiChamber daemons only: the standalone `pi` CLI runs its own foreground runtime and does not honor these leases, so concurrently editing the same session through PiChamber and `pi` remains unsupported until Pi provides compatible upstream locking. Resource configuration and richer attachment extraction remain owned by their dedicated workstreams. The session event stream is SSE over the existing authenticated runtime transport; WebSocket callers fall back to it, preserving direct and relay behavior without a second daemon listener. The public route emits named heartbeat events so native `EventSource` clients can detect a silent foreground connection, reconnect, and resume from their last accepted sequence.
|
|
45
51
|
|
|
46
52
|
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.
|
|
@@ -15,6 +15,13 @@ const credentialFile = argument('--credential-file');
|
|
|
15
15
|
const stateFile = argument('--state-file');
|
|
16
16
|
const cwd = argument('--cwd');
|
|
17
17
|
const agentDir = argument('--agent-dir');
|
|
18
|
+
const profileKey = argument('--profile-key');
|
|
19
|
+
const serverInstanceId = argument('--server-instance-id');
|
|
20
|
+
const serverPid = Number(argument('--server-pid'));
|
|
21
|
+
const daemonId = argument('--daemon-id');
|
|
22
|
+
const daemonRuntime = argument('--runtime');
|
|
23
|
+
const buildId = argument('--build-id');
|
|
24
|
+
const startedAt = new Date().toISOString();
|
|
18
25
|
|
|
19
26
|
const exitWithFailure = (code) => {
|
|
20
27
|
// Do not log configuration paths, credentials, or session data from this
|
|
@@ -39,12 +46,21 @@ const writeState = async (state) => {
|
|
|
39
46
|
await chmodIfPossible(stateFile, 0o600);
|
|
40
47
|
};
|
|
41
48
|
|
|
42
|
-
const writeReadyState = (
|
|
49
|
+
const writeReadyState = ({
|
|
50
|
+
ownerServerInstanceId = serverInstanceId,
|
|
51
|
+
ownerServerPid = serverPid,
|
|
52
|
+
} = {}) => writeState({
|
|
43
53
|
protocolVersion: 1,
|
|
44
54
|
pid: process.pid,
|
|
45
55
|
endpoint,
|
|
46
56
|
entrypoint: DAEMON_ENTRYPOINT,
|
|
47
|
-
startedAt
|
|
57
|
+
startedAt,
|
|
58
|
+
profileKey,
|
|
59
|
+
serverInstanceId: ownerServerInstanceId,
|
|
60
|
+
serverPid: ownerServerPid,
|
|
61
|
+
daemonId,
|
|
62
|
+
runtime: daemonRuntime || 'web',
|
|
63
|
+
buildId: buildId || 'unknown',
|
|
48
64
|
});
|
|
49
65
|
|
|
50
66
|
const writeFailureState = (code) => writeState({
|
|
@@ -53,6 +69,12 @@ const writeFailureState = (code) => writeState({
|
|
|
53
69
|
endpoint,
|
|
54
70
|
state: 'failed',
|
|
55
71
|
error: { code },
|
|
72
|
+
profileKey,
|
|
73
|
+
serverInstanceId,
|
|
74
|
+
serverPid,
|
|
75
|
+
daemonId,
|
|
76
|
+
runtime: daemonRuntime || 'web',
|
|
77
|
+
buildId: buildId || 'unknown',
|
|
56
78
|
});
|
|
57
79
|
|
|
58
80
|
const removeOwnState = async () => {
|
|
@@ -64,11 +86,21 @@ const removeOwnState = async () => {
|
|
|
64
86
|
}
|
|
65
87
|
};
|
|
66
88
|
|
|
67
|
-
if (!endpoint || !credentialFile || !stateFile || !cwd
|
|
89
|
+
if (!endpoint || !credentialFile || !stateFile || !cwd || !profileKey || !serverInstanceId
|
|
90
|
+
|| !Number.isInteger(serverPid) || serverPid <= 0 || !daemonId) {
|
|
68
91
|
exitWithFailure(64);
|
|
69
92
|
} else {
|
|
70
93
|
let daemon;
|
|
71
94
|
let stopping = false;
|
|
95
|
+
const stop = async () => {
|
|
96
|
+
if (stopping) return;
|
|
97
|
+
stopping = true;
|
|
98
|
+
try {
|
|
99
|
+
await daemon?.stop();
|
|
100
|
+
} finally {
|
|
101
|
+
await removeOwnState();
|
|
102
|
+
}
|
|
103
|
+
};
|
|
72
104
|
try {
|
|
73
105
|
const credential = (await readFile(credentialFile, 'utf8')).trim();
|
|
74
106
|
daemon = createSessionDaemon({
|
|
@@ -76,7 +108,20 @@ if (!endpoint || !credentialFile || !stateFile || !cwd) {
|
|
|
76
108
|
credential,
|
|
77
109
|
cwd,
|
|
78
110
|
...(agentDir ? { agentDir } : {}),
|
|
111
|
+
profileKey,
|
|
112
|
+
serverInstanceId,
|
|
113
|
+
serverPid,
|
|
114
|
+
daemonId,
|
|
115
|
+
daemonRuntime: daemonRuntime || 'web',
|
|
116
|
+
buildId: buildId || 'unknown',
|
|
79
117
|
healthMetadata: { daemonPid: process.pid },
|
|
118
|
+
onOwnershipClaim: ({ serverInstanceId: nextServerInstanceId, serverPid: nextServerPid }) => writeReadyState({
|
|
119
|
+
ownerServerInstanceId: nextServerInstanceId,
|
|
120
|
+
ownerServerPid: nextServerPid,
|
|
121
|
+
}),
|
|
122
|
+
onShutdown: () => {
|
|
123
|
+
void stop().finally(() => process.exit(0));
|
|
124
|
+
},
|
|
80
125
|
});
|
|
81
126
|
await daemon.start();
|
|
82
127
|
await writeReadyState();
|
|
@@ -98,16 +143,6 @@ if (!endpoint || !credentialFile || !stateFile || !cwd) {
|
|
|
98
143
|
exitWithFailure(1);
|
|
99
144
|
}
|
|
100
145
|
|
|
101
|
-
const stop = async () => {
|
|
102
|
-
if (stopping) return;
|
|
103
|
-
stopping = true;
|
|
104
|
-
try {
|
|
105
|
-
await daemon?.stop();
|
|
106
|
-
} finally {
|
|
107
|
-
await removeOwnState();
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
|
|
111
146
|
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
112
147
|
process.once(signal, () => {
|
|
113
148
|
void stop().finally(() => process.exit(0));
|
|
@@ -2,8 +2,10 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { createConnection } from 'node:net';
|
|
3
3
|
import { StringDecoder } from 'node:string_decoder';
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
import {
|
|
6
|
+
SESSION_DAEMON_MAX_FRAME_BYTES as MAX_FRAME_BYTES,
|
|
7
|
+
SESSION_DAEMON_PROTOCOL_VERSION as PROTOCOL_VERSION,
|
|
8
|
+
} from './ipc-protocol.js';
|
|
7
9
|
|
|
8
10
|
export class SessionDaemonClientError extends Error {
|
|
9
11
|
constructor(code, message = 'The Pi session daemon is unavailable.') {
|
|
@@ -41,17 +43,20 @@ export const requestSessionDaemon = ({ endpoint, credential, command, payload, t
|
|
|
41
43
|
});
|
|
42
44
|
socket.on('data', (chunk) => {
|
|
43
45
|
buffer += decoder.write(chunk);
|
|
44
|
-
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
|
|
45
|
-
fail('MALFORMED_DAEMON_RESPONSE');
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
46
|
|
|
49
47
|
while (true) {
|
|
50
48
|
const newline = buffer.indexOf('\n');
|
|
51
|
-
if (newline === -1)
|
|
49
|
+
if (newline === -1) {
|
|
50
|
+
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) fail('DAEMON_RESPONSE_TOO_LARGE');
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
52
53
|
const line = buffer.slice(0, newline).replace(/\r$/, '');
|
|
53
54
|
buffer = buffer.slice(newline + 1);
|
|
54
55
|
if (!line) continue;
|
|
56
|
+
if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
|
|
57
|
+
fail('DAEMON_RESPONSE_TOO_LARGE');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
55
60
|
|
|
56
61
|
let message;
|
|
57
62
|
try {
|
|
@@ -113,13 +118,19 @@ export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSe
|
|
|
113
118
|
});
|
|
114
119
|
socket.on('data', (chunk) => {
|
|
115
120
|
buffer += decoder.write(chunk);
|
|
116
|
-
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) return fail(new SessionDaemonClientError('MALFORMED_DAEMON_RESPONSE'));
|
|
117
121
|
while (true) {
|
|
118
122
|
const newline = buffer.indexOf('\n');
|
|
119
|
-
if (newline === -1)
|
|
123
|
+
if (newline === -1) {
|
|
124
|
+
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) fail(new SessionDaemonClientError('DAEMON_RESPONSE_TOO_LARGE'));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
120
127
|
const line = buffer.slice(0, newline).replace(/\r$/, '');
|
|
121
128
|
buffer = buffer.slice(newline + 1);
|
|
122
129
|
if (!line) continue;
|
|
130
|
+
if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
|
|
131
|
+
fail(new SessionDaemonClientError('DAEMON_RESPONSE_TOO_LARGE'));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
123
134
|
let message;
|
|
124
135
|
try { message = JSON.parse(line); } catch { fail(new SessionDaemonClientError('MALFORMED_DAEMON_RESPONSE')); return; }
|
|
125
136
|
if (message.protocolVersion !== PROTOCOL_VERSION) { fail(new SessionDaemonClientError('UNSUPPORTED_DAEMON_PROTOCOL')); return; }
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import { createServer } from 'node:net';
|
|
3
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import { requestSessionDaemon } from './ipc-client.js';
|
|
9
|
+
import { SESSION_DAEMON_MAX_FRAME_BYTES } from './ipc-protocol.js';
|
|
10
|
+
|
|
11
|
+
const credential = 'test-private-credential';
|
|
12
|
+
const roots = [];
|
|
13
|
+
const servers = [];
|
|
14
|
+
|
|
15
|
+
const endpointFor = (root) => process.platform === 'win32'
|
|
16
|
+
? `\\\\.\\pipe\\pichamber-ipc-test-${createHash('sha1').update(root).digest('hex').slice(0, 16)}`
|
|
17
|
+
: join(root, 'daemon.sock');
|
|
18
|
+
|
|
19
|
+
const startServer = async (respond) => {
|
|
20
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-ipc-client-'));
|
|
21
|
+
roots.push(root);
|
|
22
|
+
const endpoint = endpointFor(root);
|
|
23
|
+
const server = createServer((socket) => {
|
|
24
|
+
socket.on('error', () => {});
|
|
25
|
+
let buffer = '';
|
|
26
|
+
socket.on('data', (chunk) => {
|
|
27
|
+
buffer += chunk.toString('utf8');
|
|
28
|
+
while (buffer.includes('\n')) {
|
|
29
|
+
const newline = buffer.indexOf('\n');
|
|
30
|
+
const line = buffer.slice(0, newline);
|
|
31
|
+
buffer = buffer.slice(newline + 1);
|
|
32
|
+
if (!line) continue;
|
|
33
|
+
const frame = JSON.parse(line);
|
|
34
|
+
if (frame.kind === 'authenticate') {
|
|
35
|
+
socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'authenticated' })}\n`);
|
|
36
|
+
} else if (frame.kind === 'request') {
|
|
37
|
+
respond(socket, frame);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
servers.push(server);
|
|
43
|
+
await new Promise((resolve, reject) => {
|
|
44
|
+
server.once('error', reject);
|
|
45
|
+
server.listen({ path: endpoint }, resolve);
|
|
46
|
+
});
|
|
47
|
+
return endpoint;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
afterEach(async () => {
|
|
51
|
+
await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
|
|
52
|
+
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe('session daemon IPC client framing', () => {
|
|
56
|
+
it('distinguishes malformed JSON from an oversized response frame', async () => {
|
|
57
|
+
const malformedEndpoint = await startServer((socket) => socket.end('{not-json}\n'));
|
|
58
|
+
await expect(requestSessionDaemon({
|
|
59
|
+
endpoint: malformedEndpoint,
|
|
60
|
+
credential,
|
|
61
|
+
command: 'runtime.health',
|
|
62
|
+
})).rejects.toMatchObject({ code: 'MALFORMED_DAEMON_RESPONSE' });
|
|
63
|
+
|
|
64
|
+
const oversizedEndpoint = await startServer((socket) => {
|
|
65
|
+
socket.end(`${'A'.repeat(SESSION_DAEMON_MAX_FRAME_BYTES + 1)}\n`);
|
|
66
|
+
});
|
|
67
|
+
await expect(requestSessionDaemon({
|
|
68
|
+
endpoint: oversizedEndpoint,
|
|
69
|
+
credential,
|
|
70
|
+
command: 'runtime.health',
|
|
71
|
+
})).rejects.toMatchObject({ code: 'DAEMON_RESPONSE_TOO_LARGE' });
|
|
72
|
+
}, 20_000);
|
|
73
|
+
|
|
74
|
+
it('parses complete frames before bounding the incomplete remainder', async () => {
|
|
75
|
+
const endpoint = await startServer((socket, request) => {
|
|
76
|
+
const response = JSON.stringify({
|
|
77
|
+
protocolVersion: 1,
|
|
78
|
+
kind: 'response',
|
|
79
|
+
requestId: request.requestId,
|
|
80
|
+
result: { ok: true },
|
|
81
|
+
});
|
|
82
|
+
socket.end(`${response}\n${'A'.repeat(SESSION_DAEMON_MAX_FRAME_BYTES)}`);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
await expect(requestSessionDaemon({ endpoint, credential, command: 'runtime.health' }))
|
|
86
|
+
.resolves.toEqual({ ok: true });
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const SESSION_DAEMON_PROTOCOL_VERSION = 1;
|
|
2
|
+
export const SESSION_DAEMON_MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
3
|
+
|
|
4
|
+
// Keep normal transcript pages well below the hard frame ceiling. The final
|
|
5
|
+
// encoded response contains protocol and session metadata in addition to the
|
|
6
|
+
// projected messages.
|
|
7
|
+
export const SESSION_DAEMON_MESSAGE_PAGE_TARGET_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
export const SESSION_DAEMON_DEFAULT_MESSAGE_PAGE_LIMIT = 50;
|
|
9
|
+
export const SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT = 100;
|