@commonlyai/cli 0.1.273 → 0.1.274

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.273",
3
+ "version": "0.1.274",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -85,6 +85,7 @@ import {
85
85
  normalizeSandboxTrust,
86
86
  } from '../environment.js';
87
87
  import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
88
+ import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
88
89
  import { holdWorkspaceRealpath, workspacePinDir } from '../sandbox/workspace-pin.js';
89
90
  import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from '../sandbox/mode.js';
90
91
  import { UNSANDBOXED_FLAG } from '../sandbox/host-check.js';
@@ -1657,6 +1658,13 @@ export default {
1657
1658
  // undefined and '' as absence itself; it does not need a guard, it needs
1658
1659
  // the value.
1659
1660
  const publicTrust = isConfinedTrust(ctx.environment?.sandbox?.trust);
1661
+ // Only an MCP seat has a per-turn folder (createMcpConfig). Before skills
1662
+ // mount, because they write into the workspace.
1663
+ if (publicTrust && Array.isArray(ctx.environment?.mcp) && ctx.environment.mcp.length > 0) {
1664
+ await refuseWorkspaceHoldingTurnDirs({
1665
+ workspace: ctx.cwd, seat: `${ctx.environment.sandbox.trust} Claude agents`,
1666
+ });
1667
+ }
1660
1668
  // Only a stranger-facing seat is witnessed (TASK-256). A workspace seat is
1661
1669
  // confined too, but it answers its own team, and an outage it narrates
1662
1670
  // there is a signal, not a leak.
@@ -68,7 +68,6 @@ import {
68
68
  isAbsolute,
69
69
  join,
70
70
  resolve as pathResolve,
71
- sep,
72
71
  } from 'path';
73
72
  import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
74
73
  import { isOurGrantBroker } from '../grant-broker-guard.js';
@@ -79,6 +78,7 @@ import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } fro
79
78
  import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '../memory-bridge.js';
80
79
  import { resolveSkillSource, skillsAsText } from '../skill-prompt.js';
81
80
  import { isLegacySandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
81
+ import { contains, realpathOfNearest, refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
82
82
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
83
83
  import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
84
84
  import { resolveLaunch, resolveMcpCommand, resolveWindowsCommandWithReason } from '../windows-command.js';
@@ -401,8 +401,6 @@ const statOrNull = async (path) => {
401
401
  // refused. macOS has no arg0 helper and keeps its homes where they were.
402
402
  const LEGACY_CODEX_HOMES = (home) => join(home, '.commonly', 'codex-homes');
403
403
 
404
- const contains = (outer, inner) => inner === outer || inner.startsWith(outer.endsWith(sep) ? outer : outer + sep);
405
-
406
404
  const stateHomeUnderCommonly = (ctx, home) => new Error(
407
405
  `XDG_STATE_HOME (${ctx.env?.XDG_STATE_HOME}) puts the public Codex home under ${join(home, '.commonly')}, `
408
406
  + 'which the public sandbox denies on Linux. Point it elsewhere or unset it.',
@@ -421,26 +419,6 @@ const publicCodexHomesRoot = (ctx) => {
421
419
  return root;
422
420
  };
423
421
 
424
- // The real path of a path that may not exist yet: its nearest existing
425
- // ancestor resolved, with the rest appended.
426
- const realpathOfNearest = async (path) => {
427
- const rest = [];
428
- let current = pathResolve(path);
429
- for (;;) {
430
- try {
431
- return join(await realpath(current), ...rest);
432
- } catch (err) {
433
- // Only a missing path walks up. Anything else (EACCES, ELOOP) would leave
434
- // the containment check comparing a path nobody resolved: fail closed.
435
- if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') throw err;
436
- const parent = dirname(current);
437
- if (parent === current) return join(current, ...rest);
438
- rest.unshift(basename(current));
439
- current = parent;
440
- }
441
- }
442
- };
443
-
444
422
  const operatorCodexHome = (ctx) => ctx.env?.CODEX_HOME
445
423
  || process.env.CODEX_HOME
446
424
  || join(homedir(), '.codex');
@@ -637,6 +615,7 @@ const publicPermissionProfileFlags = (
637
615
  mcpReadDirectories = [],
638
616
  codexHelperReadPaths = [],
639
617
  platform = process.platform,
618
+ workspacePath = null,
640
619
  ) => {
641
620
  if (!PUBLIC_SANDBOX_MODES.has(mode)) {
642
621
  throw new Error(
@@ -666,6 +645,16 @@ const publicPermissionProfileFlags = (
666
645
  const gitConfigKeySet = Object.entries(commitAttributionEnv || {})
667
646
  .filter(([name]) => /^GIT_CONFIG_KEY_\d+$/.test(name))
668
647
  .map(([name, value]) => `${toml(name)}=${toml(value)}`);
648
+ // The profile denies $TMPDIR and /tmp, so a shell heredoc fails. Set for the
649
+ // model's shell alone: codex, its MCP child and the per-turn folder keep the
650
+ // host's temp root, which spawn refuses to find in the workspace. The
651
+ // workspace is the one folder this shell already writes. zsh, the macOS
652
+ // login shell codex runs, takes its heredoc file from TMPPREFIX and ignores
653
+ // TMPDIR. A read-only seat has no such folder, so its heredocs keep failing.
654
+ const shellTmpDir = workspaceAccess === 'write' && workspacePath
655
+ ? [`${toml('TMPDIR')}=${toml(workspacePath)}`, `${toml('TMPPREFIX')}=${toml(join(workspacePath, 'zsh'))}`]
656
+ : [];
657
+ const shellSet = [...gitConfigKeySet, ...shellTmpDir];
669
658
  const filesystem = [
670
659
  '":minimal"="read"',
671
660
  '"~/.commonly"="deny"',
@@ -686,7 +675,7 @@ const publicPermissionProfileFlags = (
686
675
  ...codexHelperReadPaths.map((path) => `${toml(path)}="read"`),
687
676
  ].join(',');
688
677
  const shellEnvironment = [
689
- 'PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_*',
678
+ 'PATH', 'HOME', 'TMPDIR', 'TMPPREFIX', 'LANG', 'LC_*',
690
679
  ...(commitHooksPath ? [
691
680
  ...gitConfigEnv,
692
681
  'COMMONLY_AGENT_GIT_CONFIG_INDEX',
@@ -715,9 +704,7 @@ const publicPermissionProfileFlags = (
715
704
  // Codex's default name filter treats GIT_CONFIG_KEY_n as sensitive. Set
716
705
  // only those key names after filtering; their corresponding values stay
717
706
  // in the allowlisted environment instead of riding argv.
718
- ...(gitConfigKeySet.length
719
- ? ['-c', `shell_environment_policy.set={${gitConfigKeySet.join(',')}}`]
720
- : []),
707
+ ...(shellSet.length ? ['-c', `shell_environment_policy.set={${shellSet.join(',')}}`] : []),
721
708
  ];
722
709
  };
723
710
 
@@ -797,6 +784,7 @@ const buildArgs = ({
797
784
  codexHelperReadPaths = [],
798
785
  modelBaseUrl = null,
799
786
  platform = process.platform,
787
+ workspacePath = null,
800
788
  }) => {
801
789
  const publicSandbox = publicSandboxMode !== null;
802
790
  // `--dangerously-bypass-approvals-and-sandbox` disables codex CLI's
@@ -822,6 +810,7 @@ const buildArgs = ({
822
810
  mcpReadDirectories,
823
811
  codexHelperReadPaths,
824
812
  platform,
813
+ workspacePath,
825
814
  ),
826
815
  ]
827
816
  : ['--dangerously-bypass-approvals-and-sandbox'];
@@ -1024,6 +1013,10 @@ export default {
1024
1013
  memoryReadOnly: sandbox?.trust === 'public',
1025
1014
  });
1026
1015
 
1016
+ const workspacePath = sandbox?.trust === 'public'
1017
+ ? await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'public Codex agents' })
1018
+ : null;
1019
+
1027
1020
  // Per-spawn temp dir for --output-last-message. Cleaned up in `finally`
1028
1021
  // so a crash in the middle of the spawn doesn't leak files in $TMPDIR.
1029
1022
  const dir = await mkdtemp(join(tmpdir(), 'commonly-codex-'));
@@ -1090,6 +1083,7 @@ export default {
1090
1083
  codexHelperReadPaths: publicCodexHome?.helperReadPaths || [],
1091
1084
  modelBaseUrl,
1092
1085
  platform: ctx._platform || process.platform,
1086
+ workspacePath,
1093
1087
  });
1094
1088
  // childEnv is derived from the process environment, so the bootstrap export has to be
1095
1089
  // taken back out: the declaration above moved our server onto the file,
@@ -23,6 +23,7 @@ import { startEgressProxy } from '../egress-proxy.js';
23
23
  import { startInstanceProxy } from '../instance-proxy.js';
24
24
  import { prepareMcpSpawn, selectedMcpVersionDir } from '../mcp-home.js';
25
25
  import { detectSeatbelt, wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
26
+ import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
26
27
  import { buildMemoryPreamble } from '../memory-bridge.js';
27
28
  import { commonlyMcpServer } from '../default-environment.js';
28
29
  import { effectiveSandboxTrust, refuseWorkspaceTrust, validateEnvironmentSpec } from '../environment.js';
@@ -370,6 +371,7 @@ export default {
370
371
  }
371
372
  const seatbelt = (ctx._detectSeatbelt || detectSeatbelt)();
372
373
  if (!seatbelt.available) throw new Error(`dsh adapter: a confined seat needs Seatbelt: ${seatbelt.error}`);
374
+ await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'confined dsh agents' });
373
375
  }
374
376
  if (!ctx.environment?.provider || !ctx.environment?.model) {
375
377
  throw new Error('dsh requires environment.provider and environment.model');
@@ -16,6 +16,7 @@ import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js
16
16
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
17
17
  import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
18
18
  import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
19
+ import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
19
20
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
20
21
 
21
22
  // A version enters this list only after a real headless turn with that binary.
@@ -291,26 +292,31 @@ export default {
291
292
  // eslint-disable-next-line no-console
292
293
  console.warn(`[goose] installed ${version || 'unknown'} differs from smoke-tested ${TESTED_GOOSE_VERSIONS.join(', ')}; private seat continues`);
293
294
  }
294
- const home = await mkdtemp(join(tmpdir(), 'commonly-goose-'));
295
+ if (isPublic) await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'public Goose agents' });
296
+ // Keep child-writable state separate from adapter-owned config and keys, as
297
+ // qwen does (F219). The jail reads tempDir and cannot change it: the
298
+ // Commonly MCP child runs in the jail, so the credential stays readable.
299
+ const tempDir = await mkdtemp(join(tmpdir(), 'commonly-goose-'));
300
+ const home = await mkdtemp(join(tmpdir(), 'commonly-goose-home-'));
295
301
  let proxy;
296
302
  try {
297
303
  const credential = writeCredentialFile(ctx.runtimeToken, {
298
- root: home, agentName: ctx.agentName || 'agent',
304
+ root: tempDir, agentName: ctx.agentName || 'agent',
299
305
  });
306
+ // No tokenFile: nothing here reads one, so the token is never on disk.
300
307
  if (isPublic) proxy = await startProviderProxy({
301
- provider: configured, keyFile, tokenFile: join(home, 'provider-proxy-token'), adapterLabel: 'Goose',
302
- pinnedModel: model,
308
+ provider: configured, keyFile, adapterLabel: 'Goose', pinnedModel: model,
303
309
  });
304
310
  const mcpReadDirectories = [];
305
311
  const publicExtensions = [];
306
312
  // Node's compiled-in OpenSSL config can sit outside the permitted tree
307
313
  // (including hostedtoolcache on CI). Use our empty config, retaining
308
314
  // Node's bundled TLS roots, instead of granting host configuration reads.
309
- const opensslConfig = join(home, 'openssl.cnf');
315
+ const opensslConfig = join(tempDir, 'openssl.cnf');
310
316
  if (isPublic) await writeFile(opensslConfig, '', { mode: 0o600 });
311
317
  // The recipe's own directory is the template include root, so it holds
312
- // the recipe alone, never the proxy token or the credential file.
313
- const recipeDir = join(home, 'recipe');
318
+ // the recipe alone, never the credential file.
319
+ const recipeDir = join(tempDir, 'recipe');
314
320
  const recipePath = join(recipeDir, 'public-recipe.json');
315
321
  const args = [
316
322
  'run', '--no-session', ...(!isPublic ? ['--no-profile', '--with-builtin', 'developer'] : []),
@@ -347,7 +353,7 @@ export default {
347
353
  ...(isPublic ? { OPENSSL_CONF: opensslConfig } : {}),
348
354
  OPENAI_HOST: proxy ? new URL(proxy.baseURL).origin : baseUrl.origin,
349
355
  OPENAI_BASE_PATH: `${new URL(proxy?.baseURL || baseUrl).pathname.replace(/\/$/, '')}/chat/completions`.replace(/^\//, ''),
350
- OPENAI_API_KEY: proxy ? (await readFile(proxy.tokenFile, 'utf8')).trim() : key,
356
+ OPENAI_API_KEY: proxy ? proxy.token : key,
351
357
  };
352
358
  withholdRuntimeCredential(env, { credentialFile: credential?.path || null });
353
359
  const requestedTimeout = Number(ctx.timeoutMs);
@@ -366,12 +372,12 @@ export default {
366
372
  ...(sandbox.filesystem || {}), 'write-outside': [home],
367
373
  } },
368
374
  }, { workspacePath: ctx.cwd, homePath: home,
369
- readOnlyPaths: [binary, process.execPath, ...mcpReadDirectories] });
375
+ readOnlyPaths: [tempDir, binary, process.execPath, ...mcpReadDirectories] });
370
376
  } else {
371
377
  if ((ctx._platform || process.platform) !== 'darwin') throw new Error('goose adapter: Seatbelt requires macOS');
372
378
  [executable, ...spawnArgs] = (ctx._wrapArgvWithSeatbelt || wrapArgvWithSeatbelt)([binary, ...args], {
373
379
  workspacePath: ctx.cwd, workspaceAccess: mode === 'read-only' ? 'read' : 'write',
374
- executablePath: binary, statePath: home, mcpConfigDir: home,
380
+ executablePath: binary, statePath: home, mcpConfigDir: tempDir,
375
381
  // Public seat: the CLI made this workspace, so it is pinned (F197).
376
382
  pinWorkspace: true,
377
383
  loopbackNetworkPorts: [proxy.port], readOnlyDirectories: mcpReadDirectories,
@@ -386,7 +392,7 @@ export default {
386
392
  return { text, newSessionId: null };
387
393
  } finally {
388
394
  try { await proxy?.close(); } finally {
389
- await rm(home, { recursive: true, force: true });
395
+ await Promise.all([tempDir, home].map((path) => rm(path, { recursive: true, force: true })));
390
396
  }
391
397
  }
392
398
  },
@@ -15,6 +15,7 @@ import { normalizeSandboxTrust, refuseWorkspaceTrust, validateEnvironmentSpec }
15
15
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
16
16
  import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
17
17
  import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
18
+ import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
18
19
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
19
20
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
20
21
  import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
@@ -281,6 +282,7 @@ export default {
281
282
  const executable = symlinkedBinary
282
283
  ? join(realpathSync(dirname(binary)), basename(binary)) : binary;
283
284
  const packageDir = symlinkedBinary ? dirname(realpathSync(executable)) : null;
285
+ if (isPublic) await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'public Qwen agents' });
284
286
  const tempDir = await mkdtemp(join(tmpdir(), 'commonly-qwen-'));
285
287
  await chmod(tempDir, 0o700);
286
288
  // Keep child-writable state separate from adapter-owned config and keys.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The folder an adapter keeps one turn's credential in sits under the temp
3
+ * root. The sandbox denies that root by leaving it out of every grant, so a
4
+ * workspace that holds it undoes the denial: the workspace grant covers it,
5
+ * and code in the jail can read the credential and replace the turn's files
6
+ * (F219; measured on a real `codex sandbox`, where a workspace of $TMPDIR read
7
+ * the credential and a project folder could not).
8
+ *
9
+ * Checked before the folder exists, against the root, so a refused turn writes
10
+ * nothing. OpenCode has its own check, which also walks links and git worktrees.
11
+ */
12
+ import { realpath } from 'fs/promises';
13
+ import { tmpdir } from 'os';
14
+ import {
15
+ basename, dirname, join, resolve, sep,
16
+ } from 'path';
17
+
18
+ export const contains = (outer, inner) => inner === outer
19
+ || inner.startsWith(outer.endsWith(sep) ? outer : outer + sep);
20
+
21
+ // The real path of a path that may not exist yet: its nearest existing
22
+ // ancestor resolved, with the rest appended. realpath(3) also returns the
23
+ // disk's own spelling, which matters on a volume that folds case.
24
+ export const realpathOfNearest = async (path) => {
25
+ const rest = [];
26
+ let current = resolve(path);
27
+ for (;;) {
28
+ try {
29
+ return join(await realpath(current), ...rest);
30
+ } catch (err) {
31
+ // Only a missing path walks up. Anything else (EACCES, ELOOP) would leave
32
+ // the containment check comparing a path nobody resolved: fail closed.
33
+ if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') throw err;
34
+ const parent = dirname(current);
35
+ if (parent === current) return join(current, ...rest);
36
+ rest.unshift(basename(current));
37
+ current = parent;
38
+ }
39
+ }
40
+ };
41
+
42
+ /** Throws when `workspace` holds the temp root; returns its real path otherwise. */
43
+ export const refuseWorkspaceHoldingTurnDirs = async ({
44
+ workspace, seat, tempRoot = tmpdir(),
45
+ }) => {
46
+ const [realWorkspace, realRoot] = await Promise.all([
47
+ realpathOfNearest(workspace || process.cwd()),
48
+ realpathOfNearest(tempRoot),
49
+ ]);
50
+ if (contains(realWorkspace, realRoot)) {
51
+ throw new Error(`${seat} cannot run in ${workspace || process.cwd()}: it contains the temp folder (${tempRoot}) `
52
+ + 'where each turn keeps the agent\'s credential, which the sandbox would then expose. '
53
+ + 'Run it in a project folder, or set TMPDIR outside it.');
54
+ }
55
+ return realWorkspace;
56
+ };