@pi-chamber/web 0.9.0 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +24 -8
  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 +28 -6
  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-DuGmiPZ5.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-CV-iReyY.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-DVd1MLPB.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CPnW4I90.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Dj_7hgX_.js} +3 -3
  21. package/dist/assets/JsonTreeView-Cyy0lEZR.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-C7dA3U29.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-qeik5qtT.js} +1 -1
  27. package/dist/assets/SettingsView-C57uV1YS.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Bbay2W76.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-CRTiN1CH.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-iqwryMNU.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-szfZ0Syc.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-BC3ie230.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-DbThKVSf.js} +1 -1
  36. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  37. package/dist/assets/{index-yWgKW2Fx.js → index-KIdiBFJs.js} +4 -4
  38. package/dist/assets/{index-D1IaU-Q7.js → index-v6K3L94m.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CbrmvrM6.js} +1 -1
  41. package/dist/assets/{main-DcAMXRSi.js → main-4PkIvzf4.js} +7 -7
  42. package/dist/assets/{main-DhvLreEl.js → main-DMyWi0qs.js} +2 -2
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-BD5WkOKU.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-CLMNhna4.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-rWMDwhtQ.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DLy2YoQg.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-CySRuLbN.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-DfuJVB15.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-jITqE8PV.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-C9wXMuCp.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 +46 -3
  72. package/server/lib/pi/routes.test.js +53 -0
  73. package/server/lib/pi/session-daemon/DOCUMENTATION.md +15 -9
  74. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  75. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  76. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  77. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  78. package/server/lib/pi/session-daemon/session-daemon.js +353 -66
  79. package/server/lib/pi/session-daemon/session-daemon.test.js +348 -0
  80. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  81. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  82. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  83. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  84. package/server/lib/pi/session-folders-store.js +20 -2
  85. package/server/lib/pi/session-folders-store.test.js +17 -0
  86. package/server/lib/pi/settings-store.js +3 -2
  87. package/server/lib/pi/snippets-store.js +4 -1
  88. package/server/lib/pi/ui-settings-store.js +130 -24
  89. package/server/lib/pi/ui-settings-store.test.js +58 -7
  90. package/server/lib/server/cross-process-lock.js +112 -0
  91. package/server/lib/server/cross-process-lock.test.js +70 -0
  92. package/server/lib/server/server-profile.js +110 -0
  93. package/server/lib/server/server-profile.test.js +58 -0
  94. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  95. package/server/lib/server/tunnel-service.js +8 -1
  96. package/server/lib/stt/config-store.js +3 -2
  97. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  98. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  99. package/server/lib/ui-auth/ui-auth.js +9 -2
  100. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  101. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  102. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  103. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  104. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  105. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  106. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
@@ -1,11 +1,13 @@
1
- import { createHash, randomBytes } from 'node:crypto';
1
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
2
  import { spawn as spawnChildProcess } from 'node:child_process';
3
- import { chmod, lstat, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { closeSync, openSync } from 'node:fs';
4
+ import { chmod, lstat, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
4
5
  import { userInfo } from 'node:os';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  import { dirname, isAbsolute, join, resolve } from 'node:path';
7
8
 
8
9
  import { resolvePiChamberDataDir } from '../../pichamber-data-dir.js';
10
+ import { resolveServerProfile } from '../../server/server-profile.js';
9
11
  import { isLocalSessionDaemonEndpoint } from './session-daemon.js';
10
12
  import { requestSessionDaemon, SessionDaemonClientError, subscribeSessionDaemon } from './ipc-client.js';
11
13
 
@@ -55,6 +57,8 @@ const hasValidStateIdentity = (state) => (
55
57
  && Number.isInteger(state.pid)
56
58
  && state.pid > 0
57
59
  && typeof state.endpoint === 'string'
60
+ && typeof state.profileKey === 'string'
61
+ && state.profileKey.length > 0
58
62
  );
59
63
 
60
64
  const isValidState = (state) => hasValidStateIdentity(state) && typeof state.startedAt === 'string';
@@ -129,17 +133,35 @@ const resolvePiSessionDaemonPaths = ({
129
133
  dataDir = resolvePiChamberDataDir({ env }),
130
134
  pathModule = { join, resolve, isAbsolute },
131
135
  platform = process.platform,
136
+ profile,
137
+ port,
138
+ runtime,
139
+ version,
132
140
  } = {}) => {
133
- const piDataDir = pathModule.join(dataDir, 'pi');
134
- const runtimeDir = typeof env.XDG_RUNTIME_DIR === 'string' && env.XDG_RUNTIME_DIR.trim()
135
- ? pathModule.join(pathModule.resolve(env.XDG_RUNTIME_DIR.trim()), 'pichamber')
136
- : pathModule.join(dataDir, 'runtime');
141
+ const resolvedProfile = profile && typeof profile.profileKey === 'string'
142
+ ? profile
143
+ : resolveServerProfile({ env, port, runtime, version });
144
+ const {
145
+ profileKey,
146
+ serverInstanceId,
147
+ runtime: profileRuntime,
148
+ source: profileSource,
149
+ development: profileDevelopment,
150
+ buildId,
151
+ } = resolvedProfile;
152
+ const profileDir = pathModule.join(dataDir, 'pi', 'daemons', profileKey);
153
+ const runtimeBaseDir = typeof env.XDG_RUNTIME_DIR === 'string' && env.XDG_RUNTIME_DIR.trim()
154
+ ? pathModule.join(pathModule.resolve(env.XDG_RUNTIME_DIR.trim()), 'pichamber', 'pi-daemons', profileKey)
155
+ : pathModule.join(dataDir, 'runtime', 'pi-daemons', profileKey);
137
156
  const configuredEndpoint = typeof env.PICHAMBER_PI_SESSION_DAEMON_ENDPOINT === 'string'
138
157
  ? env.PICHAMBER_PI_SESSION_DAEMON_ENDPOINT.trim()
139
158
  : '';
159
+ // An explicit endpoint override keeps per-profile sidecars but shares the
160
+ // socket path. A profile never adopts, unlinks, or signals an endpoint it
161
+ // cannot authenticate and identify as its own.
140
162
  const endpoint = configuredEndpoint || (platform === 'win32'
141
- ? `\\\\.\\pipe\\pichamber-pi-session-daemon-${getWindowsOwnerKey()}`
142
- : pathModule.join(runtimeDir, 'pi-session-daemon.sock'));
163
+ ? `\\\\.\\pipe\\pichamber-pi-session-daemon-${getWindowsOwnerKey()}-${profileKey}`
164
+ : pathModule.join(runtimeBaseDir, 'daemon.sock'));
143
165
 
144
166
  if (!isLocalSessionDaemonEndpoint(endpoint, platform)) {
145
167
  throw new PiSessionDaemonUnavailableError('INVALID_DAEMON_ENDPOINT');
@@ -149,14 +171,46 @@ const resolvePiSessionDaemonPaths = ({
149
171
  return {
150
172
  endpoint,
151
173
  agentDir: configuredAgentDir ? pathModule.resolve(configuredAgentDir) : undefined,
152
- piDataDir,
153
- runtimeDir,
154
- credentialFile: pathModule.join(piDataDir, 'session-daemon.key'),
155
- stateFile: pathModule.join(piDataDir, 'session-daemon-state.json'),
156
- lockFile: pathModule.join(piDataDir, 'session-daemon.lock'),
174
+ piDataDir: pathModule.join(dataDir, 'pi'),
175
+ profileDir,
176
+ runtimeDir: runtimeBaseDir,
177
+ credentialFile: pathModule.join(profileDir, 'session-daemon.key'),
178
+ stateFile: pathModule.join(profileDir, 'daemon-state.json'),
179
+ lockFile: pathModule.join(profileDir, 'operation.lock'),
180
+ logFile: pathModule.join(dataDir, 'logs', `pi-daemon-${profileKey}.log`),
181
+ profileKey,
182
+ serverInstanceId,
183
+ profileRuntime,
184
+ profileSource,
185
+ profileDevelopment: profileDevelopment === true,
186
+ buildId,
157
187
  };
158
188
  };
159
189
 
190
+ const LEGACY_DAEMON_FILES = (dataDir) => ({
191
+ stateFile: join(dataDir, 'pi', 'session-daemon-state.json'),
192
+ });
193
+
194
+ // Best-effort removal of a dead legacy (pre-profile) daemon record. A live
195
+ // legacy daemon is never signaled or adopted; it keeps running until its own
196
+ // owner stops it.
197
+ const cleanupDeadLegacyDaemonState = async ({ dataDir, processLike }) => {
198
+ try {
199
+ const raw = await readFile(LEGACY_DAEMON_FILES(dataDir).stateFile, 'utf8');
200
+ const state = JSON.parse(raw);
201
+ if (!Number.isInteger(state?.pid) || state.pid <= 0) return;
202
+ try {
203
+ processLike.kill(state.pid, 0);
204
+ return;
205
+ } catch (error) {
206
+ if (error?.code === 'EPERM') return;
207
+ }
208
+ await rm(LEGACY_DAEMON_FILES(dataDir).stateFile, { force: true });
209
+ } catch {
210
+ // Legacy cleanup must never block profile daemon startup.
211
+ }
212
+ };
213
+
160
214
  /**
161
215
  * Owns a single daemon for the local PiChamber host. The state sidecar is
162
216
  * deliberately non-secret; the credential is read only by this process and
@@ -173,20 +227,26 @@ export const createPiSessionDaemonSupervisor = ({
173
227
  wait = delay,
174
228
  startupTimeoutMs = OPERATION_TIMEOUT_MS,
175
229
  daemonReadyTimeoutMs = DAEMON_READY_TIMEOUT_MS,
230
+ profile,
231
+ port,
232
+ runtime,
233
+ version,
176
234
  } = {}) => {
177
- const paths = resolvePiSessionDaemonPaths({ env, dataDir, platform });
235
+ const paths = resolvePiSessionDaemonPaths({ env, dataDir, platform, profile, port, runtime, version });
236
+ const serverPid = processLike.pid;
178
237
  let startPromise = null;
179
238
  let intentionallyStopped = false;
180
239
 
181
240
  const withOperationLock = async (operation) => {
182
241
  const deadline = Date.now() + startupTimeoutMs;
183
- await mkdir(paths.piDataDir, { recursive: true, mode: 0o700 });
184
- await chmodIfPossible(paths.piDataDir, 0o700);
242
+ const nonce = randomUUID();
243
+ await mkdir(paths.profileDir, { recursive: true, mode: 0o700 });
244
+ await chmodIfPossible(paths.profileDir, 0o700);
185
245
  while (true) {
186
246
  try {
187
247
  await writeFile(
188
248
  paths.lockFile,
189
- JSON.stringify({ pid: processLike.pid, claimedAt: new Date().toISOString() }),
249
+ JSON.stringify({ pid: processLike.pid, nonce, claimedAt: new Date().toISOString() }),
190
250
  { flag: 'wx', mode: 0o600 },
191
251
  );
192
252
  await chmodIfPossible(paths.lockFile, 0o600);
@@ -204,7 +264,7 @@ export const createPiSessionDaemonSupervisor = ({
204
264
  } finally {
205
265
  try {
206
266
  const claim = JSON.parse(await readFile(paths.lockFile, 'utf8'));
207
- if (claim?.pid === processLike.pid) await rm(paths.lockFile, { force: true });
267
+ if (claim?.pid === processLike.pid && claim?.nonce === nonce) await rm(paths.lockFile, { force: true });
208
268
  } catch {
209
269
  // A missing or already-replaced lock must not remove another owner.
210
270
  }
@@ -241,8 +301,8 @@ export const createPiSessionDaemonSupervisor = ({
241
301
  };
242
302
 
243
303
  const ensureCredential = async () => {
244
- await mkdir(paths.piDataDir, { recursive: true, mode: 0o700 });
245
- await chmodIfPossible(paths.piDataDir, 0o700);
304
+ await mkdir(paths.profileDir, { recursive: true, mode: 0o700 });
305
+ await chmodIfPossible(paths.profileDir, 0o700);
246
306
  try {
247
307
  const credential = await readCredential();
248
308
  await chmodIfPossible(paths.credentialFile, 0o600);
@@ -264,9 +324,11 @@ export const createPiSessionDaemonSupervisor = ({
264
324
 
265
325
  const probe = async (credential) => {
266
326
  const state = await readState();
267
- if (!state || state.endpoint !== paths.endpoint) {
327
+ if (!state || state.endpoint !== paths.endpoint || state.profileKey !== paths.profileKey) {
268
328
  const failure = await readFailureState();
269
- if (failure?.endpoint === paths.endpoint) throw new PiSessionDaemonUnavailableError(failure.error.code);
329
+ if (failure?.endpoint === paths.endpoint && failure?.profileKey === paths.profileKey) {
330
+ throw new PiSessionDaemonUnavailableError(failure.error.code);
331
+ }
270
332
  throw new PiSessionDaemonUnavailableError('DAEMON_UNAVAILABLE');
271
333
  }
272
334
  try {
@@ -276,7 +338,13 @@ export const createPiSessionDaemonSupervisor = ({
276
338
  command: 'runtime.health',
277
339
  timeoutMs: startupTimeoutMs,
278
340
  }), startupTimeoutMs, 'DAEMON_UNAVAILABLE');
279
- if (health?.state !== 'ready' || health.daemonPid !== state.pid) {
341
+ if (health?.state !== 'ready'
342
+ || health.daemonPid !== state.pid
343
+ || health.profileKey !== paths.profileKey
344
+ || (typeof state.daemonId === 'string' && health.daemonId !== state.daemonId)
345
+ || (typeof state.serverInstanceId === 'string' && health.serverInstanceId !== state.serverInstanceId)
346
+ || (Number.isInteger(state.serverPid) && health.serverPid !== state.serverPid)
347
+ || (typeof state.buildId === 'string' && health.buildId !== state.buildId)) {
280
348
  throw new PiSessionDaemonUnavailableError('DAEMON_IDENTITY_MISMATCH');
281
349
  }
282
350
  return { state, health };
@@ -303,11 +371,38 @@ export const createPiSessionDaemonSupervisor = ({
303
371
 
304
372
  const removeStaleState = async (state) => {
305
373
  const current = await readState() ?? await readFailureState();
306
- if (current?.pid === state?.pid && current.endpoint === paths.endpoint) {
374
+ if (current?.pid === state?.pid
375
+ && current.endpoint === paths.endpoint
376
+ && current.profileKey === paths.profileKey) {
307
377
  await rm(paths.stateFile, { force: true });
308
378
  }
309
379
  };
310
380
 
381
+ // Transfer a same-profile daemon to this server instance only after its
382
+ // prior server owner has exited. The daemon persists the new owner before
383
+ // acknowledging the claim, keeping IPC identity and the sidecar in sync.
384
+ const claimDaemonOwnership = async (credential) => {
385
+ try {
386
+ await request({
387
+ endpoint: paths.endpoint,
388
+ credential,
389
+ command: 'runtime.claim',
390
+ payload: { serverInstanceId: paths.serverInstanceId, serverPid },
391
+ timeoutMs: startupTimeoutMs,
392
+ });
393
+ } catch (error) {
394
+ if (error instanceof SessionDaemonClientError && error.code === 'UNKNOWN_COMMAND') return false;
395
+ if (error instanceof SessionDaemonClientError && error.code === 'OWNERSHIP_CONFLICT') {
396
+ throw new PiSessionDaemonUnavailableError('DAEMON_PROFILE_IN_USE');
397
+ }
398
+ if (error instanceof SessionDaemonClientError) {
399
+ throw new PiSessionDaemonUnavailableError(error.code);
400
+ }
401
+ throw error;
402
+ }
403
+ return true;
404
+ };
405
+
311
406
  const recoverVerifiedStaleEndpoint = async (state, credential) => {
312
407
  if (platform === 'win32' || !state || isPidAlive(processLike, state.pid)) return false;
313
408
  try {
@@ -319,7 +414,12 @@ export const createPiSessionDaemonSupervisor = ({
319
414
  }
320
415
 
321
416
  try {
322
- await request({ endpoint: paths.endpoint, credential, command: 'runtime.health' });
417
+ await request({
418
+ endpoint: paths.endpoint,
419
+ credential,
420
+ command: 'runtime.health',
421
+ timeoutMs: startupTimeoutMs,
422
+ });
323
423
  return false;
324
424
  } catch (error) {
325
425
  // A dead owner plus an owner-only socket that either refuses or never
@@ -332,8 +432,36 @@ export const createPiSessionDaemonSupervisor = ({
332
432
  return true;
333
433
  };
334
434
 
335
- const requestDaemonExit = async (state) => {
435
+ // Authenticated shutdown: prove profile ownership over IPC before
436
+ // signaling anything. A stale server whose daemon was claimed by a newer
437
+ // instance receives an ownership error and must not terminate anything.
438
+ const requestDaemonShutdown = async (state, credential) => {
336
439
  if (!state || !Number.isInteger(state.pid) || state.pid <= 0) return;
440
+ if (state.profileKey !== paths.profileKey) {
441
+ throw new PiSessionDaemonUnavailableError('DAEMON_OWNERSHIP_MISMATCH');
442
+ }
443
+ try {
444
+ await request({
445
+ endpoint: paths.endpoint,
446
+ credential,
447
+ command: 'runtime.shutdown',
448
+ payload: { serverInstanceId: paths.serverInstanceId, daemonId: state.daemonId },
449
+ timeoutMs: startupTimeoutMs,
450
+ });
451
+ } catch (error) {
452
+ if (error instanceof SessionDaemonClientError
453
+ && (error.code === 'DAEMON_OWNERSHIP_MISMATCH' || error.code === 'OWNERSHIP_MISMATCH')) {
454
+ throw new PiSessionDaemonUnavailableError('DAEMON_OWNERSHIP_MISMATCH');
455
+ }
456
+ if (error instanceof SessionDaemonClientError
457
+ && !['DAEMON_CONNECTION_REFUSED', 'DAEMON_UNAVAILABLE'].includes(error.code)
458
+ && error.code !== 'UNKNOWN_COMMAND') {
459
+ throw new PiSessionDaemonUnavailableError(error.code);
460
+ }
461
+ // UNKNOWN_COMMAND (a daemon that predates shutdown) and unreachable
462
+ // daemons fall through to the PID wait below; only a verified owner
463
+ // reaches the signal.
464
+ }
337
465
  try {
338
466
  processLike.kill(state.pid, 'SIGTERM');
339
467
  } catch {
@@ -357,17 +485,25 @@ export const createPiSessionDaemonSupervisor = ({
357
485
  if (startPromise) return startPromise;
358
486
  startPromise = withOperationLock(async () => {
359
487
  const credential = await ensureCredential();
488
+ await cleanupDeadLegacyDaemonState({ dataDir: dirname(paths.piDataDir), processLike });
360
489
  try {
361
490
  const existing = await probe(credential);
362
- if (daemonEntrypointMatches(existing.state)) {
363
- return { state: 'ready', reused: true, protocolVersion: PROTOCOL_VERSION, capabilities: existing.health.capabilities ?? [] };
491
+ const isCompatibleBuild = daemonEntrypointMatches(existing.state)
492
+ && existing.state.buildId === paths.buildId
493
+ && existing.health.buildId === paths.buildId
494
+ && (!paths.profileDevelopment || existing.state.serverInstanceId === paths.serverInstanceId);
495
+ const claimed = await claimDaemonOwnership(credential);
496
+ if (isCompatibleBuild && claimed) {
497
+ const ready = await probe(credential);
498
+ return { state: 'ready', reused: true, protocolVersion: PROTOCOL_VERSION, capabilities: ready.health.capabilities ?? [] };
364
499
  }
365
- // A healthy daemon from another install (global npm vs this checkout)
366
- // must not keep answering getSession without the live-turn overlay.
367
- await requestDaemonExit(existing.state);
500
+ // Replace an older protocol/build, and always replace a development
501
+ // daemon so a source restart cannot keep running stale module code.
502
+ await requestDaemonShutdown(existing.state, credential);
368
503
  } catch (error) {
369
504
  if (!(error instanceof PiSessionDaemonUnavailableError)) throw error;
370
- if (error.code === 'DAEMON_STOP_FAILED' || error.code === 'DAEMON_STOP_TIMEOUT') throw error;
505
+ if (error.code === 'DAEMON_STOP_FAILED' || error.code === 'DAEMON_STOP_TIMEOUT'
506
+ || error.code === 'DAEMON_OWNERSHIP_MISMATCH' || error.code === 'DAEMON_PROFILE_IN_USE') throw error;
371
507
  }
372
508
 
373
509
  const staleState = await readState() ?? await readFailureState();
@@ -387,24 +523,46 @@ export const createPiSessionDaemonSupervisor = ({
387
523
  await mkdir(paths.runtimeDir, { recursive: true, mode: 0o700 });
388
524
  await chmod(paths.runtimeDir, 0o700);
389
525
  }
526
+ await mkdir(dirname(paths.logFile), { recursive: true, mode: 0o700 });
527
+ await chmodIfPossible(dirname(paths.logFile), 0o700);
390
528
 
391
- const child = spawn(processLike.execPath, [
392
- DAEMON_ENTRYPOINT,
393
- '--endpoint', paths.endpoint,
394
- '--credential-file', paths.credentialFile,
395
- '--state-file', paths.stateFile,
396
- '--cwd', cwd,
397
- ...(paths.agentDir ? ['--agent-dir', paths.agentDir] : []),
398
- ], {
399
- cwd,
400
- detached: platform !== 'win32',
401
- stdio: 'ignore',
402
- windowsHide: true,
403
- env: buildSessionDaemonChildEnv({
404
- env,
405
- electronVersion: processLike.versions?.electron,
406
- }),
407
- });
529
+ const daemonId = randomUUID();
530
+ let logFd = null;
531
+ try {
532
+ logFd = openSync(paths.logFile, 'a');
533
+ } catch {
534
+ logFd = null;
535
+ }
536
+ let child;
537
+ try {
538
+ child = spawn(processLike.execPath, [
539
+ DAEMON_ENTRYPOINT,
540
+ '--endpoint', paths.endpoint,
541
+ '--credential-file', paths.credentialFile,
542
+ '--state-file', paths.stateFile,
543
+ '--cwd', cwd,
544
+ '--profile-key', paths.profileKey,
545
+ '--server-instance-id', paths.serverInstanceId,
546
+ '--server-pid', String(serverPid),
547
+ '--daemon-id', daemonId,
548
+ '--runtime', paths.profileRuntime,
549
+ '--build-id', paths.buildId,
550
+ ...(paths.agentDir ? ['--agent-dir', paths.agentDir] : []),
551
+ ], {
552
+ cwd,
553
+ detached: platform !== 'win32',
554
+ stdio: logFd === null ? 'ignore' : ['ignore', logFd, logFd],
555
+ windowsHide: true,
556
+ env: buildSessionDaemonChildEnv({
557
+ env,
558
+ electronVersion: processLike.versions?.electron,
559
+ }),
560
+ });
561
+ } finally {
562
+ if (logFd !== null) {
563
+ try { closeSync(logFd); } catch { /* the child holds its own copy */ }
564
+ }
565
+ }
408
566
  child?.unref?.();
409
567
 
410
568
  // Loading Pi settings, providers, and a larger local model catalog can
@@ -438,7 +596,10 @@ export const createPiSessionDaemonSupervisor = ({
438
596
  let credential = await readCredential();
439
597
  try {
440
598
  const ready = await probe(credential);
441
- if (daemonEntrypointMatches(ready.state)) {
599
+ if (daemonEntrypointMatches(ready.state)
600
+ && ready.state.buildId === paths.buildId
601
+ && ready.health.buildId === paths.buildId
602
+ && (!paths.profileDevelopment || ready.state.serverInstanceId === paths.serverInstanceId)) {
442
603
  return { credential, ready };
443
604
  }
444
605
  } catch (probeError) {
@@ -467,8 +628,16 @@ export const createPiSessionDaemonSupervisor = ({
467
628
  };
468
629
 
469
630
  const subscribe = async ({ sessionId, fromSequence, onEvent, onError }) => {
470
- const { credential } = await ensureReady();
471
- return subscribeSessionDaemon({ endpoint: paths.endpoint, credential, sessionId, fromSequence, onEvent, onError });
631
+ try {
632
+ const { credential } = await ensureReady();
633
+ return await subscribeSessionDaemon({ endpoint: paths.endpoint, credential, sessionId, fromSequence, onEvent, onError });
634
+ } catch (error) {
635
+ throw new PiSessionDaemonUnavailableError(
636
+ error instanceof SessionDaemonClientError && error.code !== 'DAEMON_CONNECTION_REFUSED'
637
+ ? error.code
638
+ : error instanceof PiSessionDaemonUnavailableError ? error.code : 'DAEMON_UNAVAILABLE',
639
+ );
640
+ }
472
641
  };
473
642
 
474
643
  const health = async () => {
@@ -485,12 +654,33 @@ export const createPiSessionDaemonSupervisor = ({
485
654
  };
486
655
 
487
656
  const stop = async () => {
657
+ intentionallyStopped = true;
488
658
  const pendingStart = startPromise;
489
659
  if (pendingStart) await pendingStart.catch(() => {});
490
660
  return withOperationLock(async () => {
491
- const credential = await readCredential();
661
+ let credential;
662
+ try {
663
+ credential = await readCredential();
664
+ } catch (error) {
665
+ if (error?.code !== 'DAEMON_CREDENTIAL_UNAVAILABLE') throw error;
666
+ intentionallyStopped = true;
667
+ return { state: 'stopped' };
668
+ }
669
+ const recordedState = await readState();
670
+ if (!recordedState) {
671
+ const failureState = await readFailureState();
672
+ if (failureState && !isPidAlive(processLike, failureState.pid)) await removeStaleState(failureState);
673
+ intentionallyStopped = true;
674
+ return { state: 'stopped' };
675
+ }
492
676
  const { state } = await probe(credential);
493
- await requestDaemonExit(state);
677
+ // A stale server must never stop a daemon claimed by a newer instance
678
+ // of the same profile (for example a development server stopping after
679
+ // the installed server claimed the profile daemon).
680
+ if (state.serverInstanceId !== paths.serverInstanceId) {
681
+ throw new PiSessionDaemonUnavailableError('DAEMON_OWNERSHIP_MISMATCH');
682
+ }
683
+ await requestDaemonShutdown(state, credential);
494
684
  intentionallyStopped = true;
495
685
  return { state: 'stopped' };
496
686
  });