@commonlyai/cli 0.1.398 → 0.1.400

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.
@@ -44,7 +44,7 @@ import { describeTurnReap, markTurn, turnReapEnabled } from '@commonlyai/seats/t
44
44
  import { requireSeatModel, seatModelRequired } from './seat-model.js';
45
45
  import { meetsMinimumVersion, probeVersion, publicCodexVersionError } from './tested-version.js';
46
46
  import { spawn as childSpawn, spawnSync } from 'child_process';
47
- import { createHash } from 'crypto';
47
+ import { createHash, randomBytes } from 'crypto';
48
48
  import {
49
49
  accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statSync,
50
50
  } from 'fs';
@@ -53,7 +53,9 @@ import {
53
53
  lstat,
54
54
  mkdir,
55
55
  mkdtemp,
56
+ opendir,
56
57
  readFile,
58
+ readdir,
57
59
  readlink,
58
60
  realpath,
59
61
  rename,
@@ -80,13 +82,28 @@ import { brokerBridgeEntry } from './broker-bridge-entry.js';
80
82
  import { supportedGitHooks } from '../commit-attribution.js';
81
83
  import { WORKSPACE_GIT_SERVER_NAME, confinedWorkspaceGitServer, workspaceGitEnabled } from '../workspace-git.js';
82
84
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
83
- import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
85
+ import {
86
+ prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir, selectedMcpWithholdsTools,
87
+ } from '../mcp-home.js';
88
+ import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
89
+ import { describeMcpCommand } from '../mcp-server-version.js';
84
90
  import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '../memory-bridge.js';
85
91
  import { resolveSkillSource, skillsAsText } from '../skill-prompt.js';
86
92
  import { isLegacySandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
87
93
  import { contains, realpathOfNearest, refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
88
94
  import { refuseCodeRunningGitSetup } from '../sandbox/workspace-git-config.js';
89
95
  import { codexTrustedPerimeter } from '../sandbox/codex-perimeter.js';
96
+ import { resolveCodexSandboxMode } from '../sandbox/mode.js';
97
+ import {
98
+ ensureGuestDir, readGuestFile, removeGuestEntry, writeGuestFile,
99
+ } from '../sandbox/guest-home.js';
100
+ import {
101
+ GUEST_CODEX, GUEST_HOME, GUEST_PATH, GUEST_WORKSPACE, buildMicrovmRunArgs, checkMicrovmAttach,
102
+ ensureNoSeatVm, guestProxyBaseUrl, microvmSeatHome, microvmSeatLabel, msbHostEnv, prepareMicrovmHost,
103
+ refuseMicrovmMcpDeclarations,
104
+ probeWhp, startMicrovmTurn, stopOrphanSeatMsb, withSeatLock, writeMicrovmTurn,
105
+ } from '../sandbox/microsandbox.js';
106
+ import { MCP_BRIDGE_SECRET_ENV } from '../sandbox/microsandbox-mcp-bridge.js';
90
107
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
91
108
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
92
109
  import { startProviderProxy } from '../provider-proxy.js';
@@ -727,10 +744,23 @@ export const codexNativeBinary = (env) => {
727
744
  // cross it is left out whole.
728
745
  const PUBLIC_CODEX_INSTRUCTIONS_MAX_BYTES = 32 * 1024;
729
746
 
730
- const writePublicCodexInstructions = async (publicHome, ctx) => {
747
+ // The host's own file operations on a public Codex home. The microVM turn
748
+ // passes guest-home.js's instead, which follow no link (its home is the guest's
749
+ // to write).
750
+ const hostHomeFileOps = {
751
+ remove: (dir, name) => rm(join(dir, name), { force: true }),
752
+ write: async (dir, name, text) => {
753
+ const target = join(dir, name);
754
+ const staged = `${target}.${process.pid}.tmp`;
755
+ await writeFile(staged, text, { encoding: 'utf8', mode: 0o600 });
756
+ await rename(staged, target);
757
+ },
758
+ };
759
+
760
+ const writePublicCodexInstructions = async (publicHome, ctx, ops = hostHomeFileOps) => {
731
761
  // Codex loads this file before AGENTS.md when it exists. Clear any leftover
732
762
  // override on every spawn so it cannot shadow the seat's declared skills.
733
- await rm(join(publicHome, 'AGENTS.override.md'), { force: true });
763
+ await ops.remove(publicHome, 'AGENTS.override.md');
734
764
  const declared = Array.isArray(ctx.environment?.skills?.claude) ? ctx.environment.skills.claude : [];
735
765
  const baseDir = ctx.cwd || process.cwd();
736
766
  const sources = declared.map((source) => resolveSkillSource(source, baseDir));
@@ -744,15 +774,12 @@ const writePublicCodexInstructions = async (publicHome, ctx) => {
744
774
  onIncluded: (source) => included.push(source),
745
775
  },
746
776
  );
747
- const target = join(publicHome, 'AGENTS.md');
748
777
  if (!text) {
749
- await rm(target, { force: true });
778
+ await ops.remove(publicHome, 'AGENTS.md');
750
779
  ctx.onSkillsLinked?.({ mounted: [], conflicted: sources.map((path) => ({ path, reason: 'not-inlined' })) });
751
780
  return;
752
781
  }
753
- const staged = `${target}.${process.pid}.tmp`;
754
- await writeFile(staged, text, { encoding: 'utf8', mode: 0o600 });
755
- await rename(staged, target);
782
+ await ops.write(publicHome, 'AGENTS.md', text);
756
783
  ctx.onSkillsLinked?.({
757
784
  mounted: included,
758
785
  conflicted: sources.filter((source) => !included.includes(source)).map((path) => ({ path, reason: 'not-inlined' })),
@@ -1246,6 +1273,9 @@ const buildArgs = ({
1246
1273
  privateOtherCodexHomes = [],
1247
1274
  privateCodexHomeLinks = [],
1248
1275
  loginFileStore = false,
1276
+ // Only the microVM turn passes false: its host writes the Codex home's
1277
+ // config.toml fresh each turn (microvmGuestCodexConfig).
1278
+ ignoreUserConfig = true,
1249
1279
  }) => {
1250
1280
  const publicSandbox = publicSandboxMode !== null;
1251
1281
  // F387: a private seat keeps the flag below only in a cloud-codex pod, or
@@ -1278,7 +1308,7 @@ const buildArgs = ({
1278
1308
  // a user [permissions.*] table on codex-cli 0.162.1).
1279
1309
  const executionPolicy = publicSandbox
1280
1310
  ? [
1281
- '--ignore-user-config',
1311
+ ...(ignoreUserConfig ? ['--ignore-user-config'] : []),
1282
1312
  '--ignore-rules',
1283
1313
  ...publicPermissionProfileFlags(
1284
1314
  publicSandboxMode,
@@ -1431,10 +1461,547 @@ const readCodexVersion = async (ctx, env) => {
1431
1461
  return version;
1432
1462
  };
1433
1463
 
1464
+ // What the reply receipt reads from a turn's codex argv: the flags after
1465
+ // `exec` (or `exec resume <id>`), before the prompt.
1466
+ const codexControls = (args) => controlsFromArguments(
1467
+ args.slice(args.indexOf('exec') + (args[args.indexOf('exec') + 1] === 'resume' ? 3 : 1), -1),
1468
+ { modelFlag: '--model', valueFlags: ['-c', '-o', '--permission-profile'], codex: true },
1469
+ );
1470
+
1471
+ // ── native Windows, opt-in: the turn inside a microVM ─────────────────────────
1472
+ //
1473
+ // sandbox/microsandbox.js holds the VM; docs/cli/microvm-sandbox.md says what
1474
+ // holds. Codex runs in the guest from the agents volume. Its provider key stays
1475
+ // in the host proxy, the Commonly MCP server and the seat's token stay on this
1476
+ // computer behind the bridge, and the fence opens exactly those two ports.
1477
+
1478
+ // The guest's Codex home, on the seat HOME the host keeps between turns. Not
1479
+ // ~/.codex: the public profile denies that to the model's shell whole, and the
1480
+ // profile's arg0 helper lives inside the Codex home (preparePublicCodexHome).
1481
+ const GUEST_CODEX_HOME_NAME = 'codex-home';
1482
+ const GUEST_CODEX_HOME = `${GUEST_HOME}/${GUEST_CODEX_HOME_NAME}`;
1483
+ // Where codex writes the turn's last message, under a name drawn fresh each
1484
+ // turn, so a guest can't plant a link there for the host to read through.
1485
+ const GUEST_REPLIES_NAME = 'replies';
1486
+ // Beyond the profile's minimal set, the model's shell reads the helper folder
1487
+ // and the agents volume (Codex's own binary; mounted read-only, no secrets).
1488
+ // Who enforces what for that shell: Codex's Linux sandbox (bwrap, 0.172.0
1489
+ // linux-sandbox/src/bwrap.rs) starts a restricted-read profile from an empty
1490
+ // `--tmpfs /` and `--ro-bind`s only these readable roots. So the rest of the
1491
+ // Codex home (config.toml included) is absent from its view, and a write
1492
+ // outside the writable roots (none for a read-only seat) lands in that
1493
+ // private tmpfs and is gone when the command exits: measured on the Windows
1494
+ // runner, a shell write to the Codex home "succeeds" and never reaches the
1495
+ // seat HOME. The workspace mount is read-only in the VM as well, and the VM
1496
+ // has no network but the fence. Codex itself runs outside bwrap and writes
1497
+ // its home freely, hence the per-turn allowlist (GUEST_CODEX_HOME_KEPT).
1498
+ const GUEST_CODEX_HELPER_READS = Object.freeze([`${GUEST_CODEX_HOME}/tmp/arg0-linux`, '/opt/agents']);
1499
+
1500
+ // The key the host proxy holds. Codex's own name for an exec key first.
1501
+ const MICROVM_PROVIDER_KEY_ENVS = ['CODEX_API_KEY', 'OPENAI_API_KEY'];
1502
+ const microvmProviderKey = (source = {}) => {
1503
+ const name = MICROVM_PROVIDER_KEY_ENVS.find((key) => envSet(source, key));
1504
+ return name ? source[name].trim() : null;
1505
+ };
1506
+
1507
+ const proxyPortOf = (proxy) => {
1508
+ const port = Number(proxy?.port ?? new URL(proxy.baseURL).port);
1509
+ return Number.isInteger(port) && port > 0 ? port : null;
1510
+ };
1511
+
1512
+ /**
1513
+ * The host-side MCP config for the bridge, in the shape startMicrovmTurn
1514
+ * reads. The servers run on this computer, outside the VM and outside Codex's
1515
+ * `disabled_tools`, so only our own server runs there, from a warm build that
1516
+ * withholds the seat's tools itself. Anything else is refused, as claude.js
1517
+ * refuses it: on the host it would run with the workspace writable.
1518
+ */
1519
+ export const microvmHostMcpConfig = (servers, ctx = {}) => {
1520
+ const mcpServers = {};
1521
+ const unavailable = [];
1522
+ // The declaration-level refusal attach runs too, so a seat it would refuse
1523
+ // here on every turn is never published.
1524
+ refuseMicrovmMcpDeclarations(servers);
1525
+ for (const server of servers || []) {
1526
+ if (!server?.name) continue;
1527
+ const spawnCommand = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl, publicSeat: true });
1528
+ if (!spawnCommand) {
1529
+ unavailable.push(server.name);
1530
+ continue;
1531
+ }
1532
+ // Our own server only: refuseMicrovmMcpDeclarations above judged the
1533
+ // declared command, and the resolved one must be ours as well.
1534
+ if (!(isShippedCommonlyMcpCommand(server.command) || Boolean(describeMcpCommand(spawnCommand)?.isCommonly))) {
1535
+ throw new Error(`The microVM sandbox runs only the Commonly MCP server, on this computer, and ${server.name} `
1536
+ + 'is another server: it would run outside the VM. Remove it to run this seat in the microVM.');
1537
+ }
1538
+ if (!(ctx._withholdsTools || selectedMcpWithholdsTools)(spawnCommand)) {
1539
+ throw new Error(`The Commonly MCP build this seat would run for ${server.name} does not withhold a public `
1540
+ + "seat's tools itself, which the microVM sandbox needs; update @commonlyai/mcp.");
1541
+ }
1542
+ // The credential arrives as a file path (TASK-083), never a value.
1543
+ const declaredEnv = deliverSeatCredential({ ...server, command: spawnCommand }, {
1544
+ credentialFile: ctx.credentialFile,
1545
+ label: 'codex',
1546
+ }).env;
1547
+ const [command, ...args] = resolveMcpCommand(
1548
+ spawnCommand.map((arg) => substitutePlaceholders(arg, ctx)),
1549
+ ctx.commandResolution,
1550
+ { label: 'codex', name: server.name },
1551
+ );
1552
+ if (ctx.runtimeToken && [command, ...args].some((arg) => String(arg).includes(ctx.runtimeToken))) {
1553
+ throw new Error(`MCP server ${server.name} wants the seat credential as a command argument, where every `
1554
+ + "process on this computer could read it; declare it on the entry's env instead.");
1555
+ }
1556
+ mcpServers[server.name] = {
1557
+ type: 'stdio',
1558
+ command,
1559
+ args,
1560
+ env: Object.fromEntries(Object.entries(declaredEnv)
1561
+ .map(([key, value]) => [key, substitutePlaceholders(value, ctx)])),
1562
+ };
1563
+ }
1564
+ return { config: { mcpServers }, unavailable };
1565
+ };
1566
+
1567
+ // What survives in the guest Codex home from one turn to the next. Before
1568
+ // every turn the host removes everything else (then writes AGENTS.md and
1569
+ // config.toml fresh), so no file a turn leaves there (AGENTS.override.md,
1570
+ // config or hooks files, skills, memories/, history.jsonl, a state database,
1571
+ // or an extension point a later Codex adds) reaches the next turn.
1572
+ // - sessions: the seat's rollouts. `exec resume <id>` finds a thread by
1573
+ // scanning this folder's file names when the state database has no row
1574
+ // (rollout/src/list.rs, 0.172.0), and the database is cleared with the rest.
1575
+ // What is in it is the seat's own conversation (docs: Known limits).
1576
+ // - tmp/arg0-linux: where Codex links its own binary under helper names at
1577
+ // every launch and puts only that launch's folder on PATH; it prunes stale
1578
+ // ones itself. The profile's read rule names it, and its entries are links
1579
+ // by design, which the no-follow remover would refuse. Everything else in
1580
+ // tmp/ is removed.
1581
+ export const GUEST_CODEX_HOME_KEPT = Object.freeze(['sessions', 'tmp']);
1582
+ const GUEST_CODEX_TMP_KEPT = Object.freeze(['arg0-linux']);
1583
+
1584
+ // Removes every entry of `dir` not in `kept`, by the no-follow rules: a link
1585
+ // is refused, never followed or removed.
1586
+ const keepOnlyGuestEntries = async (dir, kept) => {
1587
+ for (const name of await readdir(dir)) {
1588
+ // eslint-disable-next-line no-await-in-loop
1589
+ if (!kept.includes(name)) await removeGuestEntry(dir, name);
1590
+ }
1591
+ };
1592
+
1593
+ // The reply is posted to a pod: more than this is cut, and says so.
1594
+ export const MICROVM_REPLY_MAX_BYTES = 256 * 1024;
1595
+
1596
+ /**
1597
+ * The guest Codex's config.toml, written by the host into its home before each
1598
+ * turn and removed after: only the MCP entries. Each runs the guest shim, which
1599
+ * dials the bridge. Codex passes its MCP children none of its own environment
1600
+ * (repo CLAUDE.md), so the env table carries the bridge address and the turn
1601
+ * secret. Kept out of argv on purpose: Codex's argv is readable through
1602
+ * /proc/<pid>/cmdline inside the guest, and the profile's minimal read set
1603
+ * does not cover the Codex home, so the model's shell can read neither this
1604
+ * file nor the turn folder. Everything else rides in `-c` overrides, which
1605
+ * win over this file.
1606
+ */
1607
+ export const microvmGuestCodexConfig = (mcpConfig, ctx = {}) => [
1608
+ '# Written by the Commonly CLI for one microVM turn, and removed after it.',
1609
+ ...Object.entries(mcpConfig?.mcpServers || {}).flatMap(([name, entry]) => [
1610
+ '',
1611
+ `[mcp_servers.${toml(name)}]`,
1612
+ `command = ${toml(entry.command)}`,
1613
+ `args = [${(entry.args || []).map(toml).join(', ')}]`,
1614
+ 'default_tools_approval_mode = "approve"',
1615
+ `disabled_tools = [${publicSeatWithheldTools(ctx).map(toml).join(', ')}]`,
1616
+ '',
1617
+ `[mcp_servers.${toml(name)}.env]`,
1618
+ ...Object.entries(entry.env || {}).map(([key, value]) => `${key} = ${toml(value)}`),
1619
+ ]),
1620
+ '',
1621
+ ].join('\n');
1622
+
1623
+ /** The guest Codex's whole environment: the proxy's per-turn token, never a key. */
1624
+ export const guestCodexEnv = ({ proxyToken }) => ({
1625
+ HOME: GUEST_HOME,
1626
+ PATH: GUEST_PATH,
1627
+ LANG: 'C.UTF-8',
1628
+ CODEX_HOME: GUEST_CODEX_HOME,
1629
+ [CODEX_PROVIDER_TOKEN_ENV]: proxyToken,
1630
+ });
1631
+
1632
+ // The host MCP servers' base environment: this computer's, less every
1633
+ // provider key and route name, with the seat token moved onto its file.
1634
+ const microvmServerBaseEnv = (source, credential) => {
1635
+ const env = { ...source };
1636
+ const drop = new Set([...CODEX_PROVIDER_KEY_ENVS, ...CODEX_OWN_AUTH_ENVS]);
1637
+ for (const name of Object.keys(env)) {
1638
+ if (drop.has(name.toUpperCase())) delete env[name];
1639
+ }
1640
+ return withholdRuntimeCredential(env, { credentialFile: credential?.path || null });
1641
+ };
1642
+
1643
+ // The turn's MCP bridge secret(s), redacted from anything msb or Codex prints.
1644
+ const bridgeSecrets = (mcpConfig) => Object.values(mcpConfig?.mcpServers || {})
1645
+ .map((server) => server?.env?.[MCP_BRIDGE_SECRET_ENV])
1646
+ .filter((secret) => typeof secret === 'string' && secret);
1647
+
1648
+ // writePublicCodexInstructions' file operations, through guest-home.js: no
1649
+ // link under the seat HOME is followed.
1650
+ const guestHomeFileOps = {
1651
+ remove: (dir, name) => removeGuestEntry(dir, name),
1652
+ write: (dir, name, text) => writeGuestFile(dir, name, text),
1653
+ };
1654
+
1655
+ /**
1656
+ * The seat HOME, readied for a turn while no VM of it runs. Every folder is
1657
+ * checked for links on the way down, everything in the Codex home but its
1658
+ * sessions and its arg0 helper folder is removed (GUEST_CODEX_HOME_KEPT), and
1659
+ * AGENTS.md is rewritten from the skills.
1660
+ */
1661
+ export const prepareMicrovmCodexHome = async (home, ctx) => {
1662
+ await mkdir(dirname(home), { recursive: true, mode: 0o700 });
1663
+ await ensureGuestDir(home);
1664
+ await ensureGuestDir(home, [GUEST_CODEX_HOME_NAME, 'tmp', 'arg0-linux']);
1665
+ const codexHome = await ensureGuestDir(home, [GUEST_CODEX_HOME_NAME]);
1666
+ // Replies a killed turn left behind (its HOME was not touched then) go now,
1667
+ // under the seat lock with no VM of the seat running: no turn is active.
1668
+ await removeGuestEntry(home, GUEST_REPLIES_NAME);
1669
+ const replies = await ensureGuestDir(home, [GUEST_REPLIES_NAME]);
1670
+ await keepOnlyGuestEntries(codexHome, GUEST_CODEX_HOME_KEPT);
1671
+ await keepOnlyGuestEntries(await ensureGuestDir(home, [GUEST_CODEX_HOME_NAME, 'tmp']), GUEST_CODEX_TMP_KEPT);
1672
+ await ensureGuestDir(home, [GUEST_CODEX_HOME_NAME, 'tmp', 'arg0-linux']);
1673
+ // sessions/ is kept, so it must be a real folder: a link in its place
1674
+ // refuses the turn. Links inside it are never followed (guestRolloutExists).
1675
+ await ensureGuestDir(home, [GUEST_CODEX_HOME_NAME, 'sessions']);
1676
+ await writePublicCodexInstructions(codexHome, ctx, guestHomeFileOps);
1677
+ return { codexHome, replies };
1678
+ };
1679
+
1680
+ // The turn's reply, read from the seat HOME after msb has exited, with every
1681
+ // folder on the way checked again (the guest could write them during the turn).
1682
+ // `beforeStep(step)` runs before each host step and throws once the seat
1683
+ // lock's deadline has passed, so no step starts after it.
1684
+ const readMicrovmReply = async (home, name, beforeStep = () => {}) => {
1685
+ beforeStep('checking the replies folder');
1686
+ const replies = await ensureGuestDir(home, [GUEST_REPLIES_NAME]);
1687
+ beforeStep('reading the reply');
1688
+ const read = await readGuestFile(replies, name, { maxBytes: MICROVM_REPLY_MAX_BYTES });
1689
+ if (!read) return '';
1690
+ const text = read.text.trim();
1691
+ return read.truncated ? `${text}\n\n[reply truncated at ${MICROVM_REPLY_MAX_BYTES / 1024} KB]` : text;
1692
+ };
1693
+
1694
+ // After the turn: the reply and this turn's config.toml (it names the turn's
1695
+ // bridge secret) go, by the same no-follow rules. A refusal here leaves the
1696
+ // entry, since removing through a link is exactly what must not happen. Each
1697
+ // host step is preceded by `beforeStep`; once it throws (past the seat lock's
1698
+ // deadline) nothing more is touched, and the next turn's prepare clears what
1699
+ // is left.
1700
+ const cleanMicrovmHome = async (home, replyName, beforeStep = () => {}) => {
1701
+ const step = async (name, action) => {
1702
+ beforeStep(name);
1703
+ return action();
1704
+ };
1705
+ try {
1706
+ const replies = await step('checking the replies folder', () => ensureGuestDir(home, [GUEST_REPLIES_NAME]));
1707
+ await step('removing the reply', () => removeGuestEntry(replies, replyName));
1708
+ } catch (error) {
1709
+ if (error?.code === MICROVM_PAST_DEADLINE) return;
1710
+ }
1711
+ try {
1712
+ const codexHome = await step('checking the Codex home', () => ensureGuestDir(home, [GUEST_CODEX_HOME_NAME]));
1713
+ await step('removing config.toml', () => removeGuestEntry(codexHome, 'config.toml'));
1714
+ } catch { /* left in place */ }
1715
+ };
1716
+
1717
+ const MICROVM_PAST_DEADLINE = 'microvm_past_seat_deadline';
1718
+
1719
+ // Whether the guest Codex home holds the rollout of `sessionId`
1720
+ // (sessions/YYYY/MM/DD/*-<id>.jsonl), walked without following any link: a
1721
+ // linked folder or file counts as absent. Run under the seat lock, with no VM
1722
+ // of the seat running.
1723
+ export const GUEST_ROLLOUT_ENTRY_CAP = 20000;
1724
+
1725
+ export const guestRolloutExists = async (codexHome, sessionId, cap = GUEST_ROLLOUT_ENTRY_CAP, {
1726
+ openDir = opendir,
1727
+ } = {}) => {
1728
+ if (!sessionId) return false;
1729
+ const suffix = `-${sessionId}.jsonl`;
1730
+ // sessions/ is guest-writable: a planted tree of many folders, or one folder
1731
+ // of a million entries, must not stall the host or run it out of memory
1732
+ // (it holds the seat lock meanwhile). Folders are read one entry at a time,
1733
+ // and every entry read, in any folder, is charged to one budget for the whole
1734
+ // walk. The read that goes past it ends the whole walk (cap + 1 reads at
1735
+ // most), and the thread counts as absent and starts fresh, which only costs
1736
+ // this seat its thread. Only a list that fits is sorted.
1737
+ let budget = cap;
1738
+ let exhausted = false;
1739
+ const dirsIn = async (dir) => {
1740
+ const info = await lstat(dir).catch(() => null);
1741
+ if (!info || info.isSymbolicLink() || !info.isDirectory()) return null;
1742
+ const handle = await openDir(dir).catch(() => null);
1743
+ if (!handle) return [];
1744
+ const entries = [];
1745
+ try {
1746
+ for (;;) {
1747
+ // eslint-disable-next-line no-await-in-loop
1748
+ const entry = await handle.read();
1749
+ if (!entry) break;
1750
+ budget -= 1;
1751
+ if (budget < 0) {
1752
+ exhausted = true;
1753
+ return null;
1754
+ }
1755
+ entries.push(entry);
1756
+ }
1757
+ } finally {
1758
+ await handle.close().catch(() => {});
1759
+ }
1760
+ return entries.sort((a, b) => b.name.localeCompare(a.name));
1761
+ };
1762
+ const walk = async (dir, depth) => {
1763
+ const entries = await dirsIn(dir);
1764
+ if (!entries) return false;
1765
+ for (const entry of entries) {
1766
+ if (exhausted) return false;
1767
+ if (entry.isSymbolicLink()) continue;
1768
+ if (depth === 3) {
1769
+ if (entry.isFile() && entry.name.endsWith(suffix)) return true;
1770
+ } else if (entry.isDirectory()) {
1771
+ // eslint-disable-next-line no-await-in-loop
1772
+ if (await walk(join(dir, entry.name), depth + 1)) return true;
1773
+ }
1774
+ }
1775
+ return false;
1776
+ };
1777
+ return walk(join(codexHome, 'sessions'), 0);
1778
+ };
1779
+
1780
+ // How far past a turn's timeout the seat lock's deadline sits: the checks, the
1781
+ // prepare, msb's own stop, the reply read and the cleanup fit well inside it.
1782
+ const MICROVM_SEAT_LOCK_MARGIN_MS = 15 * 60 * 1000;
1783
+
1784
+ const runMicrovmTurn = async ({
1785
+ ctx, sandbox, sessionId: storedSessionId, prompt: storedPrompt, freshPrompt = null, seatModel, credential, workspace,
1786
+ }) => {
1787
+ const platform = ctx._platform || process.platform;
1788
+ // Checked at every spawn, whatever attach saw: off Windows, without the flag
1789
+ // or without WHP this refuses, and nothing falls through.
1790
+ checkMicrovmAttach({ adapterName: 'codex', platform, probe: ctx._probeWhp || probeWhp });
1791
+ for (const key of ['read-outside', 'write-outside']) {
1792
+ if (sandbox?.filesystem?.[key]?.length) {
1793
+ throw new Error(`Codex agents in the microVM sandbox do not allow sandbox.filesystem.${key}`);
1794
+ }
1795
+ }
1796
+ // The workspace mounts read-only and the fence has no route to the web.
1797
+ if (Array.isArray(sandbox?.allow) && sandbox.allow.length) {
1798
+ throw new Error('Codex agents in the microVM sandbox run read-only, with no web access, for now; '
1799
+ + 'remove sandbox.allow to run this seat in it.');
1800
+ }
1801
+ // The guest reaches the model only through the host proxy, so there is no
1802
+ // login to carry in: a ChatGPT sign-in stays on this computer.
1803
+ const source = ctx.env || process.env;
1804
+ const key = microvmProviderKey(source);
1805
+ if (!key) {
1806
+ throw new Error('Codex agents in the microVM sandbox need CODEX_API_KEY (or OPENAI_API_KEY) in the agent\'s '
1807
+ + 'environment; the key stays on this computer and the VM gets a per-turn proxy token. A ChatGPT '
1808
+ + 'sign-in has no way into the VM.');
1809
+ }
1810
+ const baseURL = publicModelRouteBaseUrl(source) || OPENAI_DEFAULT_BASE_URL;
1811
+ // Checked before anything is installed or started.
1812
+ const hostMcp = microvmHostMcpConfig(ctx.environment?.mcp, {
1813
+ runtimeToken: ctx.runtimeToken,
1814
+ instanceUrl: ctx.instanceUrl,
1815
+ credentialFile: credential?.path || null,
1816
+ commandResolution: { env: source, ...ctx._commandResolution },
1817
+ _withholdsTools: ctx._mcpWithholdsTools,
1818
+ });
1819
+ if (hostMcp.unavailable.length) throw publicMcpUnavailableError(hostMcp.unavailable);
1820
+
1821
+ // Its own HOME per seat, apart from a Claude seat of the same name.
1822
+ const home = ctx._microvmHome || microvmSeatHome(`codex:${codexHomeIdentity(ctx)}`, 'public');
1823
+ const log = (text) => process.stderr.write(`[codex] ${text}\n`);
1824
+ const host = await (ctx._prepareMicrovmHost || prepareMicrovmHost)({ agent: 'codex', log });
1825
+ // Every host step under the HOME checks each path before acting on it, which
1826
+ // holds only while no VM has the HOME mounted. A VM can outlive msb.exe (a
1827
+ // killed turn), so before each of those steps msb is asked for this seat's
1828
+ // VMs, any alive is force-stopped, and the turn refuses if one still is.
1829
+ const seatLabel = microvmSeatLabel(home);
1830
+ const confirmNoSeatVm = () => (ctx._ensureNoSeatVm || ensureNoSeatVm)({
1831
+ msb: host.msb, label: seatLabel, env: msbHostEnv(source), log,
1832
+ });
1833
+ const timeoutMs = ctx.timeoutMs || DEFAULT_TIMEOUT_MS;
1834
+ // That check holds only if no other turn of this seat boots a VM between it
1835
+ // and this turn's last HOME step, and two `agent run` processes of one seat
1836
+ // can coexist (the daemon's and a foreground one). So the whole stretch,
1837
+ // from the first check through the cleanup, holds the seat's lock.
1838
+ return (ctx._withSeatLock || withSeatLock)(home, async ({ pastDeadline = () => false } = {}) => {
1839
+ // An msb.exe of this seat that outlived its `agent run` (a hard kill)
1840
+ // takes no lock and could boot a VM after the check below. It is found by
1841
+ // its command line and killed first, so nothing can start one after.
1842
+ (ctx._stopOrphanSeatMsb || stopOrphanSeatMsb)({
1843
+ label: seatLabel, home, platform, env: source, log,
1844
+ });
1845
+ confirmNoSeatVm();
1846
+ // Past the lock's deadline (a long sleep, say) another turn may already
1847
+ // hold the seat, so every HOME step and the launch check it first.
1848
+ if (pastDeadline()) {
1849
+ throw new Error('the codex turn passed its seat lock\'s deadline before preparing the seat; it leaves the HOME alone');
1850
+ }
1851
+ const { codexHome } = await prepareMicrovmCodexHome(home, ctx);
1852
+ // A thread stored before this seat ran in the microVM lives in another
1853
+ // Codex home; resuming it here would fail every turn, so it starts fresh.
1854
+ let sessionId = storedSessionId || null;
1855
+ let prompt = storedPrompt;
1856
+ if (sessionId && !(await guestRolloutExists(codexHome, sessionId))) {
1857
+ log('this agent now runs in the microVM sandbox, with its own Codex home, so it starts a new thread; '
1858
+ + 'what it is meant to remember is in its Commonly memory.');
1859
+ sessionId = null;
1860
+ if (freshPrompt) prompt = freshPrompt();
1861
+ }
1862
+ const replyName = `${randomBytes(16).toString('hex')}.txt`;
1863
+ let providerProxy = null;
1864
+ let turn = null;
1865
+ // True once msb.exe was killed rather than exiting on its own: its VM may
1866
+ // still be running, so nothing after it touches the HOME. The next turn's
1867
+ // confirmNoSeatVm stops that VM before its own HOME steps.
1868
+ let killed = false;
1869
+ let vmGone = false;
1870
+ const stopIfPastDeadline = (step) => {
1871
+ if (!pastDeadline()) return;
1872
+ killed = true;
1873
+ throw Object.assign(
1874
+ new Error(`the codex turn passed its seat lock's deadline before ${step}; it leaves the HOME alone`),
1875
+ { code: MICROVM_PAST_DEADLINE },
1876
+ );
1877
+ };
1878
+ try {
1879
+ providerProxy = await (ctx._startProviderProxy || startProviderProxy)({
1880
+ provider: { baseURL },
1881
+ keyMaterial: key,
1882
+ wire: 'openai-responses',
1883
+ adapterLabel: 'Codex',
1884
+ });
1885
+ const baseEnv = microvmServerBaseEnv(source, credential);
1886
+ turn = await (ctx._startMicrovmTurn || startMicrovmTurn)({
1887
+ proxyPort: proxyPortOf(providerProxy),
1888
+ hostMcpConfig: hostMcp.config,
1889
+ vars: baseEnv,
1890
+ baseEnv,
1891
+ cwd: workspace || ctx.cwd,
1892
+ serverEnv: { COMMONLY_MCP_WITHHELD_TOOLS: publicSeatWithheldTools(ctx).join(',') },
1893
+ });
1894
+ if (!turn?.turnDir) {
1895
+ throw new Error('public Codex agents in the microVM sandbox need a prepared microVM; refusing to run Codex outside it');
1896
+ }
1897
+ // The MCP entries, with the bridge secret, go in config.toml, not argv.
1898
+ stopIfPastDeadline('writing config.toml');
1899
+ await writeGuestFile(codexHome, 'config.toml', microvmGuestCodexConfig(turn.mcpConfig, ctx));
1900
+ // Inside the VM, Codex keeps the public permission profile, read-only:
1901
+ // the VM is the fence, and the profile keeps the model's shell off the
1902
+ // seat's home and the turn folder. It reads the config.toml just written
1903
+ // (and nothing else from its home config); `-c` wins over that file.
1904
+ const guestArgs = buildArgs({
1905
+ sessionId,
1906
+ prompt,
1907
+ outputFile: `${GUEST_HOME}/${GUEST_REPLIES_NAME}/${replyName}`,
1908
+ publicSandboxMode: 'read-only',
1909
+ ignoreUserConfig: false,
1910
+ model: seatModel,
1911
+ effort: ctx.environment?.effort,
1912
+ codexHelperReadPaths: GUEST_CODEX_HELPER_READS,
1913
+ providerProxy: { baseURL: guestProxyBaseUrl(providerProxy.baseURL) },
1914
+ platform: 'linux',
1915
+ workspacePath: GUEST_WORKSPACE,
1916
+ });
1917
+ // The turn folder's mcp.json is Claude's shape and unused here, so it
1918
+ // carries no server and no secret; the shim is still written beside it.
1919
+ await writeMicrovmTurn(turn.turnDir, {
1920
+ argv: [GUEST_CODEX, ...guestArgs],
1921
+ env: guestCodexEnv({ proxyToken: providerProxy.token }),
1922
+ mcpConfig: { mcpServers: {} },
1923
+ });
1924
+ if (ctx.signal?.aborted) {
1925
+ throw ctx.signal.reason || new Error('codex spawn cancelled before the process started');
1926
+ }
1927
+ let ran;
1928
+ stopIfPastDeadline('booting the VM');
1929
+ try {
1930
+ ran = await runCodex({
1931
+ command: host.msb,
1932
+ args: buildMicrovmRunArgs({
1933
+ ports: turn.ports, turnDir: turn.turnDir, workspace: workspace || ctx.cwd, home, labels: [seatLabel],
1934
+ }),
1935
+ cwd: ctx.cwd,
1936
+ env: msbHostEnv(source),
1937
+ timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
1938
+ credentials: [
1939
+ ...spawnCredentials(ctx, CODEX_PROVIDER_KEY_ENVS), key, providerProxy.token, ...bridgeSecrets(turn.mcpConfig),
1940
+ ].filter(Boolean),
1941
+ spawnImpl: ctx._spawnImpl || childSpawn,
1942
+ onSpawn: ctx.onSpawn,
1943
+ controls: codexControls(guestArgs),
1944
+ ownGroup: wantsOwnProcessGroup(ctx),
1945
+ turnReap: ctx._turnReap,
1946
+ confined: true,
1947
+ });
1948
+ } catch (error) {
1949
+ if (error?.killed || ctx.signal?.aborted) killed = true;
1950
+ throw error;
1951
+ }
1952
+ if (ctx.signal?.aborted) {
1953
+ killed = true;
1954
+ throw ctx.signal.reason || new Error('codex turn cancelled');
1955
+ }
1956
+ // Past the lock's deadline another turn may hold the seat: hands off.
1957
+ if (pastDeadline()) {
1958
+ killed = true;
1959
+ throw new Error('the codex turn ran past its seat lock\'s deadline; its reply is left unread');
1960
+ }
1961
+ // msb exited on its own, but it only warns when it can't stop its VM, so
1962
+ // the reply is read only once no VM of this seat is confirmed alive.
1963
+ confirmNoSeatVm();
1964
+ // The check above can take minutes (msb's stop), so the deadline again.
1965
+ stopIfPastDeadline('reading the reply');
1966
+ vmGone = true;
1967
+ const text = await readMicrovmReply(home, replyName, stopIfPastDeadline);
1968
+ if (!ran.turnCompleted && !text) throw adapterFailure('codex', 'the turn stopped before it finished');
1969
+ const newSessionId = ran.threadId || sessionId || null;
1970
+ const effort = ctx.environment?.effort;
1971
+ const stats = {
1972
+ ...(seatModel ? { model: String(seatModel) } : {}),
1973
+ ...(typeof effort === 'string' && effort ? { effort } : {}),
1974
+ };
1975
+ // No context-token count: reading the rollout would walk guest-written
1976
+ // folders on the host, which this mode keeps to the checked paths above.
1977
+ return {
1978
+ text, newSessionId, contextTokens: null, ...(Object.keys(stats).length ? { stats } : {}),
1979
+ };
1980
+ } finally {
1981
+ // After a kill the HOME is left as it is; otherwise it is cleaned once no
1982
+ // VM of this seat is confirmed alive. A leftover reply or config.toml is
1983
+ // cleared by the next turn's prepare, after its own check.
1984
+ if (!killed && !pastDeadline()) {
1985
+ try {
1986
+ if (!vmGone) confirmNoSeatVm();
1987
+ await cleanMicrovmHome(home, replyName, stopIfPastDeadline);
1988
+ } catch { /* left in place */ }
1989
+ }
1990
+ try { await turn?.close?.(); } catch { /* ignore */ }
1991
+ try { await providerProxy?.close(); } catch { /* ignore */ }
1992
+ }
1993
+ }, {
1994
+ ...(ctx._seatLockWaitMs ? { waitMs: ctx._seatLockWaitMs } : {}),
1995
+ // The deadline this holder writes into its lock. Past it the holder
1996
+ // touches the HOME no more, and only then may a waiter take a live pid's lock.
1997
+ holdMs: timeoutMs + MICROVM_SEAT_LOCK_MARGIN_MS,
1998
+ });
1999
+ };
2000
+
1434
2001
  // `ownGroup`: see runClaude in claude.js.
1435
2002
  const runCodex = ({
1436
2003
  args, cwd, env, timeoutMs, credentials = [], spawnImpl = childSpawn, onSpawn, controls = {}, ownGroup = false,
1437
- turnReap = turnReapEnabled(), commandResolution = {}, confined = false,
2004
+ turnReap = turnReapEnabled(), commandResolution = {}, confined = false, command = null,
1438
2005
  }) => new Promise((resolve, reject) => { // stdio: ['ignore', 'pipe', 'pipe'] — without this, child_process.spawn
1439
2006
  // defaults stdin to a fresh pipe. Codex 0.125.0's `exec` then blocks on
1440
2007
  // `Reading additional input from stdin...` because it sees an open pipe
@@ -1448,7 +2015,10 @@ const runCodex = ({
1448
2015
  // On Windows `npm i -g @openai/codex` leaves a `codex.cmd`; it is read and
1449
2016
  // its target spawned directly, never through cmd.exe, because the prompt is
1450
2017
  // the last argv element and is pod content (#2141). Identity elsewhere.
1451
- const launch = resolveLaunch('codex', args, { env: turn.env, ...commandResolution });
2018
+ // `command`: the microVM turn runs msb.exe by its full path, never a codex.
2019
+ const launch = command
2020
+ ? { command, args }
2021
+ : resolveLaunch('codex', args, { env: turn.env, ...commandResolution });
1452
2022
  const proc = spawnInOwnGroup(spawnImpl, launch.command, launch.args, { cwd, env: turn.env, stdio: ['ignore', 'pipe', 'pipe'] }, { ownGroup });
1453
2023
  observeSpawn(proc, onSpawn, controls);
1454
2024
  let stderr = '';
@@ -1471,7 +2041,10 @@ const runCodex = ({
1471
2041
  const reaped = describeTurnReap(turn.reap(proc));
1472
2042
  // eslint-disable-next-line no-console
1473
2043
  if (reaped) console.warn(`[codex] ${reaped}`);
1474
- if (timedOut) return reject(new Error(`codex timed out after ${timeoutMs}ms`));
2044
+ // `killed`: the process was stopped from outside (this timeout, or a
2045
+ // signal), not by its own exit. The microVM turn leaves the seat HOME
2046
+ // alone then, since the VM can outlive msb.exe.
2047
+ if (timedOut) return reject(Object.assign(new Error(`codex timed out after ${timeoutMs}ms`), { killed: true }));
1475
2048
  events.flush();
1476
2049
  if (events.turnFailedMessage) {
1477
2050
  // Surface the model-side failure message verbatim — the run loop posts
@@ -1481,15 +2054,19 @@ const runCodex = ({
1481
2054
  // echoed a credential this spawn was handed is redacted before it can be
1482
2055
  // posted into a pod, and a status it names is attached for the circuit
1483
2056
  // breaker rather than left to a regex.
1484
- return reject(adapterFailure('codex turn failed', events.turnFailedMessage, {
2057
+ const failed = adapterFailure('codex turn failed', events.turnFailedMessage, {
1485
2058
  credentials,
1486
2059
  limit: 2000,
1487
- }));
2060
+ });
2061
+ if (signal) failed.killed = true;
2062
+ return reject(failed);
1488
2063
  }
1489
2064
  if (code !== 0) {
1490
- return reject(adapterFailure('codex', stderr.trim(), {
2065
+ const failure = adapterFailure('codex', stderr.trim(), {
1491
2066
  credentials, exitCode: code, limit: 500, signal,
1492
- }));
2067
+ });
2068
+ if (signal) failure.killed = true;
2069
+ return reject(failure);
1493
2070
  }
1494
2071
  resolve({ threadId: events.threadId, turnCompleted: events.turnCompleted });
1495
2072
  });
@@ -1583,20 +2160,28 @@ export default {
1583
2160
  + 'what it is meant to remember is in its Commonly memory.\n');
1584
2161
  sessionId = null;
1585
2162
  }
1586
- const fullPrompt = buildPrompt(prompt, ctx.memoryLongTerm, {
1587
- freshSession: !sessionId,
2163
+ const promptFor = (freshSession) => buildPrompt(prompt, ctx.memoryLongTerm, {
2164
+ freshSession,
1588
2165
  workCues: sandbox?.trust === 'public' ? [] : [ROW_SLICING_CUE, BACKGROUND_PROCESS_CUE],
1589
2166
  // F118: a public seat reads its memory but is not offered a write.
1590
2167
  memoryReadOnly: sandbox?.trust === 'public' && ctx.ownerWoken !== true,
1591
2168
  });
2169
+ const fullPrompt = promptFor(!sessionId);
1592
2170
 
2171
+ // Native Windows, opt-in: a public seat runs inside a microVM
2172
+ // (sandbox/microsandbox.js, docs/cli/microvm-sandbox.md), whatever access
2173
+ // it declared. Resolved here and checked again inside, at every spawn.
2174
+ const microvmSandbox = sandbox?.trust === 'public'
2175
+ && resolveCodexSandboxMode(sandbox, ctx._platform || process.platform) === 'microvm';
1593
2176
  const workspacePath = sandbox?.trust === 'public'
1594
2177
  ? await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'public Codex agents' })
1595
2178
  : null;
1596
2179
  // Codex runs git in the workspace outside the seat's profile, so a
1597
2180
  // repository set up to run programs is refused before anything starts
1598
- // (sandbox/workspace-git-config.js).
1599
- if (workspacePath) {
2181
+ // (sandbox/workspace-git-config.js). In the microVM Codex and its git run
2182
+ // in the guest, over a read-only mount, so nothing in the repository runs
2183
+ // on this computer and the check does not apply.
2184
+ if (workspacePath && !microvmSandbox) {
1600
2185
  (ctx._refuseCodeRunningGitSetup || refuseCodeRunningGitSetup)(workspacePath, {
1601
2186
  seat: 'This public Codex agent', env: ctx.env || process.env,
1602
2187
  });
@@ -1619,6 +2204,14 @@ export default {
1619
2204
  const readyFiles = [];
1620
2205
  let credentialRelease = null;
1621
2206
  try {
2207
+ // The whole microVM turn, or a refusal: it never falls through to a
2208
+ // spawn on this computer, nor to Codex's own Windows sandbox.
2209
+ if (microvmSandbox) {
2210
+ return await runMicrovmTurn({
2211
+ ctx, sandbox, sessionId, prompt: fullPrompt, freshPrompt: () => promptFor(true), seatModel, credential,
2212
+ workspace: workspacePath,
2213
+ });
2214
+ }
1622
2215
  // A public seat can't run git from its shell on macOS: Homebrew's git is
1623
2216
  // outside the profile and /usr/bin/git is an xcrun shim that fails there.
1624
2217
  // So it reads its workspace's history through the read-only git tool a
@@ -1862,7 +2455,7 @@ export default {
1862
2455
  // nothing left to compare a tail against.
1863
2456
  // The per-turn proxy token is one too: codex was handed it in place of the key.
1864
2457
  credentials: [...spawnCredentials(ctx, CODEX_PROVIDER_KEY_ENVS), route?.key, providerProxy?.token].filter(Boolean),
1865
- spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(args.indexOf('exec') + (args[args.indexOf('exec') + 1] === 'resume' ? 3 : 1), -1), { modelFlag: '--model', valueFlags: ['-c', '-o', '--permission-profile'], codex: true }), // test seam only — do not use in production
2458
+ spawnImpl, onSpawn: ctx.onSpawn, controls: codexControls(args), // test seam only — do not use in production
1866
2459
  ownGroup: wantsOwnProcessGroup(ctx),
1867
2460
  turnReap: ctx._turnReap,
1868
2461
  // A public seat keeps nothing a turn leaves running, whatever the turn