@pi-chamber/web 0.8.2 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -6
- package/bin/cli.js +16 -3
- package/bin/cli.test.js +62 -0
- package/bin/lib/DOCUMENTATION.md +6 -6
- package/bin/lib/cli-args.js +26 -7
- package/bin/lib/cli-lifecycle.js +3 -0
- package/bin/lib/cli-paths.js +6 -0
- 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-lifecycle.js +14 -0
- package/bin/lib/commands-logs.js +24 -5
- package/bin/lib/commands-serve.js +176 -4
- package/bin/lib/commands-tunnel.js +35 -0
- package/bin/lib/commands-update.js +107 -39
- package/bin/lib/commands-update.test.js +97 -1
- package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-DoEOH0hY.js} +1 -1
- package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-y9Ystuhv.js} +1 -1
- package/dist/assets/DiffView-ScM4XoqZ.js +18 -0
- package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-CjkhMFqJ.js} +3 -3
- package/dist/assets/GitView-Bqi6H8I-.js +8 -0
- package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
- package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-ClnfJJ2J.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
- package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
- package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-Cy9tmnMg.js} +1 -1
- package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
- package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-DJNcTQNp.js} +4 -4
- package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-DxgVLhi9.js} +1 -1
- package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
- package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
- package/dist/assets/gitStatusPredicates-CIFSGjJs.js +134 -0
- package/dist/assets/index-D2C3q2xD.js +8 -0
- package/dist/assets/index-DNoEeZ2U.css +1 -0
- package/dist/assets/{index-CMfiVUIr.js → index-DmNPBaSo.js} +1 -1
- package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-CrvpUauF.js} +1 -1
- package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-CKvhS32g.js} +1 -1
- package/dist/assets/{main-zZrKd3hZ.js → main-BFv8slLp.js} +2 -2
- package/dist/assets/main-CjM7g4Gq.js +135 -0
- package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-DKrraAqT.js} +1 -1
- package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-hQnLS5mt.js} +2 -2
- package/dist/assets/{mobile-VU_G_SgX.js → mobile-DuXOBGs_.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
- package/dist/assets/renderMobileApp-DofX2wjB.js +11 -0
- package/dist/assets/runtimeEndpointReset-BZeYg6eN.js +54 -0
- package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C7CBxDbh.js} +1 -1
- package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
- package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
- package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
- package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-BEoW7LlC.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
- package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
- package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
- package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
- package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
- package/dist/assets/{web-components-C9ENH49P.js → web-components-Dy-Tz_LJ.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +3 -4
- 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 +11 -2
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
- package/server/lib/pi/session-daemon/daemon-process.js +48 -13
- package/server/lib/pi/session-daemon/session-daemon.js +226 -40
- package/server/lib/pi/session-daemon/session-daemon.test.js +207 -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 +3 -2
- 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/DOCUMENTATION.md +1 -1
- package/server/lib/stt/config-store.js +3 -2
- package/server/lib/terminal/DOCUMENTATION.md +3 -3
- 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/DiffView-Gh9wjthp.js +0 -18
- package/dist/assets/GitView-BmNCkkoC.js +0 -8
- package/dist/assets/JsonTreeView-CxXRXXzk.js +0 -1
- package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
- package/dist/assets/ToolOutputDialog-C_7vJLEq.js +0 -8
- package/dist/assets/computeVirtualFileMetrics-D0mQcleY.js +0 -3
- package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
- package/dist/assets/index-CzO3ooje.css +0 -1
- package/dist/assets/index-ivrh3jfy.js +0 -8
- package/dist/assets/main-BoVfUG73.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-Bi1927c8.js +0 -2
- package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
- package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
- package/dist/assets/usePushVisibilityBeacon-zYd3ppNh.js +0 -10
- package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
|
@@ -33,7 +33,16 @@ export function saveProfiles(data) {
|
|
|
33
33
|
ensureStorageDir();
|
|
34
34
|
|
|
35
35
|
try {
|
|
36
|
-
|
|
36
|
+
// Atomic replace so a concurrent server never reads a torn file. Identity
|
|
37
|
+
// edits remain last-writer-wins across servers.
|
|
38
|
+
const temporary = `${STORAGE_FILE}.tmp-${process.pid}-${Date.now()}`;
|
|
39
|
+
try {
|
|
40
|
+
fs.writeFileSync(temporary, JSON.stringify(data, null, 2), 'utf8');
|
|
41
|
+
fs.renameSync(temporary, STORAGE_FILE);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
try { fs.rmSync(temporary, { force: true }); } catch {}
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
37
46
|
return true;
|
|
38
47
|
} catch (error) {
|
|
39
48
|
console.error('Failed to save git identity profiles:', error);
|
|
@@ -814,7 +814,7 @@ export function executeUpdate(pm = detectPackageManager(), options = {}) {
|
|
|
814
814
|
}
|
|
815
815
|
|
|
816
816
|
const result = spawnSync(command, {
|
|
817
|
-
stdio: 'inherit',
|
|
817
|
+
stdio: options?.silent === true ? 'ignore' : 'inherit',
|
|
818
818
|
shell: true,
|
|
819
819
|
...getSpawnSyncBaseOptions(),
|
|
820
820
|
});
|
|
@@ -390,6 +390,17 @@ describe('CLI update exports', () => {
|
|
|
390
390
|
expect(typeof executeUpdate).toBe('function');
|
|
391
391
|
expect(typeof resolveTrustedUpdatePackageManager).toBe('function');
|
|
392
392
|
});
|
|
393
|
+
|
|
394
|
+
it('does not inherit package-manager output in silent mode', async () => {
|
|
395
|
+
const { spawnSync } = await import('node:child_process');
|
|
396
|
+
spawnSync.mockClear();
|
|
397
|
+
|
|
398
|
+
expect(executeUpdate('npm', { silent: true })).toEqual({ success: true, exitCode: 0 });
|
|
399
|
+
expect(spawnSync).toHaveBeenLastCalledWith(
|
|
400
|
+
expect.stringContaining('@pi-chamber/web@latest'),
|
|
401
|
+
expect.objectContaining({ shell: true, stdio: 'ignore' }),
|
|
402
|
+
);
|
|
403
|
+
});
|
|
393
404
|
});
|
|
394
405
|
|
|
395
406
|
describe('resolveTrustedUpdatePackageManager', () => {
|
|
@@ -2,6 +2,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
|
2
2
|
import { dirname, join } from 'node:path';
|
|
3
3
|
|
|
4
4
|
import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
|
|
5
|
+
import { withCrossProcessLock } from '../server/cross-process-lock.js';
|
|
5
6
|
|
|
6
7
|
const invalidArchive = () => {
|
|
7
8
|
const error = new Error('Pi archive metadata is invalid.');
|
|
@@ -34,7 +35,7 @@ export const createPiArchiveStore = ({ file = join(resolvePiChamberDataDir(), 'p
|
|
|
34
35
|
error.code = 'INVALID_ARGUMENT';
|
|
35
36
|
throw error;
|
|
36
37
|
}
|
|
37
|
-
const operation = writeChain.then(async () => {
|
|
38
|
+
const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
|
|
38
39
|
const current = await read();
|
|
39
40
|
if (archived) current[sessionId] = Date.now();
|
|
40
41
|
else delete current[sessionId];
|
|
@@ -43,7 +44,7 @@ export const createPiArchiveStore = ({ file = join(resolvePiChamberDataDir(), 'p
|
|
|
43
44
|
await writeFile(temporary, JSON.stringify(current), { mode: 0o600 });
|
|
44
45
|
await rename(temporary, file);
|
|
45
46
|
return archived ? current[sessionId] : undefined;
|
|
46
|
-
});
|
|
47
|
+
}));
|
|
47
48
|
writeChain = operation.catch(() => {});
|
|
48
49
|
return operation;
|
|
49
50
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname, join } from 'node:path';
|
|
3
3
|
|
|
4
|
+
import { withCrossProcessLock } from '../server/cross-process-lock.js';
|
|
5
|
+
|
|
4
6
|
const PROVIDER_ID = /^[a-z0-9][a-z0-9-_]*$/;
|
|
5
7
|
const API_KEY_REFERENCE = /^\{env:[A-Za-z_][A-Za-z0-9_]*\}$/;
|
|
6
8
|
const API_TYPES = new Set(['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai']);
|
|
@@ -146,7 +148,9 @@ export const createPiModelConfigStore = ({ file }) => {
|
|
|
146
148
|
|
|
147
149
|
const update = async (input) => {
|
|
148
150
|
const nextProvider = normalizeUpdate(input);
|
|
149
|
-
|
|
151
|
+
// models.json lives under the shared Pi agent directory, so concurrent
|
|
152
|
+
// daemons serialize here rather than in-process only.
|
|
153
|
+
const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
|
|
150
154
|
const config = await readConfig();
|
|
151
155
|
const previous = config.providers[nextProvider.providerId];
|
|
152
156
|
const provider = {
|
|
@@ -164,7 +168,7 @@ export const createPiModelConfigStore = ({ file }) => {
|
|
|
164
168
|
await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
165
169
|
await rename(temporary, file);
|
|
166
170
|
return publicProvider(nextProvider.providerId, provider);
|
|
167
|
-
});
|
|
171
|
+
}));
|
|
168
172
|
writeChain = operation.catch(() => {});
|
|
169
173
|
return operation;
|
|
170
174
|
};
|
package/server/lib/pi/routes.js
CHANGED
|
@@ -35,6 +35,9 @@ const UNAVAILABLE_CODES = new Set([
|
|
|
35
35
|
'DAEMON_CREDENTIAL_UNAVAILABLE',
|
|
36
36
|
'DAEMON_LOCK_UNAVAILABLE',
|
|
37
37
|
'DAEMON_LOCK_TIMEOUT',
|
|
38
|
+
'DAEMON_OWNERSHIP_MISMATCH',
|
|
39
|
+
'DAEMON_PROFILE_IN_USE',
|
|
40
|
+
'SESSION_LEASE_UNAVAILABLE',
|
|
38
41
|
'INVALID_DAEMON_ENDPOINT',
|
|
39
42
|
'PROVIDER_UNAVAILABLE',
|
|
40
43
|
'MALFORMED_SESSION_JSONL',
|
|
@@ -48,7 +51,9 @@ const writeDaemonError = (res, error) => {
|
|
|
48
51
|
? 503
|
|
49
52
|
: code === 'INVALID_SESSION'
|
|
50
53
|
? 404
|
|
51
|
-
: code === '
|
|
54
|
+
: code === 'SESSION_IN_USE'
|
|
55
|
+
? 409
|
|
56
|
+
: code === 'ATTACHMENT_TOO_LARGE'
|
|
52
57
|
? 413
|
|
53
58
|
: code === 'ATTACHMENT_LIMIT_REACHED'
|
|
54
59
|
? 429
|
|
@@ -801,7 +806,11 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
801
806
|
app.put('/api/pi/session-folders', async (req, res) => {
|
|
802
807
|
try {
|
|
803
808
|
res.json(await sessionFoldersStore.write(req.body));
|
|
804
|
-
} catch {
|
|
809
|
+
} catch (error) {
|
|
810
|
+
if (error?.code === 'SESSION_FOLDERS_STALE') {
|
|
811
|
+
res.status(409).json({ error: 'Session folders changed on another instance; reload and retry' });
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
805
814
|
res.status(400).json({ error: 'Invalid session folders' });
|
|
806
815
|
}
|
|
807
816
|
});
|
|
@@ -12,19 +12,25 @@ 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
|
|
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.
|
|
20
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` atomically owns shared PiChamber UI preferences at the data-root `settings.json`; it is exposed as `/api/pi/ui-settings`, not through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
|
|
21
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`, 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
36
|
- Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
|
|
@@ -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));
|