@commonlyai/cli 0.1.258 → 0.1.260

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.
@@ -14,7 +14,11 @@
14
14
  * the turn started on first use, such as tmux, and a seat it restarted. A
15
15
  * process started with COMMONLY_KEEP_PROCESS=1 is left running, and so is
16
16
  * anything it starts, even one that clears the setting; the turn's child itself
17
- * never inherits it. COMMONLY_TURN_REAP=0 turns the whole check off.
17
+ * never inherits it. A confined seat's turn does not honour the setting: what
18
+ * a confined turn leaves running is stopped whatever its environment says,
19
+ * because a process that outlives the turn would keep running with the
20
+ * turn's grants after the host has moved on to preparing the next one.
21
+ * COMMONLY_TURN_REAP=0 turns the whole check off.
18
22
  *
19
23
  * Only processes started since the turn began are read, and each one's
20
24
  * environment is only compared against the marker and the keep setting. Each
@@ -95,10 +99,12 @@ const selfAndAncestors = (table, pid) => {
95
99
  * neither kept nor under a kept one. Each one brings its descendants, except a
96
100
  * kept one and everything
97
101
  * under it, whose environments may be unreadable. The start-time window only
98
- * limits what is read; the marker is what decides. `io` is a test seam
102
+ * limits what is read; the marker is what decides. With `honorKeep: false`
103
+ * (a confined turn) nothing is kept, and a row whose environment carried the
104
+ * keep setting is returned with `keepIgnored: true`. `io` is a test seam
99
105
  * ({ table, envs, self }).
100
106
  */
101
- export const findTurnProcesses = (mark, since, io = {}) => {
107
+ export const findTurnProcesses = (mark, since, io = {}, { honorKeep = true } = {}) => {
102
108
  const { table = readProcessTable, envs = readEnvironments, self = process.pid } = io;
103
109
  if (!mark) return [];
104
110
  const rows = table();
@@ -109,7 +115,8 @@ export const findTurnProcesses = (mark, since, io = {}) => {
109
115
  const environments = envs(recent.map((row) => row.pid));
110
116
  const marked = `${TURN_MARK_ENV}=${mark}`;
111
117
  const keep = `${KEEP_PROCESS_ENV}=1`;
112
- const kept = (pid) => environments.get(pid)?.has(keep) === true;
118
+ const askedToKeep = (pid) => environments.get(pid)?.has(keep) === true;
119
+ const kept = (pid) => honorKeep && askedToKeep(pid);
113
120
  const byPid = new Map(rows.map((row) => [row.pid, row]));
114
121
  // A kept process keeps what it starts even when that drops the setting.
115
122
  const underKept = (row) => {
@@ -136,7 +143,8 @@ export const findTurnProcesses = (mark, since, io = {}) => {
136
143
  stack.push(child.pid);
137
144
  }
138
145
  }
139
- return [...found.values()];
146
+ const out = [...found.values()];
147
+ return honorKeep ? out : out.map((row) => (askedToKeep(row.pid) ? { ...row, keepIgnored: true } : row));
140
148
  };
141
149
 
142
150
  /**
@@ -147,7 +155,7 @@ export const findTurnProcesses = (mark, since, io = {}) => {
147
155
  * open until SIGKILL has gone out, so a seat stopped mid-turn still escalates.
148
156
  * `io` adds `read` (pids -> rows) to the find seam.
149
157
  */
150
- export const reapTurnProcesses = (mark, since, { graceMs = TURN_REAP_GRACE_MS, io = {} } = {}) => {
158
+ export const reapTurnProcesses = (mark, since, { graceMs = TURN_REAP_GRACE_MS, io = {}, honorKeep = true } = {}) => {
151
159
  const read = io.read || readProcesses;
152
160
  const signal = (rows, name) => {
153
161
  const now = new Map((read(rows.map((row) => row.pid)) || []).map((row) => [row.pid, row]));
@@ -156,22 +164,30 @@ export const reapTurnProcesses = (mark, since, { graceMs = TURN_REAP_GRACE_MS, i
156
164
  try { process.kill(row.pid, name); return true; } catch { return false; }
157
165
  });
158
166
  };
159
- const termed = signal(findTurnProcesses(mark, since, io), 'SIGTERM');
167
+ const termed = signal(findTurnProcesses(mark, since, io, { honorKeep }), 'SIGTERM');
160
168
  const done = termed.length === 0
161
169
  ? Promise.resolve({ killed: [] })
162
170
  : new Promise((resolve) => {
163
171
  setTimeout(() => resolve({ killed: signal(termed, 'SIGKILL').map((row) => row.pid) }), graceMs);
164
172
  });
165
- return { termed: termed.map((row) => row.pid), done };
173
+ return {
174
+ termed: termed.map((row) => row.pid),
175
+ keepIgnored: termed.filter((row) => row.keepIgnored).map((row) => row.pid),
176
+ honorKeep,
177
+ done,
178
+ };
166
179
  };
167
180
 
168
181
  /**
169
182
  * One turn's marker. `env` is the child's environment with the marker added;
170
183
  * `reap(child)` runs once the child has closed, and returns what
171
184
  * `reapTurnProcesses` does, or null when the check is off, the child never had
172
- * a pid, or the turn was already reaped.
185
+ * a pid, or the turn was already reaped. `confined` marks a confined seat's
186
+ * turn, whose reap does not honour the keep setting.
173
187
  */
174
- export const markTurn = (env, { enabled = turnReapEnabled(), now = Date.now, graceMs } = {}) => {
188
+ export const markTurn = (env, {
189
+ enabled = turnReapEnabled(), now = Date.now, graceMs, confined = false,
190
+ } = {}) => {
175
191
  if (!enabled) return { env, mark: null, reap: () => null };
176
192
  const mark = randomUUID();
177
193
  const since = now();
@@ -185,15 +201,26 @@ export const markTurn = (env, { enabled = turnReapEnabled(), now = Date.now, gra
185
201
  reap: (child, { io } = {}) => {
186
202
  if (reaped || !Number.isInteger(child?.pid) || child.pid <= 0) return null;
187
203
  reaped = true;
188
- try { return reapTurnProcesses(mark, since, { graceMs, io }); } catch { return null; }
204
+ try {
205
+ return reapTurnProcesses(mark, since, { graceMs, io, honorKeep: !confined });
206
+ } catch { return null; }
189
207
  },
190
208
  };
191
209
  };
192
210
 
193
- /** The log line for a reap that stopped something, or null. */
211
+ /**
212
+ * The log line for a reap that stopped something, or null. A confined turn's
213
+ * line offers no keep setting, and says once when one was set and not
214
+ * honoured.
215
+ */
194
216
  export const describeTurnReap = (result) => {
195
217
  if (!result?.termed?.length) return null;
196
218
  const n = result.termed.length;
197
- return `stopped ${n} process${n === 1 ? '' : 'es'} this turn left running (pid ${result.termed.join(', ')}); `
198
- + `start one with ${KEEP_PROCESS_ENV}=1 to keep it across turns`;
219
+ const stopped = `stopped ${n} process${n === 1 ? '' : 'es'} this turn left running (pid ${result.termed.join(', ')})`;
220
+ if (result.honorKeep !== false) {
221
+ return `${stopped}; start one with ${KEEP_PROCESS_ENV}=1 to keep it across turns`;
222
+ }
223
+ if (!result.keepIgnored?.length) return stopped;
224
+ return `${stopped}; ${KEEP_PROCESS_ENV}=1 was set on pid ${result.keepIgnored.join(', ')} `
225
+ + 'and is not honoured on a confined seat';
199
226
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.258",
3
+ "version": "0.1.260",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -234,6 +234,92 @@ const statOrNull = async (path) => {
234
234
  }
235
235
  };
236
236
 
237
+ // A subfolder of a seat's state, which the confined child can also write: it
238
+ // must be a real directory (created 0700 if absent), never a link the child
239
+ // left. The chmod goes through a handle opened with O_NOFOLLOW|O_DIRECTORY, so
240
+ // a link swapped in after the check (Seatbelt has no PID namespace, and a
241
+ // process a prior turn left can still run) fails the open instead of being
242
+ // followed out of the folder. `_afterCheck` is a test seam for that swap.
243
+ export const ensurePrivateDir = async (dir, { _afterCheck } = {}) => {
244
+ const refuse = () => new Error(`refusing Claude state path that is not a directory: ${dir}`);
245
+ const existing = await statOrNull(dir);
246
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) throw refuse();
247
+ if (!existing) await mkdir(dir, { mode: 0o700 });
248
+ await _afterCheck?.();
249
+ let handle;
250
+ try {
251
+ handle = await open(dir, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
252
+ } catch (err) {
253
+ if (['ELOOP', 'ENOTDIR', 'ENOENT'].includes(err?.code)) throw refuse();
254
+ throw err;
255
+ }
256
+ try {
257
+ if (!(await handle.stat()).isDirectory()) throw refuse();
258
+ await handle.chmod(0o700);
259
+ } finally {
260
+ await handle.close();
261
+ }
262
+ };
263
+
264
+ // The seat's state folder itself. A Seatbelt rule that lets the child write
265
+ // below a folder lets it write the folder too, so a child can remove it and
266
+ // leave a link in its place. Every later step of the next turn walks below this
267
+ // path (chmod, tmp, Library, the Keychains link, the auth metadata), so a link
268
+ // here refuses the turn before any of them runs. The parent is made by path;
269
+ // the folder is made and chmodded through a handle that does not follow a link.
270
+ const ensureStateFolder = async (statePath) => {
271
+ await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });
272
+ const existing = await statOrNull(statePath);
273
+ if (existing?.isSymbolicLink()) {
274
+ throw new Error(`refusing Claude state folder that is a symbolic link: ${statePath}. `
275
+ + 'A confined turn can replace its own state folder; remove the link (it is the seat\'s state, '
276
+ + 'not the place it points to) and run the turn again, which recreates the folder.');
277
+ }
278
+ await ensurePrivateDir(statePath);
279
+ };
280
+
281
+ // Removes files the host put in a child-writable folder: the one named, or
282
+ // every name `match` accepts. The folder is checked first, and nothing is
283
+ // removed if the child swapped it for a link (to the person's own ~/.claude,
284
+ // say). The check is a path check, so it holds only while no confined process
285
+ // can swap the folder: on bwrap the folders the host removes from (.claude)
286
+ // are mount points inside every jail of the seat, which the child cannot
287
+ // rename or replace (EBUSY), and between turns no child of the seat runs.
288
+ const removePrivateFile = async (dir, name, { match } = {}) => {
289
+ const dirStat = await statOrNull(dir);
290
+ if (!dirStat) return;
291
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
292
+ // eslint-disable-next-line no-console
293
+ console.warn(`[claude] not removing ${name}: ${dir} is no longer a directory`);
294
+ return;
295
+ }
296
+ const names = match ? (await readdir(dir)).filter(match) : [name];
297
+ for (const entry of names) {
298
+ try {
299
+ await rm(join(dir, entry), { force: true });
300
+ } catch (err) {
301
+ // A directory under the name is the child's, not a copy the host wrote:
302
+ // it is left, and the rest of the removal goes on.
303
+ if (!['ERR_FS_EISDIR', 'EISDIR'].includes(err?.code)) throw err;
304
+ // eslint-disable-next-line no-console
305
+ console.warn(`[claude] not removing ${join(dir, entry)}: it is not a file`);
306
+ }
307
+ }
308
+ };
309
+
310
+ // The staged name `replacePrivateFile` writes beside its target.
311
+ const stagedName = (name) => `.${name}.${randomUUID()}.tmp`;
312
+ const STAGED_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
313
+ const isStagedCopyOf = (name) => (entry) => entry.startsWith(`.${name}.`) && entry.endsWith('.tmp')
314
+ && STAGED_UUID.test(entry.slice(name.length + 2, -4));
315
+
316
+ // The login copy and any staged copy of it a failed or killed turn left: both
317
+ // hold the access token.
318
+ const removeLoginCopy = async (configDir) => {
319
+ await removePrivateFile(configDir, '.credentials.json');
320
+ await removePrivateFile(configDir, '.credentials.json', { match: isStagedCopyOf('.credentials.json') });
321
+ };
322
+
237
323
  // The non-secret account metadata Claude needs from ~/.claude.json to find its
238
324
  // login, and nothing else from that file.
239
325
  const claudeAuthMetadata = async () => {
@@ -275,11 +361,12 @@ const preparePublicClaudeState = async (ctx, { keychain = true } = {}) => {
275
361
  const stateKeychains = join(stateLibrary, 'Keychains');
276
362
  const operatorKeychains = join(homedir(), 'Library', 'Keychains');
277
363
 
278
- await mkdir(tmpPath, { recursive: true, mode: 0o700 });
279
- await mkdir(stateLibrary, { recursive: true, mode: 0o700 });
280
- await chmod(statePath, 0o700);
281
- await chmod(tmpPath, 0o700);
282
- await chmod(stateLibrary, 0o700);
364
+ // The jail writes inside this folder, so the folder or a subfolder may be a
365
+ // link a prior turn left: each is checked before the host chmods or links
366
+ // inside it.
367
+ await ensureStateFolder(statePath);
368
+ await ensurePrivateDir(tmpPath);
369
+ await ensurePrivateDir(stateLibrary);
283
370
 
284
371
  // `/usr/bin/security` resolves the default login keychain relative to HOME.
285
372
  // Keep HOME isolated while pointing that one standard location at the
@@ -302,29 +389,31 @@ const preparePublicClaudeState = async (ctx, { keychain = true } = {}) => {
302
389
  await symlink(operatorKeychains, stateKeychains);
303
390
  }
304
391
 
305
- await writeFile(
306
- configPath,
307
- `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`,
308
- { encoding: 'utf8', mode: 0o600 },
309
- );
310
- await chmod(configPath, 0o600);
392
+ // Staged and renamed, as on bwrap: a link at this name is replaced, never
393
+ // written through (F153).
394
+ await replacePrivateFile(statePath, '.claude.json', `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`);
311
395
  return { statePath, tmpPath, configPath };
312
396
  };
313
397
 
314
398
  // Writes a 0600 file into a directory the confined child can also write. The
315
399
  // directory must still be a real directory, and the file is written beside the
316
400
  // target and renamed over it, so a symlink the child left at either name is
317
- // replaced, never followed into another of the person's files.
318
- const replacePrivateFile = async (dir, name, content) => {
401
+ // replaced, never followed into another of the person's files. The directory
402
+ // check is a path check: it holds while no confined process can swap the
403
+ // directory, which on bwrap the .claude mount point inside the jail ensures.
404
+ // A failed write or rename removes the staged copy, which holds the content.
405
+ // `_writeFile` is a test seam.
406
+ export const replacePrivateFile = async (dir, name, content, { _writeFile = writeFile } = {}) => {
319
407
  const dirStat = await statOrNull(dir);
320
408
  if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
321
409
  throw new Error(`refusing to write Claude state into a non-directory: ${dir}`);
322
410
  }
323
411
  const target = join(dir, name);
324
- const staged = join(dir, `.${name}.${randomUUID()}.tmp`);
325
- await writeFile(staged, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
412
+ const staged = join(dir, stagedName(name));
326
413
  try {
327
- await chmod(staged, 0o600);
414
+ // `wx` creates the file 0600 or fails; no chmod by path after it, which
415
+ // would follow a link a concurrent child swapped in for the staged name.
416
+ await _writeFile(staged, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
328
417
  await rename(staged, target);
329
418
  } catch (err) {
330
419
  await rm(staged, { force: true });
@@ -382,7 +471,7 @@ const releaseLoginTurn = async (marker, loginPath) => {
382
471
  else await rm(join(dir, name), { force: true });
383
472
  }
384
473
  if (!live) {
385
- await rm(loginPath, { force: true });
474
+ await removeLoginCopy(dirname(loginPath));
386
475
  // Only an empty folder goes: a turn registering at this moment keeps it.
387
476
  try { await rmdir(dir); } catch { /* not empty, or already gone */ }
388
477
  }
@@ -446,7 +535,7 @@ const carryClaudeLogin = async (env, configDir, { accessOnly = false, mustOutlas
446
535
  handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
447
536
  } catch (err) {
448
537
  if (err?.code === 'ENOENT') {
449
- await rm(join(configDir, '.credentials.json'), { force: true });
538
+ await removeLoginCopy(configDir);
450
539
  return null;
451
540
  }
452
541
  if (err?.code === 'ELOOP') throw refuse();
@@ -483,22 +572,14 @@ const prepareWorkspaceBwrapClaudeState = async (ctx, { login = 'carry', seat = '
483
572
  const statePath = bwrapClaudeStatePath(ctx, seat);
484
573
  const tmpPath = join(statePath, 'tmp');
485
574
  const configDir = join(statePath, '.claude');
486
- await mkdir(statePath, { recursive: true, mode: 0o700 });
487
- await chmod(statePath, 0o700);
488
- for (const dir of [tmpPath, configDir]) {
489
- const existing = await statOrNull(dir);
490
- if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) {
491
- throw new Error(`refusing Claude state path that is not a directory: ${dir}`);
492
- }
493
- if (!existing) await mkdir(dir, { mode: 0o700 });
494
- await chmod(dir, 0o700);
495
- }
575
+ await ensureStateFolder(statePath);
576
+ for (const dir of [tmpPath, configDir]) await ensurePrivateDir(dir);
496
577
 
497
578
  const configPath = await replacePrivateFile(
498
579
  statePath, '.claude.json', `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`,
499
580
  );
500
581
  if (login === 'none') {
501
- await rm(join(configDir, '.credentials.json'), { force: true });
582
+ await removeLoginCopy(configDir);
502
583
  return { statePath, tmpPath, configPath, loginPath: null };
503
584
  }
504
585
  const loginPath = await carryClaudeLogin(ctx.env, configDir, login === 'access-only'
@@ -832,11 +913,12 @@ const runClaude = ({
832
913
  cmd, args, cwd, env, timeoutMs, credentials = [], spawnImpl = childSpawn, onSpawn, controls = {}, ownGroup = false,
833
914
  transcriptPath = null, firstOutputMs = firstOutputWindowMs(), lockProbe, stallKillGraceMs = STALL_KILL_GRACE_MS,
834
915
  processTable = readProcessTable, survivorIo, modelStream = true, turnReap = turnReapEnabled(),
835
- commandResolution = {},
916
+ commandResolution = {}, confined = false,
836
917
  }) => new Promise((resolve, reject) => {
837
918
  // Every process the turn starts inherits this marker however it detaches,
838
- // so what it leaves running is stopped once the turn has closed.
839
- const turn = markTurn(env ?? process.env, { enabled: turnReap });
919
+ // so what it leaves running is stopped once the turn has closed. A confined
920
+ // seat's turn keeps nothing: COMMONLY_KEEP_PROCESS is not honoured there.
921
+ const turn = markTurn(env ?? process.env, { enabled: turnReap, confined });
840
922
  // On Windows an npm `claude.cmd` is read, not run through cmd.exe: the
841
923
  // prompt in `args` is pod content (#2141). Off Windows this is identity.
842
924
  const launch = resolveLaunch(cmd, args, { env: turn.env, ...commandResolution });
@@ -1371,6 +1453,11 @@ const prepareArgv = async (innerArgv, ctx) => {
1371
1453
  workspaceAccess: sandboxMode === 'read-only'
1372
1454
  || (sandboxTrust === 'workspace' && !grants.includes('write')) ? 'read' : 'write',
1373
1455
  readOnlyWorkspaceEntries: sandboxTrust === 'workspace' ? ['.git'] : [],
1456
+ // A public seat's workspace is pinned: usually the scratch folder the
1457
+ // CLI made, and an `environment.workspace.path` it was given that is a
1458
+ // link refuses the turn (fail-closed). A workspace seat's folder is the
1459
+ // operator's own choice, which may be a link, and keeps following it.
1460
+ pinWorkspace: sandboxTrust === 'public',
1374
1461
  executablePath: claudeBin,
1375
1462
  statePath: ctx.publicClaudeState.statePath,
1376
1463
  mcpConfigDir: ctx.mcpConfigDir,
@@ -1440,7 +1527,12 @@ const prepareArgv = async (innerArgv, ctx) => {
1440
1527
  workspaceReadOnly: !grants.includes('write'),
1441
1528
  readOnlyWorkspaceEntries: ['.git'],
1442
1529
  homePath: statePath,
1443
- writablePaths: [statePath],
1530
+ // .claude (the login copy) and tmp are bound again on their own, after
1531
+ // the state folder: a mount point cannot be renamed or replaced from
1532
+ // inside the jail (EBUSY), so a child, this turn's or a concurrent one's,
1533
+ // cannot swap either for a link while the host writes or removes the
1534
+ // login there. The state preparation made both real directories.
1535
+ writablePaths: [statePath, join(statePath, '.claude'), join(statePath, 'tmp')],
1444
1536
  readOnlyPaths: [
1445
1537
  ctx.mcpConfigDir, commitHooksPath, originalHooksPath,
1446
1538
  ...(ctx.mcpReadDirectories || []),
@@ -1560,6 +1652,10 @@ export default {
1560
1652
  // confined too, but it answers its own team, and an outage it narrates
1561
1653
  // there is a signal, not a leak.
1562
1654
  const witnessedMcp = ctx.environment?.sandbox?.trust === 'public' ? ctx.environment?.mcp : null;
1655
+ // A stranger-facing seat keeps nothing a turn leaves running, whatever the
1656
+ // turn set (F197). A workspace seat keeps the setting for its own team's
1657
+ // long-running work in its own project.
1658
+ const reapEverything = ctx.environment?.sandbox?.trust === 'public';
1563
1659
  const workCues = publicTrust ? [] : WORK_CUES;
1564
1660
  // F118: a public seat reads its memory but is not offered a write.
1565
1661
  const memoryReadOnly = ctx.environment?.sandbox?.trust === 'public';
@@ -1783,6 +1879,7 @@ export default {
1783
1879
  survivorIo: ctx._survivorIo,
1784
1880
  turnReap: ctx._turnReap,
1785
1881
  commandResolution: ctx._commandResolution, // test seam only
1882
+ confined: reapEverything,
1786
1883
  });
1787
1884
  // TASK-440: the context this turn left, read from the transcript the
1788
1885
  // child wrote under its own env (an isolated HOME for public seats).
@@ -1858,6 +1955,7 @@ export default {
1858
1955
  survivorIo: ctx._survivorIo,
1859
1956
  turnReap: ctx._turnReap,
1860
1957
  commandResolution: ctx._commandResolution, // test seam only
1958
+ confined: reapEverything,
1861
1959
  });
1862
1960
  const contextTokens = claudeContextTokens({
1863
1961
  cwd: physicalPath(ctx.cwd), sessionId: freshId,
@@ -1870,6 +1968,12 @@ export default {
1870
1968
  stats: claudeRunStats(stdout),
1871
1969
  };
1872
1970
  }
1971
+ // F153: a Seatbelt seat with no key signs in only through the keychain.
1972
+ // When that fails, say how to give it a key instead, as bwrap does.
1973
+ if (publicNativeSandbox && !providerProxy && /not logged in/i.test(String(err?.message))) {
1974
+ err.message = `${err.message}. Sign in with \`claude\` in your own terminal on this Mac, `
1975
+ + 'or set ANTHROPIC_API_KEY (in the service env for daemon seats)';
1976
+ }
1873
1977
  throw err;
1874
1978
  } finally {
1875
1979
  if (mcpConfig?.dir) {
@@ -1880,7 +1984,7 @@ export default {
1880
1984
  // turn of the agent to finish removes it.
1881
1985
  if (publicBwrapSandbox && !workspaceBwrapSandbox && publicClaudeState?.loginPath) {
1882
1986
  if (loginTurn) await releaseLoginTurn(loginTurn, publicClaudeState.loginPath);
1883
- else await rm(publicClaudeState.loginPath, { force: true });
1987
+ else await removeLoginCopy(dirname(publicClaudeState.loginPath));
1884
1988
  }
1885
1989
  }
1886
1990
  },
@@ -372,6 +372,8 @@ export default {
372
372
  [executable, ...spawnArgs] = (ctx._wrapArgvWithSeatbelt || wrapArgvWithSeatbelt)([binary, ...args], {
373
373
  workspacePath: ctx.cwd, workspaceAccess: mode === 'read-only' ? 'read' : 'write',
374
374
  executablePath: binary, statePath: home, mcpConfigDir: home,
375
+ // Public seat: the CLI made this workspace, so it is pinned (F197).
376
+ pinWorkspace: true,
375
377
  loopbackNetworkPorts: [proxy.port], readOnlyDirectories: mcpReadDirectories,
376
378
  });
377
379
  }
@@ -917,6 +917,8 @@ export default {
917
917
  executablePath: binary,
918
918
  statePath: openCodeHome.root,
919
919
  mcpConfigDir: tempDir,
920
+ // Public seat: the CLI made this workspace, so it is pinned (F197).
921
+ pinWorkspace: true,
920
922
  loopbackNetworkPorts: providerProxy ? [providerProxy.port] : [],
921
923
  readOnlyPaths: [],
922
924
  readOnlyDirectories: mcpReadDirectories,
@@ -688,6 +688,8 @@ export default {
688
688
  executablePaths: nodePath ? [nodePath] : [],
689
689
  statePath: home,
690
690
  loopbackNetworkPorts: [proxy.port],
691
+ // Public seat: the CLI made this workspace, so it is pinned (F197).
692
+ pinWorkspace: true,
691
693
  readOnlyDirectories: [packageRoot, EXTENSION_CODE_ROOT, ...mcpReadDirectories],
692
694
  // The jailed pi holds the seat token in memory (the bridge reads it),
693
695
  // so nothing it starts may inspect it.
@@ -369,6 +369,8 @@ export default {
369
369
  workspaceAccess: mode === 'read-only' ? 'read' : 'write',
370
370
  executablePath: executable,
371
371
  statePath: home,
372
+ // Public seat: the CLI made this workspace, so it is pinned (F197).
373
+ pinWorkspace: true,
372
374
  mcpConfigDir: tempDir,
373
375
  loopbackNetworkPorts: [proxy.port],
374
376
  readOnlyDirectories: [...(packageDir ? [packageDir] : []), ...mcpReadDirectories],
@@ -22,7 +22,9 @@
22
22
  import { spawnSync } from 'child_process';
23
23
  import { lstatSync, realpathSync } from 'fs';
24
24
  import { homedir } from 'os';
25
- import { isAbsolute, join } from 'path';
25
+ import {
26
+ basename, dirname, isAbsolute, join, resolve,
27
+ } from 'path';
26
28
 
27
29
  const SANDBOX_EXEC = '/usr/bin/sandbox-exec';
28
30
  const DARWIN_MESSAGE = 'Seatbelt sandboxing is available only on macOS';
@@ -351,6 +353,53 @@ const isSymlink = (path) => {
351
353
  }
352
354
  };
353
355
 
356
+ // A folder this profile lets the jail write is one the jail can also replace:
357
+ // a write rule on a folder covers the folder's own name, so a process from an
358
+ // earlier turn can move it aside and leave a link there. The profile grants
359
+ // the folder's resolved path, so a link at that name would carry the next
360
+ // turn's write grant to wherever it points. Each such folder must therefore
361
+ // resolve to itself: its realpath must be its parent's realpath plus its own
362
+ // name. A folder that does not exist yet has nothing to resolve and is
363
+ // granted by name, as before.
364
+ //
365
+ // Returns the path to grant. It is the same realpath the check compared, read
366
+ // once, so the grant and the check cannot disagree. Seatbelt matches the
367
+ // resolved path of each access, not the name used, so a link planted after
368
+ // this read leads outside the granted path and is denied there: a swap after
369
+ // the check breaks that turn's own writes, it does not widen them. That is why
370
+ // the check is not repeated just before spawn. The time-of-check gap that
371
+ // remains is inside this function, between the two realpath reads, and a
372
+ // swap there is caught by the comparison or yields a grant on the real
373
+ // folder.
374
+ const pinnedRealpath = (given, label) => {
375
+ // Normalized first, so a trailing `.`, `..` or slash cannot make the name
376
+ // compared differ from the folder the jail is granted.
377
+ const path = resolve(given);
378
+ let stat;
379
+ try {
380
+ stat = lstatSync(path);
381
+ } catch {
382
+ return path;
383
+ }
384
+ const refuse = () => new Error(
385
+ `refusing a confined turn: its writable ${label} ${path} is a symbolic link or resolves `
386
+ + 'somewhere other than its own name. A confined turn may write only to a real folder at '
387
+ + 'the path it was given. Remove the link (the agent recreates its own folders) or point the '
388
+ + 'agent at a real folder, and run the turn again.',
389
+ );
390
+ if (stat.isSymbolicLink()) throw refuse();
391
+ let resolved;
392
+ let resolvedParent;
393
+ try {
394
+ resolved = realpathSync(path);
395
+ resolvedParent = realpathSync(dirname(path));
396
+ } catch {
397
+ throw refuse();
398
+ }
399
+ if (resolved !== join(resolvedParent, basename(path))) throw refuse();
400
+ return resolved;
401
+ };
402
+
354
403
  export const detectSeatbelt = () => {
355
404
  if (process.platform !== 'darwin') {
356
405
  return { available: false, error: DARWIN_MESSAGE };
@@ -396,6 +445,13 @@ export const buildSeatbeltProfile = ({
396
445
  // a seat credential in memory, as a public pi does. Signals are not narrowed:
397
446
  // a parent must still stop the children it started.
398
447
  processInfo = 'same-sandbox',
448
+ // Pin a writable workspace to its own name (see pinnedRealpath). Set it for
449
+ // a public seat. Its workspace is usually the scratch folder the CLI made;
450
+ // when it is an `environment.workspace.path` the operator gave and that path
451
+ // is a link, the pin refuses the turn (fail-closed) rather than follow it.
452
+ // Other seats work in a folder the operator chose, which may be a link on
453
+ // purpose, and leave this unset.
454
+ pinWorkspace = false,
399
455
  }) => {
400
456
  for (const [path, label] of [
401
457
  [workspacePath, 'workspacePath'],
@@ -427,9 +483,26 @@ export const buildSeatbeltProfile = ({
427
483
  }
428
484
  }
429
485
 
430
- const resolvedWorkspace = realpathOrSelf(workspacePath);
486
+ // Two folders here get a write grant: the state folder, and the workspace
487
+ // when it is writable. The state folder is always pinned (see
488
+ // pinnedRealpath): the CLI creates it for every seat, so it is never a link
489
+ // on purpose. The writable workspace is pinned only when the caller asks
490
+ // (pinWorkspace), which is a public seat. Its workspace is usually a
491
+ // scratch folder the CLI creates; a public seat given an
492
+ // `environment.workspace.path` that is a link is refused (fail-closed).
493
+ // Any other seat's workspace is a folder the operator chose, and a link
494
+ // there may be the operator's own, which the profile cannot tell from one a
495
+ // seat left; it keeps the link-following grant on its target, as before. A
496
+ // read-only workspace also follows links. The other write rules in this
497
+ // profile name fixed device paths (/dev/null, /dev/zero, /dev/dtracehelper,
498
+ // /dev/fd, /dev/ptmx, /dev/ttys*, /dev/tty), which no seat can replace.
499
+ //
500
+ // The turn reaper is best-effort; this pin is the boundary.
501
+ const resolvedWorkspace = workspaceAccess === 'write' && pinWorkspace
502
+ ? pinnedRealpath(workspacePath, 'workspace')
503
+ : realpathOrSelf(workspacePath);
431
504
  const resolvedExecutable = realpathOrSelf(executablePath);
432
- const resolvedState = realpathOrSelf(statePath);
505
+ const resolvedState = pinnedRealpath(statePath, 'state folder');
433
506
  const resolvedMcpConfig = mcpConfigDir ? realpathOrSelf(mcpConfigDir) : null;
434
507
  const resolvedReadOnlyPaths = [...new Set(readOnlyPaths.map(realpathOrSelf))];
435
508
  const resolvedReadOnlyDirectories = [...new Set(readOnlyDirectories.map(realpathOrSelf))];