@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
@@ -1140,6 +1140,145 @@ describe('Pi session daemon spike', () => {
1140
1140
  await client.close();
1141
1141
  });
1142
1142
 
1143
+ it('lists the hosts of signed-in providers for a sandbox allowlist, without paths or credentials', async () => {
1144
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-hosts-'));
1145
+ const endpoint = testDaemonEndpoint(root);
1146
+ const session = new FakeSession('pi-session-1');
1147
+ const signedIn = new Set(['anthropic', 'local']);
1148
+ session.modelRuntime.getModels = () => [
1149
+ { provider: 'anthropic', id: 'a', baseUrl: 'https://api.anthropic.com' },
1150
+ { provider: 'anthropic', id: 'b', baseUrl: 'https://API.anthropic.com/v1' },
1151
+ { provider: 'openai', id: 'c', baseUrl: 'https://api.openai.com/v1' },
1152
+ { provider: 'local', id: 'd', baseUrl: 'http://127.0.0.1:8080/v1' },
1153
+ { provider: 'local', id: 'e', baseUrl: 'not a url' },
1154
+ { provider: 'local', id: 'f' },
1155
+ ];
1156
+ session.modelRuntime.getProviderAuthStatus = (providerId) => ({ configured: signedIn.has(providerId) });
1157
+ daemon = createSessionDaemon({
1158
+ endpoint,
1159
+ credential,
1160
+ cwd: root,
1161
+ createRuntime: async () => new FakeRuntime({ cwd: root, session }),
1162
+ listSessions: async () => [],
1163
+ });
1164
+ await daemon.start();
1165
+ const client = connectClient(endpoint);
1166
+ await client.authenticate();
1167
+ // Loopback hosts are reached by port, never by host name, so they are
1168
+ // left out; the user allows a local server's port per project.
1169
+ await expect(client.request('providers.hosts')).resolves.toMatchObject({ result: { hosts: ['api.anthropic.com'] } });
1170
+ await client.close();
1171
+ });
1172
+
1173
+ it('answers provider questions for sandboxes without starting a runtime in a sandboxed folder', async () => {
1174
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-hosts-exclude-'));
1175
+ const agentDir = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-hosts-agent-'));
1176
+ const endpoint = testDaemonEndpoint(root);
1177
+ const started = [];
1178
+ daemon = createSessionDaemon({
1179
+ endpoint,
1180
+ credential,
1181
+ // The daemon's own folder is a sandboxed project.
1182
+ cwd: root,
1183
+ agentDir,
1184
+ createRuntime: async (options) => {
1185
+ started.push(options.cwd);
1186
+ const session = new FakeSession(`pi-session-${started.length}`);
1187
+ session.modelRuntime.getModels = () => [{ provider: 'anthropic', id: 'a', baseUrl: 'https://api.anthropic.com' }];
1188
+ session.modelRuntime.getProviderAuthStatus = () => ({ configured: true });
1189
+ session.modelRuntime.getProviders = () => [];
1190
+ return new FakeRuntime({ cwd: options.cwd, session });
1191
+ },
1192
+ listSessions: async () => [],
1193
+ });
1194
+ await daemon.start();
1195
+ const client = connectClient(endpoint);
1196
+ await client.authenticate();
1197
+ await expect(client.request('providers.hosts', { exclude: [root] })).resolves.toMatchObject({ result: { hosts: ['api.anthropic.com'] } });
1198
+ await expect(client.request('providers.oauth.refresh', { minValidityMs: 0, exclude: [root] })).resolves.toMatchObject({ result: { checked: 0, failed: [] } });
1199
+ expect(started).toEqual([agentDir]);
1200
+ await client.close();
1201
+ });
1202
+
1203
+ it('never starts a runtime in a folder a sandbox daemon owns', async () => {
1204
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-sandboxed-folder-'));
1205
+ const other = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-sandboxed-other-'));
1206
+ const agentDir = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-sandboxed-agent-'));
1207
+ const endpoint = testDaemonEndpoint(other);
1208
+ const started = [];
1209
+ let sandboxed = false;
1210
+ daemon = createSessionDaemon({
1211
+ endpoint,
1212
+ credential,
1213
+ cwd: root,
1214
+ agentDir,
1215
+ isSandboxedDirectory: (directory) => sandboxed && (directory === root || directory.startsWith(`${root}/`)),
1216
+ createRuntime: async (options) => {
1217
+ started.push(options.cwd);
1218
+ const session = new FakeSession(`pi-session-${started.length}`);
1219
+ session.modelRuntime.getModels = () => [];
1220
+ session.modelRuntime.getProviders = () => [];
1221
+ return new FakeRuntime({ cwd: options.cwd, session });
1222
+ },
1223
+ listSessions: async () => [],
1224
+ });
1225
+ await daemon.start();
1226
+ const client = connectClient(endpoint);
1227
+ await client.authenticate();
1228
+ // The user selected the project, then turned its sandbox on.
1229
+ await client.request('projects.select', { directory: root });
1230
+ sandboxed = true;
1231
+ // A request without a folder is answered from outside the project.
1232
+ await client.request('providers.list');
1233
+ await client.request('extensions.list', { directory: root });
1234
+ await client.request('providers.refresh', { directory: root });
1235
+ expect(started).toEqual([agentDir]);
1236
+ // A session in the project is the sandbox daemon's to run.
1237
+ // (The test client drops its connection on an error frame.)
1238
+ await expect(client.request('sessions.create', { cwd: root })).rejects.toThrow('Daemon connection closed');
1239
+ expect(started).toEqual([agentDir]);
1240
+ // Other folders are unaffected, and so is the project once it is off.
1241
+ const next = connectClient(endpoint);
1242
+ await next.authenticate();
1243
+ await next.request('sessions.create', { cwd: other });
1244
+ sandboxed = false;
1245
+ await next.request('sessions.create', { cwd: root });
1246
+ expect(started).toEqual([agentDir, other, root]);
1247
+ await next.close();
1248
+ });
1249
+
1250
+ it('refreshes OAuth tokens near expiry for sandbox daemons, reporting only provider ids that failed', async () => {
1251
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-oauth-'));
1252
+ const endpoint = testDaemonEndpoint(root);
1253
+ const session = new FakeSession('pi-session-1');
1254
+ const refreshed = [];
1255
+ session.modelRuntime.getProviders = () => [{ id: 'anthropic' }, { id: 'openai-codex' }, { id: 'openai' }];
1256
+ session.modelRuntime.isUsingOAuth = (providerId) => providerId !== 'openai';
1257
+ session.modelRuntime.getAuth = async (providerId, overrides) => {
1258
+ refreshed.push([providerId, overrides]);
1259
+ if (providerId === 'openai-codex') throw new Error('OAuth refresh failed for openai-codex: secret-token');
1260
+ return { auth: { apiKey: 'secret' } };
1261
+ };
1262
+ daemon = createSessionDaemon({
1263
+ endpoint,
1264
+ credential,
1265
+ cwd: root,
1266
+ createRuntime: async () => new FakeRuntime({ cwd: root, session }),
1267
+ listSessions: async () => [],
1268
+ });
1269
+ await daemon.start();
1270
+ const client = connectClient(endpoint);
1271
+ await client.authenticate();
1272
+ const response = await client.request('providers.oauth.refresh', { minValidityMs: 1_800_000 });
1273
+ expect(response.result).toEqual({ checked: 2, failed: ['openai-codex'] });
1274
+ expect(JSON.stringify(response)).not.toContain('secret');
1275
+ expect(refreshed).toEqual([
1276
+ ['anthropic', { minOAuthValidityMs: 1_800_000 }],
1277
+ ['openai-codex', { minOAuthValidityMs: 1_800_000 }],
1278
+ ]);
1279
+ await client.close();
1280
+ });
1281
+
1143
1282
  it('handles every session command with path-selected identities and preserves busy-session configuration on rejection', async () => {
1144
1283
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-'));
1145
1284
  const endpoint = testDaemonEndpoint(root);
@@ -1474,6 +1613,32 @@ describe('Pi session daemon spike', () => {
1474
1613
  })).rejects.toMatchObject({ code: 'DAEMON_RESPONSE_TOO_LARGE' });
1475
1614
  }, 30_000);
1476
1615
 
1616
+ it('does not auto-trust a folder whose trust was reset when its sandbox was turned off', async () => {
1617
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-trust-ask-'));
1618
+ const asked = join(root, 'was-sandboxed');
1619
+ const other = join(root, 'other');
1620
+ const agentDir = join(root, 'agent');
1621
+ const endpoint = testDaemonEndpoint(root);
1622
+ // Project config that needs trust (a sandboxed agent could have written it).
1623
+ await Promise.all([mkdir(join(asked, '.pi'), { recursive: true }), mkdir(join(other, '.pi'), { recursive: true }), mkdir(agentDir)]);
1624
+ await Promise.all([writeFile(join(asked, '.pi', 'settings.json'), '{}'), writeFile(join(other, '.pi', 'settings.json'), '{}')]);
1625
+ daemon = createSessionDaemon({
1626
+ endpoint, credential, cwd: root, agentDir,
1627
+ isTrustAskDirectory: (directory) => directory === asked,
1628
+ createRuntime: async () => ({ session: new FakeSession(), async dispose() {} }),
1629
+ });
1630
+ await daemon.start();
1631
+ const client = connectClient(endpoint);
1632
+ await client.authenticate();
1633
+ await expect(client.request('settings.set', { scope: 'project', directory: asked, trust: null }))
1634
+ .resolves.toMatchObject({ result: { project: { trusted: false, requiresTrust: true } } });
1635
+ await expect(client.request('settings.get', { directory: asked })).resolves.toMatchObject({ result: { project: { trusted: false, requiresTrust: true } } });
1636
+ // Other known projects keep PiChamber's automatic trust.
1637
+ await expect(client.request('settings.set', { scope: 'project', directory: other, trust: null }))
1638
+ .resolves.toMatchObject({ result: { project: { trusted: true } } });
1639
+ await client.close();
1640
+ });
1641
+
1477
1642
  it('keeps Pi global/project defaults and trust decisions authoritative', async () => {
1478
1643
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-settings-'));
1479
1644
  const cwd = join(root, 'project');
@@ -3808,4 +3973,66 @@ describe('Pi session daemon spike', () => {
3808
3973
  await daemonB.stop();
3809
3974
  }
3810
3975
  });
3976
+ it('keys leases on the real agent folder, so a sandbox daemon on a shadow folder and the main daemon exclude each other', async () => {
3977
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-lease-shadow-'));
3978
+ const endpointA = join(root, 'a.sock');
3979
+ const endpointB = join(root, 'b.sock');
3980
+ const agentDir = join(root, 'agent');
3981
+ const shadowDir = join(root, 'shadow');
3982
+ await mkdir(agentDir, { recursive: true });
3983
+ await mkdir(shadowDir, { recursive: true });
3984
+ const file1 = join(root, 'session-1.jsonl');
3985
+ await writeFile(file1, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
3986
+ const session1 = new FakeSession('session-1', file1);
3987
+ const createRuntime = async () => new FakeRuntime({ cwd: root, session: session1 });
3988
+ const listSessions = async () => [
3989
+ { path: file1, id: 'session-1', cwd: root, created: new Date(), modified: new Date(), messageCount: 0 },
3990
+ ];
3991
+ daemon = createSessionDaemon({
3992
+ endpoint: endpointA,
3993
+ credential,
3994
+ cwd: root,
3995
+ agentDir,
3996
+ profileKey: 'web-p3000',
3997
+ serverInstanceId: 'server-a',
3998
+ daemonId: 'daemon-a',
3999
+ createRuntime,
4000
+ listSessions,
4001
+ });
4002
+ const sandboxDaemon = createSessionDaemonImpl({
4003
+ endpoint: endpointB,
4004
+ credential,
4005
+ cwd: root,
4006
+ agentDir: shadowDir,
4007
+ leaseAgentDir: agentDir,
4008
+ profileKey: 'web-p3000-sbx-abc-def',
4009
+ serverInstanceId: 'server-a',
4010
+ daemonId: 'daemon-b',
4011
+ createRuntime,
4012
+ listSessions,
4013
+ });
4014
+ let clientA;
4015
+ let clientB;
4016
+ try {
4017
+ await daemon.start();
4018
+ await sandboxDaemon.start();
4019
+ clientA = connectClient(endpointA);
4020
+ await clientA.authenticate();
4021
+ clientB = connectClient(endpointB);
4022
+ await clientB.authenticate();
4023
+ await expect(clientA.request('sessions.open', { sessionId: 'session-1' })).resolves.toMatchObject({
4024
+ result: { session: { id: 'session-1' } },
4025
+ });
4026
+ clientB.socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId: 'contended', command: 'sessions.open', payload: { sessionId: 'session-1' } })}\n`);
4027
+ await expect(clientB.next((message) => message.kind === 'error'))
4028
+ .resolves.toMatchObject({ error: { code: 'SESSION_IN_USE' } });
4029
+ } finally {
4030
+ for (const client of [clientA, clientB]) {
4031
+ try {
4032
+ if (client && !client.socket.destroyed) await Promise.race([client.close(), new Promise((r) => setTimeout(r, 1_000))]);
4033
+ } catch {}
4034
+ }
4035
+ await sandboxDaemon.stop();
4036
+ }
4037
+ });
3811
4038
  });
@@ -1,5 +1,5 @@
1
1
  import { afterEach, describe, expect, it } from 'vitest';
2
- import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { createConnection } from 'node:net';
5
5
  import { tmpdir } from 'node:os';
@@ -7,6 +7,7 @@ import { join } from 'node:path';
7
7
  import { StringDecoder } from 'node:string_decoder';
8
8
 
9
9
  import { createSessionDaemon as createSessionDaemonImpl } from './session-daemon.js';
10
+ import { resolveSessionLeaseFile } from './session-lease.js';
10
11
 
11
12
  const credential = 'a-private-daemon-credential';
12
13
 
@@ -427,10 +428,14 @@ describe('Pi session daemon idle residency', () => {
427
428
  expect(runtimes.filter((runtime) => !runtime.disposed)).toHaveLength(sessionCount);
428
429
  expect(createdRuntimes).toHaveLength(sessionCount);
429
430
 
431
+ // Health counts resident sessions, so a project daemon with none can be
432
+ // stopped by its server.
433
+ await expect(client.request('runtime.health')).resolves.toMatchObject({ result: { residentSessions: sessionCount } });
430
434
  await waitFor(() => runtimes.every((runtime) => runtime.disposed), {
431
435
  timeoutMs: 8_000,
432
436
  message: 'browse-only sessions were not disposed',
433
437
  });
438
+ await expect(client.request('runtime.health')).resolves.toMatchObject({ result: { residentSessions: 0 } });
434
439
  for (const sessionFile of sessionFiles) {
435
440
  await expect(stat(sessionFile.path)).resolves.toMatchObject({ isFile: expect.any(Function) });
436
441
  }
@@ -746,4 +751,96 @@ describe('Pi session daemon idle residency', () => {
746
751
  expect(disposeCalls).toBe(1);
747
752
  expect(targetRuntime.disposed).toBe(true);
748
753
  });
754
+
755
+ it('releases a folder: idle sessions are disposed now, a busy one at its next idle edge', async () => {
756
+ const root = await createTemporaryRoot('pichamber-pi-daemon-release-');
757
+ const endpoint = testDaemonEndpoint(root);
758
+ const other = await createTemporaryRoot('pichamber-pi-daemon-release-other-');
759
+ const files = [
760
+ { id: 'idle-one', path: join(root, 'idle.jsonl'), cwd: root },
761
+ { id: 'busy-one', path: join(root, 'busy.jsonl'), cwd: root },
762
+ { id: 'elsewhere', path: join(other, 'elsewhere.jsonl'), cwd: other },
763
+ ];
764
+ for (const file of files) await writeFile(file.path, createSessionHeaderLine(file.id, file.cwd));
765
+ const runtimes = new Map();
766
+ daemon = createSessionDaemon({
767
+ endpoint,
768
+ credential,
769
+ cwd: root,
770
+ idleTimeoutMs: 60_000,
771
+ listSessions: async ({ cwd: listCwd }) => files.filter((file) => file.cwd === listCwd),
772
+ createRuntime: async (daemonOptions) => {
773
+ const file = files.find((candidate) => candidate.path === daemonOptions.sessionFile);
774
+ const runtime = new FakeRuntime({ cwd: file.cwd, session: new FakeSession(file.id, file.path) });
775
+ runtimes.set(file.id, runtime);
776
+ return runtime;
777
+ },
778
+ });
779
+ await daemon.start();
780
+ const client = await connectAuthenticatedClient(endpoint);
781
+ for (const file of files) await openSession(client, file.id, file.cwd);
782
+ const busy = runtimes.get('busy-one').session;
783
+ busy.isStreaming = true;
784
+ busy.emit({ type: 'agent_start' });
785
+
786
+ const health = await client.request('runtime.health');
787
+ expect(health.result.capabilities).toContain('sessions.release');
788
+ const first = await client.request('sessions.release', { directories: [root] });
789
+ expect(first.result).toEqual({
790
+ released: [{ sessionId: 'idle-one', directory: root }],
791
+ pending: [{ sessionId: 'busy-one', directory: root }],
792
+ streamEpoch: health.result.streamEpoch,
793
+ });
794
+ expect(runtimes.get('idle-one').disposed).toBe(true);
795
+ expect(runtimes.get('busy-one').disposed).toBe(false);
796
+ expect(runtimes.get('elsewhere').disposed).toBe(false);
797
+
798
+ // The turn ends: disposed at once, not after the idle timeout.
799
+ busy.isStreaming = false;
800
+ busy.emit({ type: 'agent_settled' });
801
+ await waitFor(() => runtimes.get('busy-one').disposed === true, { timeoutMs: 2_000, message: 'busy session was not released at its idle edge' });
802
+ const second = await client.request('sessions.release', { directories: [root] });
803
+ expect(second.result).toMatchObject({ released: [], pending: [] });
804
+ expect(runtimes.get('elsewhere').disposed).toBe(false);
805
+
806
+ const errorFrame = client.waitForMessage((message) => message.kind === 'error');
807
+ client.socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId: 'bad-release', command: 'sessions.release', payload: { directories: ['relative'] } })}\n`);
808
+ await expect(errorFrame).resolves.toMatchObject({ error: { code: 'INVALID_ARGUMENT' } });
809
+ });
810
+ it('keeps a released session pending while its lease could not be released', async () => {
811
+ const root = await createTemporaryRoot('pichamber-pi-daemon-release-lease-');
812
+ const endpoint = testDaemonEndpoint(root);
813
+ const file = { id: 'leased-one', path: join(root, 'leased.jsonl'), cwd: root };
814
+ await writeFile(file.path, createSessionHeaderLine(file.id, file.cwd));
815
+ daemon = createSessionDaemon({
816
+ endpoint,
817
+ credential,
818
+ cwd: root,
819
+ idleTimeoutMs: 60_000,
820
+ profileKey: 'profile-a',
821
+ daemonId: 'daemon-a',
822
+ serverInstanceId: 'server-a',
823
+ listSessions: async () => [file],
824
+ createRuntime: async () => new FakeRuntime({ cwd: root, session: new FakeSession(file.id, file.path) }),
825
+ });
826
+ await daemon.start();
827
+ const client = await connectAuthenticatedClient(endpoint);
828
+ await openSession(client, file.id, root);
829
+ const lease = resolveSessionLeaseFile({ agentDir: root, cwd: root, sessionId: file.id }).file;
830
+ const held = await readFile(lease, 'utf8');
831
+
832
+ // The lease cannot be read, so it cannot be released: the session is
833
+ // gone from this daemon but no other daemon may take it yet.
834
+ await writeFile(lease, '{');
835
+ const first = await client.request('sessions.release', { directories: [root] });
836
+ expect(first.result).toMatchObject({ released: [], pending: [{ sessionId: file.id, directory: root }] });
837
+
838
+ await writeFile(lease, held);
839
+ const second = await client.request('sessions.release', { directories: [root] });
840
+ expect(second.result).toMatchObject({ released: [{ sessionId: file.id, directory: root }], pending: [] });
841
+ await expect(stat(lease)).rejects.toMatchObject({ code: 'ENOENT' });
842
+ const third = await client.request('sessions.release', { directories: [root] });
843
+ expect(third.result).toMatchObject({ released: [], pending: [] });
844
+ });
749
845
  });
846
+
@@ -1,4 +1,4 @@
1
- import { createReadStream } from 'node:fs';
1
+ import { constants } from 'node:fs';
2
2
  import { mkdir, open, readdir, stat } from 'node:fs/promises';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
@@ -33,6 +33,22 @@ class SessionJsonlError extends Error {
33
33
  const malformed = () => new SessionJsonlError('MALFORMED_SESSION_JSONL');
34
34
  const unreadable = () => new SessionJsonlError('SESSION_JSONL_UNREADABLE');
35
35
 
36
+ // Session folders of a sandboxed project are writable by code in the sandbox,
37
+ // and the server and main daemon read them. A FIFO planted under a transcript
38
+ // name would hold a thread of Node's file pool for as long as nothing writes
39
+ // to it, so transcripts are opened without blocking and anything that is not
40
+ // a regular file is refused.
41
+ const openTranscript = async (filePath) => {
42
+ const handle = await open(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
43
+ try {
44
+ if (!(await handle.stat()).isFile()) throw unreadable();
45
+ } catch (error) {
46
+ await handle.close().catch(() => {});
47
+ throw error;
48
+ }
49
+ return handle;
50
+ };
51
+
36
52
  const LIST_PREVIEW_CHARS = 500;
37
53
  /** Bound in-directory JSONL listing so a large folder is not one file at a time. */
38
54
  const LIST_FILE_CONCURRENCY = 8;
@@ -107,8 +123,14 @@ export const matchesPiSessionJsonlName = (fileName, sessionId) => (
107
123
  * Read only the session header. Callers that are looking up an id must
108
124
  * not scan the rest of a multi-megabyte transcript.
109
125
  */
110
- async function readPiSessionJsonlHeader(filePath) {
111
- const input = createReadStream(filePath, { encoding: 'utf8' });
126
+ export async function readPiSessionJsonlHeader(filePath) {
127
+ let handle;
128
+ try {
129
+ handle = await openTranscript(filePath);
130
+ } catch {
131
+ throw unreadable();
132
+ }
133
+ const input = handle.createReadStream({ encoding: 'utf8' });
112
134
  const lines = createInterface({ input, crlfDelay: Infinity });
113
135
  try {
114
136
  for await (const line of lines) {
@@ -137,17 +159,24 @@ async function readPiSessionJsonlHeader(filePath) {
137
159
  * or `<id>.jsonl`) without listing or fully reading every transcript. A miss
138
160
  * is `null`, not an empty success.
139
161
  */
140
- export async function findPiSessionJsonlById({ sessionId, agentDir, resolvePath = resolve }) {
162
+ /**
163
+ * Every transcript under `agentDir` whose header holds `sessionId`. Session
164
+ * ids are unique, so more than one match means some file was written by
165
+ * something other than Pi; callers that route by transcript choose among
166
+ * them (see the project sandbox manager).
167
+ */
168
+ export async function findPiSessionJsonlsById({ sessionId, agentDir, resolvePath = resolve, limit = Infinity }) {
141
169
  if (typeof sessionId !== 'string' || sessionId.length === 0 || typeof agentDir !== 'string') {
142
- return null;
170
+ return [];
143
171
  }
144
172
  const sessionsRoot = join(resolvePath(agentDir), 'sessions');
145
173
  let dirEntries;
146
174
  try {
147
175
  dirEntries = await readdir(sessionsRoot, { withFileTypes: true });
148
176
  } catch {
149
- return null;
177
+ return [];
150
178
  }
179
+ const matches = [];
151
180
  for (const dirEntry of dirEntries) {
152
181
  if (!dirEntry.isDirectory()) continue;
153
182
  const dirPath = join(sessionsRoot, dirEntry.name);
@@ -164,20 +193,28 @@ export async function findPiSessionJsonlById({ sessionId, agentDir, resolvePath
164
193
  try {
165
194
  const header = await readPiSessionJsonlHeader(fullPath);
166
195
  if (header.id === sessionId) {
167
- return { id: sessionId, path: fullPath, cwd: header.cwd };
196
+ matches.push({ id: sessionId, path: fullPath, cwd: header.cwd });
197
+ if (matches.length >= limit) return matches;
168
198
  }
169
199
  } catch {
170
200
  continue;
171
201
  }
172
202
  }
173
203
  }
174
- return null;
204
+ return matches;
205
+ }
206
+
207
+ export async function findPiSessionJsonlById({ sessionId, agentDir, resolvePath = resolve }) {
208
+ const [found] = await findPiSessionJsonlsById({ sessionId, agentDir, resolvePath, limit: 1 });
209
+ return found ?? null;
175
210
  }
176
211
 
177
212
  export async function validatePiSessionJsonlFile(filePath) {
178
213
  let sawHeader = false;
214
+ let handle;
179
215
  try {
180
- const input = createReadStream(filePath, { encoding: 'utf8' });
216
+ handle = await openTranscript(filePath);
217
+ const input = handle.createReadStream({ encoding: 'utf8' });
181
218
  const lines = createInterface({ input, crlfDelay: Infinity });
182
219
  for await (const line of lines) {
183
220
  if (!line.trim()) continue;
@@ -196,6 +233,8 @@ export async function validatePiSessionJsonlFile(filePath) {
196
233
  } catch (error) {
197
234
  if (error instanceof SessionJsonlError) throw error;
198
235
  throw unreadable();
236
+ } finally {
237
+ await handle?.close().catch(() => {});
199
238
  }
200
239
  if (!sawHeader) throw malformed();
201
240
  }
@@ -293,7 +332,7 @@ const applyCompleteLines = (state, buffer, end) => {
293
332
  async function scanPiSessionJsonlRange(filePath, state, size, stats) {
294
333
  let handle;
295
334
  try {
296
- handle = await open(filePath, 'r');
335
+ handle = await openTranscript(filePath);
297
336
  let position = state.offset;
298
337
  let carry = [];
299
338
  let carryBytes = 0;
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { appendFile, mkdir, mkdtemp, rename, writeFile } from 'node:fs/promises';
2
3
  import { tmpdir } from 'node:os';
3
4
  import { join } from 'node:path';
@@ -12,6 +13,7 @@ import {
12
13
  listPiSessionJsonlDirectory,
13
14
  matchesPiSessionJsonlName,
14
15
  normalizeWindowsShellPath,
16
+ readPiSessionJsonlHeader,
15
17
  validatePiSessionJsonlDirectory,
16
18
  validatePiSessionJsonlFile,
17
19
  } from './session-jsonl.js';
@@ -273,4 +275,13 @@ describe('Pi session JSONL validation', () => {
273
275
  expect(cache.entries.size).toBe(0);
274
276
  });
275
277
  });
278
+
279
+ // A sandboxed project's session folder is writable from inside its sandbox.
280
+ it.skipIf(process.platform === 'win32')('refuses a FIFO under a transcript name instead of waiting on it', async () => {
281
+ const dir = await mkdtemp(join(tmpdir(), 'pichamber-jsonl-fifo-'));
282
+ const file = join(dir, 'x_abc.jsonl');
283
+ execFileSync('mkfifo', [file]);
284
+ await expect(readPiSessionJsonlHeader(file)).rejects.toMatchObject({ code: 'SESSION_JSONL_UNREADABLE' });
285
+ await expect(validatePiSessionJsonlFile(file)).rejects.toMatchObject({ code: 'SESSION_JSONL_UNREADABLE' });
286
+ });
276
287
  });