@pi-chamber/web 1.0.8-rc.1 → 1.0.8-rc.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 (146) hide show
  1. package/dist/assets/{AgentsSurface-BmHImX8m.js → AgentsSurface-wsW9VCRp.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-C71fGOm2.js → ChoicesArtifact-EwCf4Yxu.js} +1 -1
  3. package/dist/assets/{DiagramView-BZQxoiZu.js → DiagramView-BX6N99cQ.js} +1 -1
  4. package/dist/assets/{DiffView-C70pbgk-.js → DiffView-CI0eSnPP.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-Cu8c3gBV.js → FileSaveConflictDialog-GLj2W7VE.js} +1 -1
  6. package/dist/assets/{FilesView-nFJYEdRw.js → FilesView-CI0tfZQL.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-Jvv_tgbl.js → GitHubDetailScaffold-B85tZ9m7.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-BXD2ODRi.js → GitHubLinkPicker-Y6AuNiGl.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BWI706F0.js → GitHubListPrimitives-BJHBud6i.js} +1 -1
  10. package/dist/assets/{GitView-MIDG5RYW.js → GitView-DueE69kW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-uNlozeu0.js → IssuesSurface-Cg-xkdIu.js} +3 -3
  12. package/dist/assets/{JsonTreeView-CSLsTriz.js → JsonTreeView-Cvg6lc40.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cs-7BfWi.js → MarkdownRendererImpl-DExPx-QM.js} +1 -1
  14. package/dist/assets/{PatchDiff-axbsnbTJ.js → PatchDiff-_c3HZ34I.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-lwn6w_5w.js → PierreDiffViewer-CZnaqO-_.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-o_AXDjbO.js → PullRequestsSurface-C9AYPiwo.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-C4CMlcbv.js → SessionSwitcherContent-DOpnN-8S.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-DCBVuCoo.js → SessionSwitcherDropdown-CmHMPZ69.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-DyeIrsro.js → SessionUnreadDot-CZCQ4t1J.js} +1 -1
  20. package/dist/assets/SettingsView-D5PO5M3z.js +11 -0
  21. package/dist/assets/{SettingsWindow-Cb4st5y5.js → SettingsWindow-DXV5UOE8.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-BzeMEoFP.js → SubagentsArtifact-CO1ZiI1x.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BP2mOWdV.js → ToolOutputDialog-GOwNLj-y.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-D49XBR9b.js → ToolPartDiffPreview-BoaiZji6.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-CLgDONEQ.js → VirtualizedFileDiff-Chq1X8nw.js} +1 -1
  26. package/dist/assets/VisualFrame-u7aRcX7O.js +22 -0
  27. package/dist/assets/VisualsArtifact-D9vPjihW.js +1 -0
  28. package/dist/assets/{collapsible-BeyKtQGB.js → collapsible-BjpDEohv.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmO6H8u6.js → computeVirtualFileMetrics-DmPCxbok.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-DOK251YW.js → contextFileOpenGuard-CukNcUeY.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CnzR7kxA.js → fileTreeStatus-CDyfNPYO.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-4kPg2t6j.js → gitStatusPredicates-uI7Y7L5k.js} +1 -1
  33. package/dist/assets/{githubLink-QvaLfNNT.js → githubLink-B9Mxac4R.js} +1 -1
  34. package/dist/assets/{index-DMX9wT1Z.js → index-BWq2ibCw.js} +1 -1
  35. package/dist/assets/index-BxKPJ9uG.js +11 -0
  36. package/dist/assets/index-C5JgjS20.css +1 -0
  37. package/dist/assets/{main-BirYxac2.js → main-CWfC-9xT.js} +4 -4
  38. package/dist/assets/{main-BW9J3Y72.js → main-ckQ0ciIN.js} +2 -2
  39. package/dist/assets/{markdownCore-CxmcPur8.js → markdownCore-p2q2Kxwo.js} +1 -1
  40. package/dist/assets/{miniChat-BRB11eEs.js → miniChat-x2TrwRYA.js} +2 -2
  41. package/dist/assets/{mobile-DJZYYCuB.js → mobile-B0x2G8h1.js} +2 -2
  42. package/dist/assets/{nativeFileSave-B6QpoPRn.js → nativeFileSave-D542OJlG.js} +1 -1
  43. package/dist/assets/{pi-session-focus-preference-PWoh3LNA.js → pi-session-focus-preference-Q_RZUCnt.js} +1 -1
  44. package/dist/assets/{renderDiffWithHighlighter-C48T6YFJ.js → renderDiffWithHighlighter-CSFGSknx.js} +1 -1
  45. package/dist/assets/{renderElectronMiniChatApp-N-BQdJl0.js → renderElectronMiniChatApp-CFIdesZT.js} +2 -2
  46. package/dist/assets/{renderFileWithHighlighter-8Kt2MyTN.js → renderFileWithHighlighter-C5JE0mRX.js} +1 -1
  47. package/dist/assets/renderMobileApp-B1ybjcGM.js +11 -0
  48. package/dist/assets/runtimeEndpointReset-DyZSKCYM.js +66 -0
  49. package/dist/assets/{runtimeSurface-kIEoYsPP.js → runtimeSurface-BR_dhe7_.js} +1 -1
  50. package/dist/assets/{selection-BTEdLRVK.js → selection-CfOpW4rA.js} +1 -1
  51. package/dist/assets/useAppFontEffects-COMvkffC.js +226 -0
  52. package/dist/assets/{useGitHubRemoteSearch-DIBHNu8r.js → useGitHubRemoteSearch-M1AE2YuX.js} +1 -1
  53. package/dist/assets/{useSwitcherItems-DfLbfX37.js → useSwitcherItems-D0i2BYYP.js} +1 -1
  54. package/dist/assets/{web-components-C_DsTJis.js → web-components-wOQkOurQ.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 +8 -5
  62. package/plugins/visuals/package.json +1 -1
  63. package/server/index.js +90 -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 +90 -3
  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/server/lib/wallpaper/DOCUMENTATION.md +25 -0
  136. package/server/lib/wallpaper/routes.js +63 -0
  137. package/server/lib/wallpaper/routes.test.js +109 -0
  138. package/server/lib/wallpaper/store.js +87 -0
  139. package/dist/assets/SettingsView-BHBpt2Um.js +0 -7
  140. package/dist/assets/VisualFrame-CJrAvWSo.js +0 -22
  141. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +0 -1
  142. package/dist/assets/index-B2v0_mez.js +0 -11
  143. package/dist/assets/index-D3F4JrPN.css +0 -1
  144. package/dist/assets/renderMobileApp-B7cT7m5b.js +0 -11
  145. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +0 -62
  146. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +0 -225
@@ -0,0 +1,444 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { chmod, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import { createNonoLauncher, NONO_PROFILE_FILE } from '../sandbox/nono-launcher.js';
9
+ import { prepareProjectSandbox } from '../sandbox/project-sandbox.js';
10
+ import { getPiSessionDirectory } from './session-jsonl.js';
11
+ import { createPiSessionDaemonSupervisor, createSandboxedPiSessionDaemonSupervisor } from './supervisor.js';
12
+
13
+ const DAEMON_ENTRYPOINT = fileURLToPath(new URL('./daemon-process.js', import.meta.url));
14
+
15
+ const writeFakeNono = async (dir, { setupOutput = ' * Landlock V6', setupCode = 0 } = {}) => {
16
+ const file = join(dir, 'nono');
17
+ await writeFile(file, [
18
+ '#!/bin/sh',
19
+ 'if [ "$1" = "--version" ]; then echo "nono 0.82.0"; exit 0; fi',
20
+ `if [ "$1" = "setup" ]; then echo "${setupOutput}"; exit ${setupCode}; fi`,
21
+ 'exit 64',
22
+ '',
23
+ ].join('\n'));
24
+ await chmod(file, 0o755);
25
+ return file;
26
+ };
27
+
28
+ const refused = async () => {
29
+ const error = new Error('refused');
30
+ error.code = 'DAEMON_CONNECTION_REFUSED';
31
+ throw error;
32
+ };
33
+
34
+ const fakeProcess = {
35
+ execPath: '/opt/node/bin/node',
36
+ pid: process.pid,
37
+ versions: { node: '24.0.0' },
38
+ kill() {
39
+ const error = new Error('ESRCH');
40
+ error.code = 'ESRCH';
41
+ throw error;
42
+ },
43
+ };
44
+
45
+ const setup = async () => {
46
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-sandbox-supervisor-'));
47
+ const dataDir = join(root, 'data');
48
+ const agentDir = join(root, 'home', '.pi', 'agent');
49
+ const project = join(root, 'code', 'projA');
50
+ const projectId = 'a'.repeat(40);
51
+ const worktree = join(dataDir, 'worktree', projectId, 'feature');
52
+ const shared = join(root, 'shared-docs');
53
+ const scratch = join(root, 'scratch');
54
+ await Promise.all([
55
+ mkdir(join(agentDir, 'extensions'), { recursive: true }),
56
+ mkdir(project, { recursive: true }),
57
+ mkdir(worktree, { recursive: true }),
58
+ mkdir(shared, { recursive: true }),
59
+ mkdir(scratch, { recursive: true }),
60
+ ]);
61
+ await writeFile(join(agentDir, 'settings.json'), '{}');
62
+ await writeFile(join(agentDir, 'auth.json'), '{}');
63
+ const nono = await writeFakeNono(root);
64
+ // Short on purpose: the daemon socket path must fit a Unix socket address.
65
+ const runtime = await mkdtemp('/tmp/pcx-');
66
+ const env = {
67
+ PATH: process.env.PATH,
68
+ PICHAMBER_DATA_DIR: dataDir,
69
+ PICHAMBER_PI_AGENT_DIR: agentDir,
70
+ XDG_RUNTIME_DIR: runtime,
71
+ };
72
+ const sandboxOptions = {
73
+ dataDir,
74
+ agentDir,
75
+ projectRoot: project,
76
+ projectId,
77
+ worktreeDirs: [worktree],
78
+ serverPort: 3000,
79
+ readRoots: ['/opt/node', '/opt/pichamber'],
80
+ extraFolders: [{ path: shared, access: 'read' }, { path: scratch, access: 'readWrite' }],
81
+ allowHosts: ['api.anthropic.com'],
82
+ allowLocalPorts: [8080],
83
+ };
84
+ return { root, runtime, dataDir, agentDir, project, projectId, worktree, shared, scratch, nono, env, sandboxOptions };
85
+ };
86
+
87
+ const startCapturing = async ({ env, nono, sandbox, launcher }) => {
88
+ const spawns = [];
89
+ const supervisor = await createSandboxedPiSessionDaemonSupervisor({
90
+ env,
91
+ port: 3000,
92
+ launcher: launcher ?? createNonoLauncher({ command: nono, platform: 'linux', readProcVersion: async () => '' }),
93
+ sandbox,
94
+ processLike: fakeProcess,
95
+ spawn: (command, args, options) => {
96
+ spawns.push({ command, args, options });
97
+ return { pid: 1, unref() {} };
98
+ },
99
+ wait: async () => {},
100
+ startupTimeoutMs: 50,
101
+ daemonReadyTimeoutMs: 50,
102
+ request: refused,
103
+ });
104
+ await expect(supervisor.start()).rejects.toMatchObject({ code: 'DAEMON_START_TIMEOUT' });
105
+ return { supervisor, spawns };
106
+ };
107
+
108
+ describe('sandboxed Pi session daemon supervisor', () => {
109
+ it('launches the unchanged daemon command inside nono run with the project grants, network and profile', async () => {
110
+ const ctx = await setup();
111
+ const sandbox = await prepareProjectSandbox(ctx.sandboxOptions);
112
+ const { supervisor, spawns } = await startCapturing({ env: ctx.env, nono: ctx.nono, sandbox });
113
+
114
+ expect(spawns).toHaveLength(1);
115
+ const [{ command, args, options }] = spawns;
116
+ const { paths } = supervisor;
117
+ const shadow = join(ctx.dataDir, 'pi', 'sandbox', sandbox.projectKey, 'agent');
118
+ const tmp = join(ctx.dataDir, 'pi', 'sandbox', sandbox.projectKey, 'tmp');
119
+ const cache = join(ctx.dataDir, 'pi', 'sandbox', sandbox.projectKey, 'cache');
120
+
121
+ expect(paths.profileKey).toMatch(new RegExp(`^web-p3000-sbx-${sandbox.projectKey}-[0-9a-f]{12}$`));
122
+ expect(paths.profileDir).toBe(join(ctx.dataDir, 'pi', 'daemons', paths.profileKey));
123
+ // Named by a hash of the long sandbox key, so the socket path stays short.
124
+ expect(paths.runtimeDir).toMatch(new RegExp(`^${ctx.runtime}/pichamber/pi-daemons/sbx-[0-9a-f]{16}$`));
125
+ expect(command).toBe(ctx.nono);
126
+ expect(args).toEqual([
127
+ 'run', '-s', '--profile', NONO_PROFILE_FILE, '--no-rollback', '--no-audit', '--no-diagnostics',
128
+ ...[
129
+ '/opt/node',
130
+ '/opt/pichamber',
131
+ join(ctx.agentDir, 'extensions'),
132
+ // The links to the session folders, kept where the sandbox cannot
133
+ // write (see the shadow folder tests below).
134
+ join(ctx.dataDir, 'pi', 'sandbox', sandbox.projectKey, 'sessions'),
135
+ ctx.shared,
136
+ ].sort().flatMap((path) => ['--read', path]),
137
+ // The credential, in the server's own launcher folder: readable, not
138
+ // replaceable.
139
+ '--read-file', join(ctx.dataDir, 'pi', 'launchers', paths.profileKey, 'session-daemon.key'),
140
+ '--read-file', join(ctx.agentDir, 'auth.json'),
141
+ '--read-file', join(ctx.agentDir, 'settings.json'),
142
+ ...[
143
+ ctx.project,
144
+ join(ctx.agentDir, '.pichamber', 'locks', 'sandbox-sessions', sandbox.projectKey),
145
+ getPiSessionDirectory({ cwd: ctx.project, agentDir: ctx.agentDir }),
146
+ getPiSessionDirectory({ cwd: ctx.worktree, agentDir: ctx.agentDir }),
147
+ join(ctx.dataDir, 'pi', 'daemons', paths.profileKey),
148
+ shadow,
149
+ tmp,
150
+ cache,
151
+ join(ctx.dataDir, 'worktree', ctx.projectId),
152
+ ctx.scratch,
153
+ ].sort().flatMap((path) => ['--allow', path]),
154
+ '--allow-unix-socket-dir-bind', paths.runtimeDir,
155
+ '--allow-domain', 'api.anthropic.com',
156
+ '--allow-connect-port', '8080',
157
+ '--',
158
+ '/opt/node/bin/node', DAEMON_ENTRYPOINT,
159
+ '--endpoint', join(paths.runtimeDir, 'daemon.sock'),
160
+ '--credential-file', paths.credentialFile,
161
+ '--state-file', paths.stateFile,
162
+ '--cwd', ctx.project,
163
+ '--profile-key', paths.profileKey,
164
+ '--server-instance-id', paths.serverInstanceId,
165
+ '--server-pid', String(process.pid),
166
+ '--daemon-id', expect.stringMatching(/^[0-9a-f-]{36}$/),
167
+ '--runtime', 'web',
168
+ '--build-id', 'unknown',
169
+ '--agent-dir', shadow,
170
+ // Leases key on the real agent folder, so this daemon and the main
171
+ // daemon exclude each other on the same session.
172
+ '--lease-agent-dir', ctx.agentDir,
173
+ // In its own lease folder, the only one it is granted.
174
+ '--lease-scope', sandbox.projectKey,
175
+ '--open-url-socket', join(paths.runtimeDir, 'open-url.sock'),
176
+ ]);
177
+ expect(options).toMatchObject({ cwd: ctx.project, detached: true });
178
+ expect(options.env).toMatchObject({
179
+ NONO_NO_SAVE_PROMPT: '1',
180
+ NONO_NO_UPDATE_CHECK: '1',
181
+ TMPDIR: tmp,
182
+ // Tool caches go to the sandbox's own folder, not the user's.
183
+ XDG_CACHE_HOME: cache,
184
+ npm_config_cache: join(cache, 'npm'),
185
+ PATH: process.env.PATH,
186
+ });
187
+ expect(options.env.ELECTRON_RUN_AS_NODE).toBeUndefined();
188
+
189
+ const profile = JSON.parse(await readFile(NONO_PROFILE_FILE, 'utf8'));
190
+ expect(profile).toMatchObject({
191
+ extends: 'default',
192
+ groups: { exclude: ['system_write_linux'] },
193
+ security: { signal_mode: 'isolated', capability_elevation: false },
194
+ linux: { af_unix_mediation: 'pathname' },
195
+ workdir: { access: 'none' },
196
+ });
197
+ });
198
+
199
+ it('keeps the server\'s own settings and the daemon credential out of the sandbox\'s reach', async () => {
200
+ const ctx = await setup();
201
+ const sandbox = await prepareProjectSandbox(ctx.sandboxOptions);
202
+ const env = {
203
+ ...ctx.env,
204
+ PICHAMBER_UI_PASSWORD: 'ui-password',
205
+ PICHAMBER_JWT_SECRET: 'jwt-secret',
206
+ PICHAMBER_TUNNEL_TOKEN: 'tunnel-token',
207
+ PICHAMBER_PI_SESSION_DAEMON_ENDPOINT: '/tmp/main-daemon.sock',
208
+ PICHAMBER_ADDED_LATER: 'not listed, so not passed',
209
+ };
210
+ const { supervisor, spawns } = await startCapturing({ env, nono: ctx.nono, sandbox });
211
+
212
+ const names = Object.keys(spawns[0].options.env).filter((name) => name.startsWith('PICHAMBER_'));
213
+ expect(names.sort()).toEqual(['PICHAMBER_DATA_DIR', 'PICHAMBER_PI_AGENT_DIR']);
214
+ expect(spawns[0].options.env.PICHAMBER_PI_AGENT_DIR).toBe(sandbox.agentDir);
215
+
216
+ // The credential the server sends on every request sits where no
217
+ // sandbox grant can write, so sandboxed code cannot point it elsewhere.
218
+ const { paths } = supervisor;
219
+ expect(paths.credentialFile).toBe(join(ctx.dataDir, 'pi', 'launchers', paths.profileKey, 'session-daemon.key'));
220
+ expect(sandbox.grants.some((grant) => grant.kind === 'readWrite' && paths.credentialFile.startsWith(`${grant.path}/`))).toBe(false);
221
+ expect((await readFile(paths.credentialFile, 'utf8')).trim()).toMatch(/^[0-9a-f]{64}$/);
222
+ });
223
+
224
+ it('never follows or waits on what a sandbox daemon puts in place of its state file', async () => {
225
+ const ctx = await setup();
226
+ const sandbox = await prepareProjectSandbox(ctx.sandboxOptions);
227
+ const { supervisor } = await startCapturing({ env: ctx.env, nono: ctx.nono, sandbox });
228
+ const { paths } = supervisor;
229
+ const forged = join(ctx.root, 'forged-state.json');
230
+ await writeFile(forged, JSON.stringify({
231
+ protocolVersion: 1, pid: 4242, endpoint: paths.endpoint, profileKey: paths.profileKey, startedAt: new Date().toISOString(),
232
+ }));
233
+
234
+ // A symlink is not read: the daemon counts as not running.
235
+ await rm(paths.stateFile, { force: true });
236
+ await symlink(forged, paths.stateFile);
237
+ await expect(supervisor.request('sessions.list', {})).rejects.toMatchObject({ code: expect.stringMatching(/^DAEMON_/) });
238
+
239
+ // A FIFO would block a plain read until something wrote to it.
240
+ await rm(paths.stateFile, { force: true });
241
+ execFileSync('mkfifo', [paths.stateFile]);
242
+ await expect(supervisor.request('sessions.list', {})).rejects.toMatchObject({ code: expect.stringMatching(/^DAEMON_/) });
243
+ });
244
+
245
+ it('builds a shadow agent folder that links to the real Pi config, resources and session folders', async () => {
246
+ const ctx = await setup();
247
+ const sandbox = await prepareProjectSandbox(ctx.sandboxOptions);
248
+ const shadow = sandbox.agentDir;
249
+
250
+ await expect(readlink(join(shadow, 'settings.json'))).resolves.toBe(join(ctx.agentDir, 'settings.json'));
251
+ await expect(readlink(join(shadow, 'auth.json'))).resolves.toBe(join(ctx.agentDir, 'auth.json'));
252
+ await expect(readlink(join(shadow, 'extensions'))).resolves.toBe(join(ctx.agentDir, 'extensions'));
253
+ await expect(readlink(join(shadow, 'models.json'))).rejects.toMatchObject({ code: 'ENOENT' });
254
+ await expect(readlink(getPiSessionDirectory({ cwd: ctx.project, agentDir: shadow })))
255
+ .resolves.toBe(getPiSessionDirectory({ cwd: ctx.project, agentDir: ctx.agentDir }));
256
+ await expect(readlink(getPiSessionDirectory({ cwd: ctx.worktree, agentDir: shadow })))
257
+ .resolves.toBe(getPiSessionDirectory({ cwd: ctx.worktree, agentDir: ctx.agentDir }));
258
+ // The shadow's `sessions` is itself a link, to a folder beside the shadow
259
+ // that the sandbox can only read; the session links are made there.
260
+ await expect(readlink(join(shadow, 'sessions')))
261
+ .resolves.toBe(join(ctx.dataDir, 'pi', 'sandbox', sandbox.projectKey, 'sessions'));
262
+
263
+ // Preparing again (for example after a new worktree) keeps the folder valid.
264
+ await expect(prepareProjectSandbox(ctx.sandboxOptions)).resolves.toMatchObject({ agentDir: shadow });
265
+ });
266
+
267
+ it('creates nothing outside the shadow when sandboxed code swapped its folders for links', async () => {
268
+ const ctx = await setup();
269
+ const first = await prepareProjectSandbox(ctx.sandboxOptions);
270
+ const shadow = first.agentDir;
271
+ const extensions = join(ctx.agentDir, 'extensions');
272
+
273
+ // What code inside the sandbox can do: the shadow is writable, so any
274
+ // folder in it can become a link to Pi's real extensions folder.
275
+ await rm(join(shadow, 'sessions'), { recursive: true, force: true });
276
+ await symlink(extensions, join(shadow, 'sessions'));
277
+ await rm(join(shadow, '.pichamber'), { recursive: true, force: true });
278
+ await symlink(extensions, join(shadow, '.pichamber'));
279
+
280
+ await prepareProjectSandbox(ctx.sandboxOptions);
281
+
282
+ // The unsandboxed main daemon loads every folder in here.
283
+ await expect(readdir(extensions)).resolves.toEqual([]);
284
+ await expect(readlink(getPiSessionDirectory({ cwd: ctx.project, agentDir: shadow })))
285
+ .resolves.toBe(getPiSessionDirectory({ cwd: ctx.project, agentDir: ctx.agentDir }));
286
+ });
287
+
288
+ it('reuses the profile key for the same launch and uses a new one when the identity changes', async () => {
289
+ const ctx = await setup();
290
+ const first = await startCapturing({ env: ctx.env, nono: ctx.nono, sandbox: await prepareProjectSandbox(ctx.sandboxOptions) });
291
+ const same = await startCapturing({ env: ctx.env, nono: ctx.nono, sandbox: await prepareProjectSandbox(ctx.sandboxOptions) });
292
+ const otherHosts = await startCapturing({
293
+ env: ctx.env,
294
+ nono: ctx.nono,
295
+ sandbox: await prepareProjectSandbox({ ...ctx.sandboxOptions, allowHosts: ['api.openai.com'] }),
296
+ });
297
+ const otherFolders = await startCapturing({
298
+ env: ctx.env,
299
+ nono: ctx.nono,
300
+ sandbox: await prepareProjectSandbox({ ...ctx.sandboxOptions, extraFolders: [] }),
301
+ });
302
+
303
+ expect(same.supervisor.paths.profileKey).toBe(first.supervisor.paths.profileKey);
304
+ expect(otherHosts.supervisor.paths.profileKey).not.toBe(first.supervisor.paths.profileKey);
305
+ expect(otherFolders.supervisor.paths.profileKey).not.toBe(first.supervisor.paths.profileKey);
306
+ const prefix = first.supervisor.paths.profileKey.replace(/-[0-9a-f]{12}$/, '');
307
+ expect(otherHosts.supervisor.paths.profileKey.startsWith(prefix)).toBe(true);
308
+ });
309
+
310
+ it('refuses ports 80, 443 and the server port, and extra folders over PiChamber data or Pi config', async () => {
311
+ const ctx = await setup();
312
+ for (const port of [80, 443, 3000]) {
313
+ await expect(prepareProjectSandbox({ ...ctx.sandboxOptions, allowLocalPorts: [port] }))
314
+ .rejects.toMatchObject({ code: 'SANDBOX_PORT_REFUSED' });
315
+ }
316
+ for (const path of [ctx.root, ctx.dataDir, join(ctx.dataDir, 'pi'), ctx.agentDir, join(ctx.agentDir, 'extensions')]) {
317
+ await expect(prepareProjectSandbox({ ...ctx.sandboxOptions, extraFolders: [{ path, access: 'read' }] }))
318
+ .rejects.toMatchObject({ code: 'SANDBOX_GRANT_REFUSED' });
319
+ }
320
+ });
321
+
322
+ it('refuses an extra folder that reaches PiChamber data or Pi config through a symlink', async () => {
323
+ const ctx = await setup();
324
+ const toData = join(ctx.root, 'code', 'projA', 'shared');
325
+ const toAgent = join(ctx.root, 'alias-agent');
326
+ await symlink(ctx.dataDir, toData);
327
+ await symlink(join(ctx.agentDir, 'extensions'), toAgent);
328
+ for (const path of [toData, toAgent]) {
329
+ await expect(prepareProjectSandbox({ ...ctx.sandboxOptions, extraFolders: [{ path, access: 'read' }] }))
330
+ .rejects.toMatchObject({ code: 'SANDBOX_GRANT_REFUSED' });
331
+ }
332
+ });
333
+
334
+ it('refuses a project folder that holds or sits inside PiChamber data or Pi config, except a PiChamber worktree', async () => {
335
+ const ctx = await setup();
336
+ const alias = join(ctx.root, 'alias-root');
337
+ await symlink(ctx.root, alias);
338
+ for (const projectRoot of [ctx.root, alias, join(ctx.root, 'home'), ctx.dataDir, join(ctx.dataDir, 'pi'), join(ctx.agentDir, 'extensions')]) {
339
+ await expect(prepareProjectSandbox({ ...ctx.sandboxOptions, projectRoot }))
340
+ .rejects.toMatchObject({ code: 'SANDBOX_GRANT_REFUSED' });
341
+ }
342
+ await expect(prepareProjectSandbox({ ...ctx.sandboxOptions, projectRoot: ctx.worktree })).resolves.toMatchObject({ cwd: ctx.worktree });
343
+ });
344
+
345
+ it('fails closed with the launcher reason and never spawns when nono cannot sandbox', async () => {
346
+ const ctx = await setup();
347
+ const nono = await writeFakeNono(join(ctx.root, 'code'), {
348
+ setupOutput: 'nono: Setup error: Landlock is not available: Sandbox initialization failed',
349
+ setupCode: 1,
350
+ });
351
+ let spawned = false;
352
+ await expect(createSandboxedPiSessionDaemonSupervisor({
353
+ env: ctx.env,
354
+ port: 3000,
355
+ launcher: createNonoLauncher({ command: nono, platform: 'linux', readProcVersion: async () => '' }),
356
+ sandbox: await prepareProjectSandbox(ctx.sandboxOptions),
357
+ processLike: fakeProcess,
358
+ spawn: () => {
359
+ spawned = true;
360
+ return { pid: 1, unref() {} };
361
+ },
362
+ })).rejects.toMatchObject({ code: 'SANDBOX_UNAVAILABLE', reason: 'NO_LANDLOCK' });
363
+ expect(spawned).toBe(false);
364
+ });
365
+
366
+ it('refuses a sandbox whose daemon socket path would not fit a Unix socket address', async () => {
367
+ const ctx = await setup();
368
+ let spawned = false;
369
+ await expect(createSandboxedPiSessionDaemonSupervisor({
370
+ env: { ...ctx.env, XDG_RUNTIME_DIR: join(ctx.root, 'r'.repeat(60)) },
371
+ port: 3000,
372
+ launcher: createNonoLauncher({ command: ctx.nono, platform: 'linux', readProcVersion: async () => '' }),
373
+ sandbox: await prepareProjectSandbox(ctx.sandboxOptions),
374
+ processLike: fakeProcess,
375
+ spawn: () => {
376
+ spawned = true;
377
+ return { pid: 1, unref() {} };
378
+ },
379
+ })).rejects.toMatchObject({ code: 'SANDBOX_ENDPOINT_TOO_LONG' });
380
+ expect(spawned).toBe(false);
381
+ });
382
+
383
+ it('keeps a macOS sandbox socket under the data folder within the 103-byte limit', async () => {
384
+ const ctx = await setup();
385
+ // A typical macOS data folder, with no XDG_RUNTIME_DIR to shorten it.
386
+ const dataDir = '/Users/a-long-user-name/.config/pichamber';
387
+ const { XDG_RUNTIME_DIR: _runtime, ...env } = ctx.env;
388
+ const supervisor = await createSandboxedPiSessionDaemonSupervisor({
389
+ env,
390
+ dataDir,
391
+ platform: 'darwin',
392
+ port: 3000,
393
+ launcher: createNonoLauncher({ command: ctx.nono, platform: 'linux', readProcVersion: async () => '' }),
394
+ sandbox: await prepareProjectSandbox(ctx.sandboxOptions),
395
+ processLike: fakeProcess,
396
+ });
397
+ expect(supervisor.paths.endpoint).toMatch(new RegExp(`^${dataDir}/runtime/pi-daemons/sbx-[0-9a-f]{16}/daemon\\.sock$`));
398
+ expect(Buffer.byteLength(supervisor.paths.endpoint)).toBeLessThanOrEqual(103);
399
+ });
400
+
401
+ it('refuses a macOS socket path past 103 bytes that Linux would still accept', async () => {
402
+ const ctx = await setup();
403
+ const { XDG_RUNTIME_DIR: _runtime, ...env } = ctx.env;
404
+ // 104 bytes once the runtime folder and socket name are added.
405
+ const dataDir = `/${'d'.repeat(104 - '/runtime/pi-daemons/sbx-0123456789abcdef/daemon.sock'.length - 1)}`;
406
+ const options = {
407
+ env,
408
+ dataDir,
409
+ port: 3000,
410
+ launcher: createNonoLauncher({ command: ctx.nono, platform: 'linux', readProcVersion: async () => '' }),
411
+ sandbox: await prepareProjectSandbox(ctx.sandboxOptions),
412
+ processLike: fakeProcess,
413
+ };
414
+ const linux = await createSandboxedPiSessionDaemonSupervisor({ ...options, platform: 'linux' });
415
+ expect(Buffer.byteLength(linux.paths.endpoint)).toBe(104);
416
+ await expect(createSandboxedPiSessionDaemonSupervisor({ ...options, platform: 'darwin' }))
417
+ .rejects.toMatchObject({ code: 'SANDBOX_ENDPOINT_TOO_LONG' });
418
+ });
419
+
420
+ it('keeps the unsandboxed launch as the plain daemon command', async () => {
421
+ const ctx = await setup();
422
+ const spawns = [];
423
+ const supervisor = createPiSessionDaemonSupervisor({
424
+ env: ctx.env,
425
+ cwd: ctx.project,
426
+ port: 3000,
427
+ processLike: fakeProcess,
428
+ spawn: (command, args, options) => {
429
+ spawns.push({ command, args, options });
430
+ return { pid: 1, unref() {} };
431
+ },
432
+ wait: async () => {},
433
+ startupTimeoutMs: 50,
434
+ daemonReadyTimeoutMs: 50,
435
+ request: refused,
436
+ });
437
+ await expect(supervisor.start()).rejects.toMatchObject({ code: 'DAEMON_START_TIMEOUT' });
438
+ expect(supervisor.paths.profileKey).toBe('web-p3000');
439
+ expect(spawns[0].command).toBe('/opt/node/bin/node');
440
+ expect(spawns[0].args.slice(0, 3)).toEqual([DAEMON_ENTRYPOINT, '--endpoint', supervisor.paths.endpoint]);
441
+ expect(spawns[0].args).toContain(ctx.agentDir);
442
+ expect(spawns[0].options.env).toEqual(ctx.env);
443
+ });
444
+ });