@commonlyai/cli 0.1.259 → 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.259",
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",
@@ -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,
@@ -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))];