@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
@@ -0,0 +1,1461 @@
1
+ import { readdir, realpath, stat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
+
5
+ import { MAIN_DAEMON_KEY, publicDaemonStreamId } from '../session-daemon/daemon-pool.js';
6
+
7
+ import { createOpenUrlIntake } from '../../open-url/intake.js';
8
+ import { encodePiSessionCwd, findPiSessionJsonlsById, getPiSessionDirectory, readPiSessionJsonlHeader } from '../session-daemon/session-jsonl.js';
9
+ import { readSmallRegularFile } from '../../server/cross-process-lock.js';
10
+ import { createSandboxedPiSessionDaemonSupervisor } from '../session-daemon/supervisor.js';
11
+ import { isAllowedSandboxHost } from './launcher.js';
12
+ import { prepareProjectSandbox } from './project-sandbox.js';
13
+ import { readProjectSandbox, readSandboxDefaults } from './project-sandbox-setting.js';
14
+ import { createSandboxedFoldersStore } from './sandboxed-folders.js';
15
+ import { createWorktreeIdStore } from './worktree-ids.js';
16
+
17
+ // Commands a sandboxed project may run on the main daemon while its own
18
+ // daemon is stopped or unavailable. Listing reads transcripts on disk and
19
+ // runs no Pi code; an archive signal only publishes an event. Everything
20
+ // else would start a Pi runtime (extensions, tools) and must run in the
21
+ // sandbox or not at all.
22
+ const MAIN_DAEMON_READS = new Set(['sessions.list', 'archive.publish']);
23
+ // Transcript reads a sandboxed project answers from disk when its sandbox
24
+ // cannot start: the main daemon's `sessions.readPersisted` parses the JSONL
25
+ // into a read-only detail and starts no Pi runtime, extension, or tool.
26
+ const READ_ONLY_FALLBACK = new Set(['sessions.open', 'sessions.messages']);
27
+ // Polling and status reads that do not count as using a project: the
28
+ // sidebar and pending-input polls must not keep an idle daemon running.
29
+ const PASSIVE_COMMANDS = new Set(['sessions.list', 'sessions.pendingInput', 'sessions.sendReceipt']);
30
+ const REASON_PATTERN = /^[A-Z][A-Z0-9_]{1,63}$/;
31
+ const GIT_PROJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
32
+ const DEFAULT_IDLE_STOP_MS = 10 * 60_000;
33
+ const DEFAULT_IDLE_CHECK_MS = 60_000;
34
+ const DEFAULT_DRAIN_POLL_MS = 1_000;
35
+ // How long a token must stay valid after the main daemon's refresh before
36
+ // a sandbox daemon starts or keeps running (Pi itself refreshes inside the
37
+ // last five minutes, which a sandbox cannot do: auth.json is read-only).
38
+ // Deliberate deviation from #242, which only asks that refreshes keep
39
+ // sandboxed sessions working: refreshing ahead of time means a sandbox
40
+ // rarely meets an expiring token mid-turn. See ./DOCUMENTATION.md, "OAuth".
41
+ const OAUTH_MIN_VALIDITY_MS = 30 * 60_000;
42
+ // A send made from the old daemon's epoch right after its session moved is
43
+ // accepted by the new daemon for this long (see `sendEpochFor`).
44
+ const MOVED_EPOCH_TTL_MS = 2 * 60_000;
45
+ const MOVED_LIMIT = 4096;
46
+ const TRANSCRIPT_PATH_LIMIT = 4096;
47
+ const DRAIN_FAILURE_LIMIT = 3;
48
+ // A draining daemon known to hold a busy session gets longer: a few failed
49
+ // polls must not cut a running turn off.
50
+ const DRAIN_BUSY_FAILURE_LIMIT = 60;
51
+ // Pi config files a sandbox reads through single-file grants. Replacing one
52
+ // (write temp file, rename) leaves a running sandbox reading nothing, so a
53
+ // change to any of them replaces the daemon at its next idle edge.
54
+ const PI_CONFIG_FILES = ['settings.json', 'auth.json', 'models.json', 'trust.json', 'mcp.json'];
55
+ // Pi's own error text when a turn needs an OAuth token refresh it cannot
56
+ // write (`refreshStoredOAuthCredential` in pi-ai): the sandbox's auth.json
57
+ // is read-only, so the refresh must happen in the main daemon.
58
+ const OAUTH_REFRESH_FAILURE = /\b(?:OAuth refresh failed|Credential store modify failed) for \S/;
59
+
60
+ const sandboxUnavailable = (reason) => {
61
+ const error = new Error('The project sandbox is unavailable.');
62
+ error.code = 'SANDBOX_UNAVAILABLE';
63
+ error.reason = typeof reason === 'string' && REASON_PATTERN.test(reason) ? reason : 'SANDBOX_LAUNCH_FAILED';
64
+ return error;
65
+ };
66
+
67
+ const reasonOf = (error) => (error?.code === 'SANDBOX_UNAVAILABLE' ? error.reason : error?.code);
68
+
69
+ /**
70
+ * The project id PiChamber's worktrees are filed under
71
+ * (`<dataDir>/worktree/<id>`), read from `<project>/.git/pichamber`. A
72
+ * sandboxed agent can write that file, so only a commit-hash-shaped id is
73
+ * accepted; anything else grants no worktree folder.
74
+ */
75
+ const readGitProjectId = async (projectRoot) => {
76
+ try {
77
+ // The sandboxed agent can put anything at this path: the read follows no
78
+ // symlink, waits on no FIFO, and takes no more than an id's worth.
79
+ const id = (await readSmallRegularFile(join(projectRoot, '.git', 'pichamber'), 256)).trim();
80
+ return GIT_PROJECT_ID.test(id) ? id : null;
81
+ } catch {
82
+ return null;
83
+ }
84
+ };
85
+
86
+ /**
87
+ * The project a git worktree belongs to, from the `gitdir:` line of its
88
+ * `.git` file (`<project>/.git/worktrees/<name>`), as a real path.
89
+ */
90
+ const worktreeProjectRoot = async (directory) => {
91
+ try {
92
+ const pointer = /^gitdir:\s*(.+)$/m.exec(await readSmallRegularFile(join(directory, '.git'), 4096))?.[1]?.trim();
93
+ if (!pointer) return null;
94
+ const gitDir = resolve(directory, pointer);
95
+ const marker = `${sep}.git${sep}worktrees${sep}`;
96
+ const at = gitDir.lastIndexOf(marker);
97
+ if (at <= 0) return null;
98
+ const root = gitDir.slice(0, at);
99
+ return await realpath(root).catch(() => root);
100
+ } catch {
101
+ return null;
102
+ }
103
+ };
104
+
105
+ const listWorktreeDirs = async (worktreeRoot) => {
106
+ try {
107
+ const entries = await readdir(worktreeRoot, { withFileTypes: true });
108
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => join(worktreeRoot, entry.name)).sort();
109
+ } catch {
110
+ return [];
111
+ }
112
+ };
113
+
114
+ const settingKey = (setting) => JSON.stringify(setting);
115
+
116
+ const EMPTY_SETTING = Object.freeze({ allowHosts: [], allowLocalPorts: [], extraFolders: [] });
117
+
118
+ /**
119
+ * What a project runs with: its own choice, or the host default when it has
120
+ * none or chose `default`. A sandboxed project reaches the default's hosts on
121
+ * top of its own. An unreadable project setting, or an unreadable default a
122
+ * project follows, keeps the project sandboxed and unavailable (fail closed);
123
+ * only an explicit `off` stays off whatever the default says.
124
+ */
125
+ const effectiveProjectSandbox = (project, settings) => {
126
+ const { setting, invalid } = readProjectSandbox(project);
127
+ const { defaults, invalid: defaultsInvalid } = readSandboxDefaults(settings);
128
+ const choice = invalid ? 'nono' : (setting?.mode ?? 'default');
129
+ if (choice === 'off') return { choice, sandboxed: false, setting, invalid: false };
130
+ const followsDefault = choice === 'default';
131
+ const sandboxed = followsDefault ? defaultsInvalid || defaults.mode === 'nono' : true;
132
+ if (!sandboxed) return { choice, sandboxed: false, setting, invalid: false };
133
+ const own = setting ?? EMPTY_SETTING;
134
+ return {
135
+ choice,
136
+ sandboxed: true,
137
+ setting: {
138
+ mode: 'nono',
139
+ allowHosts: [...new Set([...defaults.allowHosts, ...own.allowHosts])],
140
+ allowLocalPorts: own.allowLocalPorts,
141
+ extraFolders: own.extraFolders,
142
+ },
143
+ invalid: Boolean(invalid || defaultsInvalid),
144
+ };
145
+ };
146
+
147
+
148
+ const RELEASE_ENTRY_LIMIT = 4096;
149
+ const isEntryList = (value) => Array.isArray(value) && value.length <= RELEASE_ENTRY_LIMIT && value.every((item) => item
150
+ && typeof item.sessionId === 'string' && item.sessionId.length > 0
151
+ && typeof item.directory === 'string' && isAbsolute(item.directory));
152
+
153
+ const isInside = (parent, child) => child === parent || child.startsWith(parent.endsWith(sep) ? parent : `${parent}${sep}`);
154
+
155
+ /** Whether a sandboxed turn's error is Pi failing to refresh an OAuth token. */
156
+ const isOAuthRefreshFailure = (message) => typeof message === 'string' && OAUTH_REFRESH_FAILURE.test(message);
157
+
158
+ /**
159
+ * Owns the sandbox daemons of sandboxed projects (#242). For every project
160
+ * whose setting is `nono` it registers one runtime in the daemon pool that
161
+ * owns the project root and its worktree root, so nothing in that project
162
+ * can route to the main daemon. The daemon starts on the first Pi-running
163
+ * command, through the launcher, with grants built from the project, its
164
+ * existing worktrees and extras, and a network allowlist of the signed-in
165
+ * providers' hosts plus the project's own. Each daemon gets its own Open
166
+ * request intake. When the launcher or the launch fails, every Pi-running
167
+ * command fails with SANDBOX_UNAVAILABLE and the reason; listing still works.
168
+ * A daemon with no resident sessions for `idleStopMs` stops.
169
+ *
170
+ * Moves (#247). Whenever a project's sessions change daemons (turned on or
171
+ * off, a changed setting, a stale daemon after a Pi config change, a new
172
+ * worktree), the old daemon drains: it is asked to release the project's
173
+ * folders, idle sessions move at once, and busy ones (mid-turn, compacting,
174
+ * custom surface, pending dialog) stay until their next idle edge. Every
175
+ * move is announced through the pool so clients refetch the session.
176
+ */
177
+ export const createProjectSandboxManager = ({
178
+ daemonPool,
179
+ uiSettingsStore,
180
+ launcher,
181
+ dataDir,
182
+ // The real Pi agent folder, or an (async) function returning it, so the
183
+ // Pi SDK loads only once a project is sandboxed.
184
+ agentDir,
185
+ getServerPort = () => null,
186
+ hasConnectedDevices = () => false,
187
+ // Extra supervisor options (port, version); a function is read at launch
188
+ // so the bound port is known.
189
+ supervisorOptions = {},
190
+ readRoots,
191
+ createSupervisor = createSandboxedPiSessionDaemonSupervisor,
192
+ prepareSandbox = prepareProjectSandbox,
193
+ createIntake = createOpenUrlIntake,
194
+ // Folders switched from sandboxed to off whose Pi trust must stay "ask"
195
+ // (sandbox/trust-ask.js); without one nothing is recorded.
196
+ trustAsk,
197
+ // Each project's worktree folder id, remembered so it cannot follow a
198
+ // file the sandboxed agent can rewrite (sandbox/worktree-ids.js).
199
+ worktreeIds = createWorktreeIdStore({ dataDir }),
200
+ folderRecord = createSandboxedFoldersStore({ dataDir }),
201
+ idleStopMs = DEFAULT_IDLE_STOP_MS,
202
+ idleCheckMs = DEFAULT_IDLE_CHECK_MS,
203
+ drainPollMs = DEFAULT_DRAIN_POLL_MS,
204
+ now = Date.now,
205
+ setInterval: startTimer = setInterval,
206
+ clearInterval: stopTimer = clearInterval,
207
+ log = (message, code) => console.warn(`[pi-sandbox] ${message}`, code ?? ''),
208
+ }) => {
209
+ const projects = new Map();
210
+ // Every sandboxed project's folders, for main-daemon commands that may
211
+ // start a runtime to answer: the main daemon must not start one there.
212
+ const recordFolders = () => folderRecord.set([...projects.values()].flatMap((entry) => entry.directories ?? []));
213
+ const sandboxedFolders = () => ({ exclude: [...new Set([...projects.values()].flatMap((entry) => entry.directories ?? []))].slice(0, 4096) });
214
+ // Daemons still holding sessions of a folder they no longer own.
215
+ const drains = new Set();
216
+ // sessionId -> drain still running it.
217
+ const pendingBySession = new Map();
218
+ // sessionId -> { fromEpoch, at } for sessions that just moved.
219
+ const moved = new Map();
220
+ // folder -> pool keys draining it.
221
+ const drainingKeys = new Map();
222
+ let probe = null;
223
+ let probing = null;
224
+ // Host limits the owner accepted (`sandboxDefaults.acceptedLimits`), as of
225
+ // the last reconcile. A launcher reporting a limit not in here starts no
226
+ // sandbox.
227
+ let acceptedLimits = new Set();
228
+ let timer = null;
229
+ let drainTimer = null;
230
+ let stopped = false;
231
+ let agentDirValue = null;
232
+ let oauthRefreshing = null;
233
+ const resolveAgentDir = async () => {
234
+ if (!agentDirValue) agentDirValue = resolve(typeof agentDir === 'function' ? await agentDir() : agentDir);
235
+ return agentDirValue;
236
+ };
237
+
238
+ const probeLauncher = async ({ recheck = false } = {}) => {
239
+ if (probe && !recheck) return probe;
240
+ if (!probing) {
241
+ probing = launcher.probe()
242
+ .then((result) => {
243
+ probe = result?.available === true
244
+ ? {
245
+ available: true,
246
+ version: typeof result.version === 'string' ? result.version : undefined,
247
+ // A limit outside the known codes can never be accepted, so the
248
+ // host stays unavailable rather than run with it unannounced.
249
+ limits: Array.isArray(result.limits)
250
+ ? [...new Set(result.limits.map((limit) => (REASON_PATTERN.test(limit ?? '') ? limit : 'UNKNOWN_LIMIT')))]
251
+ : [],
252
+ }
253
+ : { available: false, code: REASON_PATTERN.test(result?.code ?? '') ? result.code : 'SETUP_CHECK_FAILED' };
254
+ return probe;
255
+ })
256
+ .catch(() => {
257
+ probe = { available: false, code: 'SETUP_CHECK_FAILED' };
258
+ return probe;
259
+ })
260
+ .finally(() => { probing = null; });
261
+ }
262
+ return probing;
263
+ };
264
+
265
+ // Limits of a probed host the owner has not accepted.
266
+ const unacceptedLimits = (status) => (status?.available ? status.limits.filter((limit) => !acceptedLimits.has(limit)) : []);
267
+
268
+ // Identity of the Pi config files a sandbox pins: a replaced, rewritten,
269
+ // added or removed file changes it.
270
+ const configFingerprint = async () => {
271
+ const dir = await resolveAgentDir();
272
+ const parts = await Promise.all(PI_CONFIG_FILES.map(async (name) => {
273
+ try {
274
+ const info = await stat(join(dir, name));
275
+ return `${name}:${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}`;
276
+ } catch {
277
+ return `${name}:-`;
278
+ }
279
+ }));
280
+ return parts.join('|');
281
+ };
282
+
283
+ // Ask the main daemon to refresh OAuth tokens near expiry. Shared by
284
+ // concurrent callers.
285
+ const refreshOAuth = () => {
286
+ if (!oauthRefreshing) {
287
+ oauthRefreshing = (async () => {
288
+ const main = daemonPool.main();
289
+ if (!main) return;
290
+ try {
291
+ await main.request('providers.oauth.refresh', { minValidityMs: OAUTH_MIN_VALIDITY_MS, ...sandboxedFolders() });
292
+ } catch (error) {
293
+ // Not fatal, on purpose: the sandbox may use API keys or tokens
294
+ // that are still valid, and a turn that needs an expired token
295
+ // fails visibly in its chat (Pi's own error), which also triggers
296
+ // another refresh (`watchDaemon`). Only the error code is logged,
297
+ // never a token or Pi's message.
298
+ log('OAuth refresh in the main daemon failed; the sandbox starts anyway', error?.code);
299
+ }
300
+ })().finally(() => { oauthRefreshing = null; });
301
+ }
302
+ return oauthRefreshing;
303
+ };
304
+
305
+ const notifyPool = (entry) => {
306
+ if (projects.get(entry.projectId) !== entry) return;
307
+ daemonPool.register(entry.key, { runtime: entry.runtime, directories: entry.directories });
308
+ };
309
+
310
+ const closeWatch = (entry) => {
311
+ const close = entry.watch;
312
+ entry.watch = null;
313
+ if (typeof close === 'function') {
314
+ try { close(); } catch {}
315
+ }
316
+ };
317
+
318
+ const stopDaemon = async (entry) => {
319
+ const { supervisor, intake } = entry;
320
+ if (!supervisor) return;
321
+ entry.supervisor = null;
322
+ entry.intake = null;
323
+ entry.idleSince = null;
324
+ closeWatch(entry);
325
+ entry.stopping = (async () => {
326
+ await Promise.allSettled([supervisor.stop(), intake?.stop()]);
327
+ })();
328
+ try {
329
+ await entry.stopping;
330
+ } finally {
331
+ entry.stopping = null;
332
+ }
333
+ notifyPool(entry);
334
+ };
335
+
336
+ // --- Draining -----------------------------------------------------------
337
+
338
+ const applyDraining = (directory) => {
339
+ const keys = drainingKeys.get(directory);
340
+ daemonPool.setDraining(directory, keys ? [...keys] : []);
341
+ };
342
+
343
+ const rememberMoved = (sessionId, fromEpoch) => {
344
+ moved.delete(sessionId);
345
+ if (typeof fromEpoch === 'string' && fromEpoch.length > 0) moved.set(sessionId, { fromEpoch, at: now() });
346
+ while (moved.size > MOVED_LIMIT) moved.delete(moved.keys().next().value);
347
+ };
348
+
349
+ const finishDrain = async (drain) => {
350
+ if (!drains.delete(drain)) return;
351
+ for (const [sessionId, owner] of [...pendingBySession]) {
352
+ if (owner !== drain) continue;
353
+ pendingBySession.delete(sessionId);
354
+ rememberMoved(sessionId, drain.epoch);
355
+ daemonPool.announceMove(sessionId, drain.pending.get(sessionId));
356
+ }
357
+ for (const directory of drain.directories) {
358
+ const keys = drainingKeys.get(directory);
359
+ keys?.delete(drain.key);
360
+ if (keys && keys.size === 0) drainingKeys.delete(directory);
361
+ applyDraining(directory);
362
+ }
363
+ if (drain.stop) await drain.stop();
364
+ if (drain.unregister) {
365
+ // Only drop the key while it still holds this drain's runtime; a
366
+ // later registration under the same key is someone else's.
367
+ daemonPool.unregister(drain.key, drain.runtime);
368
+ }
369
+ };
370
+
371
+ // Ask the draining daemon to let go of its folders: idle sessions are
372
+ // disposed now, busy ones at their next idle edge. A session gone from
373
+ // both lists since the last poll was disposed in between.
374
+ const pollDrain = (drain) => {
375
+ if (drain.polling) return drain.polling;
376
+ drain.polling = (async () => {
377
+ let result;
378
+ try {
379
+ result = await drain.runtime.request('sessions.release', { directories: drain.directories });
380
+ if (!isEntryList(result?.released) || !isEntryList(result?.pending)) throw Object.assign(new Error('malformed'), { code: 'DAEMON_PROTOCOL_MISMATCH' });
381
+ drain.failures = 0;
382
+ } catch (error) {
383
+ drain.failures += 1;
384
+ // A daemon that is gone holds nothing; one that keeps failing is
385
+ // given up on (session leases still keep a session in one daemon).
386
+ const limit = drain.pending.size > 0 ? DRAIN_BUSY_FAILURE_LIMIT : DRAIN_FAILURE_LIMIT;
387
+ if (error?.code === 'DAEMON_UNAVAILABLE' || drain.failures >= limit) {
388
+ log('Draining daemon stopped answering', error?.code);
389
+ await finishDrain(drain);
390
+ }
391
+ return;
392
+ }
393
+ if (typeof result.streamEpoch === 'string' && result.streamEpoch.length > 0) drain.epoch = result.streamEpoch;
394
+ // A sandbox daemon's answer is not trusted: it may only speak for
395
+ // sessions of the folders it is draining. Naming another project's
396
+ // session would route that session's commands into the sandbox.
397
+ const released = await ownSessions(drain, result.released);
398
+ const stillPending = new Map((await ownSessions(drain, result.pending)).map((item) => [item.sessionId, item.directory]));
399
+ const moves = [];
400
+ for (const item of released) {
401
+ if (!stillPending.has(item.sessionId)) moves.push([item.sessionId, item.directory]);
402
+ }
403
+ for (const [sessionId, directory] of drain.pending) {
404
+ if (!stillPending.has(sessionId) && !moves.some(([id]) => id === sessionId)) moves.push([sessionId, directory]);
405
+ }
406
+ const newlyPending = [...stillPending].filter(([sessionId]) => !drain.pending.has(sessionId));
407
+ drain.pending = stillPending;
408
+ for (const [sessionId] of stillPending) pendingBySession.set(sessionId, drain);
409
+ for (const [sessionId, directory] of moves) {
410
+ if (pendingBySession.get(sessionId) === drain) pendingBySession.delete(sessionId);
411
+ rememberMoved(sessionId, drain.epoch);
412
+ daemonPool.announceMove(sessionId, directory);
413
+ }
414
+ // A session that now waits to switch modes changed state too: clients
415
+ // refetch it and learn it switches after this turn. A daemon
416
+ // replacement is not a switch, so nothing changes for them yet.
417
+ if (drain.to) for (const [sessionId, directory] of newlyPending) daemonPool.announceMove(sessionId, directory);
418
+ if (stillPending.size === 0) await finishDrain(drain);
419
+ })().finally(() => { drain.polling = null; });
420
+ return drain.polling;
421
+ };
422
+
423
+ // The items of a draining daemon's answer that are its own to report.
424
+ // The main daemon is trusted; a sandbox daemon is checked per session,
425
+ // once (`drain.verified`), against where the server finds the session.
426
+ const ownSessions = async (drain, items) => {
427
+ if (!drain.sandboxed) return items;
428
+ const own = [];
429
+ for (const item of items) {
430
+ let verdict = drain.verified.get(item.sessionId);
431
+ if (verdict === undefined) {
432
+ verdict = await sessionWithin(drain.directories, item.sessionId, item.directory);
433
+ drain.verified.set(item.sessionId, verdict);
434
+ if (!verdict) log('Ignored a session a sandbox daemon reported outside its folders');
435
+ }
436
+ if (verdict) own.push(item);
437
+ }
438
+ return own;
439
+ };
440
+
441
+ const ensureDrainTimer = () => {
442
+ if (drainTimer || stopped) return;
443
+ drainTimer = startTimer(() => {
444
+ for (const drain of [...drains]) pollDrain(drain).catch(() => {});
445
+ }, drainPollMs);
446
+ drainTimer?.unref?.();
447
+ };
448
+
449
+ /**
450
+ * Start draining `directories` out of the daemon `key`/`runtime`. `to` is
451
+ * the mode its sessions switch to (`nono` or `off`), or null when only
452
+ * the daemon is replaced (setting or config change), which clients do not
453
+ * see as a switch. `sandboxed` says whether the old daemon is a sandbox.
454
+ */
455
+ const startDrain = async ({ key, runtime, directories, to = null, sandboxed, stop, unregister = false, sessionRoots = [] }) => {
456
+ const drain = {
457
+ key,
458
+ runtime,
459
+ directories: [...directories],
460
+ // Session ids this drain checked (`ownSessions`), and the folders
461
+ // whose Pi session folders the draining sandbox can write.
462
+ verified: new Map(),
463
+ sessionRoots,
464
+ to,
465
+ sandboxed,
466
+ stop,
467
+ unregister,
468
+ stream: key === MAIN_DAEMON_KEY ? undefined : publicDaemonStreamId(key),
469
+ pending: new Map(),
470
+ epoch: undefined,
471
+ failures: 0,
472
+ polling: null,
473
+ };
474
+ drains.add(drain);
475
+ for (const directory of drain.directories) {
476
+ if (!drainingKeys.has(directory)) drainingKeys.set(directory, new Set());
477
+ drainingKeys.get(directory).add(key);
478
+ applyDraining(directory);
479
+ }
480
+ ensureDrainTimer();
481
+ await pollDrain(drain);
482
+ };
483
+
484
+ /**
485
+ * Hand the running sandbox daemon of `entry` over to a drain, so the
486
+ * entry's next command starts a fresh one. The old daemon keeps its pool
487
+ * key (and so its event stream) but owns no folder; the entry moves to a
488
+ * new key.
489
+ */
490
+ const retire = async (entry, { to = null, removed = false } = {}) => {
491
+ const { supervisor, intake } = entry;
492
+ if (!supervisor) return;
493
+ entry.supervisor = null;
494
+ entry.intake = null;
495
+ entry.idleSince = null;
496
+ closeWatch(entry);
497
+ const oldKey = entry.key;
498
+ const directories = entry.launchedDirectories ?? entry.directories;
499
+ const runtime = {
500
+ isLive: () => true,
501
+ request: (command, payload) => supervisor.request(command, payload),
502
+ subscribe: (options) => supervisor.subscribe(options),
503
+ health: () => supervisor.health(),
504
+ };
505
+ daemonPool.register(oldKey, { runtime, directories: [] });
506
+ if (!removed) {
507
+ // Never a key a draining daemon still holds: registering it again
508
+ // would replace that daemon in the pool mid-turn.
509
+ do {
510
+ entry.generation += 1;
511
+ entry.key = `sandbox:${entry.projectId}:${entry.generation}`;
512
+ } while ([...drains].some((drain) => drain.key === entry.key));
513
+ notifyPool(entry);
514
+ }
515
+ await startDrain({
516
+ key: oldKey,
517
+ runtime,
518
+ directories,
519
+ to,
520
+ sandboxed: true,
521
+ unregister: true,
522
+ sessionRoots: [{ projectRoot: entry.projectRoot, worktreeRoot: entry.worktreeRoot ?? null }],
523
+ stop: async () => { await Promise.allSettled([supervisor.stop(), intake?.stop()]); },
524
+ });
525
+ };
526
+
527
+ // --- Launching ----------------------------------------------------------
528
+
529
+ const launch = async (entry) => {
530
+ const status = await probeLauncher();
531
+ if (!status.available) throw sandboxUnavailable(status.code);
532
+ if (unacceptedLimits(status).length > 0) throw sandboxUnavailable('SANDBOX_LIMITS_NOT_ACCEPTED');
533
+ if (entry.invalid) throw sandboxUnavailable('INVALID_SANDBOX_SETTING');
534
+ if (entry.idUnverified) throw sandboxUnavailable('SANDBOX_WORKTREE_IDS_UNREADABLE');
535
+ if (entry.shared) throw sandboxUnavailable(entry.shared);
536
+ // The setting this launch is built from, taken before anything waits:
537
+ // one saved meanwhile must not be answered by a daemon holding the old
538
+ // grants (`ensureStarted` compares the key).
539
+ const { setting, settingKey: launchSettingKey } = entry;
540
+ // auth.json is read-only in the sandbox: tokens are refreshed by the
541
+ // main daemon first, and the config identity is taken afterwards so
542
+ // that refresh does not make the new daemon stale at once.
543
+ await refreshOAuth();
544
+ const fingerprint = await configFingerprint();
545
+ let providerHosts;
546
+ try {
547
+ const main = daemonPool.main();
548
+ if (!main) throw new Error('main daemon unavailable');
549
+ const result = await main.request('providers.hosts', sandboxedFolders());
550
+ if (!Array.isArray(result?.hosts) || result.hosts.some((host) => typeof host !== 'string')) throw new Error('malformed');
551
+ // A provider served from the server machine or the local network
552
+ // (`localhost`, a bare name, `*.local`) is not a host the proxy may
553
+ // open; it is left out instead of failing the start, and is reached
554
+ // through an allowed local port.
555
+ providerHosts = result.hosts.filter(isAllowedSandboxHost);
556
+ if (providerHosts.length !== result.hosts.length) log('Left local provider hosts out of the sandbox', String(result.hosts.length - providerHosts.length));
557
+ } catch {
558
+ throw sandboxUnavailable('PROVIDER_HOSTS_UNAVAILABLE');
559
+ }
560
+ const worktreeDirs = entry.worktreeRoot ? await listWorktreeDirs(entry.worktreeRoot) : [];
561
+ // Taken before the launch reads the profile: one edited meanwhile makes
562
+ // this daemon stale rather than current.
563
+ const profileStamp = await profileStampNow();
564
+ let supervisor;
565
+ try {
566
+ const sandbox = await prepareSandbox({
567
+ dataDir,
568
+ agentDir: await resolveAgentDir(),
569
+ projectRoot: entry.projectRoot,
570
+ ...(entry.gitProjectId ? { projectId: entry.gitProjectId } : {}),
571
+ worktreeDirs,
572
+ serverPort: getServerPort(),
573
+ ...(readRoots ? { readRoots } : {}),
574
+ extraFolders: setting.extraFolders,
575
+ allowHosts: [...providerHosts, ...setting.allowHosts],
576
+ allowLocalPorts: setting.allowLocalPorts,
577
+ });
578
+ // The folders this daemon owns, so per-daemon options (the plugin
579
+ // config) can leave out every other project.
580
+ const options = typeof supervisorOptions === 'function'
581
+ ? supervisorOptions({ roots: [...entry.directories] })
582
+ : supervisorOptions;
583
+ supervisor = await createSupervisor({ ...options, dataDir, launcher, sandbox });
584
+ } catch (error) {
585
+ throw sandboxUnavailable(reasonOf(error));
586
+ }
587
+ // Bound before the daemon starts so its first `$BROWSER` call reaches it.
588
+ const intake = createIntake({
589
+ socketPath: supervisor.paths?.openUrlSocket,
590
+ publish: (payload) => supervisor.request('openUrl.publish', payload),
591
+ hasConnectedDevices,
592
+ });
593
+ try {
594
+ await intake.start();
595
+ } catch (error) {
596
+ log('Open request intake unavailable', error?.code);
597
+ }
598
+ try {
599
+ await supervisor.start();
600
+ } catch (error) {
601
+ await Promise.allSettled([intake.stop(), supervisor.stop?.()]);
602
+ throw sandboxUnavailable(reasonOf(error));
603
+ }
604
+ return {
605
+ supervisor,
606
+ intake,
607
+ settingKey: launchSettingKey,
608
+ fingerprint,
609
+ profileStamp,
610
+ worktreeDirs,
611
+ directories: [...entry.directories],
612
+ };
613
+ };
614
+
615
+ // A sandboxed turn that failed because Pi could not refresh its OAuth
616
+ // token: the main daemon refreshes, and the changed auth.json replaces
617
+ // this daemon at its next idle edge.
618
+ const watchDaemon = async (entry, supervisor) => {
619
+ try {
620
+ const close = await supervisor.subscribe({
621
+ onEvent: (frame) => {
622
+ if (frame?.event !== 'session.error' || !isOAuthRefreshFailure(frame.payload?.message)) return;
623
+ refreshOAuth()
624
+ .then(() => checkStale(entry))
625
+ .catch((error) => log('OAuth recovery failed', error?.code));
626
+ },
627
+ onError: () => {},
628
+ });
629
+ if (entry.supervisor === supervisor && !entry.watch) entry.watch = close;
630
+ else if (typeof close === 'function') close();
631
+ } catch (error) {
632
+ log('Sandbox daemon event watch unavailable', error?.code);
633
+ }
634
+ };
635
+
636
+ const ensureStarted = async (entry) => {
637
+ if (entry.supervisor) return entry.supervisor;
638
+ if (entry.stopping) await entry.stopping;
639
+ if (!entry.starting) {
640
+ entry.starting = launch(entry)
641
+ .then(async (launched) => {
642
+ const { supervisor, intake } = launched;
643
+ if (projects.get(entry.projectId) !== entry || stopped || launched.settingKey !== entry.settingKey) {
644
+ await Promise.allSettled([supervisor.stop(), intake.stop()]);
645
+ throw sandboxUnavailable('SANDBOX_SETTING_CHANGED');
646
+ }
647
+ entry.supervisor = supervisor;
648
+ entry.intake = intake;
649
+ entry.launchedKey = launched.settingKey;
650
+ entry.launchedFingerprint = launched.fingerprint;
651
+ entry.launchedProfile = launched.profileStamp;
652
+ entry.launchedWorktrees = launched.worktreeDirs;
653
+ entry.launchedDirectories = launched.directories;
654
+ entry.failure = null;
655
+ entry.idleSince = null;
656
+ notifyPool(entry);
657
+ void watchDaemon(entry, supervisor);
658
+ return supervisor;
659
+ })
660
+ .catch((error) => {
661
+ entry.failure = error.reason;
662
+ throw error;
663
+ })
664
+ .finally(() => { entry.starting = null; });
665
+ }
666
+ return entry.starting;
667
+ };
668
+
669
+ const requestDirectory = (payload) => {
670
+ const value = typeof payload?.directory === 'string' ? payload.directory : payload?.cwd;
671
+ return typeof value === 'string' && isAbsolute(value) ? resolve(value) : null;
672
+ };
673
+
674
+ // A folder in the project's worktree root that the running daemon has no
675
+ // grant for (a worktree added since it started).
676
+ const isUngrantedWorktree = (entry, directory) => {
677
+ if (!directory || !entry.worktreeRoot || !entry.launchedWorktrees) return false;
678
+ const root = entry.worktreeRoot;
679
+ if (directory === root || !directory.startsWith(`${root}/`)) return false;
680
+ return !entry.launchedWorktrees.some((dir) => directory === dir || directory.startsWith(`${dir}/`));
681
+ };
682
+
683
+ // A transcript the sandbox cannot open, read from its JSONL by the main
684
+ // daemon. The detail is the project stream's, not main's: anything main
685
+ // could number (epoch, input state) is dropped, and it is marked
686
+ // read-only so clients commit it as history without live state. Sends
687
+ // still go to the sandbox and fail with SANDBOX_UNAVAILABLE.
688
+ const readPersisted = async (payload, reason) => {
689
+ const main = daemonPool.main();
690
+ if (!main) throw Object.assign(new Error('The Pi session daemon is unavailable.'), { code: 'DAEMON_UNAVAILABLE' });
691
+ const result = await main.request('sessions.readPersisted', payload);
692
+ if (!result || typeof result !== 'object') return result;
693
+ const { streamEpoch: _epoch, inputState: _inputState, ...detail } = result;
694
+ return { ...detail, readOnly: true, ...(REASON_PATTERN.test(reason ?? '') ? { readOnlyReason: reason } : {}) };
695
+ };
696
+
697
+ const createRuntime = (entry) => ({
698
+ // Only a running sandbox daemon is live: pending input and the
699
+ // notification watcher fan out to it, and never start one.
700
+ isLive: () => Boolean(entry.supervisor),
701
+ request: async (command, payload) => {
702
+ // A worktree of this project outside its granted folder: lists and
703
+ // transcripts are read by the main daemon, and nothing runs there.
704
+ const directory = requestDirectory(payload);
705
+ const outside = Boolean(directory)
706
+ && (entry.outsideWorktrees ?? []).some((dir) => directory === dir || directory.startsWith(`${dir}/`));
707
+ if (outside && !MAIN_DAEMON_READS.has(command)) {
708
+ if (READ_ONLY_FALLBACK.has(command)) return readPersisted(payload, 'SANDBOX_WORKTREE_OUTSIDE_FOLDER');
709
+ throw sandboxUnavailable('SANDBOX_WORKTREE_OUTSIDE_FOLDER');
710
+ }
711
+ if ((outside || !entry.supervisor) && MAIN_DAEMON_READS.has(command)) {
712
+ const main = daemonPool.main();
713
+ if (!main) throw Object.assign(new Error('The Pi session daemon is unavailable.'), { code: 'DAEMON_UNAVAILABLE' });
714
+ const result = await main.request(command, payload);
715
+ // The list answers for this project's stream, but live state in it
716
+ // is numbered by the main daemon's: drop it. Sessions the main
717
+ // daemon still runs here reach clients through the drain merge,
718
+ // stamped with the main stream.
719
+ if (command !== 'sessions.list' || !Array.isArray(result?.sessions)) return result;
720
+ const { streamEpoch: _mainEpoch, ...rest } = result;
721
+ return {
722
+ ...rest,
723
+ sessions: result.sessions.map((item) => {
724
+ if (!item || typeof item !== 'object') return item;
725
+ const { live: _live, inputState: _inputState, ...row } = item;
726
+ return row;
727
+ }),
728
+ };
729
+ }
730
+ const active = !PASSIVE_COMMANDS.has(command);
731
+ if (active) {
732
+ entry.inFlight += 1;
733
+ entry.lastUsedAt = now();
734
+ }
735
+ try {
736
+ // A new worktree changes the grants: the running daemon drains and
737
+ // a new one with the worktree starts.
738
+ if (active && entry.supervisor && isUngrantedWorktree(entry, requestDirectory(payload))) await retire(entry);
739
+ let supervisor;
740
+ try {
741
+ supervisor = await ensureStarted(entry);
742
+ } catch (error) {
743
+ if (error?.code !== 'SANDBOX_UNAVAILABLE' || !READ_ONLY_FALLBACK.has(command)) throw error;
744
+ return await readPersisted(payload, error.reason);
745
+ }
746
+ return await supervisor.request(command, payload);
747
+ } finally {
748
+ if (active) {
749
+ entry.inFlight -= 1;
750
+ entry.lastUsedAt = now();
751
+ }
752
+ }
753
+ },
754
+ subscribe: (options) => {
755
+ if (!entry.supervisor) throw Object.assign(new Error('The project sandbox daemon is not running.'), { code: 'DAEMON_UNAVAILABLE' });
756
+ return entry.supervisor.subscribe(options);
757
+ },
758
+ health: () => {
759
+ if (!entry.supervisor) throw Object.assign(new Error('The project sandbox daemon is not running.'), { code: 'DAEMON_UNAVAILABLE' });
760
+ return entry.supervisor.health();
761
+ },
762
+ });
763
+
764
+ // Which launcher profile a launch would use now: it changes when the owner
765
+ // saves, resets or hand-edits the custom profile.
766
+ const profileStampNow = async () => {
767
+ if (typeof launcher.profile !== 'function') return null;
768
+ try {
769
+ return (await launcher.profile())?.hash ?? null;
770
+ } catch {
771
+ return null;
772
+ }
773
+ };
774
+
775
+ const profileView = async () => {
776
+ const profile = typeof launcher.profile === 'function' ? await launcher.profile() : null;
777
+ if (!profile) return null;
778
+ return {
779
+ launcher: launcher.id,
780
+ custom: profile.custom,
781
+ path: profile.path,
782
+ builtInPath: profile.builtInPath,
783
+ customPath: profile.customPath,
784
+ content: profile.content,
785
+ ...(profile.unreadable ? { unreadable: true } : {}),
786
+ };
787
+ };
788
+
789
+ // The profile changed: running sandbox daemons drain and the next command
790
+ // starts one under the new profile. A start that failed on the old one is
791
+ // forgotten so the project is not shown as unavailable for it.
792
+ const profileChanged = async () => {
793
+ for (const entry of [...projects.values()]) {
794
+ if (entry.supervisor) await retire(entry);
795
+ else if (!entry.starting && !entry.invalid) entry.failure = null;
796
+ }
797
+ return profileView();
798
+ };
799
+
800
+ // A running daemon whose Pi config files, worktrees or launcher profile
801
+ // changed since it started is replaced: it drains, and the next command
802
+ // starts a new one.
803
+ const checkStale = async (entry) => {
804
+ if (!entry.supervisor || projects.get(entry.projectId) !== entry) return false;
805
+ const supervisor = entry.supervisor;
806
+ const [fingerprint, worktrees, profileStamp] = await Promise.all([
807
+ configFingerprint(),
808
+ entry.worktreeRoot ? listWorktreeDirs(entry.worktreeRoot) : Promise.resolve([]),
809
+ profileStampNow(),
810
+ ]);
811
+ if (entry.supervisor !== supervisor) return false;
812
+ const stale = fingerprint !== entry.launchedFingerprint
813
+ || profileStamp !== (entry.launchedProfile ?? null)
814
+ || JSON.stringify(worktrees) !== JSON.stringify(entry.launchedWorktrees ?? []);
815
+ if (stale) await retire(entry);
816
+ return stale;
817
+ };
818
+
819
+ // Stop a daemon once it has had no resident sessions and no requests for
820
+ // `idleStopMs`, and replace one whose config went stale.
821
+ const checkIdle = async () => {
822
+ for (const entry of projects.values()) {
823
+ const { supervisor } = entry;
824
+ if (!supervisor) continue;
825
+ try {
826
+ if (await checkStale(entry)) continue;
827
+ } catch (error) {
828
+ log('Sandbox staleness check failed', error?.code);
829
+ }
830
+ if (entry.supervisor !== supervisor || entry.inFlight > 0) continue;
831
+ let resident;
832
+ try {
833
+ resident = (await supervisor.request('runtime.health'))?.residentSessions;
834
+ } catch {
835
+ continue;
836
+ }
837
+ if (entry.supervisor !== supervisor || entry.inFlight > 0) continue;
838
+ if (!Number.isInteger(resident) || resident > 0) {
839
+ entry.idleSince = null;
840
+ continue;
841
+ }
842
+ const since = Math.max(entry.idleSince ?? now(), entry.lastUsedAt ?? 0);
843
+ entry.idleSince = entry.idleSince ?? now();
844
+ if (now() - since >= idleStopMs) await stopDaemon(entry);
845
+ }
846
+ await resumeTrustResets();
847
+ if (trustResets.size > 0 || trustMarks.size > 0) await resetTrust([]);
848
+ };
849
+
850
+ const ensureTimer = () => {
851
+ if (timer || stopped) return;
852
+ timer = startTimer(() => checkIdle().catch(() => {}), idleCheckMs);
853
+ timer?.unref?.();
854
+ };
855
+
856
+ // Folders whose Pi trust still has to be set back to "ask" (the main
857
+ // daemon was unavailable when the project was switched off).
858
+ const trustResets = new Set();
859
+ // Folders still missing from the trust-ask list (the write failed). Kept
860
+ // apart from `trustResets`: retrying the mark must not unset a trust the
861
+ // user gave since.
862
+ const trustMarks = new Set();
863
+ // The pending resets of an earlier server process are not remembered, but
864
+ // the trust-ask list is: a folder still on it has had no trust decision
865
+ // since its sandbox was turned off (a decision removes it), so a stored
866
+ // "trusted" is from before and is reset again. Read once.
867
+ let trustListRead = !trustAsk;
868
+ const resumeTrustResets = async () => {
869
+ if (trustListRead) return;
870
+ try {
871
+ for (const directory of await trustAsk.list()) trustResets.add(directory);
872
+ trustListRead = true;
873
+ } catch (error) {
874
+ log('Could not read the trust resets', error?.code);
875
+ }
876
+ };
877
+ const resetTrust = async (directories) => {
878
+ for (const directory of directories) {
879
+ trustResets.add(directory);
880
+ if (trustAsk) trustMarks.add(directory);
881
+ }
882
+ if (trustMarks.size > 0) {
883
+ const marks = [...trustMarks];
884
+ try {
885
+ await trustAsk.add(marks);
886
+ for (const directory of marks) trustMarks.delete(directory);
887
+ } catch (error) {
888
+ log('Could not record the trust reset', error?.code);
889
+ }
890
+ }
891
+ const main = daemonPool.main();
892
+ if (!main) return;
893
+ for (const directory of [...trustResets]) {
894
+ try {
895
+ await main.request('settings.set', { scope: 'project', directory, trust: null });
896
+ trustResets.delete(directory);
897
+ } catch (error) {
898
+ // A folder removed since then has no trust to reset.
899
+ if (error?.code === 'INVALID_ARGUMENT' || error?.code === 'INVALID_DIRECTORY') trustResets.delete(directory);
900
+ else log('Could not reset project trust', error?.code);
901
+ }
902
+ }
903
+ };
904
+
905
+ // A project that stops being sandboxed: its trust goes back to "ask" so
906
+ // project extensions written in the sandbox do not run outside it
907
+ // unasked, and its daemon drains into the main daemon.
908
+ const removeEntry = async (entry, { switchOff = true } = {}) => {
909
+ projects.delete(entry.projectId);
910
+ if (entry.starting) await entry.starting.catch(() => {});
911
+ // Sessions the main daemon was still finishing before they moved into
912
+ // this sandbox stay where they are: the folder is the main daemon's
913
+ // again, so nothing is left to wait for.
914
+ for (const drain of [...drains]) {
915
+ if (drain.key !== MAIN_DAEMON_KEY || !drain.directories.some((directory) => entry.directories?.includes(directory))) continue;
916
+ await finishDrain(drain);
917
+ }
918
+ if (switchOff && !stopped) {
919
+ const worktrees = entry.worktreeRoot ? await listWorktreeDirs(entry.worktreeRoot) : [];
920
+ await resetTrust([entry.projectRoot, ...worktrees]);
921
+ }
922
+ if (entry.supervisor && switchOff && !stopped) {
923
+ await retire(entry, { to: 'off', removed: true });
924
+ return;
925
+ }
926
+ // Only while the key still holds this entry's runtime: a later entry
927
+ // for the same project registers under the same key.
928
+ daemonPool.unregister(entry.key, entry.runtime);
929
+ await stopDaemon(entry);
930
+ };
931
+
932
+ // Whether the pool may be out of line with the stored settings: no
933
+ // reconcile has succeeded yet (the server listens before its first one),
934
+ // or the last one failed. Routes refuse Pi-running commands until a
935
+ // reconcile succeeds (`needsReconcile`).
936
+ let reconcileFailed = true;
937
+ let reconcileChain = Promise.resolve();
938
+
939
+ const reconcileNow = async () => {
940
+ if (stopped) return;
941
+ const settings = await uiSettingsStore.read();
942
+ const stored = Array.isArray(settings.projects) ? settings.projects : [];
943
+ const { defaults: hostDefaults, invalid: hostDefaultsInvalid } = readSandboxDefaults(settings);
944
+ acceptedLimits = new Set(hostDefaultsInvalid ? [] : hostDefaults.acceptedLimits);
945
+ // A start refused for unaccepted limits is not a failure of the project;
946
+ // availability reports the limits themselves while they still apply.
947
+ for (const entry of projects.values()) {
948
+ if (entry.failure === 'SANDBOX_LIMITS_NOT_ACCEPTED') entry.failure = null;
949
+ }
950
+ const wanted = new Map();
951
+ for (const project of stored) {
952
+ if (!project || typeof project.id !== 'string' || typeof project.path !== 'string' || !isAbsolute(project.path)) continue;
953
+ const effective = effectiveProjectSandbox(project, settings);
954
+ if (!effective.sandboxed) continue;
955
+ wanted.set(project.id, { projectRoot: resolve(project.path), setting: effective.setting, invalid: effective.invalid });
956
+ }
957
+ for (const entry of [...projects.values()]) {
958
+ const next = wanted.get(entry.projectId);
959
+ if (!next || next.projectRoot !== entry.projectRoot) await removeEntry(entry);
960
+ }
961
+ // The id each known project's own file names, sandboxed or not: an id
962
+ // another project uses is never remembered for a sandboxed one.
963
+ const fileIds = new Map();
964
+ for (const project of stored) {
965
+ if (!project || typeof project.id !== 'string' || typeof project.path !== 'string' || !isAbsolute(project.path)) continue;
966
+ const root = resolve(project.path);
967
+ fileIds.set(project.id, { root, id: await readGitProjectId(root) });
968
+ }
969
+ const plans = new Map();
970
+ for (const [projectId, next] of wanted) {
971
+ const entry = projects.get(projectId);
972
+ // The id is taken from the project's file only the first time it is
973
+ // seen; afterwards the remembered one stands, whatever the file says.
974
+ const fileId = fileIds.get(projectId)?.id ?? null;
975
+ const taken = [...fileIds].filter(([id, other]) => id !== projectId && other.root !== next.projectRoot && other.id)
976
+ .map(([, other]) => other.id);
977
+ let gitProjectId;
978
+ // No remembered id can be had (the record is unreadable or full). The
979
+ // sandboxed agent can write the file, so its id is used only to keep
980
+ // those worktrees away from the main daemon; no sandbox starts on it.
981
+ let idUnverified = false;
982
+ try {
983
+ gitProjectId = await worktreeIds.remember(next.projectRoot, fileId, { taken });
984
+ } catch (error) {
985
+ log('Could not read the remembered worktree ids', error?.code);
986
+ if (entry?.gitProjectId && !entry.idUnverified) {
987
+ gitProjectId = entry.gitProjectId;
988
+ } else {
989
+ gitProjectId = fileId;
990
+ idUnverified = true;
991
+ }
992
+ }
993
+ const worktreeRoot = gitProjectId ? join(dataDir, 'worktree', gitProjectId) : null;
994
+ // The project is also owned under its real path, so a symlinked
995
+ // spelling of it cannot route to the main daemon.
996
+ const realRoot = await realpath(next.projectRoot).catch(() => next.projectRoot);
997
+ const directories = [...new Set([next.projectRoot, realRoot, ...(worktreeRoot ? [worktreeRoot] : [])])];
998
+ plans.set(projectId, { gitProjectId, worktreeRoot, directories, idUnverified, shared: null, realRoot, outside: [] });
999
+ }
1000
+ // Worktrees made before a project had its own folder sit in a folder
1001
+ // no sandbox owns (the one its repository's clones shared). They are
1002
+ // not granted, so sessions there are refused rather than run outside
1003
+ // the sandbox. Each names its project in its `.git` file, which only
1004
+ // code outside every sandbox can write there.
1005
+ const ownedRoots = new Set([...plans.values()].map((plan) => plan.worktreeRoot).filter(Boolean));
1006
+ for (const root of await listWorktreeDirs(join(dataDir, 'worktree'))) {
1007
+ if (ownedRoots.has(root)) continue;
1008
+ for (const directory of await listWorktreeDirs(root)) {
1009
+ const owner = await worktreeProjectRoot(directory);
1010
+ const plan = owner && [...plans.values()].find((candidate) => candidate.realRoot === owner);
1011
+ if (!plan) continue;
1012
+ plan.outside.push(directory);
1013
+ plan.directories.push(directory);
1014
+ }
1015
+ }
1016
+ // Two paths can encode to one Pi session folder (`/a/b` and `/a-b`). A
1017
+ // sandbox granted it could read the other project's transcripts and
1018
+ // would be handed its sessions, so it does not start.
1019
+ for (const [projectId, plan] of plans) {
1020
+ const own = fileIds.get(projectId).root;
1021
+ if ([...fileIds].some(([id, other]) => id !== projectId && other.root !== own
1022
+ && encodePiSessionCwd(other.root) === encodePiSessionCwd(own))) {
1023
+ plan.shared = 'SANDBOX_SESSION_FOLDER_SHARED';
1024
+ }
1025
+ }
1026
+ // Written before anything is registered or drained: a project that left
1027
+ // the sandbox is the main daemon's again, and the main daemon must
1028
+ // already refuse every folder about to be sandboxed, or a request on
1029
+ // its way there could start a runtime the drain below never sees.
1030
+ await folderRecord.set([
1031
+ ...[...projects.values()].flatMap((entry) => entry.directories ?? []),
1032
+ ...[...plans.values()].flatMap((plan) => plan.directories),
1033
+ ]);
1034
+ for (const [projectId, next] of wanted) {
1035
+ let entry = projects.get(projectId);
1036
+ const { gitProjectId, worktreeRoot, directories, idUnverified, shared, outside } = plans.get(projectId);
1037
+ const created = !entry;
1038
+ if (!entry) {
1039
+ // A daemon of this project that is still draining keeps its pool
1040
+ // key (and event stream) until it is done; the new entry takes the
1041
+ // next free one.
1042
+ let generation = 0;
1043
+ let key = `sandbox:${projectId}`;
1044
+ while ([...drains].some((drain) => drain.key === key)) {
1045
+ generation += 1;
1046
+ key = `sandbox:${projectId}:${generation}`;
1047
+ }
1048
+ entry = {
1049
+ projectId,
1050
+ key,
1051
+ generation,
1052
+ projectRoot: next.projectRoot,
1053
+ supervisor: null,
1054
+ intake: null,
1055
+ watch: null,
1056
+ starting: null,
1057
+ stopping: null,
1058
+ failure: null,
1059
+ inFlight: 0,
1060
+ idleSince: null,
1061
+ lastUsedAt: null,
1062
+ launchedKey: null,
1063
+ };
1064
+ entry.runtime = createRuntime(entry);
1065
+ projects.set(projectId, entry);
1066
+ }
1067
+ const changed = entry.settingKey !== settingKey(next.setting) || entry.invalid !== next.invalid
1068
+ || Boolean(entry.idUnverified) !== idUnverified
1069
+ || (entry.shared ?? null) !== shared;
1070
+ Object.assign(entry, {
1071
+ setting: next.setting,
1072
+ settingKey: settingKey(next.setting),
1073
+ invalid: next.invalid,
1074
+ gitProjectId,
1075
+ worktreeRoot,
1076
+ directories,
1077
+ idUnverified,
1078
+ shared,
1079
+ outsideWorktrees: outside,
1080
+ });
1081
+ if (changed) entry.failure = null;
1082
+ daemonPool.register(entry.key, { runtime: entry.runtime, directories });
1083
+ // Sessions the main daemon runs in a newly sandboxed project move
1084
+ // into the sandbox; a changed setting replaces a running daemon.
1085
+ const main = daemonPool.main();
1086
+ if (created && main) {
1087
+ await startDrain({ key: MAIN_DAEMON_KEY, runtime: main, directories, to: 'nono', sandboxed: false });
1088
+ } else if (changed && entry.supervisor && entry.launchedKey !== entry.settingKey) {
1089
+ await retire(entry);
1090
+ } else if (entry.supervisor && shared) {
1091
+ // Another project now uses a session folder this sandbox is granted:
1092
+ // running turns finish, then the next command fails closed.
1093
+ await retire(entry);
1094
+ } else if (entry.supervisor && unacceptedLimits(probe).length > 0) {
1095
+ // The owner withdrew a limit this host has: running turns finish,
1096
+ // then the next command fails closed.
1097
+ await retire(entry);
1098
+ }
1099
+ }
1100
+ // The main daemon reads this before it starts a runtime; a failed write
1101
+ // fails the reconcile, so routes stay closed rather than run a sandboxed
1102
+ // project on it.
1103
+ await recordFolders();
1104
+ await resumeTrustResets();
1105
+ if (trustResets.size > 0) await resetTrust([]);
1106
+ if (projects.size > 0 || trustResets.size > 0 || trustMarks.size > 0 || !trustListRead) ensureTimer();
1107
+ };
1108
+
1109
+ /**
1110
+ * Bring the pool in line with the stored project settings. Runs one at a
1111
+ * time: two passes working from different settings would otherwise undo
1112
+ * each other's registrations and leave a sandboxed project unowned.
1113
+ */
1114
+ const reconcile = () => {
1115
+ const run = reconcileChain.then(async () => {
1116
+ try {
1117
+ await reconcileNow();
1118
+ reconcileFailed = false;
1119
+ } catch (error) {
1120
+ reconcileFailed = true;
1121
+ throw error;
1122
+ }
1123
+ });
1124
+ reconcileChain = run.catch(() => {});
1125
+ return run;
1126
+ };
1127
+
1128
+ // The save already happened; a failed apply is retried before the next
1129
+ // Pi-running request (`needsReconcile`) and must not read as a failed save.
1130
+ const reconcileAfterSave = () => reconcile().catch((error) => log('Could not apply the saved sandbox settings', error?.code));
1131
+
1132
+ const ownedBySandbox = (directory) => {
1133
+ const owner = daemonPool.forDirectory(directory);
1134
+ for (const entry of projects.values()) if (entry.runtime === owner) return entry;
1135
+ return null;
1136
+ };
1137
+
1138
+ const worktreeBase = join(resolve(dataDir), 'worktree');
1139
+
1140
+ // A project sandboxed before it had any worktree owns no worktree root
1141
+ // yet. The first request into a PiChamber worktree nobody owns picks the
1142
+ // root up before it is routed.
1143
+ const adoptWorktree = async (directory) => {
1144
+ if (!directory.startsWith(`${worktreeBase}${sep}`) || ownedBySandbox(directory)) return;
1145
+ for (const entry of projects.values()) {
1146
+ if (entry.gitProjectId || !await readGitProjectId(entry.projectRoot)) continue;
1147
+ await reconcile();
1148
+ return;
1149
+ }
1150
+ };
1151
+
1152
+ /**
1153
+ * The folder to pick a daemon by for a folder a client named. While any
1154
+ * project is sandboxed it is spelled the way the daemon will read it
1155
+ * (trimmed, `~` as the home folder), and a spelling that reaches a
1156
+ * sandboxed project through a symlink routes to that project. Anything
1157
+ * that is not an absolute path is refused, since the pool would hand it
1158
+ * to the main daemon.
1159
+ */
1160
+ const routeDirectory = async (value) => {
1161
+ if (typeof value !== 'string' || value.length === 0 || projects.size === 0) return value;
1162
+ const trimmed = value.trim();
1163
+ const named = trimmed === '~' ? homedir() : trimmed;
1164
+ if (!isAbsolute(named)) throw Object.assign(new Error('The directory path must be absolute.'), { code: 'INVALID_ARGUMENT' });
1165
+ const directory = resolve(named);
1166
+ await adoptWorktree(directory);
1167
+ if (ownedBySandbox(directory)) return directory;
1168
+ const real = await realpath(directory).catch(() => directory);
1169
+ if (real !== directory) {
1170
+ await adoptWorktree(real);
1171
+ if (ownedBySandbox(real)) return real;
1172
+ }
1173
+ return directory;
1174
+ };
1175
+
1176
+ // The Pi session folders some sandbox daemon, running or draining, can
1177
+ // write: those of each sandboxed project root and of its worktrees.
1178
+ const sandboxWritableSessionDirs = async (agentDirectory) => {
1179
+ const roots = [
1180
+ ...[...projects.values()].map((entry) => ({ projectRoot: entry.projectRoot, worktreeRoot: entry.worktreeRoot ?? null })),
1181
+ ...[...drains].flatMap((drain) => drain.sessionRoots),
1182
+ ];
1183
+ const dirs = new Set();
1184
+ for (const { projectRoot, worktreeRoot } of roots) {
1185
+ const worktrees = worktreeRoot ? await listWorktreeDirs(worktreeRoot) : [];
1186
+ for (const cwd of [projectRoot, ...worktrees]) dirs.add(getPiSessionDirectory({ cwd, agentDir: agentDirectory }));
1187
+ }
1188
+ return dirs;
1189
+ };
1190
+
1191
+ // Where each session's transcript was last found. Every session request
1192
+ // asks while a project is sandboxed, and a transcript never moves, so the
1193
+ // search through every session folder runs once per session; afterwards
1194
+ // only the header of the remembered file is read. A file that is gone, or
1195
+ // no longer holds the session, is searched for again.
1196
+ const transcriptPaths = new Map();
1197
+ const findTranscript = async (sessionId, agentDirectory) => {
1198
+ const remembered = transcriptPaths.get(sessionId);
1199
+ if (remembered) {
1200
+ try {
1201
+ const header = await readPiSessionJsonlHeader(remembered);
1202
+ if (header.id === sessionId) return { id: sessionId, path: remembered, cwd: header.cwd };
1203
+ } catch {}
1204
+ transcriptPaths.delete(sessionId);
1205
+ }
1206
+ const matches = await findPiSessionJsonlsById({ sessionId, agentDir: agentDirectory });
1207
+ let found = matches[0] ?? null;
1208
+ if (matches.length > 1) {
1209
+ // Session ids are unique, so a second transcript with this id is a
1210
+ // copy something planted. A sandbox can only write its own project's
1211
+ // session folders: a transcript stored anywhere else is the real one.
1212
+ const writable = await sandboxWritableSessionDirs(agentDirectory);
1213
+ found = matches.find((match) => !writable.has(dirname(match.path))) ?? found;
1214
+ }
1215
+ if (found) {
1216
+ transcriptPaths.set(sessionId, found.path);
1217
+ while (transcriptPaths.size > TRANSCRIPT_PATH_LIMIT) transcriptPaths.delete(transcriptPaths.keys().next().value);
1218
+ }
1219
+ return found;
1220
+ };
1221
+
1222
+ /**
1223
+ * The folder that decides which daemon runs a persisted session, or null
1224
+ * when it has no transcript. A transcript stored in a sandboxed project's
1225
+ * session folder belongs to that project whatever its header says: the
1226
+ * sandboxed agent can rewrite the header, but it cannot move the file out
1227
+ * of the folders it was granted.
1228
+ */
1229
+ const directoryForSession = async (sessionId) => {
1230
+ const agentDirectory = await resolveAgentDir();
1231
+ const found = await findTranscript(sessionId, agentDirectory);
1232
+ if (!found) return null;
1233
+ const stored = dirname(found.path);
1234
+ for (const entry of projects.values()) {
1235
+ const worktrees = entry.worktreeRoot ? await listWorktreeDirs(entry.worktreeRoot) : [];
1236
+ for (const cwd of [entry.projectRoot, ...worktrees]) {
1237
+ if (getPiSessionDirectory({ cwd, agentDir: agentDirectory }) === stored) return cwd;
1238
+ }
1239
+ }
1240
+ return typeof found.cwd === 'string' && isAbsolute(found.cwd) ? found.cwd : null;
1241
+ };
1242
+
1243
+ /**
1244
+ * Whether a session belongs to `directories`, by what the server itself
1245
+ * finds: the folder of its transcript, or, for a session not yet written
1246
+ * to disk, the folder it is reported in. Used to check what a sandbox
1247
+ * daemon says about a session (drain answers, event frames).
1248
+ */
1249
+ const sessionWithin = async (directories, sessionId, reportedDirectory) => {
1250
+ let directory = null;
1251
+ try {
1252
+ directory = await directoryForSession(sessionId);
1253
+ } catch {
1254
+ return false;
1255
+ }
1256
+ if (!directory && typeof reportedDirectory === 'string' && isAbsolute(reportedDirectory)) directory = resolve(reportedDirectory);
1257
+ return Boolean(directory) && directories.some((owned) => isInside(owned, directory));
1258
+ };
1259
+
1260
+ const availabilityOf = (entry, status) => {
1261
+ if (!entry) return { state: 'off' };
1262
+ if (entry.invalid) return { state: 'unavailable', reason: 'INVALID_SANDBOX_SETTING' };
1263
+ if (entry.idUnverified) return { state: 'unavailable', reason: 'SANDBOX_WORKTREE_IDS_UNREADABLE' };
1264
+ if (entry.shared) return { state: 'unavailable', reason: entry.shared };
1265
+ if (status && !status.available) return { state: 'unavailable', reason: status.code };
1266
+ if (unacceptedLimits(status).length > 0) return { state: 'unavailable', reason: 'SANDBOX_LIMITS_NOT_ACCEPTED' };
1267
+ if (entry.failure) return { state: 'unavailable', reason: entry.failure };
1268
+ return { state: 'available' };
1269
+ };
1270
+
1271
+ const projectView = (project, status) => {
1272
+ const { setting, invalid } = readProjectSandbox(project);
1273
+ const entry = projects.get(project.id);
1274
+ const mode = entry ? 'nono' : 'off';
1275
+ return {
1276
+ projectId: project.id,
1277
+ mode,
1278
+ launcher: mode === 'off' ? null : 'nono',
1279
+ availability: availabilityOf(entry, status),
1280
+ // The project's own choice: `default` follows the host default.
1281
+ choice: invalid ? 'nono' : (setting?.mode ?? 'default'),
1282
+ allowHosts: setting?.allowHosts ?? [],
1283
+ allowLocalPorts: setting?.allowLocalPorts ?? [],
1284
+ extraFolders: setting?.extraFolders ?? [],
1285
+ };
1286
+ };
1287
+
1288
+ const listProjects = async () => {
1289
+ const settings = await uiSettingsStore.read();
1290
+ const stored = (Array.isArray(settings.projects) ? settings.projects : [])
1291
+ .filter((project) => project && typeof project.id === 'string');
1292
+ const status = projects.size > 0 ? await probeLauncher() : probe;
1293
+ return stored.map((project) => projectView(project, status));
1294
+ };
1295
+
1296
+ const sandboxForDirectory = (directory) => (ownedBySandbox(directory) ? { launcher: launcher.id } : null);
1297
+
1298
+ return {
1299
+ /** Launcher state for the public status route (no paths, no raw output). */
1300
+ launcherStatus: async ({ recheck = false } = {}) => {
1301
+ const status = await probeLauncher({ recheck });
1302
+ // Check again also forgets failed starts, so a project is not shown as
1303
+ // unavailable for a start that timed out once; its next command tries
1304
+ // again (and fails closed again if it must).
1305
+ if (recheck) {
1306
+ for (const entry of projects.values()) {
1307
+ if (!entry.supervisor && !entry.starting && !entry.invalid) entry.failure = null;
1308
+ }
1309
+ }
1310
+ return [{
1311
+ id: launcher.id,
1312
+ available: status.available,
1313
+ ...(status.available && status.version ? { version: status.version } : {}),
1314
+ // What this host cannot enforce, and whether the owner accepted it.
1315
+ ...(status.available && status.limits.length > 0
1316
+ ? { limits: [...status.limits], limitsAccepted: unacceptedLimits(status).length === 0 }
1317
+ : {}),
1318
+ ...(!status.available ? { reason: status.code } : {}),
1319
+ }];
1320
+ },
1321
+ listProjects,
1322
+ /** Save one project's setting, apply it, and return its public state. */
1323
+ setProjectSandbox: async (projectId, patch) => {
1324
+ await uiSettingsStore.setProjectSandbox(projectId, patch);
1325
+ await reconcileAfterSave();
1326
+ return (await listProjects()).find((project) => project.projectId === projectId);
1327
+ },
1328
+ /** The host's sandbox default. */
1329
+ sandboxDefaults: async () => {
1330
+ const { defaults, invalid } = readSandboxDefaults(await uiSettingsStore.read());
1331
+ return {
1332
+ mode: defaults.mode,
1333
+ allowHosts: [...defaults.allowHosts],
1334
+ acceptedLimits: [...defaults.acceptedLimits],
1335
+ ...(invalid ? { invalid: true } : {}),
1336
+ };
1337
+ },
1338
+ /** Save the host's sandbox default (`mode`, `allowHosts`,
1339
+ * `acceptedLimits`, or several; a field left out keeps its stored
1340
+ * value), apply it to every project that follows it (and every
1341
+ * sandboxed project's hosts and the host's accepted limits), and
1342
+ * return it. */
1343
+ setSandboxDefaults: async (patch) => {
1344
+ const { defaults } = readSandboxDefaults(await uiSettingsStore.setSandboxDefaults(patch));
1345
+ await reconcileAfterSave();
1346
+ return { mode: defaults.mode, allowHosts: [...defaults.allowHosts], acceptedLimits: [...defaults.acceptedLimits] };
1347
+ },
1348
+ /**
1349
+ * The launcher profile in use on this host, for the owner: where the
1350
+ * built-in and custom files are, which one launches use, and its text.
1351
+ * Null when the launcher has no profile here (unsupported platform).
1352
+ */
1353
+ sandboxProfile: profileView,
1354
+ /** Save the owner's custom profile and replace running sandbox daemons. */
1355
+ setSandboxProfile: async (content) => {
1356
+ if (typeof launcher.saveProfile !== 'function') throw Object.assign(new Error('No profile to edit.'), { code: 'SANDBOX_PROFILE_UNSUPPORTED' });
1357
+ await launcher.saveProfile(content);
1358
+ return profileChanged();
1359
+ },
1360
+ /** Remove the custom profile and replace running sandbox daemons. */
1361
+ resetSandboxProfile: async () => {
1362
+ if (typeof launcher.resetProfile !== 'function') throw Object.assign(new Error('No profile to edit.'), { code: 'SANDBOX_PROFILE_UNSUPPORTED' });
1363
+ await launcher.resetProfile();
1364
+ return profileChanged();
1365
+ },
1366
+ reconcile,
1367
+ /** Whether the last reconcile failed, so the pool cannot be trusted to
1368
+ * own every sandboxed project. */
1369
+ needsReconcile: () => reconcileFailed,
1370
+ routeDirectory,
1371
+ /** Whether any project is sandboxed (directory-less session commands
1372
+ * then route by the transcript's folder). */
1373
+ hasSandboxedProjects: () => projects.size > 0,
1374
+ /** The launcher a directory's sessions run under, or null. */
1375
+ sandboxFor: sandboxForDirectory,
1376
+ /**
1377
+ * Where a session runs right now, for its public row: `sandboxed` when
1378
+ * a sandbox daemon runs it, and `pendingSwitch: { to }` while it waits
1379
+ * in the old daemon to switch mode after its turn.
1380
+ */
1381
+ sessionState: (sessionId, directory) => {
1382
+ const drain = pendingBySession.get(sessionId);
1383
+ if (drain) {
1384
+ // The switch is to wherever the folder's sessions run now: a project
1385
+ // turned off and on again while a turn runs is no switch at all.
1386
+ const target = sandboxForDirectory(directory) ? 'nono' : 'off';
1387
+ return {
1388
+ sandboxed: drain.sandboxed,
1389
+ ...(drain.to && (target === 'nono') !== drain.sandboxed ? { pendingSwitch: { to: target } } : {}),
1390
+ };
1391
+ }
1392
+ return { sandboxed: Boolean(sandboxForDirectory(directory)) };
1393
+ },
1394
+ /**
1395
+ * The daemon still running a session that waits to move: `{ runtime,
1396
+ * stream }` (stream undefined for the main daemon), or null.
1397
+ */
1398
+ /**
1399
+ * Whether the daemon registered as `key` may report on a session: the
1400
+ * session must belong to a folder that daemon owns or is draining. The
1401
+ * event stream asks before it passes a project daemon's frames on.
1402
+ */
1403
+ sessionOnDaemon: (key, sessionId, directory) => {
1404
+ const folders = new Set();
1405
+ for (const entry of projects.values()) if (entry.key === key) for (const owned of entry.directories ?? []) folders.add(owned);
1406
+ for (const drain of drains) if (drain.key === key) for (const owned of drain.directories) folders.add(owned);
1407
+ return sessionWithin([...folders], sessionId, directory);
1408
+ },
1409
+ drainingSession: (sessionId) => {
1410
+ const drain = pendingBySession.get(sessionId);
1411
+ return drain ? { runtime: drain.runtime, stream: drain.stream } : null;
1412
+ },
1413
+ /**
1414
+ * The epoch a send should carry on `runtime`. A client that sends right
1415
+ * after its session moved, before it has seen the new daemon's first
1416
+ * frame, still holds the old daemon's epoch; for a short while that one
1417
+ * epoch is mapped to the new daemon's current epoch. Any other epoch is
1418
+ * passed through, so the daemon still refuses stale sends.
1419
+ */
1420
+ sendEpochFor: async (sessionId, epoch, runtime) => {
1421
+ const record = moved.get(sessionId);
1422
+ if (!record || record.fromEpoch !== epoch) return epoch;
1423
+ if (now() - record.at > MOVED_EPOCH_TTL_MS) {
1424
+ moved.delete(sessionId);
1425
+ return epoch;
1426
+ }
1427
+ try {
1428
+ const health = await runtime.request('runtime.health');
1429
+ return typeof health?.streamEpoch === 'string' && health.streamEpoch.length > 0 ? health.streamEpoch : epoch;
1430
+ } catch {
1431
+ return epoch;
1432
+ }
1433
+ },
1434
+ /**
1435
+ * PiChamber wrote Pi config (models, settings, credentials, trust):
1436
+ * running sandbox daemons drain and are replaced.
1437
+ */
1438
+ configChanged: async () => {
1439
+ for (const entry of [...projects.values()]) {
1440
+ if (entry.supervisor) await retire(entry);
1441
+ }
1442
+ },
1443
+ directoryForSession,
1444
+ checkIdle,
1445
+ checkDrains: async () => {
1446
+ await Promise.allSettled([...drains].map(pollDrain));
1447
+ },
1448
+ stop: async () => {
1449
+ stopped = true;
1450
+ if (timer) stopTimer(timer);
1451
+ if (drainTimer) stopTimer(drainTimer);
1452
+ timer = null;
1453
+ drainTimer = null;
1454
+ await Promise.allSettled([...projects.values()].map((entry) => removeEntry(entry, { switchOff: false })));
1455
+ await Promise.allSettled([...drains].map(async (drain) => {
1456
+ drains.delete(drain);
1457
+ await drain.stop?.();
1458
+ }));
1459
+ },
1460
+ };
1461
+ };