@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
@@ -2675,8 +2675,8 @@ describe('Pi extension config routes', () => {
2675
2675
  app.use(express.json());
2676
2676
  registerPiRuntimeRoutes(app, {
2677
2677
  getPiSessionDaemonRuntime: () => ({
2678
- request: async (command, payload) => {
2679
- calls.push({ command, payload });
2678
+ request: async (command, payload, options) => {
2679
+ calls.push(options === undefined ? { command, payload } : { command, payload, options });
2680
2680
  return request(command, payload);
2681
2681
  },
2682
2682
  }),
@@ -2782,6 +2782,91 @@ describe('Pi extension config routes', () => {
2782
2782
  ]);
2783
2783
  });
2784
2784
 
2785
+ it('projects package.json fields and drops bad values', async () => {
2786
+ const packages = [
2787
+ { id: PKG, source: 'npm:pi-btw@0.8.1', scope: 'user', kind: 'npm', installed: true, filtered: false, name: '@acme/pi-btw', version: '0.8.1', pichamber: true, pinned: true },
2788
+ { id: ID, source: 'https://github.com/acme/tool', scope: 'user', kind: 'git', installed: true, filtered: false, name: 'Bad Name', version: '1.0.0 && rm', pichamber: 'yes', pinned: true },
2789
+ ];
2790
+ const { api } = await start(async () => daemonList({ packages, extensions: [] }));
2791
+ const body = await (await fetch(`${api}/config`)).json();
2792
+ expect(body.packages).toEqual([
2793
+ { id: PKG, source: 'npm:pi-btw@0.8.1', scope: 'user', kind: 'npm', installed: true, filtered: false, name: '@acme/pi-btw', version: '0.8.1', pichamber: true, pinned: true },
2794
+ { id: ID, source: 'https://github.com/acme/tool', scope: 'user', kind: 'git', installed: true, filtered: false },
2795
+ ]);
2796
+ });
2797
+
2798
+ it('validates install bodies strictly and forwards with a long timeout', async () => {
2799
+ let fail = null;
2800
+ const { calls, api } = await start(async () => {
2801
+ if (fail) {
2802
+ const error = new Error('x');
2803
+ error.code = fail;
2804
+ throw error;
2805
+ }
2806
+ return { ...daemonList(), installedId: PKG };
2807
+ });
2808
+ const post = (body) => fetch(`${api}/packages`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
2809
+ for (const body of [
2810
+ { name: 'pi-btw' },
2811
+ { name: 'pi-btw', scope: 'global' },
2812
+ { name: 'pi-btw', scope: 'project' },
2813
+ { name: 'pi-btw', scope: 'user', extra: 1 },
2814
+ { name: 'npm:pi-btw', scope: 'user' },
2815
+ { name: 'pi-btw@1.0.0', scope: 'user' },
2816
+ { name: '../x', scope: 'user' },
2817
+ { name: 'https://github.com/acme/tool', scope: 'user' },
2818
+ { name: 'Pi-Btw', scope: 'user' },
2819
+ { name: '.hidden', scope: 'user' },
2820
+ { name: 'a'.repeat(215), scope: 'user' },
2821
+ [],
2822
+ ]) {
2823
+ expect((await post(body)).status).toBe(400);
2824
+ }
2825
+ expect(calls).toEqual([]);
2826
+ const installed = await post({ name: '@acme/pi-btw', scope: 'project', directory: '/work' });
2827
+ expect(installed.status).toBe(200);
2828
+ expect((await installed.json()).installedId).toBe(PKG);
2829
+ expect(calls).toEqual([{
2830
+ command: 'extensions.packages.install',
2831
+ payload: { name: '@acme/pi-btw', scope: 'project', directory: '/work' },
2832
+ options: { timeoutMs: 600_000 },
2833
+ }]);
2834
+ for (const [code, status] of [
2835
+ ['PACKAGE_ALREADY_INSTALLED', 409],
2836
+ ['PACKAGE_INSTALL_FAILED', 502],
2837
+ ['PROJECT_UNTRUSTED', 400],
2838
+ ['PI_SETTINGS_INVALID', 400],
2839
+ ]) {
2840
+ fail = code;
2841
+ const response = await post({ name: 'pi-btw', scope: 'user' });
2842
+ expect(response.status).toBe(status);
2843
+ await expect(response.json()).resolves.toEqual({ error: { code } });
2844
+ }
2845
+ });
2846
+
2847
+ it('updates a package by id and maps daemon errors', async () => {
2848
+ let fail = null;
2849
+ const { calls, api } = await start(async () => {
2850
+ if (fail) {
2851
+ const error = new Error('x');
2852
+ error.code = fail;
2853
+ throw error;
2854
+ }
2855
+ return daemonList({ installedId: PKG });
2856
+ });
2857
+ expect((await fetch(`${api}/packages/nope/update`, { method: 'POST' })).status).toBe(400);
2858
+ const updated = await fetch(`${api}/packages/${PKG}/update?directory=${encodeURIComponent('/work')}`, { method: 'POST' });
2859
+ expect(updated.status).toBe(200);
2860
+ expect('installedId' in await updated.json()).toBe(false);
2861
+ expect(calls).toEqual([{ command: 'extensions.packages.update', payload: { id: PKG, directory: '/work' }, options: { timeoutMs: 600_000 } }]);
2862
+ for (const [code, status] of [['PACKAGE_PINNED', 409], ['PACKAGE_UPDATE_FAILED', 502], ['RESOURCE_NOT_FOUND', 400], ['INVALID_ARGUMENT', 400]]) {
2863
+ fail = code;
2864
+ const response = await fetch(`${api}/packages/${PKG}/update`, { method: 'POST' });
2865
+ expect(response.status).toBe(status);
2866
+ await expect(response.json()).resolves.toEqual({ error: { code } });
2867
+ }
2868
+ });
2869
+
2785
2870
  it('removes a package by id and maps daemon errors', async () => {
2786
2871
  let fail = null;
2787
2872
  const { calls, api } = await start(async () => {
@@ -0,0 +1,68 @@
1
+ # Project sandboxes
2
+
3
+ ## Purpose
4
+
5
+ A project can run its sessions in a separate Pi session daemon inside a sandbox (#242, tickets #243-#249). This module owns everything about that choice except the daemon itself: the launcher seam and the nono launcher, PiChamber's nono profile, a project's grants and setting, the manager that starts, routes, drains and stops sandbox daemons, the public sandbox routes, OAuth refresh on a sandbox's behalf, and the trust reset when a project leaves its sandbox. Nothing here runs unless a project is sandboxed (its setting is `nono`, or `default` while the host default is on): with no sandboxed project the server starts no sandbox daemon, probes nothing, and routes every request to the main daemon unchanged.
6
+
7
+ The daemon side (the supervisor launching a daemon through a launcher, launch identity and profile keys, liveness and stop, session leases across the boundary, the merged event stream, and `sessions.readPersisted`) is in `../session-daemon/DOCUMENTATION.md`, "Sandbox launchers".
8
+
9
+ ## Ownership
10
+
11
+ - `launcher.js`: the launcher contract, grant and network validation, and launch identity.
12
+ - `nono-launcher.js`: the nono probe and the `nono run` command. `nono-profile.json`, `nono-profile-wsl2.json`, `nono-profile-macos.json`: PiChamber's static nono policy for each host kind.
13
+ - `project-sandbox.js`: one project's grants, network, shadow Pi agent folder, and private temp folder (`prepareProjectSandbox`).
14
+ - `project-sandbox-setting.js`: the per-project `sandbox` setting and its normalization.
15
+ - `project-sandbox-manager.js`: registers sandbox daemons in the daemon pool and starts them lazily. It also answers the fail-closed and read-only fallbacks, drains sessions between daemons, replaces stale daemons, refreshes OAuth through the main daemon, resets trust when a project is switched off.
16
+ - `sandbox-routes.js`: `/api/pi/sandbox` (status and `recheck`), `/api/pi/sandbox/projects`, `/api/pi/sandbox/defaults`, and `/api/pi/sandbox/profile`.
17
+ - `worktree-ids.js`: the remembered worktree folder id of each sandboxed project.
18
+ - `trust-ask.js`: the server-owned list of folders whose Pi trust must stay "ask".
19
+ - `sandboxed-folders.js`: the server-owned record of the folders sandbox daemons own, which the main daemon reads before it starts a runtime.
20
+
21
+ The composition root (`packages/web/server/index.js`) creates the manager with the nono launcher, and passes the manager to the Pi routes (`../routes.js`). The manager calls `supervisorOptions({ roots })` for each launch with the folders that daemon owns; the composition root uses it to give the daemon a plugin sync hook whose `plugins.configure` payload lists only those folders' project values (`../../plugins/DOCUMENTATION.md`).
22
+
23
+ ## Behaviour and invariants
24
+
25
+ - Contract. A launcher has `id`, `platforms`, `transport: 'local-socket'`, `probe()` (`{ available: true, version, capabilities, limits? }` or `{ available: false, code }`), `identity({ grants, network })`, and `prepare({ argv, env, cwd, grants, network, tmpDir })`. `prepare` returns `{ command, args, env }` that wraps `argv` unchanged. Grants are structured (`read`, `readWrite`, `readFile`, `readWriteFile`, `unixSocketBind`) with absolute paths, never raw user strings. Network is `{ mode: 'proxy', allowHosts, allowLocalPorts }` or `{ mode: 'none' }`. An allowed host is a public name: at least two labels (two after a `*.` wildcard), at most 253 characters and 63 per label, not `localhost`, `*.localhost` or `*.local`, and no last label starting with a digit (any IP literal); anything else is `SANDBOX_INVALID_NETWORK`, because the PiChamber server listens on the same machine. `launcher.js` validates both, de-duplicates grants, and sorts them, so the same request always gives the same command and identity.
26
+ - nono probe (`nono-launcher.js`). The host kind comes first: `darwin` is macOS, and `linux` is WSL2 when `/proc/version` names Microsoft or WSL, otherwise Linux. Any other platform is `UNSUPPORTED_PLATFORM` without running nono. Then: binary missing is `NOT_INSTALLED`, unreadable `--version` output is `VERSION_UNKNOWN`, below 0.82.0 is `TOO_OLD`. On Linux and WSL2, `nono setup --check-only` failing with "Landlock is not available" (or without a Landlock ABI line) is `NO_LANDLOCK`, and on WSL2 an ABI below V4 is `WSL_KERNEL_TOO_OLD` (no TCP rules, so nothing holds the sandbox to nono's proxy; `wsl --update` fixes it). On macOS the check must exit 0 and print "Seatbelt sandbox support verified". Any other failure is `SETUP_CHECK_FAILED`. Success reports the version, `landlock-abi-<n>` or `seatbelt`, and the host's `limits` when it has any. `identity` and `prepare` refuse to run before a successful probe, and use the profile of the probed host kind, so the same request has a different identity on each.
27
+ - Host limits. A limit is a rule the sandbox cannot enforce on this host (`SANDBOX_LIMIT_CODES` in `launcher.js`). WSL2 has `UNIX_SOCKETS`: nono's `af_unix_mediation` needs seccomp user notification, WSL2's init already holds the only listener, and nono refuses to start with the setting, so the WSL2 profile leaves it out. Pathname Unix sockets are then reachable from inside the sandbox, and code there can ask a local service (the systemd user manager, D-Bus, an SSH or GPG agent, Docker) to act outside it. The main daemon's socket still requires its credential, which the sandbox cannot read. WSL2 also has `PROXY_PORT`: Landlock filters TCP by port only, and the seccomp check that holds the proxy's port to the proxy on Linux is missing, so code in the sandbox can connect to any host on that port (checked by hand on a WSL2 6.18 kernel: `1.1.1.1:<proxy port>` was not refused, `1.1.1.1:443` was). A server listening on every port can therefore receive data, whatever the allowed hosts say. Files stay limited, and with no allowed host (`--block-net`) the network is fully blocked. The owner accepts a host's limits in the host default (`acceptedLimits`); until every reported limit is accepted, every sandboxed project is unavailable with `SANDBOX_LIMITS_NOT_ACCEPTED` and no sandbox starts. Withdrawing acceptance retires running sandbox daemons (a drain, so a running turn finishes) and the next command fails closed. Linux and macOS have no limits.
28
+ - nono command. `nono run -s --profile <nono-profile.json> --no-rollback --no-audit --no-diagnostics`, the grant flags (`--read`, `--allow`, `--read-file`, `--allow-file`, `--allow-unix-socket-dir-bind`), the network flags, then `--` and the daemon argv. Environment: the daemon's environment plus `NONO_NO_SAVE_PROMPT=1`, `NONO_NO_UPDATE_CHECK=1`, and `TMPDIR` set to the project's private temp folder. Network: each allowed host is `--allow-domain` (proxy mode). On Linux and WSL2 each local port is `--allow-connect-port`, and with no allowed host and no port, or mode `none`, it is `--block-net`, because nono without a proxy or port rule leaves the network open. Ports 80 and 443 are refused (`SANDBOX_PORT_REFUSED`): on Linux a port grant applies to every host and bypasses the proxy. macOS: nono refuses `--allow-connect-port` (Seatbelt cannot filter TCP by port), so each local port is `--open-port`, which allows that port on localhost only; with no allowed host it adds `--block-net`, which keeps those localhost rules. Seatbelt cannot limit binding or inbound connections by port either, so any port grant on macOS also lets the sandbox listen on any port.
29
+ - Profiles. Each holds only policy, close to nono's Pi profile: runtime groups, `signal_mode: isolated`, and `workdir.access: none`. Unlike nono's Pi profile, none includes a user cache group (`~/.cache`, `~/Library/Caches`) or grants `/dev/pts` (see Caches and Pseudo-terminals). `nono-profile.json` (Linux) excludes `system_write_linux` (it grants all of `/tmp`) and sets `linux.af_unix_mediation: pathname` (without it the sandbox can connect to any Unix socket it can name, including the main daemon's). `nono-profile-wsl2.json` is the same without `af_unix_mediation` (see Host limits). `nono-profile-macos.json` excludes `system_write_macos` (all of `/tmp` and `/var/folders`); Seatbelt starts proxy and blocked modes from `deny network*` and allows only Unix sockets granted by flag. Every path is a per-launch flag. PiChamber never installs the nono Pi pack.
30
+ - Packaged desktop. The server package sits in `app.asar`, which the nono binary cannot read. When a profile path runs through an `.asar` archive, `createNonoLauncher({ stageDir })` copies that profile to `<stageDir>/nono-profile-<content hash>.json` (mode 0600, written through a temp file and renamed) and passes that path; a profile outside an archive is used in place. A failed copy is `SANDBOX_PROFILE_UNREADABLE`. The server passes `stageDir = <dataDir>/pi/sandbox`.
31
+ - Custom profile. The per-project setting (hosts, ports, extra folders) is the intended way to open a sandbox up; the profile is for an owner who needs more, such as another runtime group. `createNonoLauncher({ customProfileFile })` names one file, `<dataDir>/pi/sandbox/nono-profile.custom.json` on the server. While that file exists every launch on this host uses it in place of the built-in profile of the host kind; there is one per machine, and it is a full copy (nono's `extends` takes a profile name, not a file), so it does not follow later changes to the built-in one. No grant covers files directly in `<dataDir>/pi/sandbox/` (projects get `<project key>/` subfolders), and an extra folder overlapping the data folder is refused, so sandboxed code cannot write its own policy. `launcher.profile()` reports `{ hostKind, builtInPath, customPath, custom, path, content, hash, unreadable? }` (the host kind is detected without a probe, so it answers while nono is missing; null on an unsupported platform). `saveProfile(content)` accepts a JSON object up to 64 KB, writes it to a temporary file beside the target (mode 0600), runs `nono profile validate --json` on that file, and renames it over the custom file only when nono reports it valid. A refusal is `NonoProfileError` (`INVALID_SANDBOX_PROFILE`) with nono's messages, the temporary path replaced by "the profile"; without nono installed only the JSON is checked. `resetProfile()` removes the file. The custom file is read as a small regular file and never through a symlink. Its hash (salted, so the same text as the built-in profile is still a different identity) goes into the launch identity. A custom file that is there but unreadable, or one edited on disk into something nono refuses (`prepare` validates each new text once), fails the launch with `SANDBOX_PROFILE_INVALID`: the launcher never falls back to the built-in profile the owner replaced. The manager records the profile hash each daemon started under and treats a different one as stale (the idle check), and a save or reset through the routes retires every running sandbox daemon at once (a drain, so a running turn finishes) and forgets failed starts.
32
+ - Project grants (`prepareProjectSandbox`). Read-write: the project folder, `<dataDir>/worktree/<project id>/`, the private temp folder `<dataDir>/pi/sandbox/<project key>/tmp`, the private cache folder `<dataDir>/pi/sandbox/<project key>/cache`, the shadow agent folder `<dataDir>/pi/sandbox/<project key>/agent`, the real Pi session folder of the project and of each worktree passed in, and the project's own session lease folder (see Session leases). Read: the session links folder `<dataDir>/pi/sandbox/<project key>/sessions` (see Shadow agent folder), the runtime (the real Node install prefix, or the Electron app folder), the PiChamber install and the outer `node_modules` holding the Pi SDK, and the existing Pi resource folders (`extensions`, `prompts`, `themes`, `skills`, `tools`, `bin`). Read single files: the existing `settings.json`, `auth.json`, `models.json`, `trust.json`, `mcp.json`. User extras are folders, read or read-write; one that overlaps the PiChamber data folder or the Pi agent folder is refused (`SANDBOX_GRANT_REFUSED`), checked by both its written path and its real path, so a symlink cannot reach them. The project folder itself is refused the same way when it contains either folder or sits inside one (a worktree under `<dataDir>/worktree` is the exception). Local ports also refuse the server's own port. Never granted: the data folder as a whole, other daemons' profile folders and credentials, other projects' session folders, or the `sessions/` parent.
33
+ - What the server trusts. Code in the sandbox can rewrite everything in the daemon's profile folder (`<dataDir>/pi/daemons/<profile key>/`): the state sidecar and its pid. So the server never signals a pid read from there, and reads the state sidecar only as a small regular file: never through a symlink, and never a FIFO that would hold a file-pool thread. The daemon's credential is not in that folder. The server sends it to the daemon's socket on every request, so a credential file the sandbox could replace with a symlink would have the server read any file of the user's and hand it to sandboxed code. It is `<dataDir>/pi/launchers/<profile key>/session-daemon.key`, and the sandbox gets one read-only file grant for it. The daemon's environment is the server's without the server's own variables: every `PICHAMBER_*` name is dropped except `PICHAMBER_DATA_DIR` and `PICHAMBER_PI_AGENT_DIR` (`sandboxDaemonEnv` in `../session-daemon/supervisor.js`), so the UI password, JWT secret and tunnel token never reach sandboxed code, and a server variable added later stays out unless it is listed there. Transcripts in a sandboxed project's session folders are opened without blocking and refused unless they are regular files (`../session-daemon/session-jsonl.js`). When it starts a sandbox daemon, it records the launcher process it spawned (the pid and, on Linux, its start time from `/proc`; on macOS, its `ps` start time) in `<dataDir>/pi/launchers/<profile key>/launcher.json`. The operation lock for that daemon sits in the same folder. No grant covers `<dataDir>/pi/launchers/`. Stop asks the daemon for an authenticated shutdown, then sends SIGTERM to the recorded launcher only, and only while its identity still matches. nono forwards the SIGTERM to the daemon and exits after it. The record also names the owning server instance; a claim rewrites it. The details are in `../session-daemon/DOCUMENTATION.md`, "Sandbox launchers".
34
+ - Shadow agent folder. Pi takes a lock folder beside `settings.json` and `auth.json` even to read them, and loads no credentials from a read-only agent folder. The sandbox daemon gets `--agent-dir` pointing at the shadow folder, which holds symlinks to the real config files and resource folders, and a `sessions` symlink to the session links folder beside it, which holds one symlink per project or worktree folder to its real session folder. Lock folders land in the shadow; writes to the real config fail. Preparing again repoints links and never deletes a real file or folder found where a link belongs (`SANDBOX_SHADOW_CONFLICT`). Invariant: the server, which runs with the user's access, creates and removes entries only directly in the shadow folder or in folders the sandbox cannot write, and only through calls that do not follow a symlink in the last name. Everything below the shadow is writable from inside, so any folder there may have been swapped for a symlink, and creating something inside it would land wherever that link points (for example a session link in Pi's real `extensions/`, which the unsandboxed main daemon then loads). The shadow folder itself cannot be replaced from inside on Linux: Landlock needs a right on its parent, which is not granted.
35
+ - Setting (`project-sandbox-setting.js`). A project entry's `sandbox` field is `{ mode: 'off' | 'nono', allowHosts, allowLocalPorts, extraFolders: [{ path, access: 'read' | 'readWrite' }] }`, normalized and bounded (64 hosts, 32 ports, 32 folders; ports 80 and 443 and relative folders are refused as `INVALID_SANDBOX_SETTING`). A refusal carries `reason` when one list caused it: `HOSTS`, `PORTS` (not a port number), `REFUSED_PORT` (80 or 443) or `FOLDERS`; a wrong shape, an unknown mode or a list over its bound carries none. It is host-local: it lives in the runtime state file (`../ui-settings-store.js`, `setProjectSandbox`), never in portable settings. A save names the fields it changes (`mergeProjectSandboxSetting`); a field left out keeps its stored value, merged under the settings store lock, so a device still showing Off that adds a host cannot turn off a sandbox another device turned on. A project with no stored setting starts from `default` with empty lists, and one whose stored setting is unreadable from `nono`, which is what it runs as. A client's settings write cannot set, change, or drop it; the store carries the current value over by project id. A malformed stored value counts as sandboxed and unavailable, never as off. `mode: 'default'`, or no `sandbox` field, follows the host default. Known limit: allowed hosts are checked by name only. A public name that resolves to a loopback or private address is accepted and handed to nono's proxy; whether the proxy refuses such an address after it resolves the name was not verified for nono 0.82.0. Hosts are the owner's choice, so this needs the owner to allow a name someone else controls.
36
+ - Host default (`normalizeSandboxDefaults`, `readSandboxDefaults`). The runtime state file's `sandboxDefaults` is `{ mode: 'off' | 'nono', allowHosts, acceptedLimits }` (64 hosts at most; `acceptedLimits` lists known limit codes, see Host limits), set only through `setSandboxDefaults`; like a project's setting, a client's settings write and a legacy portable file cannot set it. Missing means off, so projects with no setting keep running unsandboxed until someone turns the default on. `effectiveProjectSandbox(project, settings)` is the one place that decides: an explicit `off` is off whatever the default says; `nono`, or `default` while the default is on, is sandboxed with `allowHosts` = default hosts + the project's own, and its own ports and folders. An unreadable default sandboxes every project that follows it as unavailable; an unreadable project setting does the same for that project. Changing the default's hosts changes every sandboxed project's setting key, so running daemons are retired into new ones. An update to an unreadable stored default must name a `mode` (400 `INVALID_SANDBOX_SETTING`, reason `MODE`): the mode reported for it is a placeholder (off) while projects that follow it stay closed, and a hosts-only or limits-only update would store that placeholder and run them unsandboxed. The settings page disables the limits checkbox and does not save hosts until the mode is chosen.
37
+ - Manager (`project-sandbox-manager.js`). `reconcile()` reads the projects and registers `sandbox:<project id>` in the pool for each `nono` project, owning the project root (as stored and as its real path) and its worktree root `<dataDir>/worktree/<git project id>` (see Worktree ids). It runs at server start and after each settings write and setting change, and retires the daemons of projects no longer sandboxed (see Switching below). Passes run one at a time, in the order they were asked for: two overlapping passes working from different settings would undo each other's registrations. A pass that removes an entry unregisters its pool key only while that entry's runtime still holds it, and a project turned on again while its old daemon drains takes the next free `sandbox:<project id>:<generation>` key. A registered daemon starts lazily on its first command: probe (cached until `recheck`), `providers.hosts` from the main daemon (hosts of signed-in providers' model base URLs) merged into the project's allowed hosts (a provider host `normalizeNetwork` would refuse, such as a bare or `.local` name, is left out and logged by count), `prepareProjectSandbox`, the per-daemon intake, then the supervisor; concurrent first commands share one start. An idle daemon (`runtime.health` `residentSessions` 0 for 10 minutes) is stopped and restarts on the next command; passive reads (`sessions.list`, `sessions.pendingInput`, `sessions.sendReceipt`) neither start one nor count as activity.
38
+ - Worktree ids (`worktree-ids.js`). PiChamber files a project's worktrees under `<dataDir>/worktree/<id>`, and a sandbox is granted and owns that folder. The id normally comes from `<project>/.git/pichamber` (the repository's root commit), which a sandboxed agent can rewrite or delete, and which two clones of one repository share. So the manager remembers an id per project root the first time it sees the project sandboxed, in `<dataDir>/pi/sandbox/worktree-ids.json` (mode 0600, at most 4096 projects; a full record takes no new project, `SANDBOX_WORKTREE_IDS_FULL`, and forgets none), which no sandbox can write. It remembers the file's id only when the file holds a 40 or 64 character hex id that no other known project's file names and that is not remembered for another root. Otherwise, and for a project with no file yet, it remembers the project's own id, a hash of its path (`ownWorktreeId`). From then on the remembered id decides the worktree folder, across restarts and whatever the file says, and the Git panel files new worktrees under it too (`../../git/service.js`, `ensurePiChamberProjectId`), refusing to create one while the record is unreadable. Two clones of one repository therefore both work: the sandboxed one gets a folder of its own and is never granted the shared one. Worktrees it made in the shared folder before that are not granted. Each reconcile reads the `.git` file of every worktree in folders no sandbox owns (only code outside every sandbox can write there); one that names a sandboxed project is routed to that project and refused with `SANDBOX_WORKTREE_OUTSIDE_FOLDER` (lists and transcripts are still read by the main daemon), so it never runs outside the sandbox. The git service reads the id file only as a regular file of at most 256 bytes, never through a symlink, and replaces it by renaming a new random-named file over it. A remembered id is the only one a sandbox starts on: when the record cannot be read or is full and the server has no id it remembered itself, the project is unavailable with `SANDBOX_WORKTREE_IDS_UNREADABLE`, and the id in the file is used only to keep those worktree folders owned by that (stopped) project instead of the main daemon. The git service also keeps a project nothing is remembered for out of a folder remembered for another project: a clone added after its repository's folder went to a sandboxed project files its new worktrees under its own id. Known limits: a file id is trusted on first use when the project already had one; and a project that was first sandboxed alone keeps its repository's shared folder, so worktrees a later-added clone already had there (made before, under the same id) are inside that sandbox. Session folders: two paths can encode to one Pi session folder (`/a/b` and `/a-b`); a sandboxed project that shares its session folder with another known project is unavailable with `SANDBOX_SESSION_FOLDER_SHARED`, and a running daemon drains.
39
+ - Routing. While any project is sandboxed, every folder a client names is spelled the way the daemon will read it before a daemon is chosen (`routeDirectory`: trimmed, `~` as the home folder, resolved); a spelling that reaches a sandboxed project or worktree through a symlink routes to that project, and a path that is not absolute is refused with 400 `INVALID_ARGUMENT`, since the pool would give it to the main daemon. A persisted session is routed by where its transcript is stored (`directoryForSession`): a transcript in the session folder of a sandboxed project or of one of its worktrees belongs to that project whatever `cwd` its header names, because the sandboxed agent can rewrite the header but cannot move the file out of the folders it was granted. Only a transcript stored elsewhere is routed by its header. Session ids are unique, so two transcripts with one id mean one was planted; a sandbox can write only its own project's session folders, so the copy stored outside every sandbox's session folders (running or draining) is the real one. The manager remembers where each session's transcript was found (at most 4096 sessions), so the search through every session folder runs once per session; later requests read only that file's header, and a file that is gone or holds another session is searched for again.
40
+ - Unapplied settings. A reconcile that fails leaves the pool possibly short of a sandboxed project, so the manager reports `needsReconcile()`. The Pi routes then retry it before each `/api/pi` request and, while it still fails, answer 503 `SANDBOX_UNAVAILABLE` with reason `SANDBOX_SETTINGS_UNREADABLE` instead of using the main daemon. `/api/pi/ui-settings`, `/api/pi/sandbox*` and `/api/pi/events` stay open so the cause can be seen and fixed. This covers a failed reconcile at server start as well as one after a save. The same holds before the first reconcile of a server process: the server listens before it, so `needsReconcile` starts true and the first Pi request waits for a reconcile.
41
+ - Caches. What sits in the user's cache folders is run later by tools outside the sandbox (PiChamber's own Browser panel starts the newest Playwright browser build it finds there; package managers run cached tools), so a sandbox that could write them could get code run unsandboxed. Each project gets its own cache folder instead, and the launcher points tools at it through the daemon's environment: `XDG_CACHE_HOME`, and by name `npm_config_cache`, `YARN_CACHE_FOLDER`, `BUN_INSTALL_CACHE_DIR`, `COREPACK_HOME`, `PIP_CACHE_DIR`, `UV_CACHE_DIR`, `PRE_COMMIT_HOME`, `GOCACHE`, and `PLAYWRIGHT_BROWSERS_PATH` (`cacheEnv` in `nono-launcher.js`). These override anything inherited. A tool that ignores them and writes the user's cache folder is refused. Caches are not shared between projects, so the first install in each sandbox downloads again.
42
+ - Pseudo-terminals. The profiles do not grant `/dev/pts`: a sandbox that can write it can write to the terminals of the user's other shells. Programs that allocate a pseudo-terminal (`tmux`, `script`, `ssh -t`) do not work inside the sandbox. Known limit: nono's base policy on Linux still lets the sandbox open existing `/dev/pts/*` entries for reading, so input typed in another terminal of the same user can be taken by sandboxed code. This comes from nono's `system_read_linux_core` group, not from these profiles.
43
+ - Session leases. A session must not run in two daemons (`../session-daemon/session-lease.js`). Daemons outside a sandbox keep their leases in `<agentDir>/.pichamber/locks/sessions/`, which no sandbox is granted: it names every project's live sessions. Each sandbox daemon is started with `--lease-scope <project key>` and keeps its leases in `<agentDir>/.pichamber/locks/sandbox-sessions/<project key>/`, the only lease folder it is granted; a replacement daemon of the same project, or the same project under another PiChamber data folder, uses the same one. Before a daemon outside a sandbox takes a session it also looks for that session's lease file in every scope folder, so it stays out of a session a sandbox runs. The scope folders are written by sandboxed code and nothing in them is trusted: files are read without following a symlink, without waiting on a FIFO, and only up to 8 KiB (`../../server/cross-process-lock.js`), a lease counts only when it names that very session, and leases are written through a random-named temp file created exclusively. Known limits: a sandbox daemon cannot see leases held outside its folder, so keeping it out of a session the main daemon still runs is the manager's job (drains, and the main daemon refusing sandboxed folders); two PiChamber servers sharing one agent folder with different sandbox settings for a project are not kept apart in that direction. Sandboxed code can block sessions by writing leases in its folder: its own project's, and any other session whose id it knows, since the main daemon does not check which project a scope folder belongs to. Such a lease holds only while the process it names can be signalled by this user, so one naming pid 1 or another user's process is ignored, but one naming a live process of this user holds until that process exits, and the scope folder is not cleared when the project leaves the sandbox.
44
+ - Fail closed. A sandboxed project's Pi runtime never starts outside its sandbox. A failed probe, provider-host lookup, prepare, or start fails the request as HTTP 503 `SANDBOX_UNAVAILABLE` with `reason` (the launcher reason code, `PROVIDER_HOSTS_UNAVAILABLE`, or the start error's code), and is retried on the next command. A sandbox daemon gets 45 s to report ready (the main daemon 15 s), since nono's setup and proxy add to its start. `POST /api/pi/sandbox/recheck` also forgets each stopped project's last start failure, so a one-off timeout does not leave the project shown as unavailable; its next command starts it again. Some reads still answer without the sandbox, because none of them runs Pi code: `sessions.list` and `archive.publish` go to the main daemon whenever the project's daemon is not running (see List fallback), and `sessions.open` and `sessions.messages` fall back to the main daemon's `sessions.readPersisted` when the sandbox fails to start with `SANDBOX_UNAVAILABLE` (see Read-only transcripts). Every other command fails closed, including prompt, steer, follow-up, bash, navigate, fork, compact, model and thinking changes, `sessions.tree`, and extension responses. Commands that name only a session id (no directory) are routed by the cwd in that session's JSONL header whenever any project is sandboxed.
45
+ - Main daemon stays out. The manager writes every folder a sandbox daemon owns (project root, its real path, its worktree root) to `<dataDir>/pi/sandboxed-folders.json` (mode 0600, at most 4096 folders) before a reconcile registers or drains anything (with the folders about to be sandboxed already in it), at its end, and right after projects leave the sandbox; a failed write fails the reconcile, so routes stay closed. The supervisor starts only the main daemon with `--sandboxed-folders-file`. That daemon checks the record, by written and real path, before it creates any Pi runtime and refuses with `DIRECTORY_SANDBOXED`; a missing record lists nothing and an unreadable one counts as every folder. A request that names no folder while the active folder is sandboxed, and a catalog read that names a sandboxed folder (`providers.refresh`, `resources.list`, `extensions.list`, prompt-mutation services), is answered from a folder outside every sandbox: the daemon's startup folder, or the Pi agent folder. Runtimes the main daemon already runs in a newly sandboxed folder keep running until the drain releases them. Routes send changes to a project's own prompts and instruction files (`resources.update`, `resources.prompts.*` with a folder) to the daemon that owns the folder; creating a global prompt stays with the main daemon, since a sandbox cannot write Pi's agent folder. Extension config follows the same split: a project's view (`extensions.config.list` with a folder) and its own choices (`extensions.config.set` with `scope: 'project'`) go to the folder's owner, while global choices and `extensions.packages.remove` stay with the main daemon. A composer control click (`extensions.control`) and a draft discard (`sessions.discardDraft`) are session operations: the transcript's folder routes them, and a draft, which has no transcript yet, is routed by the folder the client sends. A write is skipped only while the file still holds the same list, so a deleted or altered record is put back by the next reconcile.
46
+ - Read-only transcripts. While a project's sandbox cannot start, opening one of its sessions (`GET /api/pi/sessions/:id`, `/snapshot`, `/messages`) is answered by the main daemon's `sessions.readPersisted` (`../session-daemon/DOCUMENTATION.md`). That command parses the JSONL into an in-memory Pi session manager and projects it like `sessions.open`. It starts no runtime, extension, or tool, takes no lease, and writes nothing. The manager drops any `streamEpoch` or `inputState` from the answer and marks it `readOnly: true` with `readOnlyReason`, the reason code the failed start gave (the route passes it on only when it looks like a code). The detail is idle with `lastSequence: -1` and no extension or bash state, and the route stamps it with the project's `stream`. The UI commits it as history without binding the session to that stream (`packages/ui/src/sync/DOCUMENTATION.md`). A send to the session still goes to the sandbox and fails with `SANDBOX_UNAVAILABLE`. A sandbox that is merely stopped (idle) is started by opening, as before; only a failed start falls back. Tests: `../routes-sandbox.test.js` and `../session-daemon/session-daemon-read-persisted.test.js`.
47
+ - List fallback. When the main daemon answers `sessions.list` for a sandboxed project whose daemon is not running, the rows lose `live`, `inputState`, and the top-level `streamEpoch`: that state is the main daemon's, not the sandbox stream's. The response still names the project's `stream` and its rows keep `sandboxed: true` (opening one runs in the sandbox, or reads it read-only while the sandbox cannot start), so clients list those rows as metadata only.
48
+ - Routes (`sandbox-routes.js`). `GET /api/pi/sandbox` and `POST /api/pi/sandbox/recheck` return `{ launchers: [{ id, available, version? | reason?, limits?, limitsAccepted? }] }`. `GET /api/pi/sandbox/projects` returns `{ projects: [{ projectId, mode, launcher, availability: { state: 'off' | 'available' | 'unavailable', reason? }, allowHosts, allowLocalPorts, extraFolders }] }`, without project paths. Each project also carries `choice` (`default`, `off` or `nono`, its own setting; `mode` is what it runs with after the default) and only its own hosts. `GET /api/pi/sandbox/defaults` returns `{ defaults: { mode, allowHosts, acceptedLimits, invalid? } }`; `PUT` takes any of `mode`, `allowHosts` and `acceptedLimits` (none is 400 `INVALID_SANDBOX_SETTING`, and so is an unknown limit code); a field left out keeps its stored value, merged under the settings store lock, so a page that only edits hosts cannot undo a mode or acceptance set elsewhere. It saves, reconciles, and returns `{ defaults, projects }`, since every project that follows it may have changed. A save that was stored answers 200 even when applying it failed; the apply is retried before the next Pi request (see Unapplied settings). `GET /api/pi/sandbox/profile` returns `{ profile: { launcher, custom, path, builtInPath, customPath, content, unreadable? } | null }`, `PUT` with `{ content }` saves the custom profile and `DELETE` removes it; both return the profile now in use. A refused profile is 400 `INVALID_SANDBOX_PROFILE` with `messages`. These are the only sandbox routes that carry server paths and launcher output: the owner needs the path to edit the file and nono's words to fix it. `PUT /api/pi/sandbox/projects/:projectId` takes any of `mode` (`default`, `off` or `nono`), `allowHosts`, `allowLocalPorts` and `extraFolders` (none is 400 `INVALID_SANDBOX_SETTING`), keeps the stored value of every field left out (see Setting), and returns `{ project }`; errors are 400 `INVALID_SANDBOX_SETTING` (with `error.reason` when the setting names one, see Setting; only reason codes are passed on, never the refused value), 404 `PROJECT_NOT_FOUND`. Session rows, details, and created, forked, or cloned sessions in a sandboxed project carry `session.sandboxed: true`.
49
+ - Switching (#247). Every move of a project's sessions between daemons drains: the old daemon stays registered under its own key while the new one owns the folders. Turning a project on (itself or through the default) drains the main daemon's sessions in it; turning it off (or removing the project) retires the sandbox daemon into the main daemon; a changed setting retires the running sandbox daemon into a new one under `sandbox:<project id>:<generation>`. A retired daemon is re-registered with `directories: []` and named by `setDraining` for the folders. The manager polls `sessions.release` on it at once and then every second: each released session, and each pending one that vanished, gets `announceMove` (clients reset and refetch it). When nothing is pending, the drain clears `setDraining`, stops the old daemon (and its intake), and unregisters it. `DAEMON_UNAVAILABLE` also ends the drain, and so do failed polls in a row: three when nothing is pending, sixty (about a minute) while a session is still pending, so a short stall does not cut off a running turn. A project turned off again while the main daemon still finishes sessions for it ends that drain at once: the sessions stay in the main daemon, are announced so clients drop the pending switch, and take new work again. A launch keeps the setting it started with: if the setting changes while the daemon starts, the launch stays under its own key and the request fails with `SANDBOX_SETTING_CHANGED` instead of running under the new key with old grants. A replaced daemon's project takes the next pool key no draining daemon holds, never one still in use: registering a held key again would cut a daemon off mid-turn.
50
+ - A sandbox daemon is not trusted about sessions. Its `sessions.release` answers and its event frames may only concern sessions of its own folders. The manager checks each session once per drain (`ownSessions`) and the event stream once per session and connection (`sessionOnDaemon`, `../merged-event-stream.js`), both through `sessionWithin`: the folder of the session's transcript, or the reported folder for a session not yet written to disk, must lie inside the folders that daemon owns or is draining. Anything else is ignored (drain) or dropped (frames), so a sandbox cannot pull another project's session, its steer text, or its dialogs into itself, nor show frames in another project's session. A release answer of more than 4096 entries is refused as malformed. Known limit: a session that has no transcript yet is judged by the folder the daemon reports.
51
+ - Pending sessions. While a session is pending in a draining daemon, session rows and details carry `pendingSwitch: { to: 'nono' | 'off' }` (only when the drain is a setting switch, not a staleness replacement) and `sandboxed` reflects the daemon running it now. `drainingSession(id)` routes these commands to the old daemon: `sessions.open`, messages, tree, abort, abortBash, steer, `sessions.sendReceipt`, `extensions.draft`, `sessions.discardDraft`, and `extensions.custom.*`; responses carry the old daemon's `stream`. Any other command (prompt, followUp, model, fork, ...) fails with HTTP 409 `SESSION_IN_USE` and `reason: 'SESSION_SWITCHING'` until the turn ends. The reason tells a client this refusal apart from a session another PiChamber instance holds: the command never ran and can be sent again once the session has moved. `extensions.respond` asks the folder's draining daemons first and its owner only when none of them holds the request, so answering a dialog of a session that is still finishing never waits for, or fails on, a sandbox that is not running. `pendingSwitch.to` is where the folder's sessions run now, and it is left out when that is where the session already runs (a project turned off and on again during a turn).
52
+ - Old epochs after a move. A client that sends right after `session.moved` may still hold the old daemon's `streamEpoch`. The manager remembers the epoch each moved session had (2 minutes, at most 4096 sessions); a send or send receipt carrying exactly that epoch is rewritten to the new daemon's current epoch. Any other mismatch still fails as before.
53
+ - Staleness. Single-file grants (`settings.json`, `auth.json`, `models.json`, `trust.json`, `mcp.json`) pin the file the daemon saw at launch; an atomic replace leaves the sandbox reading the old one. The manager records a fingerprint (device, inode, size, mtime of each file) and the granted worktree list at launch. On each idle tick, after every route that writes Pi config through the main daemon (`providers.models.set/add`, `settings.set`, logout, and login once its state is `complete`), and before a request into a worktree the daemon was not granted, it compares them; a change retires the daemon at once into a fresh one (a drain, so busy sessions finish first). A request into an ungranted worktree waits for the new daemon.
54
+ - OAuth. A sandbox daemon reads `auth.json` but cannot write it, so it cannot refresh an expiring token. Before each sandbox start the manager asks the main daemon for `providers.oauth.refresh` with 30 minutes of minimum validity (single-flight). That call and `providers.hosts` pass every sandboxed folder as `exclude`, so the main daemon never starts a runtime in one to answer them. The proactive refresh is a deliberate deviation from #242, which only asks that token refreshes keep sandboxed sessions working. Pi refreshes inside a token's last five minutes, which a sandbox cannot do, so refreshing ahead of time keeps a running sandbox from meeting an expired token mid-turn. A failed refresh does not stop the start: the sandbox may use API keys or still-valid tokens, and a turn that needs an expired token fails visibly in its chat. The manager logs a warning with the error code only, never a token or Pi's message. A sandbox `session.error` frame matching Pi's "OAuth refresh failed for <provider>" or "Credential store modify failed for <provider>" (pi-ai's `refreshStoredOAuthCredential`) triggers the same refresh, then the staleness check, so the new token reaches a fresh daemon. `../routes-sandbox.test.js` produces both messages with the installed pi-ai, so an upstream rewording fails a test.
55
+ - Trust after turning off. Code that ran inside the sandbox may have trusted the project. Turning a project off (or removing it) resets Pi trust for its root and worktrees to unset (`settings.set` `trust: null`), and adds them to the server-owned trust-ask list (`trust-ask.js`, `<dataDir>/pi/trust-ask.json`, mode 0600, at most 4096 folders; a full list refuses the new folder with `TRUST_ASK_FULL` instead of dropping an older one). A missing file is an empty list; one that exists but cannot be read or parsed makes the store's `list`, `add` and `remove` throw `TRUST_ASK_UNREADABLE` and never overwrites it, so reset folders are not forgotten. The daemon's automatic trust of known folders skips any folder in or under a listed one, by its written and its real path (`createSessionDaemon({ isTrustAskDirectory })`; an unreadable or malformed list counts as listing every folder), so Pi asks again. An explicit trust decision through `settings.set` removes the folder from the list. A failed reset is retried on the next idle tick. Unsetting trust and adding the folder to the list are retried separately: when only the list write failed, the retry does not unset trust again, so a decision the user made in between is kept. Pending resets are kept in memory only, so after a restart the manager resets every folder still on the trust-ask list once more: a folder on the list has had no trust decision since its sandbox was turned off (a decision removes it), so a stored "trusted" there is from before.
56
+ - Scope. Only Pi session daemons (the agent) run in the sandbox. PiChamber's own Git panel, terminal, browser and GitHub features, and worktree hooks and start commands, run outside it with the user's access, so git config, hooks or filters an agent writes into the repo can run when the user or the Git panel runs git. This is a known, accepted trade-off. Git for every folder runs as it does without a sandbox.
57
+ - Open requests. Each sandbox daemon gets its own `<runtime folder>/open-url.sock`. The manager starts an intake on that socket before the daemon (`../../open-url/intake.js`) that publishes through that daemon's `openUrl.publish`, and stops it with the daemon.
58
+
59
+ ## Tests
60
+
61
+ - `nono-launcher.test.js`: probe codes and host kinds, the profile for each, the macOS port flags, and the custom profile (save, refusal, reset, an invalid or symlinked file failing closed).
62
+ - `launcher.test.js`: host and port validation.
63
+ - `trust-ask.test.js`: the trust-ask list.
64
+ - `worktree-ids.test.js`: the remembered worktree ids.
65
+ - `sandboxed-folders.test.js`: the sandboxed folder record and the main daemon's reader.
66
+ - `../routes-sandbox.test.js`: routing, fail closed, read-only transcripts, switching, staleness, the profile routes, OAuth, trust reset, overlapping saves, forged transcript headers, path spellings, worktree ids, and unapplied settings.
67
+ - `../session-daemon/supervisor-sandbox.test.js` and `../session-daemon/supervisor-sandbox-nono.e2e.test.js`: the launched command and socket path limits. The e2e test runs the daemon under real nono and checks from inside the sandbox what it can reach: the project, other folders and sessions, Pi's config, the main credential, a loopback TCP server, a granted local port, and a Unix socket outside (reachable only on WSL2). It skips when the probe says nono cannot run; `PICHAMBER_REQUIRE_NONO_E2E=1` makes that a failure.
68
+ - CI. GitHub's Linux runners have no Landlock, so the Linux and WSL2 paths are run by hand on a Landlock host. `.github/workflows/sandbox-macos.yml` runs the e2e test on macOS with a checksum-verified nono release whenever this folder or `../session-daemon` changes.
@@ -0,0 +1,122 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { posix } from 'node:path';
3
+
4
+ /**
5
+ * Sandbox launcher contract (see ../session-daemon/DOCUMENTATION.md).
6
+ *
7
+ * A launcher turns a daemon launch request into a command:
8
+ *
9
+ * {
10
+ * id, platforms, transport: 'local-socket',
11
+ * probe(): Promise<{ available: true, version, capabilities, limits? } | { available: false, code }>,
12
+ * identity({ grants, network }): string,
13
+ * prepare({ argv, env, cwd, grants, network, tmpDir }): Promise<{ command, args, env, cleanup? }>,
14
+ * }
15
+ *
16
+ * Grants are structured, never raw user strings:
17
+ * { kind: 'read' | 'readWrite', path } folder, recursive
18
+ * { kind: 'readFile' | 'readWriteFile', path } single file
19
+ * { kind: 'unixSocketBind', dir } bind sockets in a folder
20
+ * Network:
21
+ * { mode: 'proxy', allowHosts: string[], allowLocalPorts: number[] } | { mode: 'none' }
22
+ *
23
+ * `limits` names what the sandbox cannot enforce on this host, from
24
+ * `SANDBOX_LIMIT_CODES`. A host with limits runs sandboxes only after its
25
+ * owner accepts every one of them (`sandboxDefaults.acceptedLimits`).
26
+ */
27
+
28
+ /** What a launcher may report it cannot enforce on a host.
29
+ * UNIX_SOCKETS: pathname Unix sockets are not mediated (nono on WSL2).
30
+ * PROXY_PORT: connections on the proxy's port are not held to the proxy, so
31
+ * they reach any host (nono on WSL2). */
32
+ export const SANDBOX_LIMIT_CODES = Object.freeze(['UNIX_SOCKETS', 'PROXY_PORT']);
33
+
34
+ export class SandboxLaunchError extends Error {
35
+ constructor(code) {
36
+ super('The sandbox launch request is invalid.');
37
+ this.code = code;
38
+ }
39
+ }
40
+
41
+ const GRANT_KINDS = new Set(['read', 'readWrite', 'readFile', 'readWriteFile', 'unixSocketBind']);
42
+ const HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
43
+
44
+ // Hosts a sandboxed agent may reach through nono's proxy. The PiChamber
45
+ // server's own API is on the same machine, so anything that could name it
46
+ // (loopback, local names, raw IPs) is refused, as are names too broad or
47
+ // too long to be public host names.
48
+ const isRefusedHost = (value) => {
49
+ const name = value.startsWith('*.') ? value.slice(2) : value;
50
+ if (value.length > 253) return true;
51
+ const labels = name.split('.');
52
+ // One label (`localhost`, `com`), or one label under a wildcard (`*.com`).
53
+ if (labels.length < 2) return true;
54
+ if (labels.some((label) => label.length > 63)) return true;
55
+ if (name === 'localhost' || name.endsWith('.localhost') || name.endsWith('.local')) return true;
56
+ // IP literals in any spelling a resolver takes (`127.0.0.1`, `1.2.3.0x4`):
57
+ // no public top-level name starts with a digit.
58
+ if (/^\d/.test(labels[labels.length - 1])) return true;
59
+ return false;
60
+ };
61
+
62
+ /** Whether `host` is a name `normalizeNetwork` accepts as an allowed host. */
63
+ export const isAllowedSandboxHost = (host) => {
64
+ const value = typeof host === 'string' ? host.trim().toLowerCase() : '';
65
+ return HOST_PATTERN.test(value) && !isRefusedHost(value);
66
+ };
67
+
68
+ const normalizePath = (value) => {
69
+ if (typeof value !== 'string' || !value.startsWith('/') || /[\0\n\r]/.test(value)) {
70
+ throw new SandboxLaunchError('SANDBOX_INVALID_GRANT');
71
+ }
72
+ const normalized = posix.normalize(value);
73
+ return normalized.length > 1 ? normalized.replace(/\/+$/, '') : normalized;
74
+ };
75
+
76
+ /** Validated, de-duplicated grants in a stable order. */
77
+ export const normalizeGrants = (grants) => {
78
+ if (!Array.isArray(grants)) throw new SandboxLaunchError('SANDBOX_INVALID_GRANT');
79
+ const seen = new Map();
80
+ for (const grant of grants) {
81
+ if (!grant || !GRANT_KINDS.has(grant.kind)) throw new SandboxLaunchError('SANDBOX_INVALID_GRANT');
82
+ const path = normalizePath(grant.kind === 'unixSocketBind' ? grant.dir : grant.path);
83
+ seen.set(`${grant.kind}\0${path}`, { kind: grant.kind, path });
84
+ }
85
+ return [...seen.values()].sort((a, b) => (a.kind === b.kind
86
+ ? (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
87
+ : (a.kind < b.kind ? -1 : 1)));
88
+ };
89
+
90
+ export const normalizeNetwork = (network) => {
91
+ if (network?.mode === 'none') return { mode: 'none' };
92
+ if (network?.mode !== 'proxy') throw new SandboxLaunchError('SANDBOX_INVALID_NETWORK');
93
+ const hosts = (network.allowHosts ?? []).map((host) => {
94
+ if (!isAllowedSandboxHost(host)) throw new SandboxLaunchError('SANDBOX_INVALID_NETWORK');
95
+ return host.trim().toLowerCase();
96
+ });
97
+ const ports = (network.allowLocalPorts ?? []).map((port) => {
98
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new SandboxLaunchError('SANDBOX_INVALID_NETWORK');
99
+ return port;
100
+ });
101
+ return {
102
+ mode: 'proxy',
103
+ allowHosts: [...new Set(hosts)].sort(),
104
+ allowLocalPorts: [...new Set(ports)].sort((a, b) => a - b),
105
+ };
106
+ };
107
+
108
+ /**
109
+ * Short hash of everything that shapes a sandbox: launcher, its version, its
110
+ * policy file, grants and network. It goes into the daemon profile key, so a
111
+ * change in any of them starts a new daemon instead of reusing an old one.
112
+ */
113
+ export const launchIdentity = ({ launcher, version, profile, grants, network }) => createHash('sha256')
114
+ .update(JSON.stringify({
115
+ launcher,
116
+ version,
117
+ profile,
118
+ grants: normalizeGrants(grants),
119
+ network: normalizeNetwork(network),
120
+ }))
121
+ .digest('hex')
122
+ .slice(0, 12);
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { normalizeNetwork, SandboxLaunchError } from './launcher.js';
4
+
5
+ const allowHosts = (allowHosts) =>
6
+ normalizeNetwork({ mode: 'proxy', allowHosts, allowLocalPorts: [] }).allowHosts;
7
+
8
+ const expectRefused = (host) => {
9
+ let error;
10
+ try {
11
+ allowHosts([host]);
12
+ } catch (cause) {
13
+ error = cause;
14
+ }
15
+ expect(error).toBeInstanceOf(SandboxLaunchError);
16
+ expect(error?.code).toBe('SANDBOX_INVALID_NETWORK');
17
+ };
18
+
19
+ describe('normalizeNetwork hosts', () => {
20
+ it('accepts ordinary public host names and wildcards with two or more labels', () => {
21
+ expect(allowHosts([
22
+ 'api.anthropic.com',
23
+ 'registry.npmjs.org',
24
+ '*.githubusercontent.com',
25
+ 'index.rubygems.org',
26
+ 'npm.jsr.io',
27
+ 'repo.maven.apache.org',
28
+ 'proxy.golang.org',
29
+ ])).toEqual([
30
+ '*.githubusercontent.com',
31
+ 'api.anthropic.com',
32
+ 'index.rubygems.org',
33
+ 'npm.jsr.io',
34
+ 'proxy.golang.org',
35
+ 'registry.npmjs.org',
36
+ 'repo.maven.apache.org',
37
+ ]);
38
+ });
39
+
40
+ it('accepts a 63-character label', () => {
41
+ expect(allowHosts([`${'a'.repeat(63)}.com`])).toEqual([`${'a'.repeat(63)}.com`]);
42
+ });
43
+
44
+ it('lowercases, trims, de-duplicates and sorts hosts', () => {
45
+ expect(allowHosts([' GitHub.com ', 'github.com', 'api.github.com', 'GITHUB.COM'])).toEqual([
46
+ 'api.github.com',
47
+ 'github.com',
48
+ ]);
49
+ });
50
+
51
+ it('refuses one-label names', () => {
52
+ for (const host of ['localhost', 'com', 'myserver', 'LocalHost']) expectRefused(host);
53
+ });
54
+
55
+ it('refuses localhost and .local names', () => {
56
+ for (const host of ['foo.localhost', '*.localhost', 'printer.local', 'myserver.local']) {
57
+ expectRefused(host);
58
+ }
59
+ });
60
+
61
+ it('refuses IPv4 literals and names ending in a number', () => {
62
+ for (const host of ['127.0.0.1', '10.0.0.5', '1.2.3.4', 'example.123', '1.2.3.0x4', '0x7f.0.0.1']) expectRefused(host);
63
+ });
64
+
65
+ it('refuses wildcards wider than *.example.com', () => {
66
+ expectRefused('*.com');
67
+ });
68
+
69
+ it('refuses malformed names', () => {
70
+ for (const host of ['', 'https://x', 'a..b', '-bad.com', 'bad-.com', 'under_score.com', '*.']) {
71
+ expectRefused(host);
72
+ }
73
+ });
74
+
75
+ it('refuses a label above 63 characters or a name above 253 characters', () => {
76
+ expectRefused(`${'a'.repeat(64)}.com`);
77
+ expectRefused(Array(5).fill('a'.repeat(50)).join('.'));
78
+ });
79
+
80
+ it('keeps refusing non-proxy and malformed network values', () => {
81
+ expect(normalizeNetwork({ mode: 'none' })).toEqual({ mode: 'none' });
82
+ expect(() => normalizeNetwork({})).toThrowError(expect.objectContaining({ code: 'SANDBOX_INVALID_NETWORK' }));
83
+ expect(() => normalizeNetwork({ mode: 'proxy', allowHosts: ['ok.example.com'], allowLocalPorts: [0] }))
84
+ .toThrowError(expect.objectContaining({ code: 'SANDBOX_INVALID_NETWORK' }));
85
+ });
86
+
87
+ it('sorts and de-duplicates local ports', () => {
88
+ expect(normalizeNetwork({ mode: 'proxy', allowHosts: [], allowLocalPorts: [11434, 8080, 8080] }))
89
+ .toEqual({ mode: 'proxy', allowHosts: [], allowLocalPorts: [8080, 11434] });
90
+ });
91
+ });