@commonlyai/cli 0.1.259 → 0.1.261

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.259",
3
+ "version": "0.1.261",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -913,11 +913,12 @@ const runClaude = ({
913
913
  cmd, args, cwd, env, timeoutMs, credentials = [], spawnImpl = childSpawn, onSpawn, controls = {}, ownGroup = false,
914
914
  transcriptPath = null, firstOutputMs = firstOutputWindowMs(), lockProbe, stallKillGraceMs = STALL_KILL_GRACE_MS,
915
915
  processTable = readProcessTable, survivorIo, modelStream = true, turnReap = turnReapEnabled(),
916
- commandResolution = {},
916
+ commandResolution = {}, confined = false,
917
917
  }) => new Promise((resolve, reject) => {
918
918
  // Every process the turn starts inherits this marker however it detaches,
919
- // so what it leaves running is stopped once the turn has closed.
920
- 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 });
921
922
  // On Windows an npm `claude.cmd` is read, not run through cmd.exe: the
922
923
  // prompt in `args` is pod content (#2141). Off Windows this is identity.
923
924
  const launch = resolveLaunch(cmd, args, { env: turn.env, ...commandResolution });
@@ -1452,6 +1453,11 @@ const prepareArgv = async (innerArgv, ctx) => {
1452
1453
  workspaceAccess: sandboxMode === 'read-only'
1453
1454
  || (sandboxTrust === 'workspace' && !grants.includes('write')) ? 'read' : 'write',
1454
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',
1455
1461
  executablePath: claudeBin,
1456
1462
  statePath: ctx.publicClaudeState.statePath,
1457
1463
  mcpConfigDir: ctx.mcpConfigDir,
@@ -1646,6 +1652,10 @@ export default {
1646
1652
  // confined too, but it answers its own team, and an outage it narrates
1647
1653
  // there is a signal, not a leak.
1648
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';
1649
1659
  const workCues = publicTrust ? [] : WORK_CUES;
1650
1660
  // F118: a public seat reads its memory but is not offered a write.
1651
1661
  const memoryReadOnly = ctx.environment?.sandbox?.trust === 'public';
@@ -1869,6 +1879,7 @@ export default {
1869
1879
  survivorIo: ctx._survivorIo,
1870
1880
  turnReap: ctx._turnReap,
1871
1881
  commandResolution: ctx._commandResolution, // test seam only
1882
+ confined: reapEverything,
1872
1883
  });
1873
1884
  // TASK-440: the context this turn left, read from the transcript the
1874
1885
  // child wrote under its own env (an isolated HOME for public seats).
@@ -1944,6 +1955,7 @@ export default {
1944
1955
  survivorIo: ctx._survivorIo,
1945
1956
  turnReap: ctx._turnReap,
1946
1957
  commandResolution: ctx._commandResolution, // test seam only
1958
+ confined: reapEverything,
1947
1959
  });
1948
1960
  const contextTokens = claudeContextTokens({
1949
1961
  cwd: physicalPath(ctx.cwd), sessionId: freshId,
@@ -324,6 +324,16 @@ const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
324
324
  && typeof value === 'string'
325
325
  && value.includes(ctx.runtimeToken);
326
326
  if (carriesRuntimeToken) {
327
+ // Codex reads these as its own credential or model route, so a value
328
+ // forwarded under one of these names would be sent to the model endpoint.
329
+ // Compared in upper case on every platform: Windows env names are
330
+ // case-insensitive, and refusing a lower-case spelling elsewhere costs nothing.
331
+ if (CODEX_OWN_AUTH_ENVS.includes(key.toUpperCase())) {
332
+ throw new Error(
333
+ `codex MCP server ${server.name} sets ${key} to the seat token; codex reads ${key} `
334
+ + 'as its own credential, so declare the token under another name',
335
+ );
336
+ }
327
337
  if (forwardedEnv[key] !== undefined && forwardedEnv[key] !== value) {
328
338
  throw new Error(
329
339
  `codex MCP servers declare conflicting token-bearing values for env var ${key}`,
@@ -431,10 +441,12 @@ const realpathOfNearest = async (path) => {
431
441
  }
432
442
  };
433
443
 
444
+ const operatorCodexHome = (ctx) => ctx.env?.CODEX_HOME
445
+ || process.env.CODEX_HOME
446
+ || join(homedir(), '.codex');
447
+
434
448
  const preparePublicCodexHome = async (ctx, childEnv) => {
435
- const operatorHome = ctx.env?.CODEX_HOME
436
- || process.env.CODEX_HOME
437
- || join(homedir(), '.codex');
449
+ const operatorHome = operatorCodexHome(ctx);
438
450
  const identity = ctx.agentName || ctx.cwd || 'anonymous';
439
451
  const identityHash = createHash('sha256').update(identity).digest('hex').slice(0, 20);
440
452
  const homesRoot = publicCodexHomesRoot(ctx);
@@ -704,6 +716,66 @@ const publicPermissionProfileFlags = (
704
716
  ];
705
717
  };
706
718
 
719
+ // F188: the host's OpenAI-compatible model route, for a public seat. That seat
720
+ // runs with `--ignore-user-config`, so config.toml's `openai_base_url` never
721
+ // loads, and codex-cli 0.162.1 does not read the OPENAI_BASE_URL env either
722
+ // (Growth's D252 walk, 11-05): a host routed at LiteLLM or another
723
+ // OpenAI-compatible endpoint sent every turn to api.openai.com and got a 401.
724
+ // The env is the declaration, as ANTHROPIC_BASE_URL is for the claude adapter;
725
+ // buildArgs passes it on as `-c openai_base_url=...`, the top-level key the
726
+ // 0.162.1 binary carries. Only a plain http(s) URL: one carrying credentials,
727
+ // a query or a fragment could put a key into argv, so it is refused rather
728
+ // than trimmed, and the refusal does not echo the value. The key itself stays
729
+ // where codex already reads it (auth.json in the public home, or the env).
730
+ export const publicModelRouteBaseUrl = (source = {}) => {
731
+ const raw = typeof source.OPENAI_BASE_URL === 'string' ? source.OPENAI_BASE_URL.trim() : '';
732
+ if (!raw) return null;
733
+ let url = null;
734
+ try { url = new URL(raw); } catch { /* refused below */ }
735
+ if (!url || !['http:', 'https:'].includes(url.protocol) || !url.hostname
736
+ || url.username || url.password || /[?#\s]/.test(raw)) {
737
+ throw new Error('codex adapter: OPENAI_BASE_URL must be a plain http(s) URL with no credentials, '
738
+ + 'query or fragment (e.g. https://litellm.example.com/v1); fix or unset it before a public seat runs.');
739
+ }
740
+ return raw;
741
+ };
742
+
743
+ // F188 guard: `openai_base_url` moves wherever the seat's credential goes, a
744
+ // ChatGPT session included (the built-in provider swaps only its default base
745
+ // for a ChatGPT login). So the route is forwarded only to a seat that signs in
746
+ // with an API key, and a ChatGPT session token is never pointed at a URL from
747
+ // the env. The public home links the operator's auth.json, so that file decides:
748
+ // its `auth_mode` alone is read (codex-cli 0.162.1 writes "apikey", "chatgpt",
749
+ // "chatgptAuthTokens", ...), the parsed object is dropped, and nothing else from
750
+ // it is kept or logged. Only "apikey" counts as a key; a file with any other
751
+ // mode, no mode, or that does not parse is treated as a login and fails closed,
752
+ // whatever OPENAI_API_KEY says, since codex prefers its stored login. With no
753
+ // auth.json, an OPENAI_API_KEY or CODEX_API_KEY in the env is the key. A
754
+ // CODEX_ACCESS_TOKEN in the env is a token codex sends in place of either, so
755
+ // it counts as a login whatever auth.json says.
756
+ const CODEX_OWN_AUTH_ENVS = ['OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_ACCESS_TOKEN', 'OPENAI_BASE_URL'];
757
+
758
+ const CHATGPT_ROUTE_IGNORED = 'OPENAI_BASE_URL is ignored while Codex is signed in with ChatGPT; '
759
+ + 'use an API key for a custom route';
760
+
761
+ const envSet = (source, name) => typeof source[name] === 'string' && source[name].trim() !== '';
762
+
763
+ export const codexAuthKind = async (operatorHome, source = {}) => {
764
+ if (envSet(source, 'CODEX_ACCESS_TOKEN')) return 'login';
765
+ let text = null;
766
+ try {
767
+ text = await readFile(join(operatorHome, 'auth.json'), 'utf8');
768
+ } catch (err) {
769
+ if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') return 'login';
770
+ }
771
+ if (text === null) {
772
+ return envSet(source, 'OPENAI_API_KEY') || envSet(source, 'CODEX_API_KEY') ? 'apikey' : 'none';
773
+ }
774
+ let mode = null;
775
+ try { mode = JSON.parse(text)?.auth_mode ?? null; } catch { /* unreadable: a login */ }
776
+ return mode === 'apikey' ? 'apikey' : 'login';
777
+ };
778
+
707
779
  // Build the argv after the `codex` binary. Resume vs new turn is a
708
780
  // subcommand-level distinction in modern codex, not an option flag — keep
709
781
  // that detail isolated here so the spawn path stays linear.
@@ -718,6 +790,7 @@ const buildArgs = ({
718
790
  commitAttributionEnv = null,
719
791
  mcpReadDirectories = [],
720
792
  codexHelperReadPaths = [],
793
+ modelBaseUrl = null,
721
794
  }) => {
722
795
  const publicSandbox = publicSandboxMode !== null;
723
796
  // `--dangerously-bypass-approvals-and-sandbox` disables codex CLI's
@@ -749,6 +822,10 @@ const buildArgs = ({
749
822
  '--json',
750
823
  '--skip-git-repo-check',
751
824
  ...executionPolicy,
825
+ // F188: only a public seat drops config.toml; a private one keeps its own
826
+ // route there. In `common`, so it lands after `exec` / `exec resume <id>`,
827
+ // the only position codex parses it from.
828
+ ...(publicSandbox && modelBaseUrl ? ['-c', `openai_base_url=${toml(modelBaseUrl)}`] : []),
752
829
  ...(model ? ['--model', String(model)] : []),
753
830
  ...(effort ? ['-c', 'model_reasoning_effort=' + toml(effort)] : []),
754
831
  ...mcpFlags,
@@ -978,6 +1055,16 @@ export default {
978
1055
  const publicSandboxMode = sandbox?.trust === 'public'
979
1056
  ? sandbox?.mode ?? 'workspace'
980
1057
  : null;
1058
+ // Checked before the public home is prepared, so a refused route changes nothing.
1059
+ // Only a seat that will forward the URL validates it: a ChatGPT host with an
1060
+ // OPENAI_BASE_URL set for some other tool keeps running, as it did before.
1061
+ let modelBaseUrl = null;
1062
+ const routeEnv = ctx.env || process.env;
1063
+ if (publicSandboxMode !== null && String(routeEnv.OPENAI_BASE_URL || '').trim()) {
1064
+ const authKind = await codexAuthKind(operatorCodexHome(ctx), routeEnv);
1065
+ if (authKind === 'apikey') modelBaseUrl = publicModelRouteBaseUrl(routeEnv);
1066
+ else if (authKind === 'login') process.stderr.write(`[codex] ${CHATGPT_ROUTE_IGNORED}\n`);
1067
+ }
981
1068
  const childEnv = { ...(ctx.env || process.env), ...mcp.forwardedEnv };
982
1069
  const publicCodexHome = publicSandboxMode !== null
983
1070
  ? await preparePublicCodexHome(ctx, childEnv)
@@ -993,6 +1080,7 @@ export default {
993
1080
  effort: ctx.environment?.effort,
994
1081
  commitAttributionEnv: ctx.commitAttributionEnv,
995
1082
  codexHelperReadPaths: publicCodexHome?.helperReadPaths || [],
1083
+ modelBaseUrl,
996
1084
  });
997
1085
  // childEnv is derived from the process environment, so the bootstrap export has to be
998
1086
  // taken back out: the declaration above moved our server onto the file,
@@ -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))];