@pi-chamber/web 0.3.3 → 0.5.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.
- package/README.md +1 -0
- package/bin/lib/cli-startup.js +1 -0
- package/dist/assets/CommitSection-Cz-ACBaD.js +1 -0
- package/dist/assets/DiagramEditor-BNUOrd9m.js +1 -0
- package/dist/assets/DiagramView-D4YR9YRt.js +1 -0
- package/dist/assets/{DiffView-DGD9DMS7.js → DiffView-DPW8dcg_.js} +3 -3
- package/dist/assets/FilesView-BFGIdY6b.js +14 -0
- package/dist/assets/GitView-CKtiKOfJ.js +6 -0
- package/dist/assets/JsonTreeView-c-UJUw3D.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-V1HMFCjr.js → MarkdownRendererImpl-CvC9eXoa.js} +2 -2
- package/dist/assets/PatchDiff-YGHsZUIR.js +1 -0
- package/dist/assets/PierreDiffViewer-CoXa-JJK.js +136 -0
- package/dist/assets/SessionSwitcherContent-B7eep3dO.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-CZOFeJHH.js +2 -0
- package/dist/assets/SessionUnreadDot-ClpeYFPz.js +1 -0
- package/dist/assets/SettingsView-CPmHHDbQ.js +4 -0
- package/dist/assets/SettingsWindow-2CBpoJ8H.js +1 -0
- package/dist/assets/{ToolOutputDialog-2zKUdGYL.js → ToolOutputDialog-HMW-Kh19.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-C3nbNbxk.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-UMgLcO4Q.js → VirtualizedFileDiff-DEX83nQ0.js} +3 -3
- package/dist/assets/{SessionSwitcherDropdown-o1RjhCfF.js → WindowsWindowControls-PPk5H89-.js} +172 -118
- package/dist/assets/collapsible-Dux-9hAC.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-Cy0nxMJB.js +3 -0
- package/dist/assets/contextFileOpenGuard-Dn_38hd9.js +1 -0
- package/dist/assets/index--zDkVFU6.css +1 -0
- package/dist/assets/index-DU2OBBy5.js +8 -0
- package/dist/assets/index-EN7MioVf.js +1 -0
- package/dist/assets/isDiffPlainText-DSWRVq-W.js +1 -0
- package/dist/assets/isFilePlainText-7RAjjrQ5.js +1 -0
- package/dist/assets/{main-CmkRaMOR.js → main-BGKjg-qW.js} +8 -8
- package/dist/assets/main-DGHrBx_u.js +2 -0
- package/dist/assets/markdownCore-BYPqQtbE.js +3 -0
- package/dist/assets/miniChat-DW2PVX49.js +2 -0
- package/dist/assets/mobile-0Gxc02iO.js +2 -0
- package/dist/assets/renderElectronMiniChatApp-C-qpqp1i.js +2 -0
- package/dist/assets/renderMobileApp-UB9bhC1x.js +14 -0
- package/dist/assets/{runtimeSurface-CkHYYg0E.js → runtimeSurface-DefD-2Iv.js} +1 -1
- package/dist/assets/{useInlineCommentController-DD31jQNC.js → useInlineCommentController-B8p2XwXA.js} +2 -2
- package/dist/assets/usePanelSlide-CbqVf-y8.js +56 -0
- package/dist/assets/usePushVisibilityBeacon-CvjN-47R.js +10 -0
- package/dist/assets/useSwitcherItems-B6_F-J-z.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-Dp_Z-0GD.js → vendor-codemirror-language-data-BhBdEPsJ.js} +2 -2
- package/dist/assets/{vendor-katex-CHD9BdDO.js → vendor-katex-CNckGUMB.js} +1 -1
- package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
- package/dist/assets/{web-components-Cct1r-wn.js → web-components-C9yVPsWN.js} +2 -2
- package/dist/index.html +8 -5
- package/dist/mini-chat.html +7 -4
- package/dist/mobile.html +7 -4
- package/dist/sw.js +1 -1
- package/package.json +1 -1
- package/server/index.js +27 -5
- package/server/lib/fs/routes.js +0 -21
- package/server/lib/git/DOCUMENTATION.md +15 -5
- package/server/lib/git/issue-2746-longpaths.test.js +11 -11
- package/server/lib/git/routes.js +80 -4
- package/server/lib/git/routes.test.js +135 -0
- package/server/lib/git/service.js +144 -82
- package/server/lib/git/service.test.js +182 -36
- package/server/lib/pi/extension-protocol.js +62 -0
- package/server/lib/pi/extension-protocol.test.js +34 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +251 -0
- package/server/lib/pi/routes-extension-events.test.js +152 -0
- package/server/lib/pi/routes.js +345 -7
- package/server/lib/pi/routes.test.js +43 -28
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +8 -5
- package/server/lib/pi/session-daemon/extension-bridge.js +488 -0
- package/server/lib/pi/session-daemon/message-entry-aliases.js +53 -13
- package/server/lib/pi/session-daemon/message-entry-aliases.test.js +110 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +215 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +559 -0
- package/server/lib/pi/session-daemon/session-daemon.js +483 -54
- package/server/lib/pi/session-daemon/session-daemon.test.js +212 -4
- package/server/lib/pi/session-daemon/session-retry-limits.js +55 -0
- package/server/lib/pi/session-daemon/session-retry-limits.test.js +53 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.js +39 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.test.js +41 -0
- package/server/lib/pi/session-daemon/supervisor.js +3 -0
- package/server/lib/pi/small-model-generation.js +104 -0
- package/server/lib/pi/small-model-generation.test.js +66 -0
- package/server/lib/preview/proxy-runtime.js +11 -1
- package/server/lib/preview/proxy-runtime.test.js +3 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/server/cors.js +0 -2
- package/server/lib/server/cors.test.js +4 -4
- package/server/lib/stt/DOCUMENTATION.md +38 -0
- package/server/lib/stt/audio.js +47 -0
- package/server/lib/stt/config-store.js +81 -0
- package/server/lib/stt/config-store.test.js +36 -0
- package/server/lib/stt/local/model-catalog.js +57 -0
- package/server/lib/stt/local/model-downloader.js +127 -0
- package/server/lib/stt/local/recognizer.js +64 -0
- package/server/lib/stt/local/sherpa-loader.js +43 -0
- package/server/lib/stt/local/worker-client.js +115 -0
- package/server/lib/stt/local/worker-process.js +64 -0
- package/server/lib/stt/protocol.js +38 -0
- package/server/lib/stt/protocol.test.js +17 -0
- package/server/lib/stt/providers/local-worker-provider.js +11 -0
- package/server/lib/stt/providers/openai-compatible-provider.js +31 -0
- package/server/lib/stt/providers/openai-compatible-provider.test.js +31 -0
- package/server/lib/stt/runtime.js +111 -0
- package/server/lib/stt/service.js +106 -0
- package/server/lib/stt/stream-manager.js +188 -0
- package/server/lib/stt/stream-manager.test.js +64 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
- package/server/lib/ui-auth/ui-auth.js +8 -3
- package/server/lib/ui-auth/ui-auth.test.js +8 -0
- package/server/lib/workspace/host.js +19 -3
- package/dist/assets/CommitSection-BAYzLtBf.js +0 -1
- package/dist/assets/DiagramEditor-D1yc4joK.js +0 -1
- package/dist/assets/DiagramView-CAlJiG11.js +0 -1
- package/dist/assets/FilesView-DB5VI7EN.js +0 -14
- package/dist/assets/GitView-CFlPcSn9.js +0 -6
- package/dist/assets/JsonTreeView-CoX1ZscV.js +0 -1
- package/dist/assets/PatchDiff-D6Gs7K5B.js +0 -1
- package/dist/assets/PierreDiffViewer-COYd5Qr-.js +0 -136
- package/dist/assets/SettingsView-BYqvfMTS.js +0 -4
- package/dist/assets/SettingsWindow-CtNS0tQn.js +0 -1
- package/dist/assets/ToolPartDiffPreview-CBFC9min.js +0 -8
- package/dist/assets/collapsible-Kx4bmsQM.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DdOCbMyK.js +0 -3
- package/dist/assets/contextFileOpenGuard-BRldMp0d.js +0 -1
- package/dist/assets/index-BAqpUCjs.js +0 -8
- package/dist/assets/index-CuSNEV7s.js +0 -1
- package/dist/assets/index-riABQmQ_.css +0 -1
- package/dist/assets/isDiffPlainText-CGIf0q8p.js +0 -1
- package/dist/assets/isFilePlainText-D4hgTRxT.js +0 -1
- package/dist/assets/main-By_pvk90.js +0 -2
- package/dist/assets/markdownCore-CAVCyFnI.js +0 -2
- package/dist/assets/miniChat-_XK2gGZE.js +0 -2
- package/dist/assets/mobile-B4E4JqAf.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-Ca4hZgIz.js +0 -1
- package/dist/assets/renderMobileApp-ClA5Cnmw.js +0 -14
- package/dist/assets/usePanelSlide-a4c67FIY.js +0 -56
- package/dist/assets/useWindowTitle-DoHrUC5r.js +0 -10
- package/server/lib/pi/legacy-ui-model-defaults.js +0 -57
- package/server/lib/pi/legacy-ui-model-defaults.test.js +0 -65
|
@@ -6,15 +6,18 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
6
6
|
|
|
7
7
|
## Entrypoints
|
|
8
8
|
|
|
9
|
+
- `../extension-protocol.js` owns the bounded form descriptor and response validation shared by the private daemon bridge and public route projection, so both sides of the IPC seam accept the same field contract.
|
|
10
|
+
- `extension-bridge.js` owns extension UI bindings, pending dialog lifecycle, normalized status/widget/panel/app state, snapshot projection, and extension event publication. `session-daemon.js` supplies runtime lookup, publication, redaction, and directory dependencies through its narrow factory interface.
|
|
9
11
|
- `session-daemon.js`
|
|
10
|
-
- `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,
|
|
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
|
+
- 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; both are kept in per-session maps and replayed through `session.snapshot` so reconnects rebuild 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.
|
|
11
14
|
- `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
|
|
12
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.
|
|
13
16
|
- `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
|
|
14
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.
|
|
15
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.
|
|
16
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.
|
|
17
|
-
- `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, 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. `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.
|
|
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.
|
|
18
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.
|
|
19
22
|
|
|
20
23
|
## Protocol and security invariants
|
|
@@ -25,12 +28,12 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
25
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`.
|
|
26
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.
|
|
27
30
|
- Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
|
|
28
|
-
- 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`, 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; extensions
|
|
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.
|
|
29
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.
|
|
30
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.
|
|
31
|
-
- 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`. A later prompt on the same session invalidates
|
|
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.
|
|
32
35
|
- Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
|
|
33
|
-
- After `agent_settled
|
|
36
|
+
- 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.
|
|
34
37
|
- 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.
|
|
35
38
|
- 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`.
|
|
36
39
|
- The web server starts warming the supervisor immediately after HTTP listen without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`.
|
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
MAX_EXTENSION_APP_HTML_CHARS,
|
|
5
|
+
sanitizeExtensionFormFields,
|
|
6
|
+
validateExtensionFormValues,
|
|
7
|
+
} from '../extension-protocol.js';
|
|
8
|
+
|
|
9
|
+
const MAX_EXTENSION_PANELS_PER_SESSION = 24;
|
|
10
|
+
const MAX_EXTENSION_APPS_PER_SESSION = 8;
|
|
11
|
+
const MAX_EXTENSION_PANEL_ACTIONS = 8;
|
|
12
|
+
const MAX_EXTENSION_EDITOR_TEXT_CHARS = 100_000;
|
|
13
|
+
const MAX_EXTENSION_TITLE_CHARS = 256;
|
|
14
|
+
const PROVIDER_OBSERVER = Symbol('pichamber.extension-provider-observer');
|
|
15
|
+
const LABEL_OBSERVER = Symbol('pichamber.extension-label-observer');
|
|
16
|
+
|
|
17
|
+
const textFromContent = (content) => (
|
|
18
|
+
Array.isArray(content)
|
|
19
|
+
? content.filter((part) => part?.type === 'text' && typeof part.text === 'string').map((part) => part.text).join('')
|
|
20
|
+
: ''
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
/** Owns extension UI bridge state and translation for one daemon instance. */
|
|
24
|
+
export const createExtensionBridge = ({
|
|
25
|
+
publish,
|
|
26
|
+
resolveDirectory,
|
|
27
|
+
redactAttachmentPaths,
|
|
28
|
+
redactAttachmentValues,
|
|
29
|
+
findRuntimeBySessionId,
|
|
30
|
+
getDefaultDirectory,
|
|
31
|
+
getSequence,
|
|
32
|
+
protocolError,
|
|
33
|
+
requestSessionShutdown,
|
|
34
|
+
}) => {
|
|
35
|
+
const extensionStatusesBySession = new Map();
|
|
36
|
+
const extensionWidgetsBySession = new Map();
|
|
37
|
+
const extensionPanelsBySession = new Map();
|
|
38
|
+
const extensionAppsBySession = new Map();
|
|
39
|
+
const extensionTitlesBySession = new Map();
|
|
40
|
+
// --- Extension bridging -------------------------------------------------
|
|
41
|
+
// Pi extensions run inside each session runtime. Their user-interaction
|
|
42
|
+
// surface (dialogs, notifications, statuses, widgets) is translated here
|
|
43
|
+
// into public stream events; blocking dialogs are resolved by the
|
|
44
|
+
// `extensions.respond` daemon command.
|
|
45
|
+
const pendingExtensionDialogs = new Map();
|
|
46
|
+
|
|
47
|
+
const cancelPendingExtensionDialogs = (sessionId, reason = 'aborted') => {
|
|
48
|
+
for (const pending of pendingExtensionDialogs.values()) {
|
|
49
|
+
if (sessionId !== undefined && pending.sessionId !== sessionId) continue;
|
|
50
|
+
pending.settle({}, reason);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const directoryForSession = (sessionId) => findRuntimeBySessionId(sessionId)?.cwd || getDefaultDirectory();
|
|
55
|
+
const publishForSession = (event, payload, sessionId) => publish(event, payload, sessionId, directoryForSession(sessionId));
|
|
56
|
+
|
|
57
|
+
const clearOneExtensionState = (sessionId) => {
|
|
58
|
+
const statuses = extensionStatusesBySession.get(sessionId);
|
|
59
|
+
const widgets = extensionWidgetsBySession.get(sessionId);
|
|
60
|
+
const panels = extensionPanelsBySession.get(sessionId);
|
|
61
|
+
const apps = extensionAppsBySession.get(sessionId);
|
|
62
|
+
if (statuses) for (const key of statuses.keys()) publishForSession('extension.status', { key }, sessionId);
|
|
63
|
+
if (widgets) for (const key of widgets.keys()) publishForSession('extension.widget', { key }, sessionId);
|
|
64
|
+
if (panels) for (const id of panels.keys()) publishForSession('extension.ui', { id, removed: true }, sessionId);
|
|
65
|
+
if (apps) for (const appId of apps.keys()) publishForSession('extension.app', { appId, removed: true }, sessionId);
|
|
66
|
+
if (extensionTitlesBySession.has(sessionId)) publishForSession('extension.title', {}, sessionId);
|
|
67
|
+
extensionStatusesBySession.delete(sessionId);
|
|
68
|
+
extensionWidgetsBySession.delete(sessionId);
|
|
69
|
+
extensionPanelsBySession.delete(sessionId);
|
|
70
|
+
extensionAppsBySession.delete(sessionId);
|
|
71
|
+
extensionTitlesBySession.delete(sessionId);
|
|
72
|
+
cancelPendingExtensionDialogs(sessionId, 'session-closed');
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const clearExtensionState = (sessionId) => {
|
|
76
|
+
if (sessionId) {
|
|
77
|
+
clearOneExtensionState(sessionId);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const sessionIds = new Set([
|
|
81
|
+
...extensionStatusesBySession.keys(),
|
|
82
|
+
...extensionWidgetsBySession.keys(),
|
|
83
|
+
...extensionPanelsBySession.keys(),
|
|
84
|
+
...extensionAppsBySession.keys(),
|
|
85
|
+
...extensionTitlesBySession.keys(),
|
|
86
|
+
]);
|
|
87
|
+
for (const id of sessionIds) clearOneExtensionState(id);
|
|
88
|
+
cancelPendingExtensionDialogs(undefined, 'daemon-stopped');
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const publishCatalogChange = (sessionId, flags) => {
|
|
92
|
+
publishForSession('extension.catalog', flags, sessionId);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const installMutationObservers = (session) => {
|
|
96
|
+
const modelRuntime = session?.modelRuntime;
|
|
97
|
+
if (modelRuntime) {
|
|
98
|
+
const observer = modelRuntime[PROVIDER_OBSERVER];
|
|
99
|
+
if (observer) {
|
|
100
|
+
observer.sessionId = session.sessionId;
|
|
101
|
+
} else {
|
|
102
|
+
const state = { sessionId: session.sessionId };
|
|
103
|
+
Object.defineProperty(modelRuntime, PROVIDER_OBSERVER, { value: state });
|
|
104
|
+
for (const method of ['registerProvider', 'registerNativeProvider', 'unregisterProvider']) {
|
|
105
|
+
if (typeof modelRuntime[method] !== 'function') continue;
|
|
106
|
+
const original = modelRuntime[method].bind(modelRuntime);
|
|
107
|
+
modelRuntime[method] = (...args) => {
|
|
108
|
+
const result = original(...args);
|
|
109
|
+
if (!state.suppress) publishCatalogChange(state.sessionId, { providers: true });
|
|
110
|
+
return result;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const manager = session?.sessionManager;
|
|
117
|
+
if (manager && !manager[LABEL_OBSERVER] && typeof manager.appendLabelChange === 'function') {
|
|
118
|
+
Object.defineProperty(manager, LABEL_OBSERVER, { value: true });
|
|
119
|
+
const original = manager.appendLabelChange.bind(manager);
|
|
120
|
+
manager.appendLabelChange = (...args) => {
|
|
121
|
+
const result = original(...args);
|
|
122
|
+
publishForSession('session.tree.updated', {}, session.sessionId);
|
|
123
|
+
return result;
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const createExtensionUIContext = (sessionId) => {
|
|
129
|
+
const dialog = (method, fields, opts, parseResponse) => {
|
|
130
|
+
const requestId = randomUUID();
|
|
131
|
+
return new Promise((resolve) => {
|
|
132
|
+
const settle = (response, reason = 'answered') => {
|
|
133
|
+
if (pendingExtensionDialogs.get(requestId)?.settle !== settle) return;
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
signal?.removeEventListener('abort', onAbort);
|
|
136
|
+
pendingExtensionDialogs.delete(requestId);
|
|
137
|
+
publish('extension.dialog.dismiss', { requestId, reason }, sessionId);
|
|
138
|
+
resolve(parseResponse(response));
|
|
139
|
+
};
|
|
140
|
+
const onAbort = () => settle({}, 'aborted');
|
|
141
|
+
const timer = opts?.timeout
|
|
142
|
+
? setTimeout(() => settle({}, 'timeout'), opts.timeout)
|
|
143
|
+
: undefined;
|
|
144
|
+
const signal = opts?.signal;
|
|
145
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
146
|
+
const payload = {
|
|
147
|
+
requestId,
|
|
148
|
+
method,
|
|
149
|
+
...fields,
|
|
150
|
+
...(Number.isFinite(opts?.timeout) ? { timeoutMs: opts.timeout } : {}),
|
|
151
|
+
};
|
|
152
|
+
pendingExtensionDialogs.set(requestId, { sessionId, settle, timer, payload });
|
|
153
|
+
publish('extension.dialog', payload, sessionId);
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
return {
|
|
158
|
+
select: (title, options, opts) => dialog(
|
|
159
|
+
'select',
|
|
160
|
+
{ title, options: options.map((option) => String(option)) },
|
|
161
|
+
opts,
|
|
162
|
+
(response) => (typeof response?.value === 'string' ? response.value : undefined),
|
|
163
|
+
),
|
|
164
|
+
confirm: (title, message, opts) => dialog(
|
|
165
|
+
'confirm',
|
|
166
|
+
{ title, message },
|
|
167
|
+
opts,
|
|
168
|
+
(response) => response?.confirmed === true,
|
|
169
|
+
),
|
|
170
|
+
input: (title, placeholder, opts) => dialog(
|
|
171
|
+
'input',
|
|
172
|
+
{ title, ...(typeof placeholder === 'string' ? { placeholder } : {}) },
|
|
173
|
+
opts,
|
|
174
|
+
(response) => (typeof response?.value === 'string' ? response.value : undefined),
|
|
175
|
+
),
|
|
176
|
+
form: (title, fields, opts) => {
|
|
177
|
+
// PiChamber-specific extension of the pi UI bridge (gate with
|
|
178
|
+
// isPiChamber(ctx)): structured multi-input dialogs resolved with a
|
|
179
|
+
// values object keyed by field id.
|
|
180
|
+
const sanitizedFields = sanitizeExtensionFormFields(fields);
|
|
181
|
+
return dialog(
|
|
182
|
+
'form',
|
|
183
|
+
{ title, ...(sanitizedFields.length > 0 ? { fields: sanitizedFields } : {}) },
|
|
184
|
+
opts,
|
|
185
|
+
(response) => (response?.values && typeof response.values === 'object' && !Array.isArray(response.values)
|
|
186
|
+
? response.values
|
|
187
|
+
: undefined),
|
|
188
|
+
);
|
|
189
|
+
},
|
|
190
|
+
editor: (title, prefill) => dialog(
|
|
191
|
+
'editor',
|
|
192
|
+
{ title, ...(typeof prefill === 'string' ? { prefill } : {}) },
|
|
193
|
+
undefined,
|
|
194
|
+
(response) => (typeof response?.value === 'string' ? response.value : undefined),
|
|
195
|
+
),
|
|
196
|
+
notify: (message, level) => {
|
|
197
|
+
publish('extension.notify', {
|
|
198
|
+
message: String(message ?? ''),
|
|
199
|
+
...(level === 'warning' || level === 'error' ? { level } : { level: 'info' }),
|
|
200
|
+
}, sessionId);
|
|
201
|
+
},
|
|
202
|
+
setStatus: (key, text) => {
|
|
203
|
+
if (typeof key !== 'string' || key.length === 0) return;
|
|
204
|
+
// Mirror into server-side normalized state for snapshot / reconnect.
|
|
205
|
+
const statuses = extensionStatusesBySession.get(sessionId) ?? new Map();
|
|
206
|
+
if (typeof text === 'string' && text.length > 0) statuses.set(key, String(text).slice(0, 1000));
|
|
207
|
+
else statuses.delete(key);
|
|
208
|
+
if (statuses.size === 0) extensionStatusesBySession.delete(sessionId);
|
|
209
|
+
else extensionStatusesBySession.set(sessionId, statuses);
|
|
210
|
+
publish('extension.status', {
|
|
211
|
+
key,
|
|
212
|
+
...(typeof text === 'string' && text.length > 0 ? { text: String(text).slice(0, 1000) } : {}),
|
|
213
|
+
}, sessionId);
|
|
214
|
+
},
|
|
215
|
+
setWidget: (key, content, options) => {
|
|
216
|
+
if (typeof key !== 'string' || key.length === 0) return;
|
|
217
|
+
// Only string-array widgets are representable over the wire.
|
|
218
|
+
if (content !== undefined && !Array.isArray(content)) return;
|
|
219
|
+
const widgets = extensionWidgetsBySession.get(sessionId) ?? new Map();
|
|
220
|
+
if (Array.isArray(content) && content.length > 0) {
|
|
221
|
+
const lines = content.map((line) => String(line).slice(0, 2000)).slice(0, 100);
|
|
222
|
+
const placement = options?.placement === 'belowEditor' ? 'belowEditor' : 'aboveEditor';
|
|
223
|
+
widgets.set(key, { lines, placement });
|
|
224
|
+
} else {
|
|
225
|
+
widgets.delete(key);
|
|
226
|
+
}
|
|
227
|
+
if (widgets.size === 0) extensionWidgetsBySession.delete(sessionId);
|
|
228
|
+
else extensionWidgetsBySession.set(sessionId, widgets);
|
|
229
|
+
publish('extension.widget', {
|
|
230
|
+
key,
|
|
231
|
+
...(Array.isArray(content) && content.length > 0 ? { lines: content.map((line) => String(line).slice(0, 2000)).slice(0, 100) } : {}),
|
|
232
|
+
...(options?.placement === 'belowEditor' ? { placement: 'belowEditor' } : Array.isArray(content) && content.length > 0 ? { placement: 'aboveEditor' } : {}),
|
|
233
|
+
}, sessionId);
|
|
234
|
+
},
|
|
235
|
+
// Terminal-only surfaces have no PiChamber equivalent yet.
|
|
236
|
+
onTerminalInput: () => () => {},
|
|
237
|
+
setWorkingMessage: () => {},
|
|
238
|
+
setWorkingVisible: () => {},
|
|
239
|
+
setWorkingIndicator: () => {},
|
|
240
|
+
setHiddenThinkingLabel: () => {},
|
|
241
|
+
setFooter: () => {},
|
|
242
|
+
setHeader: () => {},
|
|
243
|
+
setTitle: (value) => {
|
|
244
|
+
const title = String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, MAX_EXTENSION_TITLE_CHARS);
|
|
245
|
+
if (title) extensionTitlesBySession.set(sessionId, title);
|
|
246
|
+
else extensionTitlesBySession.delete(sessionId);
|
|
247
|
+
publishForSession('extension.title', title ? { title } : {}, sessionId);
|
|
248
|
+
},
|
|
249
|
+
custom: async () => undefined,
|
|
250
|
+
pasteToEditor: (value) => {
|
|
251
|
+
publishForSession('extension.editor', { text: String(value ?? '').slice(0, MAX_EXTENSION_EDITOR_TEXT_CHARS) }, sessionId);
|
|
252
|
+
},
|
|
253
|
+
setEditorText: (value) => {
|
|
254
|
+
publishForSession('extension.editor', { text: String(value ?? '').slice(0, MAX_EXTENSION_EDITOR_TEXT_CHARS) }, sessionId);
|
|
255
|
+
},
|
|
256
|
+
getEditorText: () => '',
|
|
257
|
+
addAutocompleteProvider: () => {},
|
|
258
|
+
setEditorComponent: () => {},
|
|
259
|
+
getEditorComponent: () => undefined,
|
|
260
|
+
getAllThemes: () => [],
|
|
261
|
+
getTheme: () => undefined,
|
|
262
|
+
setTheme: () => ({ success: false, error: 'Theme switching is not supported in PiChamber sessions.' }),
|
|
263
|
+
getToolsExpanded: () => false,
|
|
264
|
+
setToolsExpanded: () => {},
|
|
265
|
+
// Extensions may style status/widget strings with theme helpers; those
|
|
266
|
+
// strings are rendered as plain text in PiChamber, so pass them through.
|
|
267
|
+
get theme() {
|
|
268
|
+
return identityTheme;
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
const identityTheme = {
|
|
274
|
+
fg: (_color, text) => text,
|
|
275
|
+
bg: (_color, text) => text,
|
|
276
|
+
bold: (text) => text,
|
|
277
|
+
italic: (text) => text,
|
|
278
|
+
strikethrough: (text) => text,
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const buildExtensionBindings = (session) => {
|
|
282
|
+
installMutationObservers(session);
|
|
283
|
+
return {
|
|
284
|
+
uiContext: createExtensionUIContext(session.sessionId),
|
|
285
|
+
mode: 'rpc',
|
|
286
|
+
commandContextActions: {
|
|
287
|
+
waitForIdle: () => session.waitForIdle(),
|
|
288
|
+
newSession: async (options) => {
|
|
289
|
+
const owner = findRuntimeBySessionId(session.sessionId);
|
|
290
|
+
if (!owner) throw new Error('Session runtime is no longer available.');
|
|
291
|
+
return owner.newSession(options);
|
|
292
|
+
},
|
|
293
|
+
fork: async (entryId, forkOptions) => {
|
|
294
|
+
const owner = findRuntimeBySessionId(session.sessionId);
|
|
295
|
+
if (!owner) throw new Error('Session runtime is no longer available.');
|
|
296
|
+
const result = await owner.fork(entryId, forkOptions);
|
|
297
|
+
return { cancelled: result.cancelled };
|
|
298
|
+
},
|
|
299
|
+
navigateTree: async (targetId, navigateOptions) => {
|
|
300
|
+
const result = await session.navigateTree(targetId, {
|
|
301
|
+
summarize: navigateOptions?.summarize,
|
|
302
|
+
customInstructions: navigateOptions?.customInstructions,
|
|
303
|
+
replaceInstructions: navigateOptions?.replaceInstructions,
|
|
304
|
+
label: navigateOptions?.label,
|
|
305
|
+
});
|
|
306
|
+
return { cancelled: result.cancelled };
|
|
307
|
+
},
|
|
308
|
+
switchSession: async (sessionPath, switchOptions) => {
|
|
309
|
+
const owner = findRuntimeBySessionId(session.sessionId);
|
|
310
|
+
if (!owner) throw new Error('Session runtime is no longer available.');
|
|
311
|
+
return owner.switchSession(sessionPath, switchOptions);
|
|
312
|
+
},
|
|
313
|
+
reload: async () => {
|
|
314
|
+
clearExtensionState(session.sessionId);
|
|
315
|
+
const providerObserver = session.modelRuntime?.[PROVIDER_OBSERVER];
|
|
316
|
+
if (providerObserver) providerObserver.suppress = true;
|
|
317
|
+
try {
|
|
318
|
+
await session.reload();
|
|
319
|
+
} finally {
|
|
320
|
+
if (providerObserver) providerObserver.suppress = false;
|
|
321
|
+
}
|
|
322
|
+
publishCatalogChange(session.sessionId, { providers: true, resources: true, commands: true });
|
|
323
|
+
},
|
|
324
|
+
},
|
|
325
|
+
shutdownHandler: () => requestSessionShutdown?.(session.sessionId),
|
|
326
|
+
onError: (error) => {
|
|
327
|
+
publish('extension.error', {
|
|
328
|
+
source: typeof error?.extensionPath === 'string' ? error.extensionPath : 'unknown',
|
|
329
|
+
...(typeof error?.event === 'string' ? { event: error.event } : {}),
|
|
330
|
+
message: String(error?.error ?? 'Unknown extension error.'),
|
|
331
|
+
}, session.sessionId);
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
// Resolves a pending extension dialog. Unknown or already-settled request
|
|
338
|
+
// ids resolve to `{ resolved: false }` instead of throwing: a stale client
|
|
339
|
+
// retry must never tear down the shared daemon socket.
|
|
340
|
+
const resolveExtensionDialog = async (payload) => {
|
|
341
|
+
if (!payload || typeof payload.requestId !== 'string' || payload.requestId.length === 0) {
|
|
342
|
+
throw protocolError('INVALID_ARGUMENT', 'The extension dialog response is invalid.');
|
|
343
|
+
}
|
|
344
|
+
const pending = pendingExtensionDialogs.get(payload.requestId);
|
|
345
|
+
if (!pending) {
|
|
346
|
+
return { resolved: false };
|
|
347
|
+
}
|
|
348
|
+
if (payload.directory !== undefined) await resolveDirectory(payload.directory);
|
|
349
|
+
if (payload.cancelled === true) {
|
|
350
|
+
// Dialog closures derive their typed result (undefined/false) from an
|
|
351
|
+
// empty response, which mirrors a timeout or explicit cancellation.
|
|
352
|
+
pending.settle({}, 'cancelled');
|
|
353
|
+
} else if (payload.confirmed === true) {
|
|
354
|
+
pending.settle({ confirmed: true });
|
|
355
|
+
} else if (typeof payload.value === 'string') {
|
|
356
|
+
pending.settle({ value: payload.value });
|
|
357
|
+
} else if (payload.values && typeof payload.values === 'object' && !Array.isArray(payload.values)) {
|
|
358
|
+
const values = {};
|
|
359
|
+
for (const [key, entry] of Object.entries(payload.values)) {
|
|
360
|
+
if (typeof key === 'string' && key.length > 0 && key.length <= 128 && typeof entry === 'string' && entry.length <= 8_000) {
|
|
361
|
+
values[key] = entry;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (pending.payload?.method !== 'form' || !validateExtensionFormValues(pending.payload.fields, values)) {
|
|
365
|
+
throw protocolError('INVALID_ARGUMENT', 'The extension form response is invalid.');
|
|
366
|
+
}
|
|
367
|
+
pending.settle({ values });
|
|
368
|
+
} else {
|
|
369
|
+
pending.settle({});
|
|
370
|
+
}
|
|
371
|
+
return { resolved: true };
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const publishExtensionCustomMessage = (sessionId, message, directory = getDefaultDirectory()) => {
|
|
375
|
+
if (typeof message.customType !== 'string' || message.customType.length === 0) return;
|
|
376
|
+
// Context-only custom messages (display: false) are not user-visible content.
|
|
377
|
+
if (message.display === false) return;
|
|
378
|
+
const text = typeof message.content === 'string'
|
|
379
|
+
? message.content
|
|
380
|
+
: Array.isArray(message.content)
|
|
381
|
+
? textFromContent(message.content)
|
|
382
|
+
: '';
|
|
383
|
+
const timestamp = Number.isFinite(message.timestamp) ? message.timestamp : Date.now();
|
|
384
|
+
publish('extension.message', {
|
|
385
|
+
id: `custom-${sessionId}-${getSequence() + 1}`,
|
|
386
|
+
customType: message.customType,
|
|
387
|
+
text: redactAttachmentPaths(text),
|
|
388
|
+
...(message.details !== undefined ? { details: redactAttachmentValues(message.details) } : {}),
|
|
389
|
+
createdAt: timestamp,
|
|
390
|
+
}, sessionId, directory);
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
// Mirrors a declarative `pichamber.ui` descriptor into normalized panel
|
|
394
|
+
// state and publishes an `extension.ui` event. Latest wins per stable id;
|
|
395
|
+
// `removed: true` (or a payload without component/title) unregisters.
|
|
396
|
+
const mirrorExtensionPanel = (sessionId, descriptor, directory) => {
|
|
397
|
+
const id = typeof descriptor.id === 'string' && descriptor.id.length > 0 ? descriptor.id.slice(0, 128) : '';
|
|
398
|
+
if (!id) return;
|
|
399
|
+
const hasBody = typeof descriptor.component === 'string'
|
|
400
|
+
|| typeof descriptor.title === 'string'
|
|
401
|
+
|| Array.isArray(descriptor.actions);
|
|
402
|
+
const removed = descriptor.removed === true || !hasBody;
|
|
403
|
+
const panels = extensionPanelsBySession.get(sessionId) ?? new Map();
|
|
404
|
+
const normalized = removed ? undefined : {
|
|
405
|
+
id,
|
|
406
|
+
...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
|
|
407
|
+
...(typeof descriptor.component === 'string' ? { component: descriptor.component.slice(0, 64) } : {}),
|
|
408
|
+
...(descriptor.props && typeof descriptor.props === 'object' && !Array.isArray(descriptor.props) ? { props: redactAttachmentValues(descriptor.props) } : {}),
|
|
409
|
+
...(Array.isArray(descriptor.actions) ? { actions: descriptor.actions.slice(0, MAX_EXTENSION_PANEL_ACTIONS) } : {}),
|
|
410
|
+
};
|
|
411
|
+
if (removed) {
|
|
412
|
+
panels.delete(id);
|
|
413
|
+
} else {
|
|
414
|
+
panels.set(id, normalized);
|
|
415
|
+
}
|
|
416
|
+
if (panels.size > MAX_EXTENSION_PANELS_PER_SESSION) {
|
|
417
|
+
const oldest = [...panels.keys()].slice(0, panels.size - MAX_EXTENSION_PANELS_PER_SESSION);
|
|
418
|
+
for (const key of oldest) panels.delete(key);
|
|
419
|
+
}
|
|
420
|
+
if (panels.size === 0) extensionPanelsBySession.delete(sessionId);
|
|
421
|
+
else extensionPanelsBySession.set(sessionId, panels);
|
|
422
|
+
publish('extension.ui', removed ? { id, removed: true } : normalized, sessionId, directory);
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
// Mirrors a `pichamber.app` descriptor into normalized app state and
|
|
426
|
+
// publishes an `extension.app` event. HTML is capped; removal unregisters.
|
|
427
|
+
const mirrorExtensionApp = (sessionId, descriptor, directory) => {
|
|
428
|
+
const appId = typeof descriptor.appId === 'string' && descriptor.appId.length > 0 ? descriptor.appId.slice(0, 128) : '';
|
|
429
|
+
if (!appId) return;
|
|
430
|
+
const html = typeof descriptor.html === 'string'
|
|
431
|
+
? (descriptor.html.length > MAX_EXTENSION_APP_HTML_CHARS ? descriptor.html.slice(0, MAX_EXTENSION_APP_HTML_CHARS) : descriptor.html)
|
|
432
|
+
: undefined;
|
|
433
|
+
const removed = descriptor.removed === true || !html || html.length === 0;
|
|
434
|
+
const apps = extensionAppsBySession.get(sessionId) ?? new Map();
|
|
435
|
+
if (removed) {
|
|
436
|
+
apps.delete(appId);
|
|
437
|
+
} else {
|
|
438
|
+
apps.set(appId, {
|
|
439
|
+
appId,
|
|
440
|
+
...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
|
|
441
|
+
html,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
if (apps.size > MAX_EXTENSION_APPS_PER_SESSION) {
|
|
445
|
+
const oldest = [...apps.keys()].slice(0, apps.size - MAX_EXTENSION_APPS_PER_SESSION);
|
|
446
|
+
for (const key of oldest) apps.delete(key);
|
|
447
|
+
}
|
|
448
|
+
if (apps.size === 0) extensionAppsBySession.delete(sessionId);
|
|
449
|
+
else extensionAppsBySession.set(sessionId, apps);
|
|
450
|
+
publish('extension.app', {
|
|
451
|
+
appId,
|
|
452
|
+
...(removed ? { removed: true } : {
|
|
453
|
+
...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
|
|
454
|
+
html,
|
|
455
|
+
}),
|
|
456
|
+
}, sessionId, directory);
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
const getSnapshotState = (sessionId) => {
|
|
460
|
+
if (!sessionId) return {};
|
|
461
|
+
const statuses = extensionStatusesBySession.get(sessionId);
|
|
462
|
+
const widgets = extensionWidgetsBySession.get(sessionId);
|
|
463
|
+
const panels = extensionPanelsBySession.get(sessionId);
|
|
464
|
+
const apps = extensionAppsBySession.get(sessionId);
|
|
465
|
+
const title = extensionTitlesBySession.get(sessionId);
|
|
466
|
+
const dialogs = [...pendingExtensionDialogs.values()]
|
|
467
|
+
.filter((pending) => pending.sessionId === sessionId)
|
|
468
|
+
.map((pending) => pending.payload);
|
|
469
|
+
return {
|
|
470
|
+
...(statuses?.size ? { statuses: [...statuses.entries()].map(([key, text]) => ({ key, text })) } : {}),
|
|
471
|
+
...(widgets?.size ? { widgets: [...widgets.entries()].map(([key, widget]) => ({ key, ...widget })) } : {}),
|
|
472
|
+
...(dialogs.length ? { dialogs } : {}),
|
|
473
|
+
...(panels?.size ? { panels: [...panels.values()] } : {}),
|
|
474
|
+
...(apps?.size ? { apps: [...apps.values()] } : {}),
|
|
475
|
+
...(title ? { title } : {}),
|
|
476
|
+
};
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
return {
|
|
480
|
+
buildExtensionBindings,
|
|
481
|
+
clearExtensionState,
|
|
482
|
+
getSnapshotState,
|
|
483
|
+
mirrorExtensionApp,
|
|
484
|
+
mirrorExtensionPanel,
|
|
485
|
+
publishExtensionCustomMessage,
|
|
486
|
+
resolveExtensionDialog,
|
|
487
|
+
};
|
|
488
|
+
};
|