@commonlyai/cli 0.1.334 → 0.1.336

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.334",
3
+ "version": "0.1.336",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -3199,6 +3199,11 @@ export const performRun = ({
3199
3199
  runtimeToken: opened.token,
3200
3200
  instanceUrl,
3201
3201
  agentName,
3202
+ // The seat's local key (F306), which a Codex seat's own home is keyed
3203
+ // on (F450): `name@instance` for a second instance, the bare name for
3204
+ // every other seat, including one saved under its name that runs a
3205
+ // non-default instance, so no existing seat moves to a new home.
3206
+ seatKey: stateKey,
3202
3207
  metadata: { event },
3203
3208
  };
3204
3209
  // Supervised or plain, a failure is thrown exactly as the adapter's own
@@ -90,7 +90,7 @@ import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
90
90
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
91
91
  import { startProviderProxy } from '../provider-proxy.js';
92
92
  import { resolveLaunch, resolveMcpCommand, resolveWindowsCommandWithReason } from '../windows-command.js';
93
- import { codexContextTokens, codexHomeFor } from '../session-recycle.js';
93
+ import { codexContextTokens, codexHomeFor, codexRolloutPath } from '../session-recycle.js';
94
94
 
95
95
  // Default timeout for a single codex spawn (exec mode).
96
96
  //
@@ -370,10 +370,10 @@ const statOrNull = async (path) => {
370
370
  // refused. macOS has no arg0 helper and keeps its homes where they were.
371
371
  const LEGACY_CODEX_HOMES = (home) => join(home, '.commonly', 'codex-homes');
372
372
 
373
- const stateHomeUnderCommonly = (ctx, home) => new Error(
374
- `XDG_STATE_HOME (${ctx.env?.XDG_STATE_HOME}) puts the public Codex home under ${join(home, '.commonly')}, `
375
- + 'which the public sandbox denies on Linux. Point it elsewhere or unset it.',
376
- );
373
+ const stateHomeUnderCommonly = (ctx, home, seat = 'public') => Object.assign(new Error(
374
+ `XDG_STATE_HOME (${ctx.env?.XDG_STATE_HOME}) puts the ${seat} Codex home under ${join(home, '.commonly')}, `
375
+ + `which the ${seat} sandbox denies on Linux. Point it elsewhere or unset it.`,
376
+ ), { code: 'state_home_under_commonly' });
377
377
 
378
378
  const publicCodexHomesRoot = (ctx) => {
379
379
  const home = ctx._homeDir || homedir();
@@ -402,12 +402,139 @@ const operatorCodexHome = (ctx) => ctx.env?.CODEX_HOME
402
402
  || process.env.CODEX_HOME
403
403
  || join(homedir(), '.codex');
404
404
 
405
+ // F445: on Linux a private seat runs with a Codex home of its own, beside the
406
+ // public ones, so the folder its shell can see holds no other session's logs,
407
+ // databases or history: F444 denied a shared home entry by entry, from a
408
+ // listing taken when the turn's keys are built, and anything another session
409
+ // wrote there under a new name, or during a command, stayed readable. The home
410
+ // starts with no history: nothing is copied from the shared one, which holds
411
+ // other sessions' history, the thing being fenced off. What the agent is meant
412
+ // to remember lives in Commonly. Only the person's own setup is carried over,
413
+ // as symlinks Codex follows outside the sandbox: their login, config.toml (a
414
+ // private seat keeps its own config) and global AGENTS.md. macOS denies the
415
+ // shared home whole under Seatbelt and keeps running from it.
416
+ const PRIVATE_CODEX_HOMES = 'codex-private-homes';
417
+ const PRIVATE_HOME_LINKS = Object.freeze(['auth.json', 'config.toml', 'AGENTS.md']);
418
+
419
+ /** The shared Codex home a private seat's setup comes from. */
420
+ const privateSourceCodexHome = (ctx, env) => pathResolve(
421
+ ctx.cwd || process.cwd(),
422
+ env?.CODEX_HOME || join(env?.HOME || homedir(), '.codex'),
423
+ );
424
+
425
+ /**
426
+ * Who a seat's own Codex home belongs to (F450): the seat's local key, as the
427
+ * run loop names its sessions and state (F306). A second instance's is
428
+ * `name@instance`, so it gets a home of its own; every other seat's is its
429
+ * bare name, so every home made before this keeps its seat, including a seat
430
+ * saved under its name that runs a non-default instance.
431
+ */
432
+ export const codexHomeIdentity = (ctx) => ctx.seatKey || ctx.agentName || ctx.cwd || 'anonymous';
433
+
434
+ /** Where this private seat's own Codex home is, or null where it has none. */
435
+ export const privateCodexHomePath = (ctx) => {
436
+ if (ctx._privateCodexHome) return ctx._privateCodexHome;
437
+ const identity = codexHomeIdentity(ctx);
438
+ const hash = createHash('sha256').update(`private:${identity}`).digest('hex').slice(0, 20);
439
+ let publicRoot;
440
+ try {
441
+ publicRoot = publicCodexHomesRoot(ctx);
442
+ } catch (error) {
443
+ if (error?.code !== 'state_home_under_commonly') throw error;
444
+ throw stateHomeUnderCommonly(ctx, ctx._homeDir || homedir(), 'private');
445
+ }
446
+ return join(dirname(publicRoot), PRIVATE_CODEX_HOMES, hash);
447
+ };
448
+
449
+ // F450: a login Codex keeps in the keyring is filed under the Codex home's own
450
+ // path and leaves no auth.json, so a seat in a home of its own can't reach it.
451
+ // Said once per process per home, at the first turn.
452
+ const keyringLoginNoted = new Set();
453
+ const KEYRING_STORE = /^\s*cli_auth_credentials_store\s*=\s*["'](keyring|auto)["']/m;
454
+ // Only the keys above the first table header are the top level.
455
+ const topLevelToml = (text) => text.split(/^\s*\[/m)[0];
456
+ const noteKeyringLogin = async (source, home) => {
457
+ if (keyringLoginNoted.has(home)) return;
458
+ keyringLoginNoted.add(home);
459
+ if (await statOrNull(join(source, 'auth.json'))) return;
460
+ const config = await readFile(join(source, 'config.toml'), 'utf8').catch(() => '');
461
+ const store = topLevelToml(config).match(KEYRING_STORE)?.[1];
462
+ if (!store) return;
463
+ process.stderr.write(`[codex] this agent runs from a Codex home of its own (${home}). Your config.toml `
464
+ + `sets cli_auth_credentials_store = "${store}" and there is no auth.json to link, so a login kept in `
465
+ + 'the keyring can\'t reach it. '
466
+ + 'To fix it, set cli_auth_credentials_store = "file" in your config.toml and run `codex login`.\n');
467
+ };
468
+
469
+ const preparePrivateCodexHome = async (ctx, childEnv) => {
470
+ const source = privateSourceCodexHome(ctx, childEnv);
471
+ const home = privateCodexHomePath(ctx);
472
+ if (pathResolve(home) === source) throw new Error('a private Codex home must be apart from the shared CODEX_HOME');
473
+ const workspacePath = pathResolve(ctx.cwd || process.cwd());
474
+ const userHome = ctx._homeDir || homedir();
475
+ const [workspace, realHome, realSource, realCommonly] = await Promise.all([
476
+ // As in realpathOfNearest: only a missing workspace falls back to its own path.
477
+ realpath(workspacePath).catch((error) => {
478
+ if (error?.code === 'ENOENT') return workspacePath;
479
+ throw error;
480
+ }),
481
+ realpathOfNearest(home),
482
+ realpathOfNearest(source),
483
+ realpathOfNearest(join(userHome, '.commonly')),
484
+ ]);
485
+ if (contains(workspace, realHome)) {
486
+ throw new Error(`private codex agents cannot run in ${ctx.cwd}: it contains the agent's own Codex home `
487
+ + `(${home}), which the sandbox would then expose. Run it in a project folder.`);
488
+ }
489
+ // Both are denied whole, and a home inside either would hide Codex's own
490
+ // sandbox helper, so every turn would stop at start.
491
+ if (contains(realSource, realHome) || contains(realCommonly, realHome)) {
492
+ throw new Error(`a private Codex agent's own home (${home}) resolves inside `
493
+ + `${contains(realSource, realHome) ? `the shared Codex home (${source})` : join(userHome, '.commonly')}, `
494
+ + 'which its sandbox denies on Linux. Point XDG_STATE_HOME elsewhere or unset it.');
495
+ }
496
+ await mkdir(home, { recursive: true, mode: 0o700 });
497
+ await chmod(home, 0o700);
498
+ for (const name of PRIVATE_HOME_LINKS) {
499
+ const from = join(source, name);
500
+ const to = join(home, name);
501
+ const [fromStat, toStat] = await Promise.all([statOrNull(from), statOrNull(to)]);
502
+ // A file the seat's Codex wrote in its own home is its own: kept.
503
+ if (toStat && !toStat.isSymbolicLink()) continue;
504
+ if (!fromStat) {
505
+ // A link to a login the person removed would sign in through it anyway.
506
+ if (toStat) await unlink(to);
507
+ continue;
508
+ }
509
+ const current = toStat ? pathResolve(dirname(to), await readlink(to)) : null;
510
+ if (current !== from) {
511
+ if (toStat) await unlink(to);
512
+ // Another turn of the same seat may have just made it.
513
+ await symlink(from, to).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
514
+ }
515
+ }
516
+ await noteKeyringLogin(source, home);
517
+ await mkdir(join(home, 'tmp', 'arg0-linux'), { recursive: true, mode: 0o700 });
518
+ // Every other private seat's home, as it stands now. One created during this
519
+ // turn is denied from the next turn on: until then, what that seat's first
520
+ // turn writes there stays readable to this turn's commands.
521
+ const others = entriesOf(dirname(home)).filter((name) => name !== basename(home)).sort()
522
+ .map((name) => join(dirname(home), name));
523
+ // The links into the shared home, which is denied whole with their targets.
524
+ const links = [];
525
+ for (const name of PRIVATE_HOME_LINKS) {
526
+ const stat = await statOrNull(join(home, name));
527
+ if (stat?.isSymbolicLink() && pathResolve(home, await readlink(join(home, name))) === join(source, name)) links.push(name);
528
+ }
529
+ return { home, source, realSource, others, links };
530
+ };
531
+
405
532
  // `login: false` is the proxy route (D250): codex authenticates with the
406
533
  // per-turn token, so the public home gets no link to the person's Codex login,
407
534
  // and a link an earlier turn left is removed.
408
535
  const preparePublicCodexHome = async (ctx, childEnv, { login = true } = {}) => {
409
536
  const operatorHome = operatorCodexHome(ctx);
410
- const identity = ctx.agentName || ctx.cwd || 'anonymous';
537
+ const identity = codexHomeIdentity(ctx);
411
538
  const identityHash = createHash('sha256').update(identity).digest('hex').slice(0, 20);
412
539
  const homesRoot = publicCodexHomesRoot(ctx);
413
540
  const publicHome = ctx._publicCodexHome || join(homesRoot, identityHash);
@@ -805,7 +932,13 @@ const entriesOf = (dir) => {
805
932
  }
806
933
  };
807
934
 
808
- export const privateCodexHomeDenies = ({ codexHome = null, platform = process.platform, home = homedir() } = {}) => {
935
+ // `links`: entries of the run home that are links into a home denied whole
936
+ // (F445). A key on one makes bwrap follow it into the hidden folder and stop
937
+ // every turn at start ("Can't create file at …/auth.json: No such file or
938
+ // directory", run 43114789288); its target is out of reach already.
939
+ export const privateCodexHomeDenies = ({
940
+ codexHome = null, platform = process.platform, home = homedir(), links = [],
941
+ } = {}) => {
809
942
  const defaultHome = join(home, '.codex');
810
943
  const runHome = codexHome ? realOrSelf(codexHome) : null;
811
944
  const runsFromDefault = !runHome || runHome === realOrSelf(defaultHome);
@@ -823,6 +956,7 @@ export const privateCodexHomeDenies = ({ codexHome = null, platform = process.pl
823
956
  .forEach((name) => SQLITE_SIDECARS.forEach((suffix) => names.add(`${name}${suffix}`)));
824
957
  }
825
958
  names.delete(keep);
959
+ if (depth === 0) links.forEach((name) => names.delete(name));
826
960
  denies.push(...[...names].sort().map((name) => join(dir, name)));
827
961
  dir = join(dir, keep);
828
962
  }
@@ -900,6 +1034,7 @@ const privatePermissionProfileFlags = ({
900
1034
  codexHome = null,
901
1035
  home = homedir(),
902
1036
  otherCodexHomes = [],
1037
+ codexHomeLinks = [],
903
1038
  } = {}) => {
904
1039
  const { commitHooksPath, originalHookPaths } = commitHookReadPaths(commitAttributionEnv);
905
1040
  const posix = platform !== 'win32';
@@ -917,7 +1052,7 @@ const privatePermissionProfileFlags = ({
917
1052
  // no drive and Codex would refuse the whole profile (as with /private/tmp
918
1053
  // in publicPermissionProfileFlags).
919
1054
  posix ? '"/"="read"' : '":minimal"="read"',
920
- ...[...PRIVATE_SECRET_DENIES, ...privateCodexHomeDenies({ codexHome, platform, home }), ...otherCodexHomes]
1055
+ ...[...PRIVATE_SECRET_DENIES, ...privateCodexHomeDenies({ codexHome, platform, home, links: codexHomeLinks }), ...otherCodexHomes]
921
1056
  .map((path) => `${toml(path)}="deny"`),
922
1057
  ...deniedTemp.map((path) => `${toml(path)}="deny"`),
923
1058
  ...(shellTemp ? [`${toml(shellTemp)}="write"`] : []),
@@ -1070,6 +1205,8 @@ const buildArgs = ({
1070
1205
  privateCodexHome = null,
1071
1206
  privateHome = homedir(),
1072
1207
  privateOtherCodexHomes = [],
1208
+ privateCodexHomeLinks = [],
1209
+ loginFileStore = false,
1073
1210
  }) => {
1074
1211
  const publicSandbox = publicSandboxMode !== null;
1075
1212
  // F387: a private seat keeps the flag below only in a cloud-codex pod, or
@@ -1128,6 +1265,7 @@ const buildArgs = ({
1128
1265
  codexHome: privateCodexHome,
1129
1266
  home: privateHome,
1130
1267
  otherCodexHomes: privateOtherCodexHomes,
1268
+ codexHomeLinks: privateCodexHomeLinks,
1131
1269
  });
1132
1270
  const common = [
1133
1271
  '--json',
@@ -1139,6 +1277,7 @@ const buildArgs = ({
1139
1277
  ...(publicSandbox && modelBaseUrl ? ['-c', `openai_base_url=${toml(modelBaseUrl)}`] : []),
1140
1278
  ...(model ? ['--model', String(model)] : []),
1141
1279
  ...(effort ? ['-c', 'model_reasoning_effort=' + toml(effort)] : []),
1280
+ ...(loginFileStore ? ['-c', 'cli_auth_credentials_store="file"'] : []),
1142
1281
  ...mcpFlags,
1143
1282
  '-o',
1144
1283
  outputFile,
@@ -1353,8 +1492,20 @@ export default {
1353
1492
  // alone. claude.js adds parallel reads, whose cue names Claude's Agent tool;
1354
1493
  // Codex has agent tools of its own, under other names. A public seat answers
1355
1494
  // strangers rather than working board rows, so it is taught neither.
1495
+ // F445: a private seat on Linux resumes only a thread in its own Codex
1496
+ // home; one in the shared home (a run before F445) starts fresh, which the
1497
+ // prompt has to know.
1498
+ const ownPrivateHome = (ctx._platform || process.platform) === 'linux' && sandbox?.trust !== 'public'
1499
+ && !codexTrustedPerimeter(ctx.env || process.env) && ctx.hostUnconfined !== true
1500
+ ? privateCodexHomePath(ctx) : null;
1501
+ let sessionId = ctx.sessionId || null;
1502
+ if (ownPrivateHome && sessionId && !codexRolloutPath({ codexHome: ownPrivateHome, sessionId })) {
1503
+ process.stderr.write('[codex] this agent now keeps its own Codex home, so it starts a new thread; '
1504
+ + 'what it is meant to remember is in its Commonly memory.\n');
1505
+ sessionId = null;
1506
+ }
1356
1507
  const fullPrompt = buildPrompt(prompt, ctx.memoryLongTerm, {
1357
- freshSession: !ctx.sessionId,
1508
+ freshSession: !sessionId,
1358
1509
  workCues: sandbox?.trust === 'public' ? [] : [ROW_SLICING_CUE, BACKGROUND_PROCESS_CUE],
1359
1510
  // F118: a public seat reads its memory but is not offered a write.
1360
1511
  memoryReadOnly: sandbox?.trust === 'public' && ctx.ownerWoken !== true,
@@ -1496,6 +1647,9 @@ export default {
1496
1647
  const publicCodexHome = publicSandboxMode !== null
1497
1648
  ? await preparePublicCodexHome(ctx, childEnv, { login: !route })
1498
1649
  : null;
1650
+ const privateCodexHome = privateProfile && ownPrivateHome
1651
+ ? await preparePrivateCodexHome(ctx, childEnv)
1652
+ : null;
1499
1653
  // The private shell's TMPDIR: inside this turn's folder, which `finally`
1500
1654
  // removes, and beside (not over) the token's folder.
1501
1655
  const privateShellTemp = privateProfile ? join(dir, 'shell-tmp') : null;
@@ -1510,7 +1664,7 @@ export default {
1510
1664
  childEnv[CODEX_PROVIDER_TOKEN_ENV] = providerProxy.token;
1511
1665
  }
1512
1666
  const args = buildArgs({
1513
- sessionId: ctx.sessionId || null,
1667
+ sessionId,
1514
1668
  prompt: fullPrompt,
1515
1669
  outputFile,
1516
1670
  mcpFlags: mcp.flags,
@@ -1537,12 +1691,32 @@ export default {
1537
1691
  // The home Codex runs with, and the HOME its `~` keys expand against.
1538
1692
  // Codex reads a relative CODEX_HOME from its own folder, the turn's.
1539
1693
  privateCodexHome: privateProfile
1540
- ? pathResolve(ctx.cwd || process.cwd(), childEnv.CODEX_HOME || join(childEnv.HOME || homedir(), '.codex'))
1694
+ ? privateCodexHome?.home || privateSourceCodexHome(ctx, childEnv)
1541
1695
  : null,
1542
1696
  privateHome: childEnv.HOME || homedir(),
1543
1697
  // Public seats' Codex homes (their sessions and logs): under the denied
1544
- // ~/.commonly on macOS, outside it on Linux.
1545
- privateOtherCodexHomes: privateProfile ? privatePublicHomesDeny(ctx) : [],
1698
+ // ~/.commonly on macOS, outside it on Linux. With a home of its own, the
1699
+ // shared one it came from and every other private seat's are denied whole.
1700
+ privateOtherCodexHomes: privateProfile
1701
+ ? [...new Set([
1702
+ ...privatePublicHomesDeny(ctx),
1703
+ // By its real path too, when it is a link to another folder.
1704
+ ...(privateCodexHome
1705
+ ? [privateCodexHome.source, privateCodexHome.realSource, ...privateCodexHome.others]
1706
+ : []),
1707
+ ])]
1708
+ : [],
1709
+ privateCodexHomeLinks: privateCodexHome?.links || [],
1710
+ // F450: a seat with a home of its own keeps the person's login in
1711
+ // auth.json, linked to theirs. Codex's file store writes a refreshed
1712
+ // login through that link (open + truncate, codex-rs login
1713
+ // auth/storage.rs at rust-v0.164.0), so the person's file gets the new
1714
+ // tokens. Its keyring and auto stores save to the keyring under the
1715
+ // seat home's own path and delete the seat's auth.json, which would
1716
+ // leave the person's file holding the refresh token the refresh just
1717
+ // rotated. config.toml is linked in, so the seat would inherit those
1718
+ // modes; this keeps it on the file store.
1719
+ loginFileStore: Boolean(privateCodexHome),
1546
1720
  });
1547
1721
  // childEnv is derived from the process environment, so the bootstrap export has to be
1548
1722
  // taken back out: the declaration above moved our server onto the file,
@@ -1560,6 +1734,7 @@ export default {
1560
1734
  childEnv.CODEX_HOME = publicCodexHome.home;
1561
1735
  await writePublicCodexInstructions(childEnv.CODEX_HOME, ctx);
1562
1736
  }
1737
+ if (privateCodexHome) childEnv.CODEX_HOME = privateCodexHome.home;
1563
1738
 
1564
1739
  // The awaits above can outlast a supervisor stall window. Once it has
1565
1740
  // aborted, the attempt has already settled and a retry may be running,
@@ -1610,7 +1785,7 @@ export default {
1610
1785
  // a new session, often re-emitted on resume) > the persisted id we
1611
1786
  // came in with > null. The wrapper persists whichever non-null value
1612
1787
  // we return so subsequent turns hit `codex exec resume <id>`.
1613
- const newSessionId = threadId || ctx.sessionId || null;
1788
+ const newSessionId = threadId || sessionId || null;
1614
1789
  // F404: what the turn's last request was sent, from the rollout the child
1615
1790
  // wrote under its own CODEX_HOME. Null keeps resuming.
1616
1791
  const contextTokens = newSessionId