@pi-chamber/web 1.0.8-rc.1 → 1.0.8-rc.2

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 (142) hide show
  1. package/dist/assets/{AgentsSurface-BmHImX8m.js → AgentsSurface-CcWBqAWV.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-C71fGOm2.js → ChoicesArtifact-Kk-qvrSB.js} +1 -1
  3. package/dist/assets/{DiagramView-BZQxoiZu.js → DiagramView-DZUBo1uP.js} +1 -1
  4. package/dist/assets/{DiffView-C70pbgk-.js → DiffView-CiZy4jFA.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-Cu8c3gBV.js → FileSaveConflictDialog-DZ9NDwOO.js} +1 -1
  6. package/dist/assets/{FilesView-nFJYEdRw.js → FilesView-DqiZ9kw9.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-Jvv_tgbl.js → GitHubDetailScaffold-DM2DH7o8.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-BXD2ODRi.js → GitHubLinkPicker-ChB8NZ1h.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BWI706F0.js → GitHubListPrimitives-CibDiJGq.js} +1 -1
  10. package/dist/assets/{GitView-MIDG5RYW.js → GitView--EaZQrBr.js} +5 -5
  11. package/dist/assets/{IssuesSurface-uNlozeu0.js → IssuesSurface-CySTpaD1.js} +3 -3
  12. package/dist/assets/{JsonTreeView-CSLsTriz.js → JsonTreeView-_yMHKKQZ.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cs-7BfWi.js → MarkdownRendererImpl-D_-2fQw0.js} +1 -1
  14. package/dist/assets/{PatchDiff-axbsnbTJ.js → PatchDiff-bHObDlhD.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-lwn6w_5w.js → PierreDiffViewer-UY7Cse-s.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-o_AXDjbO.js → PullRequestsSurface-iXy6chwc.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-C4CMlcbv.js → SessionSwitcherContent-DJGCa_wN.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-DCBVuCoo.js → SessionSwitcherDropdown-CDOX-5Y2.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-DyeIrsro.js → SessionUnreadDot-Dwc3MdvA.js} +1 -1
  20. package/dist/assets/SettingsView-DA-U9lsj.js +11 -0
  21. package/dist/assets/{SettingsWindow-Cb4st5y5.js → SettingsWindow-CUg49Mfh.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-BzeMEoFP.js → SubagentsArtifact-DUZX9tDe.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BP2mOWdV.js → ToolOutputDialog-BuZZaRw4.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-D49XBR9b.js → ToolPartDiffPreview-CKncG6i2.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-CLgDONEQ.js → VirtualizedFileDiff-BGZiLPe_.js} +1 -1
  26. package/dist/assets/VisualFrame-DBZkHFnG.js +22 -0
  27. package/dist/assets/VisualsArtifact-Bq0vMO-i.js +1 -0
  28. package/dist/assets/{collapsible-BeyKtQGB.js → collapsible-Bro9KrfM.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmO6H8u6.js → computeVirtualFileMetrics-DJQqK49u.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-DOK251YW.js → contextFileOpenGuard-ByWK3Sru.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CnzR7kxA.js → fileTreeStatus-CyJ3TOYD.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-4kPg2t6j.js → gitStatusPredicates-BsXrwngT.js} +1 -1
  33. package/dist/assets/{githubLink-QvaLfNNT.js → githubLink-g2bmC0qi.js} +1 -1
  34. package/dist/assets/index-B_L9GVYw.css +1 -0
  35. package/dist/assets/{index-DMX9wT1Z.js → index-C9rUUQ_Y.js} +1 -1
  36. package/dist/assets/index-CKKWVoND.js +11 -0
  37. package/dist/assets/{main-BW9J3Y72.js → main-DT-4_fhe.js} +2 -2
  38. package/dist/assets/{main-BirYxac2.js → main-DsLMU9CT.js} +4 -4
  39. package/dist/assets/{markdownCore-CxmcPur8.js → markdownCore-QmM_aOnZ.js} +1 -1
  40. package/dist/assets/{miniChat-BRB11eEs.js → miniChat-BqGslD2z.js} +2 -2
  41. package/dist/assets/{mobile-DJZYYCuB.js → mobile-C5JOcDIC.js} +2 -2
  42. package/dist/assets/{nativeFileSave-B6QpoPRn.js → nativeFileSave-DSMsJqXM.js} +1 -1
  43. package/dist/assets/{pi-session-focus-preference-PWoh3LNA.js → pi-session-focus-preference-Cc_S4zi1.js} +1 -1
  44. package/dist/assets/{renderDiffWithHighlighter-C48T6YFJ.js → renderDiffWithHighlighter-BXhnIAHg.js} +1 -1
  45. package/dist/assets/{renderElectronMiniChatApp-N-BQdJl0.js → renderElectronMiniChatApp-CiSkecEE.js} +2 -2
  46. package/dist/assets/{renderFileWithHighlighter-8Kt2MyTN.js → renderFileWithHighlighter-CK29YZtC.js} +1 -1
  47. package/dist/assets/renderMobileApp-C4JuoxsZ.js +11 -0
  48. package/dist/assets/runtimeEndpointReset-Dwj-jCDS.js +66 -0
  49. package/dist/assets/{runtimeSurface-kIEoYsPP.js → runtimeSurface-0K7vuUpd.js} +1 -1
  50. package/dist/assets/{selection-BTEdLRVK.js → selection-CnYkEsu_.js} +1 -1
  51. package/dist/assets/useAppFontEffects-CV5UyTRw.js +226 -0
  52. package/dist/assets/{useGitHubRemoteSearch-DIBHNu8r.js → useGitHubRemoteSearch-CgP-zEBj.js} +1 -1
  53. package/dist/assets/{useSwitcherItems-DfLbfX37.js → useSwitcherItems-C8G5F0hs.js} +1 -1
  54. package/dist/assets/{web-components-C_DsTJis.js → web-components-BpncHjnV.js} +1 -1
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +3 -3
  57. package/dist/mobile.html +3 -3
  58. package/package.json +1 -1
  59. package/plugins/featured.json +12 -0
  60. package/plugins/subagents/package.json +1 -1
  61. package/plugins/visuals/extension.js +7 -4
  62. package/plugins/visuals/package.json +1 -1
  63. package/server/index.js +86 -27
  64. package/server/lib/git/DOCUMENTATION.md +4 -0
  65. package/server/lib/git/service.js +70 -5
  66. package/server/lib/git/service.test.js +179 -0
  67. package/server/lib/github/DOCUMENTATION.md +2 -0
  68. package/server/lib/marketplace/DOCUMENTATION.md +95 -0
  69. package/server/lib/marketplace/featured.js +176 -0
  70. package/server/lib/marketplace/featured.test.js +207 -0
  71. package/server/lib/marketplace/npm-registry.js +255 -0
  72. package/server/lib/marketplace/npm-registry.test.js +227 -0
  73. package/server/lib/marketplace/routes.js +64 -0
  74. package/server/lib/marketplace/routes.test.js +119 -0
  75. package/server/lib/marketplace/service.js +225 -0
  76. package/server/lib/marketplace/service.test.js +174 -0
  77. package/server/lib/notifications/DOCUMENTATION.md +10 -4
  78. package/server/lib/notifications/pi-notification-watcher.js +92 -33
  79. package/server/lib/notifications/pi-notification-watcher.test.js +79 -0
  80. package/server/lib/open-url/DOCUMENTATION.md +1 -0
  81. package/server/lib/pi/merged-event-stream.js +316 -0
  82. package/server/lib/pi/merged-event-stream.test.js +95 -0
  83. package/server/lib/pi/routes-daemon-pool.test.js +348 -0
  84. package/server/lib/pi/routes-merged-events.test.js +327 -0
  85. package/server/lib/pi/routes-sandbox.test.js +1684 -0
  86. package/server/lib/pi/routes.js +491 -90
  87. package/server/lib/pi/routes.test.js +87 -2
  88. package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
  89. package/server/lib/pi/sandbox/launcher.js +122 -0
  90. package/server/lib/pi/sandbox/launcher.test.js +91 -0
  91. package/server/lib/pi/sandbox/nono-launcher.js +455 -0
  92. package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
  93. package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
  94. package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
  95. package/server/lib/pi/sandbox/nono-profile.json +22 -0
  96. package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
  97. package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
  98. package/server/lib/pi/sandbox/project-sandbox.js +207 -0
  99. package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
  100. package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
  101. package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
  102. package/server/lib/pi/sandbox/trust-ask.js +135 -0
  103. package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
  104. package/server/lib/pi/sandbox/worktree-ids.js +96 -0
  105. package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
  106. package/server/lib/pi/session-daemon/DOCUMENTATION.md +26 -6
  107. package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
  108. package/server/lib/pi/session-daemon/daemon-process.js +10 -1
  109. package/server/lib/pi/session-daemon/extension-config.js +206 -23
  110. package/server/lib/pi/session-daemon/extension-config.test.js +180 -0
  111. package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
  112. package/server/lib/pi/session-daemon/session-daemon.js +368 -56
  113. package/server/lib/pi/session-daemon/session-daemon.test.js +227 -0
  114. package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
  115. package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
  116. package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
  117. package/server/lib/pi/session-daemon/session-lease.js +93 -15
  118. package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
  119. package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
  120. package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
  121. package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
  122. package/server/lib/pi/session-daemon/supervisor.js +386 -35
  123. package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
  124. package/server/lib/pi/ui-settings-store.js +88 -2
  125. package/server/lib/pi/ui-settings-store.test.js +118 -0
  126. package/server/lib/plugins/DOCUMENTATION.md +17 -5
  127. package/server/lib/plugins/daemon-sync.js +16 -6
  128. package/server/lib/plugins/daemon-sync.test.js +12 -0
  129. package/server/lib/plugins/impact.test.js +2 -1
  130. package/server/lib/plugins/manifest.js +25 -0
  131. package/server/lib/plugins/manifest.test.js +9 -0
  132. package/server/lib/plugins/routes.test.js +28 -0
  133. package/server/lib/plugins/service.js +24 -2
  134. package/server/lib/server/cross-process-lock.js +28 -3
  135. package/dist/assets/SettingsView-BHBpt2Um.js +0 -7
  136. package/dist/assets/VisualFrame-CJrAvWSo.js +0 -22
  137. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +0 -1
  138. package/dist/assets/index-B2v0_mez.js +0 -11
  139. package/dist/assets/index-D3F4JrPN.css +0 -1
  140. package/dist/assets/renderMobileApp-B7cT7m5b.js +0 -11
  141. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +0 -62
  142. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +0 -225
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
- import { spawn as spawnChildProcess } from 'node:child_process';
2
+ import { execFile, spawn as spawnChildProcess } from 'node:child_process';
3
3
  import { closeSync, openSync } from 'node:fs';
4
4
  import { chmod, lstat, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import { userInfo } from 'node:os';
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
  import { dirname, isAbsolute, join, resolve } from 'node:path';
8
8
 
9
9
  import { resolvePiChamberDataDir } from '../../pichamber-data-dir.js';
10
+ import { readSmallRegularFile } from '../../server/cross-process-lock.js';
10
11
  import { resolveServerProfile } from '../../server/server-profile.js';
11
12
  import { isLocalSessionDaemonEndpoint } from './session-daemon.js';
12
13
  import { requestSessionDaemon, SessionDaemonClientError, subscribeSessionDaemon } from './ipc-client.js';
@@ -14,7 +15,14 @@ import { requestSessionDaemon, SessionDaemonClientError, subscribeSessionDaemon
14
15
  const PROTOCOL_VERSION = 1;
15
16
  const OPERATION_TIMEOUT_MS = 5_000;
16
17
  const DAEMON_READY_TIMEOUT_MS = 15_000;
18
+ // A sandbox daemon starts the same Node process behind nono's setup and its
19
+ // network proxy. On a slow machine two of them starting together took over
20
+ // 15 s; the start still fails closed, it only waits longer.
21
+ const SANDBOX_DAEMON_READY_TIMEOUT_MS = 45_000;
17
22
  const RETRY_DELAY_MS = 100;
23
+ // sun_path holds 108 bytes on Linux and 104 on macOS, including the
24
+ // terminating NUL.
25
+ const maxUnixSocketPathBytes = (platform) => (platform === 'darwin' ? 103 : 107);
18
26
  const DAEMON_ENTRYPOINT = fileURLToPath(new URL('./daemon-process.js', import.meta.url));
19
27
 
20
28
  class PiSessionDaemonUnavailableError extends Error {
@@ -81,6 +89,18 @@ const buildSessionDaemonChildEnv = ({ env = {}, electronVersion } = {}) => {
81
89
  return next;
82
90
  };
83
91
 
92
+ // The server's own settings stay out of a sandbox: its UI password, JWT
93
+ // secret and tunnel token would let sandboxed code sign in to this server and
94
+ // run anything through it, and a shared endpoint override would point the
95
+ // sandbox at the main daemon's socket. Only what a daemon reads is kept, so a
96
+ // server variable added later is left out unless it is listed here.
97
+ const SANDBOX_KEPT_PICHAMBER_ENV = new Set(['PICHAMBER_DATA_DIR', 'PICHAMBER_PI_AGENT_DIR']);
98
+ const sandboxDaemonEnv = (env = {}) => Object.fromEntries(
99
+ Object.entries(env).filter(([name]) => (
100
+ !name.toUpperCase().startsWith('PICHAMBER_') || SANDBOX_KEPT_PICHAMBER_ENV.has(name)
101
+ )),
102
+ );
103
+
84
104
  const isPidAlive = (processLike, pid) => {
85
105
  try {
86
106
  processLike.kill(pid, 0);
@@ -90,11 +110,51 @@ const isPidAlive = (processLike, pid) => {
90
110
  }
91
111
  };
92
112
 
113
+ // What identifies a process besides its pid, so a recorded launcher pid that
114
+ // was reused by another process is never signaled. Linux: the start time
115
+ // (clock ticks since boot) from /proc/<pid>/stat; a zombie counts as gone.
116
+ // macOS: `ps` state and start time, which has one-second resolution, so a pid
117
+ // reused within the same second is not told apart. Elsewhere (Windows has no
118
+ // sandbox launcher) nothing is checked and the answer is null, which signals
119
+ // nothing.
120
+ const readProcessIdentityFor = (platform) => async (pid) => {
121
+ if (!Number.isInteger(pid) || pid <= 1) return null;
122
+ if (platform === 'linux') {
123
+ try {
124
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
125
+ // The command name (field 2) can hold spaces and parentheses, so fields
126
+ // are counted from the last ')'. fields[0] is the state (field 3) and
127
+ // fields[19] the start time (field 22).
128
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
129
+ if (fields[0] === 'Z' || fields[0] === 'X') return null;
130
+ return /^\d+$/.test(fields[19] ?? '') ? `linux-start:${fields[19]}` : null;
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+ if (platform === 'darwin') {
136
+ return new Promise((resolveIdentity) => {
137
+ execFile('/bin/ps', ['-o', 'stat=', '-o', 'lstart=', '-p', String(pid)], { timeout: 2_000 }, (error, stdout) => {
138
+ const line = typeof stdout === 'string' ? stdout.trim() : '';
139
+ if (error || !line || line.startsWith('Z')) {
140
+ resolveIdentity(null);
141
+ return;
142
+ }
143
+ resolveIdentity(`darwin-start:${line.replace(/^\S+\s+/, '').replace(/\s+/g, ' ')}`);
144
+ });
145
+ });
146
+ }
147
+ return null;
148
+ };
149
+
93
150
  const RETRYABLE_LOCK_CREATE_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY', 'EAGAIN']);
94
151
  const FRESH_LOCK_MS = 250;
95
152
 
96
153
  const chmodIfPossible = async (filePath, mode) => {
97
154
  try {
155
+ // A sandbox daemon can write its own profile folder; chmod follows a
156
+ // symlink, so one planted here must not reach the file it points at.
157
+ if ((await lstat(filePath)).isSymbolicLink()) return;
98
158
  await chmod(filePath, mode);
99
159
  } catch {
100
160
  // Windows and some filesystems reject POSIX mode bits; the lock/credential
@@ -137,6 +197,9 @@ const resolvePiSessionDaemonPaths = ({
137
197
  port,
138
198
  runtime,
139
199
  version,
200
+ // The runtime folder's name (default: the profile key). Sandbox daemons
201
+ // pass a short one so their socket path fits a Unix socket address.
202
+ runtimeName,
140
203
  } = {}) => {
141
204
  const resolvedProfile = profile && typeof profile.profileKey === 'string'
142
205
  ? profile
@@ -150,9 +213,10 @@ const resolvePiSessionDaemonPaths = ({
150
213
  buildId,
151
214
  } = resolvedProfile;
152
215
  const profileDir = pathModule.join(dataDir, 'pi', 'daemons', profileKey);
216
+ const runtimeFolder = runtimeName ?? profileKey;
153
217
  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);
218
+ ? pathModule.join(pathModule.resolve(env.XDG_RUNTIME_DIR.trim()), 'pichamber', 'pi-daemons', runtimeFolder)
219
+ : pathModule.join(dataDir, 'runtime', 'pi-daemons', runtimeFolder);
156
220
  const configuredEndpoint = typeof env.PICHAMBER_PI_SESSION_DAEMON_ENDPOINT === 'string'
157
221
  ? env.PICHAMBER_PI_SESSION_DAEMON_ENDPOINT.trim()
158
222
  : '';
@@ -234,12 +298,42 @@ export const createPiSessionDaemonSupervisor = ({
234
298
  port,
235
299
  runtime,
236
300
  version,
301
+ launch,
302
+ leaseAgentDir,
303
+ leaseScope,
304
+ runtimeName,
305
+ readProcessIdentity = readProcessIdentityFor(platform),
237
306
  // Runs after every successful health probe, before the request it precedes.
238
307
  // `request` talks to that verified daemon directly. Errors are swallowed:
239
308
  // the hook must never fail the caller's request.
240
309
  onDaemonReady,
241
310
  } = {}) => {
242
- const paths = resolvePiSessionDaemonPaths({ env, dataDir, platform, profile, port, runtime, version });
311
+ const resolvedPaths = resolvePiSessionDaemonPaths({ env, dataDir, platform, profile, port, runtime, version, runtimeName });
312
+ // A daemon started through a launcher runs untrusted code (the agent's
313
+ // shell commands, project extensions) with read-write access to its own
314
+ // profile folder, so its state sidecar, credential and anything else there
315
+ // can be forged. The server keeps what it must trust about that daemon (the
316
+ // launcher it spawned, and the operation lock) in
317
+ // `<dataDir>/pi/launchers/<profileKey>/`. No sandbox grant covers it: the
318
+ // grants are the project, folders under `<dataDir>/pi/sandbox/<key>/`, the
319
+ // session and lease folders under the Pi agent folder,
320
+ // `<dataDir>/worktree/<projectId>`, the profile folder under
321
+ // `<dataDir>/pi/daemons/`, and socket binds in the runtime folder. It sits
322
+ // in the data folder rather than the runtime folder so the record survives
323
+ // a server restart: the detached daemon outlives it and the next server
324
+ // reuses or stops it.
325
+ const launcherDir = launch ? join(resolvedPaths.piDataDir, 'launchers', resolvedPaths.profileKey) : null;
326
+ const paths = launch
327
+ ? {
328
+ ...resolvedPaths,
329
+ lockFile: join(launcherDir, 'operation.lock'),
330
+ launcherFile: join(launcherDir, 'launcher.json'),
331
+ // The server sends the credential to the daemon on every request, so
332
+ // it must be a file the sandbox cannot replace: there the daemon may
333
+ // read it (one read-only file grant) and nothing more.
334
+ credentialFile: join(launcherDir, 'session-daemon.key'),
335
+ }
336
+ : resolvedPaths;
243
337
  const serverPid = processLike.pid;
244
338
  let startPromise = null;
245
339
  let intentionallyStopped = false;
@@ -247,8 +341,10 @@ export const createPiSessionDaemonSupervisor = ({
247
341
  const withOperationLock = async (operation) => {
248
342
  const deadline = Date.now() + startupTimeoutMs;
249
343
  const nonce = randomUUID();
250
- await mkdir(paths.profileDir, { recursive: true, mode: 0o700 });
251
- await chmodIfPossible(paths.profileDir, 0o700);
344
+ // The profile folder for the main daemon; the launcher folder for a
345
+ // launcher daemon.
346
+ await mkdir(dirname(paths.lockFile), { recursive: true, mode: 0o700 });
347
+ await chmodIfPossible(dirname(paths.lockFile), 0o700);
252
348
  while (true) {
253
349
  try {
254
350
  await writeFile(
@@ -279,9 +375,11 @@ export const createPiSessionDaemonSupervisor = ({
279
375
  }
280
376
  };
281
377
 
378
+ // A launcher daemon writes its own state file, so it is read as hostile
379
+ // input: never through a symlink, and never a FIFO that would block.
282
380
  const readState = async () => {
283
381
  try {
284
- const state = JSON.parse(await readFile(paths.stateFile, 'utf8'));
382
+ const state = JSON.parse(await readSmallRegularFile(paths.stateFile));
285
383
  return isValidState(state) ? state : null;
286
384
  } catch {
287
385
  return null;
@@ -290,7 +388,7 @@ export const createPiSessionDaemonSupervisor = ({
290
388
 
291
389
  const readFailureState = async () => {
292
390
  try {
293
- const state = JSON.parse(await readFile(paths.stateFile, 'utf8'));
391
+ const state = JSON.parse(await readSmallRegularFile(paths.stateFile));
294
392
  return isValidFailureState(state) ? state : null;
295
393
  } catch {
296
394
  return null;
@@ -299,7 +397,7 @@ export const createPiSessionDaemonSupervisor = ({
299
397
 
300
398
  const readCredential = async () => {
301
399
  try {
302
- const credential = (await readFile(paths.credentialFile, 'utf8')).trim();
400
+ const credential = (await readSmallRegularFile(paths.credentialFile)).trim();
303
401
  if (credential.length < 32) throw new Error('invalid credential');
304
402
  return credential;
305
403
  } catch {
@@ -310,6 +408,8 @@ export const createPiSessionDaemonSupervisor = ({
310
408
  const ensureCredential = async () => {
311
409
  await mkdir(paths.profileDir, { recursive: true, mode: 0o700 });
312
410
  await chmodIfPossible(paths.profileDir, 0o700);
411
+ await mkdir(dirname(paths.credentialFile), { recursive: true, mode: 0o700 });
412
+ await chmodIfPossible(dirname(paths.credentialFile), 0o700);
313
413
  try {
314
414
  const credential = await readCredential();
315
415
  await chmodIfPossible(paths.credentialFile, 0o600);
@@ -385,6 +485,88 @@ export const createPiSessionDaemonSupervisor = ({
385
485
  }
386
486
  };
387
487
 
488
+ // Launcher record: the process this server spawned for a launcher daemon
489
+ // (the launcher itself, `child.pid`), its identity, and the server instance
490
+ // that owns it. It is the only pid a launcher daemon's stop signals.
491
+ const readLauncherRecord = async () => {
492
+ if (!launch) return null;
493
+ try {
494
+ const record = JSON.parse(await readFile(paths.launcherFile, 'utf8'));
495
+ if (!Number.isInteger(record?.pid) || record.pid <= 1
496
+ || typeof record.identity !== 'string' || record.identity.length === 0
497
+ || record.profileKey !== paths.profileKey
498
+ || typeof record.serverInstanceId !== 'string') return null;
499
+ return record;
500
+ } catch {
501
+ return null;
502
+ }
503
+ };
504
+
505
+ const writeLauncherRecord = async (record) => {
506
+ await mkdir(launcherDir, { recursive: true, mode: 0o700 });
507
+ const temporary = `${paths.launcherFile}.${randomUUID()}.tmp`;
508
+ try {
509
+ await writeFile(temporary, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
510
+ await rename(temporary, paths.launcherFile);
511
+ } catch (error) {
512
+ await rm(temporary, { force: true });
513
+ throw error;
514
+ }
515
+ };
516
+
517
+ const removeLauncherRecord = async (record) => {
518
+ const current = await readLauncherRecord();
519
+ if (current?.pid === record.pid && current.identity === record.identity) {
520
+ await rm(paths.launcherFile, { force: true });
521
+ }
522
+ };
523
+
524
+ const isLauncherAlive = async (record) => (
525
+ Boolean(record) && (await readProcessIdentity(record.pid)) === record.identity
526
+ );
527
+
528
+ // Wait for a launcher daemon to stop, signaling only the launcher process
529
+ // this server recorded, after confirming its identity. A launcher daemon's
530
+ // `state.pid` is never signaled: the sandbox can write any pid there.
531
+ // Under `nono run` (0.82.0) the launcher is nono's supervisor process. It
532
+ // forwards SIGTERM to the sandboxed daemon and exits after the daemon does,
533
+ // so waiting on it waits on the daemon. The daemon shares nono's process
534
+ // group (it has no terminal, so nono opens no PTY and makes no new
535
+ // session), so the group is not signaled: the daemon would get SIGTERM
536
+ // twice, and its handler is one-shot, so the second would kill it before
537
+ // its own shutdown finished.
538
+ const finishLauncherDaemonStop = async (state) => {
539
+ const record = await readLauncherRecord();
540
+ const deadline = Date.now() + startupTimeoutMs;
541
+ if (!record) {
542
+ // No record (a daemon started before records existed, or a lost
543
+ // record): signal nothing and give the authenticated shutdown time to
544
+ // take effect. A forged `state.pid` can only make this wait time out.
545
+ while (state && Date.now() < deadline) {
546
+ if (!isPidAlive(processLike, state.pid)) {
547
+ await removeStaleState(state);
548
+ return;
549
+ }
550
+ await wait(RETRY_DELAY_MS);
551
+ }
552
+ if (state) throw new PiSessionDaemonUnavailableError('DAEMON_STOP_TIMEOUT');
553
+ return;
554
+ }
555
+ if (await isLauncherAlive(record)) {
556
+ try {
557
+ processLike.kill(record.pid, 'SIGTERM');
558
+ } catch {
559
+ if (await isLauncherAlive(record)) throw new PiSessionDaemonUnavailableError('DAEMON_STOP_FAILED');
560
+ }
561
+ while (await isLauncherAlive(record)) {
562
+ if (Date.now() >= deadline) throw new PiSessionDaemonUnavailableError('DAEMON_STOP_TIMEOUT');
563
+ await wait(RETRY_DELAY_MS);
564
+ }
565
+ }
566
+ await removeLauncherRecord(record);
567
+ if (state) await removeStaleState(state);
568
+ };
569
+
388
570
  // Transfer a same-profile daemon to this server instance only after its
389
571
  // prior server owner has exited. The daemon persists the new owner before
390
572
  // acknowledging the claim, keeping IPC identity and the sidecar in sync.
@@ -442,11 +624,7 @@ export const createPiSessionDaemonSupervisor = ({
442
624
  // Authenticated shutdown: prove profile ownership over IPC before
443
625
  // signaling anything. A stale server whose daemon was claimed by a newer
444
626
  // instance receives an ownership error and must not terminate anything.
445
- const requestDaemonShutdown = async (state, credential) => {
446
- if (!state || !Number.isInteger(state.pid) || state.pid <= 0) return;
447
- if (state.profileKey !== paths.profileKey) {
448
- throw new PiSessionDaemonUnavailableError('DAEMON_OWNERSHIP_MISMATCH');
449
- }
627
+ const requestShutdownOverIpc = async (state, credential) => {
450
628
  try {
451
629
  await request({
452
630
  endpoint: paths.endpoint,
@@ -469,6 +647,18 @@ export const createPiSessionDaemonSupervisor = ({
469
647
  // daemons fall through to the PID wait below; only a verified owner
470
648
  // reaches the signal.
471
649
  }
650
+ };
651
+
652
+ const requestDaemonShutdown = async (state, credential) => {
653
+ if (!state || !Number.isInteger(state.pid) || state.pid <= 0) return;
654
+ if (state.profileKey !== paths.profileKey) {
655
+ throw new PiSessionDaemonUnavailableError('DAEMON_OWNERSHIP_MISMATCH');
656
+ }
657
+ await requestShutdownOverIpc(state, credential);
658
+ if (launch) {
659
+ await finishLauncherDaemonStop(state);
660
+ return;
661
+ }
472
662
  try {
473
663
  processLike.kill(state.pid, 'SIGTERM');
474
664
  } catch {
@@ -500,6 +690,14 @@ export const createPiSessionDaemonSupervisor = ({
500
690
  && existing.health.buildId === paths.buildId
501
691
  && (!paths.profileDevelopment || existing.state.serverInstanceId === paths.serverInstanceId);
502
692
  const claimed = await claimDaemonOwnership(credential);
693
+ if (claimed) {
694
+ // The daemon now answers to this server, so the launcher record,
695
+ // which a launcher daemon's stop checks ownership against, does too.
696
+ const record = await readLauncherRecord();
697
+ if (record && record.serverInstanceId !== paths.serverInstanceId) {
698
+ await writeLauncherRecord({ ...record, serverInstanceId: paths.serverInstanceId });
699
+ }
700
+ }
503
701
  if (isCompatibleBuild && claimed) {
504
702
  const ready = await probe(credential);
505
703
  return {
@@ -525,6 +723,14 @@ export const createPiSessionDaemonSupervisor = ({
525
723
  if (staleState && isPidAlive(processLike, staleState.pid)) {
526
724
  throw new PiSessionDaemonUnavailableError('DAEMON_UNAVAILABLE');
527
725
  }
726
+ // A launcher this server spawned that is still running holds a daemon
727
+ // that does not answer yet; never start a second one beside it, and
728
+ // never lose its record by writing another.
729
+ const previousLauncher = await readLauncherRecord();
730
+ if (previousLauncher) {
731
+ if (await isLauncherAlive(previousLauncher)) throw new PiSessionDaemonUnavailableError('DAEMON_UNAVAILABLE');
732
+ await removeLauncherRecord(previousLauncher);
733
+ }
528
734
  if (await endpointExists()) {
529
735
  const recovered = await recoverVerifiedStaleEndpoint(staleState, credential);
530
736
  if (!recovered) {
@@ -550,30 +756,49 @@ export const createPiSessionDaemonSupervisor = ({
550
756
  }
551
757
  let child;
552
758
  let spawnError = null;
759
+ let command = processLike.execPath;
760
+ let args = [
761
+ DAEMON_ENTRYPOINT,
762
+ '--endpoint', paths.endpoint,
763
+ '--credential-file', paths.credentialFile,
764
+ '--state-file', paths.stateFile,
765
+ '--cwd', cwd,
766
+ '--profile-key', paths.profileKey,
767
+ '--server-instance-id', paths.serverInstanceId,
768
+ '--server-pid', String(serverPid),
769
+ '--daemon-id', daemonId,
770
+ '--runtime', paths.profileRuntime,
771
+ '--build-id', paths.buildId,
772
+ ...(paths.agentDir ? ['--agent-dir', paths.agentDir] : []),
773
+ ...(leaseAgentDir ? ['--lease-agent-dir', leaseAgentDir] : []),
774
+ ...(leaseScope ? ['--lease-scope', leaseScope] : []),
775
+ ...(paths.openUrlSocket ? ['--open-url-socket', paths.openUrlSocket] : []),
776
+ // A daemon started without a launcher is the main daemon: it must
777
+ // stay out of the folders sandbox daemons own.
778
+ ...(launch ? [] : ['--sandboxed-folders-file', join(paths.piDataDir, 'sandboxed-folders.json')]),
779
+ ];
780
+ let childEnv = buildSessionDaemonChildEnv({
781
+ env,
782
+ electronVersion: processLike.versions?.electron,
783
+ });
784
+ try {
785
+ // A sandbox launcher wraps the unchanged daemon command. Its stop
786
+ // signals only the launcher process recorded below, never the pid in
787
+ // the state sidecar.
788
+ if (launch) ({ command, args, env: childEnv } = await launch({ command, args, env: childEnv, cwd, paths }));
789
+ } catch (error) {
790
+ if (logFd !== null) {
791
+ try { closeSync(logFd); } catch { /* nothing was spawned */ }
792
+ }
793
+ throw new PiSessionDaemonUnavailableError(typeof error?.code === 'string' ? error.code : 'SANDBOX_LAUNCH_FAILED');
794
+ }
553
795
  try {
554
- child = spawn(processLike.execPath, [
555
- DAEMON_ENTRYPOINT,
556
- '--endpoint', paths.endpoint,
557
- '--credential-file', paths.credentialFile,
558
- '--state-file', paths.stateFile,
559
- '--cwd', cwd,
560
- '--profile-key', paths.profileKey,
561
- '--server-instance-id', paths.serverInstanceId,
562
- '--server-pid', String(serverPid),
563
- '--daemon-id', daemonId,
564
- '--runtime', paths.profileRuntime,
565
- '--build-id', paths.buildId,
566
- ...(paths.agentDir ? ['--agent-dir', paths.agentDir] : []),
567
- ...(paths.openUrlSocket ? ['--open-url-socket', paths.openUrlSocket] : []),
568
- ], {
796
+ child = spawn(command, args, {
569
797
  cwd,
570
798
  detached: platform !== 'win32',
571
799
  stdio: logFd === null ? 'ignore' : ['ignore', logFd, logFd],
572
800
  windowsHide: true,
573
- env: buildSessionDaemonChildEnv({
574
- env,
575
- electronVersion: processLike.versions?.electron,
576
- }),
801
+ env: childEnv,
577
802
  });
578
803
  } catch {
579
804
  throw new PiSessionDaemonUnavailableError('DAEMON_SPAWN_FAILED');
@@ -588,6 +813,29 @@ export const createPiSessionDaemonSupervisor = ({
588
813
  });
589
814
  }
590
815
  child?.unref?.();
816
+ if (launch && Number.isInteger(child?.pid) && child.pid > 1) {
817
+ // Record the launcher before waiting for readiness, so a daemon that
818
+ // never becomes ready can still be found and stopped. A launcher
819
+ // whose identity cannot be read (already gone, or no way to check on
820
+ // this platform) gets no record, and stop signals nothing.
821
+ const identity = await readProcessIdentity(child.pid);
822
+ if (identity) {
823
+ try {
824
+ await writeLauncherRecord({
825
+ pid: child.pid,
826
+ identity,
827
+ profileKey: paths.profileKey,
828
+ serverInstanceId: paths.serverInstanceId,
829
+ recordedAt: new Date().toISOString(),
830
+ });
831
+ } catch {
832
+ // Without its record the daemon could never be stopped by
833
+ // signal, so it does not get to run.
834
+ try { processLike.kill(child.pid, 'SIGTERM'); } catch { /* already gone */ }
835
+ throw new PiSessionDaemonUnavailableError('DAEMON_LAUNCHER_RECORD_FAILED');
836
+ }
837
+ }
838
+ }
591
839
 
592
840
  // Loading Pi settings, providers, and a larger local model catalog can
593
841
  // legitimately exceed the short lock/stop operation budget.
@@ -665,10 +913,18 @@ export const createPiSessionDaemonSupervisor = ({
665
913
  return ready;
666
914
  };
667
915
 
668
- const requestDaemon = async (command, payload) => {
916
+ // `options.timeoutMs` overrides the IPC client's default for slow
917
+ // commands such as package installs.
918
+ const requestDaemon = async (command, payload, options = {}) => {
669
919
  try {
670
920
  const { credential } = await ensureReadyAndNotify();
671
- return await request({ endpoint: paths.endpoint, credential, command, payload });
921
+ return await request({
922
+ endpoint: paths.endpoint,
923
+ credential,
924
+ command,
925
+ payload,
926
+ ...(Number.isFinite(options?.timeoutMs) && options.timeoutMs > 0 ? { timeoutMs: options.timeoutMs } : {}),
927
+ });
672
928
  } catch (error) {
673
929
  throw new PiSessionDaemonUnavailableError(
674
930
  error instanceof SessionDaemonClientError && error.code !== 'DAEMON_CONNECTION_REFUSED'
@@ -713,11 +969,38 @@ export const createPiSessionDaemonSupervisor = ({
713
969
  }
714
970
  };
715
971
 
972
+ // Stop a launcher daemon this server has a record for. Ownership comes from
973
+ // the server-owned record, which a claim rewrites, not from the state
974
+ // sidecar. The authenticated shutdown is still asked for first, but the
975
+ // credential, sidecar and health answer all sit where the sandbox can
976
+ // write, so a missing, forged or refused answer cannot keep the server
977
+ // from stopping the launcher it started.
978
+ const stopRecordedLauncherDaemon = async (record) => {
979
+ if (record.serverInstanceId !== paths.serverInstanceId) {
980
+ throw new PiSessionDaemonUnavailableError('DAEMON_OWNERSHIP_MISMATCH');
981
+ }
982
+ let state = null;
983
+ try {
984
+ const credential = await readCredential();
985
+ ({ state } = await probe(credential));
986
+ await requestShutdownOverIpc(state, credential);
987
+ } catch (error) {
988
+ if (!(error instanceof PiSessionDaemonUnavailableError)) throw error;
989
+ }
990
+ await finishLauncherDaemonStop(state ?? await readState() ?? await readFailureState());
991
+ };
992
+
716
993
  const stop = async () => {
717
994
  intentionallyStopped = true;
718
995
  const pendingStart = startPromise;
719
996
  if (pendingStart) await pendingStart.catch(() => {});
720
997
  return withOperationLock(async () => {
998
+ const launcherRecord = await readLauncherRecord();
999
+ if (launcherRecord) {
1000
+ await stopRecordedLauncherDaemon(launcherRecord);
1001
+ intentionallyStopped = true;
1002
+ return { state: 'stopped' };
1003
+ }
721
1004
  let credential;
722
1005
  try {
723
1006
  credential = await readCredential();
@@ -748,3 +1031,71 @@ export const createPiSessionDaemonSupervisor = ({
748
1031
 
749
1032
  return { paths, start, health, request: requestDaemon, subscribe, stop };
750
1033
  };
1034
+
1035
+ /**
1036
+ * Supervise a project's sandbox daemon: the same daemon command, started
1037
+ * through a sandbox launcher. The profile key carries the launch identity,
1038
+ * so a changed launcher version, policy, grant set or network never reuses
1039
+ * an older daemon. Fails closed with SANDBOX_UNAVAILABLE and the launcher's
1040
+ * reason code when the launcher cannot sandbox on this host.
1041
+ */
1042
+ export const createSandboxedPiSessionDaemonSupervisor = async ({
1043
+ launcher,
1044
+ sandbox,
1045
+ env = process.env,
1046
+ port,
1047
+ runtime,
1048
+ version,
1049
+ ...options
1050
+ }) => {
1051
+ const probe = await launcher.probe();
1052
+ if (!probe.available) {
1053
+ const error = new PiSessionDaemonUnavailableError('SANDBOX_UNAVAILABLE');
1054
+ error.reason = probe.code;
1055
+ throw error;
1056
+ }
1057
+ const identity = launcher.identity({ grants: sandbox.grants, network: sandbox.network });
1058
+ const base = resolveServerProfile({ env, port, runtime, version });
1059
+ const profile = { ...base, profileKey: `${base.profileKey}-sbx-${sandbox.projectKey}-${identity}` };
1060
+ // The full key is about 40 characters. Without XDG_RUNTIME_DIR (macOS) the
1061
+ // runtime folder sits under the data folder, where a socket path built
1062
+ // from it would pass macOS's 103-byte limit, so it is named by a hash.
1063
+ const runtimeName = `sbx-${createHash('sha256').update(profile.profileKey).digest('hex').slice(0, 16)}`;
1064
+ const ownEnv = sandboxDaemonEnv(env);
1065
+ const supervisor = createPiSessionDaemonSupervisor({
1066
+ daemonReadyTimeoutMs: SANDBOX_DAEMON_READY_TIMEOUT_MS,
1067
+ ...options,
1068
+ env: { ...ownEnv, PICHAMBER_PI_AGENT_DIR: sandbox.agentDir },
1069
+ cwd: sandbox.cwd,
1070
+ profile,
1071
+ runtimeName,
1072
+ // The daemon reads Pi config through the shadow folder but keys session
1073
+ // leases on the real one, like the main daemon.
1074
+ leaseAgentDir: sandbox.leaseAgentDir,
1075
+ // Its own lease folder, the only one it is granted.
1076
+ leaseScope: sandbox.leaseScope,
1077
+ launch: ({ command, args, env: childEnv, cwd, paths }) => launcher.prepare({
1078
+ argv: [command, ...args],
1079
+ env: childEnv,
1080
+ cwd,
1081
+ tmpDir: sandbox.tmpDir,
1082
+ cacheDir: sandbox.cacheDir,
1083
+ network: sandbox.network,
1084
+ // The daemon's own profile and runtime folders derive from the
1085
+ // identity, so they are added here rather than hashed into it.
1086
+ grants: [
1087
+ ...sandbox.grants,
1088
+ { kind: 'readWrite', path: paths.profileDir },
1089
+ { kind: 'readFile', path: paths.credentialFile },
1090
+ { kind: 'unixSocketBind', dir: paths.runtimeDir },
1091
+ ],
1092
+ }),
1093
+ });
1094
+ // A long data folder or XDG_RUNTIME_DIR can still push the socket path
1095
+ // past the Unix socket address limit, and the daemon's listen would then
1096
+ // fail with EINVAL, so refuse it up front with a stable code.
1097
+ if (Buffer.byteLength(supervisor.paths.endpoint) > maxUnixSocketPathBytes(options.platform ?? process.platform)) {
1098
+ throw new PiSessionDaemonUnavailableError('SANDBOX_ENDPOINT_TOO_LONG');
1099
+ }
1100
+ return { ...supervisor, sandbox: { launcher: launcher.id, version: probe.version, identity } };
1101
+ };
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
 
7
7
  import { getPiSessionDirectory } from './session-jsonl.js';
8
+ import { requestSessionDaemon } from './ipc-client.js';
8
9
  import { createPiSessionDaemonSupervisor } from './supervisor.js';
9
10
 
10
11
  const waitForExit = async (pid) => {
@@ -113,6 +114,33 @@ describe('Pi session daemon supervisor', () => {
113
114
  });
114
115
  }, 20_000);
115
116
 
117
+ it('passes a per-request timeout to the IPC client and keeps the default otherwise', async () => {
118
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-timeout-'));
119
+ const cwd = join(root, 'project');
120
+ const agentDir = join(root, 'agent');
121
+ await Promise.all([mkdir(cwd), mkdir(agentDir)]);
122
+ const env = {
123
+ ...process.env,
124
+ PI_OFFLINE: '1',
125
+ PICHAMBER_DATA_DIR: join(root, 'data'),
126
+ PICHAMBER_PI_AGENT_DIR: agentDir,
127
+ XDG_RUNTIME_DIR: join(root, 'runtime'),
128
+ };
129
+ const seen = [];
130
+ supervisor = createPiSessionDaemonSupervisor({
131
+ env,
132
+ cwd,
133
+ request: (options) => {
134
+ if (options.command === 'sessions.list') seen.push(options.timeoutMs);
135
+ return requestSessionDaemon(options);
136
+ },
137
+ });
138
+ await supervisor.start();
139
+ await supervisor.request('sessions.list', undefined, { timeoutMs: 600_000 });
140
+ await supervisor.request('sessions.list');
141
+ expect(seen).toEqual([600_000, undefined]);
142
+ }, 20_000);
143
+
116
144
  it('replaces a healthy daemon that predates entrypoint identity', async () => {
117
145
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-entrypoint-'));
118
146
  const cwd = join(root, 'project');