@pi-chamber/web 0.9.0 → 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.
Files changed (101) hide show
  1. package/README.md +22 -6
  2. package/bin/cli.js +11 -1
  3. package/bin/cli.test.js +18 -0
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +7 -3
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +6 -0
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-logs.js +22 -4
  12. package/bin/lib/commands-serve.js +10 -2
  13. package/bin/lib/commands-tunnel.js +14 -0
  14. package/bin/lib/commands-update.js +18 -14
  15. package/bin/lib/commands-update.test.js +2 -1
  16. package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DoEOH0hY.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-y9Ystuhv.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-ScM4XoqZ.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CjkhMFqJ.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Bqi6H8I-.js} +3 -3
  21. package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-ClnfJJ2J.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
  27. package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Cy9tmnMg.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-DJNcTQNp.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-DxgVLhi9.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-CIFSGjJs.js} +1 -1
  36. package/dist/assets/{index-yWgKW2Fx.js → index-D2C3q2xD.js} +4 -4
  37. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  38. package/dist/assets/{index-D1IaU-Q7.js → index-DmNPBaSo.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-CrvpUauF.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CKvhS32g.js} +1 -1
  41. package/dist/assets/{main-DhvLreEl.js → main-BFv8slLp.js} +2 -2
  42. package/dist/assets/{main-DcAMXRSi.js → main-CjM7g4Gq.js} +7 -7
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-DKrraAqT.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-hQnLS5mt.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-DuXOBGs_.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DofX2wjB.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-BZeYg6eN.js} +3 -3
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-C7CBxDbh.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-BEoW7LlC.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-Dy-Tz_LJ.js} +2 -2
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +3 -3
  60. package/server/index.js +26 -7
  61. package/server/lib/client-auth/pairing.js +13 -2
  62. package/server/lib/client-auth/remote-clients.js +13 -2
  63. package/server/lib/fs/DOCUMENTATION.md +3 -1
  64. package/server/lib/fs/routes.test.js +74 -0
  65. package/server/lib/git/DOCUMENTATION.md +1 -1
  66. package/server/lib/git/identity-storage.js +10 -1
  67. package/server/lib/package-manager.js +1 -1
  68. package/server/lib/package-manager.test.js +11 -0
  69. package/server/lib/pi/archive-store.js +3 -2
  70. package/server/lib/pi/model-config-store.js +6 -2
  71. package/server/lib/pi/routes.js +11 -2
  72. package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
  73. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  74. package/server/lib/pi/session-daemon/session-daemon.js +226 -40
  75. package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
  76. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  77. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  78. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  79. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  80. package/server/lib/pi/session-folders-store.js +20 -2
  81. package/server/lib/pi/session-folders-store.test.js +17 -0
  82. package/server/lib/pi/settings-store.js +3 -2
  83. package/server/lib/pi/snippets-store.js +4 -1
  84. package/server/lib/pi/ui-settings-store.js +3 -2
  85. package/server/lib/server/cross-process-lock.js +112 -0
  86. package/server/lib/server/cross-process-lock.test.js +70 -0
  87. package/server/lib/server/server-profile.js +110 -0
  88. package/server/lib/server/server-profile.test.js +58 -0
  89. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  90. package/server/lib/server/tunnel-service.js +8 -1
  91. package/server/lib/stt/config-store.js +3 -2
  92. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  93. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  94. package/server/lib/ui-auth/ui-auth.js +9 -2
  95. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  96. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  97. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  98. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  99. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  100. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  101. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
package/server/index.js CHANGED
@@ -48,10 +48,10 @@ let signalsAttached = false;
48
48
 
49
49
  const isEnvFlagEnabled = (value) => value === true || value === 1 || (typeof value === 'string' && ['1', 'true'].includes(value.trim().toLowerCase()));
50
50
 
51
- // Serve-time tunnel startup was removed with the OpenChamber migration; the
52
- // standalone `pichamber tunnel` command still manages cloudflared. Options
53
- // parsed for the removed integration must fail loudly instead of being
54
- // silently ignored — a user passing --tunnel expects an exposed URL.
51
+ // Serve-time tunnel startup is intentionally separate from server startup; the
52
+ // standalone `pichamber tunnel` command manages cloudflared. Options parsed for
53
+ // the unsupported serve integration must fail loudly instead of being silently
54
+ // ignored. A user passing --tunnel expects an exposed URL.
55
55
  const IGNORED_TUNNEL_OPTION_NAMES = ['tryCfTunnel', 'tunnelProvider', 'tunnelMode', 'tunnelConfigPath', 'tunnelToken', 'tunnelHostname'];
56
56
  const warnIgnoredTunnelOptions = (options) => {
57
57
  const ignored = IGNORED_TUNNEL_OPTION_NAMES.filter((name) => options[name] !== undefined && options[name] !== false && options[name] !== null && options[name] !== '');
@@ -126,7 +126,10 @@ export async function startWebUiServer(options = {}) {
126
126
  const clientPairingRuntime = createClientPairingRuntime({ fsPromises: fs.promises, path, crypto: await import('node:crypto'), storePath: dataPath('client-pairing-sessions.json'), remoteClientAuthRuntime });
127
127
  const tunnelAuthController = createTunnelAuth();
128
128
  const uiAuthController = createUiAuth({ password: uiPassword, readSettingsFromDiskMigrated: async () => ({}) , clientAuthController: remoteClientAuthRuntime });
129
- const piSessionDaemonRuntime = createPiSessionDaemonSupervisor({ dataDir: PICHAMBER_DATA_DIR });
129
+ // One daemon per server profile. The supervisor is created after HTTP
130
+ // listen so the profile key uses the bound port; routes observe it through
131
+ // the getter and report unavailable until it exists.
132
+ let piSessionDaemonRuntime = null;
130
133
  const tunnelService = createTunnelService({
131
134
  dataDir: PICHAMBER_DATA_DIR,
132
135
  getPort: () => {
@@ -217,7 +220,18 @@ export async function startWebUiServer(options = {}) {
217
220
 
218
221
  await listen(server, port, host);
219
222
  const resolvedPort = typeof server.address() === 'object' && server.address() ? server.address().port : null;
220
- if (typeof resolvedPort === 'number') process.send?.({ type: 'pichamber:ready', port: resolvedPort });
223
+ piSessionDaemonRuntime = createPiSessionDaemonSupervisor({
224
+ dataDir: PICHAMBER_DATA_DIR,
225
+ port: typeof resolvedPort === 'number' ? resolvedPort : port,
226
+ version: PICHAMBER_VERSION,
227
+ });
228
+ if (typeof resolvedPort === 'number') {
229
+ process.send?.({
230
+ type: 'pichamber:ready',
231
+ port: resolvedPort,
232
+ profileKey: piSessionDaemonRuntime.paths.profileKey,
233
+ });
234
+ }
221
235
  // Warm the detached daemon as soon as HTTP is listening. Requests arriving
222
236
  // during cold start share the supervisor's startPromise; server readiness
223
237
  // itself never waits for provider/model initialization in the child.
@@ -232,13 +246,18 @@ export async function startWebUiServer(options = {}) {
232
246
  return typeof address === 'object' && address ? address.port : null;
233
247
  },
234
248
  getTunnelUrl: () => null,
249
+ getDaemonProfileKey: () => piSessionDaemonRuntime?.paths?.profileKey ?? null,
235
250
  getQuitRiskStatus: () => ({ tunnel: { active: false } }),
236
251
  isReady: () => !stopped,
237
252
  stop: async ({ exitProcess = false } = {}) => {
238
253
  if (stopped) return;
239
254
  stopped = true;
240
255
  if (activeController === controller) activeController = null;
241
- await Promise.allSettled([workspaceRuntime.shutdown(), piSessionDaemonRuntime.stop(), close(server)]);
256
+ await Promise.allSettled([
257
+ workspaceRuntime.shutdown(),
258
+ piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
259
+ close(server),
260
+ ]);
242
261
  uiAuthController.dispose?.();
243
262
  if (exitProcess) process.exit(0);
244
263
  },
@@ -1,3 +1,5 @@
1
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
2
+
1
3
  const STORE_VERSION = 1;
2
4
  const PAIRING_ID_PREFIX = 'pair_';
3
5
  const SECRET_BYTES = 32;
@@ -114,7 +116,9 @@ export const createClientPairingRuntime = ({
114
116
  });
115
117
  await previous;
116
118
  try {
117
- return await fn();
119
+ // The queue orders one server; the file lock orders every server
120
+ // sharing this data directory.
121
+ return await withCrossProcessLock(`${storePath}.lock`, fn);
118
122
  } finally {
119
123
  release();
120
124
  }
@@ -155,7 +159,14 @@ export const createClientPairingRuntime = ({
155
159
 
156
160
  const writeStore = async (store) => {
157
161
  await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
158
- await fsPromises.writeFile(storePath, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
162
+ const temporary = `${storePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
163
+ try {
164
+ await fsPromises.writeFile(temporary, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
165
+ await fsPromises.rename(temporary, storePath);
166
+ } catch (error) {
167
+ await fsPromises.rm?.(temporary, { force: true }).catch(() => {});
168
+ throw error;
169
+ }
159
170
  if (typeof fsPromises.chmod === 'function') {
160
171
  await fsPromises.chmod(storePath, 0o600).catch(() => {});
161
172
  }
@@ -1,3 +1,5 @@
1
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
2
+
1
3
  const STORE_VERSION = 1;
2
4
  const TOKEN_PREFIX = 'oc_client_';
3
5
  const TOKEN_BYTES = 32;
@@ -65,7 +67,9 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
65
67
  });
66
68
  await previous;
67
69
  try {
68
- return await fn();
70
+ // The queue orders one server; the file lock orders every server
71
+ // sharing this data directory.
72
+ return await withCrossProcessLock(`${storePath}.lock`, fn);
69
73
  } finally {
70
74
  release();
71
75
  }
@@ -106,7 +110,14 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
106
110
 
107
111
  const writeStore = async (store) => {
108
112
  await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
109
- await fsPromises.writeFile(storePath, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
113
+ const temporary = `${storePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
114
+ try {
115
+ await fsPromises.writeFile(temporary, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
116
+ await fsPromises.rename(temporary, storePath);
117
+ } catch (error) {
118
+ await fsPromises.rm?.(temporary, { force: true }).catch(() => {});
119
+ throw error;
120
+ }
110
121
  if (typeof fsPromises.chmod === 'function') {
111
122
  await fsPromises.chmod(storePath, 0o600).catch(() => {});
112
123
  }
@@ -12,6 +12,7 @@ Own filesystem API behavior for the web server runtime, including workspace-boun
12
12
  - Registers all filesystem routes:
13
13
  - `GET /api/fs/home`
14
14
  - `POST /api/fs/mkdir`
15
+ - `POST /api/fs/clone`
15
16
  - `GET /api/fs/read`
16
17
  - `GET /api/fs/raw`
17
18
  - `GET /api/fs/serve/:path(*)`
@@ -36,4 +37,5 @@ Own filesystem API behavior for the web server runtime, including workspace-boun
36
37
  - Keep filesystem policy (workspace root checks, error mapping, exec timeout behavior) inside this module, not in the composition root.
37
38
  - Filesystem `EPERM`/`EACCES` failures use the stable `reason: "os-permission"` response marker. Policy denials such as workspace-boundary or missing-grant failures must not use that marker because a native folder picker cannot remediate them.
38
39
  - If adding new `/api/fs/*` endpoints, add them in `routes.js` and extend this document.
39
- - `GET /api/fs/list` may resolve symlinks with `realpath` to read directory contents, but the response `path` and each entry `path` must stay in the caller's requested path space (`path.join(requestedPath, name)`). Returning real paths breaks file-tree expansion for directories reached through workspace symlinks.
40
+ - `POST /api/fs/clone` clones a repository into the requested destination and can apply a stored Git identity. It returns the cloned path and rejects an existing destination with HTTP 409.
41
+ - `GET /api/fs/list` may resolve symlinks with `realpath` to read directory contents, but the response `path` and each entry `path` must stay in the caller’s requested path space (`path.join(requestedPath, name)`). Returning real paths breaks file-tree expansion for directories reached through workspace symlinks.
@@ -200,6 +200,26 @@ const registerMkdir = (fsPromises) => {
200
200
  return getRoute('POST', '/api/fs/mkdir');
201
201
  };
202
202
 
203
+ const registerClone = ({ fsPromises, spawn }) => {
204
+ const { app, getRoute } = createRouteRegistry();
205
+ registerFsRoutes(app, {
206
+ os: { homedir: () => '/home/user' },
207
+ path: path.posix,
208
+ fsPromises: {
209
+ realpath: async (targetPath) => targetPath,
210
+ ...fsPromises,
211
+ },
212
+ spawn,
213
+ crypto: { randomUUID: () => 'job-0' },
214
+ normalizeDirectoryPath: (p) => p,
215
+ resolveProjectDirectory: async () => ({ directory: '/repo' }),
216
+ buildAugmentedPath: () => '/usr/bin',
217
+ resolveGitBinaryForSpawn: () => 'git',
218
+ pichamberUserConfigRoot: '/home/user/.config',
219
+ });
220
+ return getRoute('POST', '/api/fs/clone');
221
+ };
222
+
203
223
  const registerReveal = ({ fsPromises, spawn, platform = 'linux' }) => {
204
224
  const { app, getRoute } = createRouteRegistry();
205
225
  registerFsRoutes(app, {
@@ -251,6 +271,12 @@ const callMkdir = async (handler, body) => {
251
271
  return res;
252
272
  };
253
273
 
274
+ const callClone = async (handler, body) => {
275
+ const res = createMockResponse();
276
+ await handler({ body }, res);
277
+ return res;
278
+ };
279
+
254
280
  const callReveal = async (handler, body) => {
255
281
  const res = createMockResponse();
256
282
  await handler({ body }, res);
@@ -458,6 +484,54 @@ describe('fs read', () => {
458
484
  });
459
485
  });
460
486
 
487
+ describe('fs clone', () => {
488
+ it('clones into a new destination through the registered route', async () => {
489
+ const notFound = () => Promise.reject(Object.assign(new Error('not found'), { code: 'ENOENT' }));
490
+ const fsPromises = {
491
+ stat: vi.fn(notFound),
492
+ access: vi.fn(notFound),
493
+ mkdir: vi.fn(async () => undefined),
494
+ };
495
+ const { spawn } = createSpawn();
496
+ const handler = registerClone({ fsPromises, spawn });
497
+
498
+ const res = await callClone(handler, {
499
+ remoteUrl: 'https://github.com/example/repository.git',
500
+ destinationPath: '/home/user/projects/repository',
501
+ });
502
+
503
+ expect(res.statusCode).toBe(200);
504
+ expect(res.body).toEqual({
505
+ success: true,
506
+ path: '/home/user/projects/repository',
507
+ output: '',
508
+ });
509
+ expect(fsPromises.mkdir).toHaveBeenCalledWith('/home/user/projects', { recursive: true });
510
+ expect(spawn).toHaveBeenCalledWith(
511
+ 'git',
512
+ ['clone', '--', 'https://github.com/example/repository.git', 'repository'],
513
+ expect.objectContaining({
514
+ cwd: '/home/user/projects',
515
+ env: expect.objectContaining({ GIT_TERMINAL_PROMPT: '0' }),
516
+ }),
517
+ );
518
+ });
519
+
520
+ it('rejects a clone request without a repository URL', async () => {
521
+ const { spawn } = createSpawn();
522
+ const handler = registerClone({
523
+ fsPromises: { stat: vi.fn(), access: vi.fn(), mkdir: vi.fn() },
524
+ spawn,
525
+ });
526
+
527
+ const res = await callClone(handler, { destinationPath: '/home/user/projects/repository' });
528
+
529
+ expect(res.statusCode).toBe(400);
530
+ expect(res.body).toEqual({ error: 'Repository URL is required' });
531
+ expect(spawn).not.toHaveBeenCalled();
532
+ });
533
+ });
534
+
461
535
  describe('fs reveal', () => {
462
536
  it.each([
463
537
  ['linux', 'xdg-open', ['/repo']],
@@ -125,7 +125,7 @@ The following functions are internal helpers used by exported functions:
125
125
  Authenticated `GET /api/git/worktrees`, `POST /api/git/worktrees/validate`, `POST /api/git/worktrees`, `DELETE /api/git/worktrees`, and `GET /api/git/worktrees/bootstrap-status` expose worktree discovery and lifecycle operations to the shared web runtime. Electron, hosted mobile, and Capacitor clients use the same server implementation. The delete route requires a registered non-primary worktree and only forces removal when the caller explicitly sends `force: true`; the shared UI obtains confirmation for dirty files and refuses removal while a session is active. The user-facing route never deletes local branches, so unpushed commits remain recoverable.
126
126
 
127
127
  ### Runtime availability of range diffs
128
- - `GET /api/git/range-diff` is served by the PiChamber web server, so it is available to web, desktop, and mobile clients. The shared `GitAPI.getGitRangeDiff` is therefore optional: web supplies the HTTP implementation, and VS Code does not implement it because the extension host serves Git through its own bridge rather than these routes. Features built on range diffs (currently the AI diff walkthrough) are not offered in VS Code.
128
+ - `GET /api/git/range-diff` is served by the PiChamber web server, so it is available to web, desktop, hosted mobile, and Capacitor clients. The shared `GitAPI.getGitRangeDiff` is optional because the web runtime supplies the HTTP implementation.
129
129
 
130
130
  ### Staged and unstaged change handling
131
131
  - `status.files` exposes both `index` and `working_dir` codes. Shared UI uses these as separate scopes: staged rows are derived from non-empty `index` statuses, while unstaged rows are derived from `working_dir` statuses and untracked files.
@@ -33,7 +33,16 @@ export function saveProfiles(data) {
33
33
  ensureStorageDir();
34
34
 
35
35
  try {
36
- fs.writeFileSync(STORAGE_FILE, JSON.stringify(data, null, 2), 'utf8');
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
- const operation = writeChain.then(async () => {
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
  };
@@ -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 === 'ATTACHMENT_TOO_LARGE'
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 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.
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
- - 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>` works the same as a POSIX socket path.
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 PiChamber 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 and must match the state sidecar before the supervisor reuses or signals 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.
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 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`.
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 = () => writeState({
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: new Date().toISOString(),
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));