@commonlyai/cli 0.1.332 → 0.1.334

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.332",
3
+ "version": "0.1.334",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -112,11 +112,11 @@ import { prepareCommitAttribution } from '../lib/commit-attribution.js';
112
112
  import { detectBwrap } from '../lib/sandbox/bwrap.js';
113
113
  import { resolvePublicSandboxMode } from '../lib/sandbox/mode.js';
114
114
  import {
115
- UNSANDBOXED_FLAG, bwrapRefusedMessage, hostSandboxRefusal, windowsSandboxMessage,
115
+ CODEX_OPTED_IN_PUBLIC_POD_MESSAGE, UNSANDBOXED_FLAG, bwrapRefusedMessage, hostSandboxRefusal, windowsSandboxMessage,
116
116
  } from '../lib/sandbox/host-check.js';
117
117
  import {
118
- CODEX_UNSANDBOXED_NOTICE, UNSANDBOXED_NOTICE, codexUnconfinedForRun, hostReportFailureMessage, hostUnconfinedForRun, runOptedInUnsandboxed,
119
- unsandboxedFlagRefusal,
118
+ UNSANDBOXED_NOTICE, codexUnconfinedForRun, codexUnsandboxedNotice, hostReportFailureMessage, hostUnconfinedForRun,
119
+ runOptedInUnsandboxed, unsandboxedFlagRefusal,
120
120
  } from '../lib/sandbox/windows-unsandboxed.js';
121
121
  import { prepareMcpBeforeFirstPoll } from '../lib/mcp-first-run.js';
122
122
  import { installedCliVersion, startUpdateNotice } from '../lib/update-check.js';
@@ -2868,13 +2868,17 @@ export const performRun = ({
2868
2868
  // failed read is not: it throws, so the event stays unacked and comes back
2869
2869
  // through the spawn-retry backoff instead of being refused for good.
2870
2870
  if (placement.reason) {
2871
- const turnRefusal = placement.unconfinedRefused ? UNCONFINED_TURN_REFUSAL : hostSandboxRefusal({
2871
+ // A Codex run its person opted out of the sandbox was allowed for private
2872
+ // pods only, so a turn placed public is refused on every platform. On
2873
+ // Linux a public Codex seat would otherwise pass the host check and run
2874
+ // in the owner's workspace with strangers able to direct it (F387).
2875
+ const turnRefusal = placement.unconfinedRefused ? UNCONFINED_TURN_REFUSAL : (hostSandboxRefusal({
2872
2876
  environment: placement.environment,
2873
2877
  adapterName: adapter.name,
2874
2878
  hostUnconfined,
2875
2879
  optedIn: codexUnconfined,
2876
2880
  ...(detectBwrapImpl ? { detectBwrap: detectBwrapImpl } : {}),
2877
- });
2881
+ }) || (codexUnconfined ? CODEX_OPTED_IN_PUBLIC_POD_MESSAGE : null));
2878
2882
  if (turnRefusal && placement.readError) {
2879
2883
  throw Object.assign(
2880
2884
  new Error(`turn deferred, because its pods could not be read: ${placement.readError.message}`, {
@@ -3173,8 +3177,11 @@ export const performRun = ({
3173
3177
  // A public seat's Commonly server writes nothing once Commonly is
3174
3178
  // unreachable in its process (lib/public-seat-mcp-flag.js).
3175
3179
  environment: publicSeat ? withPublicSeatMcpFlag(placement.environment) : placement.environment,
3176
- // Only when set, so every other spawn context stays as it was.
3177
- ...(hostUnconfined === true ? { hostUnconfined: true } : {}),
3180
+ // Only when set, so every other spawn context stays as it was. A Codex
3181
+ // run its person opted out with every pod confirmed private keeps
3182
+ // Codex's own policy, never the permission profile (F387): the adapter
3183
+ // reads this, not the environment.
3184
+ ...(hostUnconfined === true || codexUnconfined === true ? { hostUnconfined: true } : {}),
3178
3185
  ...(publicSeat && !memoryWithheld && opened.ownerWoken === true ? { ownerWoken: true } : {}),
3179
3186
  onSkillsLinked: ({ mounted, conflicted }) => {
3180
3187
  skillMount = {
@@ -5489,7 +5496,7 @@ Docs:
5489
5496
  .option('--cascade-reset <ms>', `Silence window that clears the streak (env ${CASCADE_ENV_VARS.resetMs}, default ${CASCADE_DEFAULTS.resetMs})`)
5490
5497
  .option('--refusal-handoff <agent>', 'Agent to @mention when the model provider refuses a request\'s content; the request is acked as refused, never retried')
5491
5498
  .option('--allow <grants>', 'On first run of an agent that works in its folder, also let it edit files and run commands (write) and/or fetch web pages (web), comma-separated. Commands reach the network.')
5492
- .option('--unsandboxed', 'Native Windows only: run this agent without a sandbox, with your own access to files and commands. It gets no connector grants. Codex can run commands in invite-only pods, where anyone in the pod, including people invited later, can direct it.')
5499
+ .option('--unsandboxed', 'Native Windows, or a private Codex agent on Linux: run this agent without a sandbox, with your own access to files and commands. It gets no connector grants. Codex can run commands in invite-only pods, where anyone in the pod, including people invited later, can direct it.')
5493
5500
  .action(async (typedName, opts) => {
5494
5501
  // F306: the seat this run is. `name` is the local key (the token file,
5495
5502
  // the log label, the daemon's plist); the server identity is the record's.
@@ -5504,7 +5511,9 @@ Docs:
5504
5511
  const named = instanceId !== null;
5505
5512
  let name = named ? seatKey(agentArg, instanceId) : agentArg;
5506
5513
  if (opts.unsandboxed) {
5507
- const flagRefusal = unsandboxedFlagRefusal();
5514
+ // On Linux the flag is for a Codex agent only, which the record says;
5515
+ // it is checked again once that is read (F387).
5516
+ const flagRefusal = unsandboxedFlagRefusal(process.platform, { adapterName: opts.adapter || null, deferred: true });
5508
5517
  if (flagRefusal) {
5509
5518
  console.error(`${stamp()} [${name}] ${flagRefusal}`);
5510
5519
  process.exit(1);
@@ -5580,6 +5589,13 @@ Docs:
5580
5589
  // marker is read only by the seats that daemon spawns). Nothing from the
5581
5590
  // server decides this, and the environment never carries it: the seat
5582
5591
  // keeps its trust and tool policy, and only the OS jail is skipped.
5592
+ if (opts.unsandboxed) {
5593
+ const flagRefusal = unsandboxedFlagRefusal(process.platform, { adapterName: record.adapter });
5594
+ if (flagRefusal) {
5595
+ console.error(`${stamp()} [${name}] ${flagRefusal}`);
5596
+ process.exit(1);
5597
+ }
5598
+ }
5583
5599
  const optedIn = runOptedInUnsandboxed({ flag: opts.unsandboxed === true });
5584
5600
  const hostUnconfined = hostUnconfinedForRun({
5585
5601
  optedIn,
@@ -5593,7 +5609,7 @@ Docs:
5593
5609
  // the saved record, loses its sandbox block. A read that fails stays
5594
5610
  // refused: nothing here may assume a pod is private.
5595
5611
  let codexUnconfined = false;
5596
- if (optedIn && record.adapter === 'codex' && process.platform === 'win32') {
5612
+ if (optedIn && record.adapter === 'codex' && (process.platform === 'win32' || process.platform === 'linux')) {
5597
5613
  const seatClient = createClient({ instance: record.instanceUrl, token: record.runtimeToken });
5598
5614
  let installations = null;
5599
5615
  try {
@@ -5618,7 +5634,7 @@ Docs:
5618
5634
  }
5619
5635
  }
5620
5636
  }
5621
- if (codexUnconfined) console.warn(`${stamp()} [${name}] ${CODEX_UNSANDBOXED_NOTICE}`);
5637
+ if (codexUnconfined) console.warn(`${stamp()} [${name}] ${codexUnsandboxedNotice(process.platform)}`);
5622
5638
  let runEnvironment = record.environment;
5623
5639
  if (codexUnconfined && runEnvironment) {
5624
5640
  const { sandbox: _sandbox, ...unsandboxed } = runEnvironment;
@@ -5637,6 +5653,14 @@ Docs:
5637
5653
  console.error(`${stamp()} [${name}] ${hostRefusal}`);
5638
5654
  process.exit(1);
5639
5655
  }
5656
+ // F444: on Linux a private Codex seat has a sandbox, so a flag its pods
5657
+ // rule out leaves it there; say so rather than let the flag look applied.
5658
+ if (optedIn && record.adapter === 'codex' && process.platform === 'linux' && !codexUnconfined) {
5659
+ console.warn(`${stamp()} [${name}] ${UNSANDBOXED_FLAG} was not applied: ${
5660
+ effectiveSandboxTrust(record.environment?.sandbox?.trust) === 'workspace'
5661
+ ? 'this agent is set to workspace trust'
5662
+ : "a pod this agent answers in isn't confirmed private and invite-only"}, so it runs in Codex's own sandbox.`);
5663
+ }
5640
5664
  if (saved && record !== saved) saveAgentToken(name, record);
5641
5665
  if (bootstrapped) {
5642
5666
  // A named instance is saved under its seat key; an unnamed run keeps
@@ -45,7 +45,9 @@ 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
47
  import { createHash } from 'crypto';
48
- import { accessSync, constants, existsSync, realpathSync } from 'fs';
48
+ import {
49
+ accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statSync,
50
+ } from 'fs';
49
51
  import {
50
52
  chmod,
51
53
  lstat,
@@ -83,6 +85,7 @@ import { resolveSkillSource, skillsAsText } from '../skill-prompt.js';
83
85
  import { isLegacySandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
84
86
  import { contains, realpathOfNearest, refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
85
87
  import { refuseCodeRunningGitSetup } from '../sandbox/workspace-git-config.js';
88
+ import { codexTrustedPerimeter } from '../sandbox/codex-perimeter.js';
86
89
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
87
90
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
88
91
  import { startProviderProxy } from '../provider-proxy.js';
@@ -333,6 +336,9 @@ const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
333
336
 
334
337
  const PUBLIC_PERMISSION_PROFILE = 'commonly_public';
335
338
  const PUBLIC_SANDBOX_MODES = new Set(['workspace', 'read-only']);
339
+ // F387: a private seat outside a cloud-codex pod. Not a sandbox for untrusted
340
+ // input: public seats keep commonly_public.
341
+ const PRIVATE_PERMISSION_PROFILE = 'commonly_private';
336
342
 
337
343
  const statOrNull = async (path) => {
338
344
  try {
@@ -382,6 +388,16 @@ const publicCodexHomesRoot = (ctx) => {
382
388
  return root;
383
389
  };
384
390
 
391
+ // An XDG_STATE_HOME under ~/.commonly throws above, and that tree is denied anyway.
392
+ const privatePublicHomesDeny = (ctx) => {
393
+ if ((ctx._platform || process.platform) !== 'linux') return [];
394
+ try {
395
+ return [publicCodexHomesRoot(ctx)];
396
+ } catch {
397
+ return [];
398
+ }
399
+ };
400
+
385
401
  const operatorCodexHome = (ctx) => ctx.env?.CODEX_HOME
386
402
  || process.env.CODEX_HOME
387
403
  || join(homedir(), '.codex');
@@ -626,20 +642,9 @@ const parseCodexVersion = (stdout) => (
626
642
  /^codex-cli (\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\s*$/m.exec(String(stdout))?.[1] || null
627
643
  );
628
644
 
629
- const publicPermissionProfileFlags = (
630
- mode,
631
- commitAttributionEnv = null,
632
- mcpReadDirectories = [],
633
- codexHelperReadPaths = [],
634
- platform = process.platform,
635
- workspacePath = null,
636
- ) => {
637
- if (!PUBLIC_SANDBOX_MODES.has(mode)) {
638
- throw new Error(
639
- `public codex agents require sandbox.mode=workspace or read-only, got ${mode || 'unset'}`,
640
- );
641
- }
642
- const workspaceAccess = mode === 'read-only' ? 'read' : 'write';
645
+ // The commit-attribution hooks a profile has to let the shell read: the hooks
646
+ // folder Commonly installs, and each executable hook the repository already had.
647
+ const commitHookReadPaths = (commitAttributionEnv) => {
643
648
  const commitHooksPath = commitAttributionEnv?.COMMONLY_AGENT_HOOKS_PATH || null;
644
649
  const originalHooksPath = commitAttributionEnv?.COMMONLY_AGENT_ORIGINAL_HOOKS_PATH || null;
645
650
  const originalHookPaths = originalHooksPath
@@ -654,14 +659,37 @@ const publicPermissionProfileFlags = (
654
659
  }
655
660
  })
656
661
  : [];
662
+ return { commitHooksPath, originalHookPaths };
663
+ };
664
+
665
+ // Codex's default name filter treats GIT_CONFIG_KEY_n as sensitive, so the
666
+ // attribution keys are set again after filtering. Their values stay in the
667
+ // environment instead of riding argv.
668
+ const gitConfigKeyShellSet = (commitAttributionEnv) => Object.entries(commitAttributionEnv || {})
669
+ .filter(([name]) => /^GIT_CONFIG_KEY_\d+$/.test(name))
670
+ .map(([name, value]) => `${toml(name)}=${toml(value)}`);
671
+
672
+ const publicPermissionProfileFlags = (
673
+ mode,
674
+ commitAttributionEnv = null,
675
+ mcpReadDirectories = [],
676
+ codexHelperReadPaths = [],
677
+ platform = process.platform,
678
+ workspacePath = null,
679
+ ) => {
680
+ if (!PUBLIC_SANDBOX_MODES.has(mode)) {
681
+ throw new Error(
682
+ `public codex agents require sandbox.mode=workspace or read-only, got ${mode || 'unset'}`,
683
+ );
684
+ }
685
+ const workspaceAccess = mode === 'read-only' ? 'read' : 'write';
686
+ const { commitHooksPath, originalHookPaths } = commitHookReadPaths(commitAttributionEnv);
657
687
  // Preserve caller-supplied git config entries alongside the appended
658
688
  // hooksPath entry. The explicit allowlist below admits only these concrete
659
689
  // variable names, not arbitrary environment variables.
660
690
  const gitConfigEnv = Object.keys(commitAttributionEnv || {})
661
691
  .filter((name) => /^GIT_CONFIG_(?:COUNT|KEY_\d+|VALUE_\d+)$/.test(name));
662
- const gitConfigKeySet = Object.entries(commitAttributionEnv || {})
663
- .filter(([name]) => /^GIT_CONFIG_KEY_\d+$/.test(name))
664
- .map(([name, value]) => `${toml(name)}=${toml(value)}`);
692
+ const gitConfigKeySet = gitConfigKeyShellSet(commitAttributionEnv);
665
693
  // The profile denies $TMPDIR and /tmp, so a shell heredoc fails. Set for the
666
694
  // model's shell alone: codex, its MCP child and the per-turn folder keep the
667
695
  // host's temp root, which spawn refuses to find in the workspace. The
@@ -725,6 +753,204 @@ const publicPermissionProfileFlags = (
725
753
  ];
726
754
  };
727
755
 
756
+ // Host secrets a private seat's shell never reads. ~/.commonly holds every
757
+ // seat's tokens and state; the seat's own workspace sits under it and is
758
+ // admitted by the more specific workspace rule (on Linux too: measured on
759
+ // codex-cli 0.164.0, a write key inside a denied folder works there). The
760
+ // Codex home is privateCodexHomeDenies'. gh keeps working: on macOS its
761
+ // login is in the keychain, which a credential the seat itself uses has to be.
762
+ const PRIVATE_SECRET_DENIES = Object.freeze([
763
+ '~/.commonly', '~/.claude', '~/.ssh', '~/.aws', '~/.gnupg',
764
+ '~/.kube', '~/.docker', '~/.netrc', '~/.config/gcloud',
765
+ ]);
766
+
767
+ const realOrSelf = (path) => {
768
+ try {
769
+ return realpathSync(path);
770
+ } catch {
771
+ return path;
772
+ }
773
+ };
774
+
775
+ // F444: what the private profile denies of the Codex home the seat runs with.
776
+ // On macOS the home is denied whole. On Linux Codex execs its sandbox helper
777
+ // from `<home>/tmp/arg0-linux` inside bwrap, and a denied home stops every turn
778
+ // at start ("bwrap: execvp codex-linux-sandbox: Permission denied"; a read key
779
+ // for `tmp` under the denied home does not lift it). Measured with `codex
780
+ // sandbox` and a real turn on codex-cli 0.164.0, ubuntu-22.04. So there the
781
+ // home itself stays readable and everything in it is denied except the helper
782
+ // folder: each entry present now, and the names Codex writes later even while
783
+ // they are absent (a key for a missing path is accepted there). Codex's SQLite
784
+ // databases write a `-wal` file during the turn that holds their newest rows,
785
+ // other sessions' included, and SQLite removes it when the last connection
786
+ // closes; so every database name, listed or known, takes its `-wal`, `-shm`
787
+ // and `-journal` too. A database under a new name is listed, with those, from
788
+ // the next turn. No globs: Codex's `*` crosses `/`, and a glob that matched a
789
+ // file inside a folder already denied stopped every turn at start ("bwrap:
790
+ // Can't create file at …: Read-only file system", run 43103991434).
791
+ // `~/.codex` is denied whole when it isn't that home.
792
+ const CODEX_HOME_SECRET_NAMES = Object.freeze([
793
+ 'auth.json', 'config.toml', 'sessions', 'archived_sessions', 'history.jsonl', 'log',
794
+ 'session_index.jsonl', 'shell_snapshots', 'memories',
795
+ 'logs_2.sqlite', 'state_5.sqlite', 'goals_1.sqlite', 'queue_1.sqlite',
796
+ ]);
797
+ const SQLITE_SIDECARS = Object.freeze(['-wal', '-shm', '-journal']);
798
+ const CODEX_HELPER_PATH = Object.freeze(['tmp', 'arg0-linux']);
799
+
800
+ const entriesOf = (dir) => {
801
+ try {
802
+ return readdirSync(dir);
803
+ } catch {
804
+ return [];
805
+ }
806
+ };
807
+
808
+ export const privateCodexHomeDenies = ({ codexHome = null, platform = process.platform, home = homedir() } = {}) => {
809
+ const defaultHome = join(home, '.codex');
810
+ const runHome = codexHome ? realOrSelf(codexHome) : null;
811
+ const runsFromDefault = !runHome || runHome === realOrSelf(defaultHome);
812
+ if (platform !== 'linux') return runsFromDefault ? ['~/.codex'] : ['~/.codex', runHome];
813
+ const helperHome = runHome || realOrSelf(defaultHome);
814
+ const denies = runsFromDefault ? [] : ['~/.codex'];
815
+ // Deny every sibling of the helper path at each level, so only the path
816
+ // itself stays reachable.
817
+ let dir = helperHome;
818
+ for (const [depth, keep] of CODEX_HELPER_PATH.entries()) {
819
+ const names = new Set(entriesOf(dir));
820
+ if (depth === 0) {
821
+ CODEX_HOME_SECRET_NAMES.forEach((name) => names.add(name));
822
+ [...names].filter((name) => /\.(sqlite|db)$/.test(name))
823
+ .forEach((name) => SQLITE_SIDECARS.forEach((suffix) => names.add(`${name}${suffix}`)));
824
+ }
825
+ names.delete(keep);
826
+ denies.push(...[...names].sort().map((name) => join(dir, name)));
827
+ dir = join(dir, keep);
828
+ }
829
+ return denies;
830
+ };
831
+
832
+ // What a commit writes, and nothing that runs code. Codex keeps a workspace's
833
+ // `.git` read-only even inside a writable root, and only an explicit absolute
834
+ // key opens it (measured with `codex sandbox` on 0.162.1: the same key inside
835
+ // :workspace_roots did not). `config` and `hooks` stay read-only, because a
836
+ // hook or a config-defined program (core.fsmonitor, a filter) would run as the
837
+ // person in every later git command there, outside any sandbox; renaming over
838
+ // them is refused too (measured). A git worktree keeps its admin folder
839
+ // outside the workspace (`.git` is a file naming it), and a commit there also
840
+ // writes the shared repository's objects, refs and logs, and packed-refs when
841
+ // git repacks them. Read from the files git leaves, without running git.
842
+ // Measured: a worktree whose repository lies under the denied ~/.commonly
843
+ // can't commit (git can't resolve the path), whatever these keys are.
844
+ const gitAdminKeys = (workspace) => {
845
+ if (!workspace) return [];
846
+ const dotGit = join(workspace, '.git');
847
+ const ownRepository = (dir) => {
848
+ const real = realOrSelf(dir);
849
+ return [
850
+ [real, 'write'],
851
+ [join(real, 'config'), 'read'],
852
+ [join(real, 'config.worktree'), 'read'],
853
+ [join(real, 'hooks'), 'read'],
854
+ ];
855
+ };
856
+ try {
857
+ if (statSync(dotGit).isDirectory()) return ownRepository(dotGit);
858
+ } catch {
859
+ return [];
860
+ }
861
+ try {
862
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, 'utf8'))?.[1]?.trim();
863
+ if (!pointer) return [];
864
+ const gitDir = pathResolve(workspace, pointer);
865
+ let commonDir = null;
866
+ try {
867
+ commonDir = pathResolve(gitDir, readFileSync(join(gitDir, 'commondir'), 'utf8').trim());
868
+ } catch {
869
+ // A linked gitdir that is a whole repository of its own.
870
+ return ownRepository(gitDir);
871
+ }
872
+ const realGitDir = realOrSelf(gitDir);
873
+ const realCommon = realOrSelf(commonDir);
874
+ return [
875
+ [realGitDir, 'write'],
876
+ [join(realGitDir, 'config.worktree'), 'read'],
877
+ ...['objects', 'refs', 'logs', 'packed-refs', 'packed-refs.lock']
878
+ .map((name) => [join(realCommon, name), 'write']),
879
+ ];
880
+ } catch {
881
+ // An unreadable `.git` file.
882
+ return [];
883
+ }
884
+ };
885
+
886
+ // F387: the profile for a private Codex seat outside a cloud-codex pod. It is
887
+ // the seat owner's own agent doing dev work, so the disk stays readable, the
888
+ // network is on and the environment is inherited (with Codex's secret-name
889
+ // filter on); what it removes is every host secret the seat doesn't use
890
+ // itself. It is not a sandbox for untrusted input: public seats keep
891
+ // commonly_public.
892
+ const privatePermissionProfileFlags = ({
893
+ commitAttributionEnv = null,
894
+ mcpReadDirectories = [],
895
+ codexHelperReadPaths = [],
896
+ platform = process.platform,
897
+ workspace = null,
898
+ tempRoots = [],
899
+ shellTempDir = null,
900
+ codexHome = null,
901
+ home = homedir(),
902
+ otherCodexHomes = [],
903
+ } = {}) => {
904
+ const { commitHooksPath, originalHookPaths } = commitHookReadPaths(commitAttributionEnv);
905
+ const posix = platform !== 'win32';
906
+ // The temp roots hold every seat's per-turn folder: its runtime token and the
907
+ // reply file Codex posts from. So they are denied whole, and the shell gets
908
+ // one folder of its own inside this turn's, as TMPDIR (and TMPPREFIX, which
909
+ // zsh takes its heredoc files from). Codex, and the MCP child that reads the
910
+ // token, run outside the profile. On Windows these keys have no drive.
911
+ const deniedTemp = posix
912
+ ? [...new Set(['/private/tmp', ...tempRoots.filter(Boolean).map(realOrSelf)])]
913
+ : [];
914
+ const shellTemp = posix && shellTempDir ? realOrSelf(shellTempDir) : null;
915
+ const filesystem = [
916
+ // Codex reads every key as a path for its own platform; on Windows "/" has
917
+ // no drive and Codex would refuse the whole profile (as with /private/tmp
918
+ // in publicPermissionProfileFlags).
919
+ posix ? '"/"="read"' : '":minimal"="read"',
920
+ ...[...PRIVATE_SECRET_DENIES, ...privateCodexHomeDenies({ codexHome, platform, home }), ...otherCodexHomes]
921
+ .map((path) => `${toml(path)}="deny"`),
922
+ ...deniedTemp.map((path) => `${toml(path)}="deny"`),
923
+ ...(shellTemp ? [`${toml(shellTemp)}="write"`] : []),
924
+ '":workspace_roots"={"."="write",".commonly/**"="deny",".codex/**"="deny"}',
925
+ ...gitAdminKeys(workspace).map(([path, mode]) => `${toml(path)}=${toml(mode)}`),
926
+ ...(commitHooksPath ? [`${toml(commitHooksPath)}="read"`] : []),
927
+ ...originalHookPaths.map((hookPath) => `${toml(hookPath)}="read"`),
928
+ ...mcpReadDirectories.map((path) => `${toml(path)}="read"`),
929
+ ...codexHelperReadPaths.map((path) => `${toml(path)}="read"`),
930
+ ].join(',');
931
+ const shellSet = [
932
+ ...gitConfigKeyShellSet(commitAttributionEnv),
933
+ ...(shellTemp
934
+ ? [
935
+ `${toml('TMPDIR')}=${toml(shellTemp)}`,
936
+ `${toml('TMPPREFIX')}=${toml(join(shellTemp, 'zsh'))}`,
937
+ // macOS's /usr/bin tools are xcrun shims, which keep a cache in the
938
+ // user temp root (denied above) and print an error on every call
939
+ // without this.
940
+ `${toml('xcrun_db')}=${toml(join(shellTemp, 'xcrun_db'))}`,
941
+ ]
942
+ : []),
943
+ ];
944
+ return [
945
+ '-c', `default_permissions=${toml(PRIVATE_PERMISSION_PROFILE)}`,
946
+ '-c', `permissions.${PRIVATE_PERMISSION_PROFILE}.filesystem={${filesystem}}`,
947
+ '-c', `permissions.${PRIVATE_PERMISSION_PROFILE}.network.enabled=true`,
948
+ '-c', 'shell_environment_policy.inherit="all"',
949
+ '-c', 'shell_environment_policy.ignore_default_excludes=false',
950
+ ...(shellSet.length ? ['-c', `shell_environment_policy.set={${shellSet.join(',')}}`] : []),
951
+ ];
952
+ };
953
+
728
954
  // F188: the host's OpenAI-compatible model route, for a public seat. That seat
729
955
  // runs with `--ignore-user-config`, so config.toml's `openai_base_url` never
730
956
  // loads, and codex-cli 0.162.1 does not read the OPENAI_BASE_URL env either
@@ -836,8 +1062,21 @@ const buildArgs = ({
836
1062
  providerProxy = null,
837
1063
  platform = process.platform,
838
1064
  workspacePath = null,
1065
+ trustedContainerPerimeter = false,
1066
+ operatorUnconfined = false,
1067
+ privateWorkspace = null,
1068
+ tempRoots = [],
1069
+ shellTempDir = null,
1070
+ privateCodexHome = null,
1071
+ privateHome = homedir(),
1072
+ privateOtherCodexHomes = [],
839
1073
  }) => {
840
1074
  const publicSandbox = publicSandboxMode !== null;
1075
+ // F387: a private seat keeps the flag below only in a cloud-codex pod, or
1076
+ // when its operator opted this run out of the OS sandbox (D245, native
1077
+ // Windows only: Codex can't enforce a profile's read denies there).
1078
+ const keepsOwnPolicy = trustedContainerPerimeter || operatorUnconfined;
1079
+ const privateProfile = !publicSandbox && !keepsOwnPolicy;
841
1080
  // `--dangerously-bypass-approvals-and-sandbox` disables codex CLI's
842
1081
  // bubblewrap (bwrap) sandbox + approval prompts. bwrap needs CAP_SYS_ADMIN
843
1082
  // or unprivileged user-namespaces — neither available to standard k8s
@@ -852,6 +1091,15 @@ const buildArgs = ({
852
1091
  // versions spawn admits (PUBLIC_CODEX_MIN_VERSION). Do not
853
1092
  // pass legacy `--sandbox` alongside them: Codex documents that the legacy
854
1093
  // mode disables permission-profile composition.
1094
+ //
1095
+ // F387 (TASK-280): the flag above belongs to a cloud-codex k8s pod, where
1096
+ // bwrap cannot run and the pod is the boundary, or to a run its operator
1097
+ // opted out (keepsOwnPolicy). Every other private seat gets
1098
+ // privatePermissionProfileFlags: readable disk, network on, host secret dirs
1099
+ // denied. It keeps the seat's own config and route (no --ignore-user-config),
1100
+ // since a private seat relies on its config.toml; the -c profile still wins
1101
+ // over config defaults (checked against sandbox_mode, default_permissions and
1102
+ // a user [permissions.*] table on codex-cli 0.162.1).
855
1103
  const executionPolicy = publicSandbox
856
1104
  ? [
857
1105
  '--ignore-user-config',
@@ -867,7 +1115,20 @@ const buildArgs = ({
867
1115
  ...providerRouteFlags(providerProxy),
868
1116
  ...PUBLIC_BUILTIN_TOOL_FLAGS,
869
1117
  ]
870
- : ['--dangerously-bypass-approvals-and-sandbox'];
1118
+ : keepsOwnPolicy
1119
+ ? ['--dangerously-bypass-approvals-and-sandbox']
1120
+ : privatePermissionProfileFlags({
1121
+ commitAttributionEnv,
1122
+ mcpReadDirectories,
1123
+ codexHelperReadPaths,
1124
+ platform,
1125
+ workspace: privateWorkspace,
1126
+ tempRoots,
1127
+ shellTempDir,
1128
+ codexHome: privateCodexHome,
1129
+ home: privateHome,
1130
+ otherCodexHomes: privateOtherCodexHomes,
1131
+ });
871
1132
  const common = [
872
1133
  '--json',
873
1134
  '--skip-git-repo-check',
@@ -884,8 +1145,9 @@ const buildArgs = ({
884
1145
  ];
885
1146
  // Approval policy is a global option in Codex 0.144, so it must precede
886
1147
  // the `exec` subcommand. A denied operation is returned to the model;
887
- // non-interactive public agents never hang waiting for an operator.
888
- const prefix = publicSandbox ? ['--ask-for-approval', 'never'] : [];
1148
+ // non-interactive agents never hang waiting for an operator. A private seat
1149
+ // under its profile keeps its own config.toml, which may ask for approvals.
1150
+ const prefix = publicSandbox || privateProfile ? ['--ask-for-approval', 'never'] : [];
889
1151
  if (sessionId) {
890
1152
  // Place <sessionId> immediately after the `exec resume` subcommand so a
891
1153
  // future codex parser change can't accidentally consume it as the value
@@ -1212,16 +1474,32 @@ export default {
1212
1474
  if (routeNames.has(name.toUpperCase())) delete childEnv[name];
1213
1475
  }
1214
1476
  }
1477
+ // F387: only a cloud-codex pod sets the perimeter env
1478
+ // (sandbox/codex-perimeter.js), and only the operator's own D245 opt-in
1479
+ // sets hostUnconfined. Every other private seat runs under the private
1480
+ // permission profile.
1481
+ const trustedContainerPerimeter = codexTrustedPerimeter(ctx.env || process.env);
1482
+ const operatorUnconfined = ctx.hostUnconfined === true;
1483
+ const privateProfile = publicSandboxMode === null && !trustedContainerPerimeter && !operatorUnconfined;
1215
1484
  // Before the public home is prepared, so a refused seat changes nothing.
1216
- if (publicSandboxMode !== null) {
1485
+ // A private profile uses the same permission keys, tested to the same bar.
1486
+ if (publicSandboxMode !== null || privateProfile) {
1217
1487
  const codexVersion = await readCodexVersion(ctx, childEnv);
1218
1488
  if (!meetsMinimumVersion(codexVersion, PUBLIC_CODEX_MIN_VERSION)) {
1219
- throw publicCodexVersionError({ found: codexVersion, required: PUBLIC_CODEX_MIN_VERSION });
1489
+ throw publicCodexVersionError({
1490
+ found: codexVersion,
1491
+ required: PUBLIC_CODEX_MIN_VERSION,
1492
+ seat: publicSandboxMode !== null ? 'public seat' : 'private seat',
1493
+ });
1220
1494
  }
1221
1495
  }
1222
1496
  const publicCodexHome = publicSandboxMode !== null
1223
1497
  ? await preparePublicCodexHome(ctx, childEnv, { login: !route })
1224
1498
  : null;
1499
+ // The private shell's TMPDIR: inside this turn's folder, which `finally`
1500
+ // removes, and beside (not over) the token's folder.
1501
+ const privateShellTemp = privateProfile ? join(dir, 'shell-tmp') : null;
1502
+ if (privateShellTemp) await mkdir(privateShellTemp, { mode: 0o700 });
1225
1503
  if (route) {
1226
1504
  providerProxy = await (ctx._startProviderProxy || startProviderProxy)({
1227
1505
  provider: { baseURL: route.baseURL },
@@ -1249,6 +1527,22 @@ export default {
1249
1527
  providerProxy,
1250
1528
  platform: ctx._platform || process.platform,
1251
1529
  workspacePath,
1530
+ trustedContainerPerimeter,
1531
+ operatorUnconfined,
1532
+ privateWorkspace: privateProfile && ctx.cwd ? pathResolve(ctx.cwd) : null,
1533
+ // Both roots: this process's, where every seat's per-turn folder
1534
+ // lives, and the one the shell would inherit.
1535
+ tempRoots: privateProfile ? [tmpdir(), childEnv.TMPDIR] : [],
1536
+ shellTempDir: privateShellTemp,
1537
+ // The home Codex runs with, and the HOME its `~` keys expand against.
1538
+ // Codex reads a relative CODEX_HOME from its own folder, the turn's.
1539
+ privateCodexHome: privateProfile
1540
+ ? pathResolve(ctx.cwd || process.cwd(), childEnv.CODEX_HOME || join(childEnv.HOME || homedir(), '.codex'))
1541
+ : null,
1542
+ privateHome: childEnv.HOME || homedir(),
1543
+ // Public seats' Codex homes (their sessions and logs): under the denied
1544
+ // ~/.commonly on macOS, outside it on Linux.
1545
+ privateOtherCodexHomes: privateProfile ? privatePublicHomesDeny(ctx) : [],
1252
1546
  });
1253
1547
  // childEnv is derived from the process environment, so the bootstrap export has to be
1254
1548
  // taken back out: the declaration above moved our server onto the file,
@@ -41,11 +41,13 @@ export const PUBLIC_CODEX_VERSION_CODE = 'public_codex_version';
41
41
 
42
42
  // `found` stays in this message, which only the seat's log shows. The line a pod
43
43
  // sees is built from `requiredVersion` (turn-failure-notice.js).
44
- export const publicCodexVersionError = ({ found, required }) => {
44
+ // `seat` names which seat refused: a private seat under its permission profile
45
+ // (F387) needs the same tested version as a public one.
46
+ export const publicCodexVersionError = ({ found, required, seat = 'public seat' }) => {
45
47
  const error = new Error(found
46
- ? `public seat refused this turn: Codex ${found} is older than this seat needs. `
48
+ ? `${seat} refused this turn: Codex ${found} is older than this seat needs. `
47
49
  + `Upgrade Codex to at least ${required} and start the agent again.`
48
- : 'public seat refused this turn: could not read the Codex version. '
50
+ : `${seat} refused this turn: could not read the Codex version. `
49
51
  + `Check that \`codex --version\` works for this agent, upgrade Codex to at least ${required} `
50
52
  + 'if it is older, and start the agent again.');
51
53
  error.code = PUBLIC_CODEX_VERSION_CODE;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * F387: a cloud-codex k8s pod declares itself with this env var, set only by
3
+ * k8s/helm/commonly/templates/agents/cloud-codex-deployment.yaml. bwrap can't
4
+ * run in a standard k8s container and the pod is the boundary, so a Codex seat
5
+ * there keeps the pod's execution policy. Anywhere else a private Codex seat
6
+ * runs under the private permission profile (adapters/codex.js); on Linux it
7
+ * is refused by default until that profile is walked there (host-check.js).
8
+ *
9
+ * Only the exact value "1" counts, so a missing or mistyped value lands on the
10
+ * profile.
11
+ */
12
+ export const CODEX_TRUSTED_PERIMETER_ENV = 'COMMONLY_CODEX_TRUSTED_PERIMETER';
13
+
14
+ export const codexTrustedPerimeter = (env = process.env) => (
15
+ String(env?.[CODEX_TRUSTED_PERIMETER_ENV] ?? '').trim() === '1'
16
+ );
@@ -21,6 +21,7 @@ import { normalizeSandboxTrust } from '../environment.js';
21
21
  import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from './mode.js';
22
22
  import { detectBwrap as defaultDetectBwrap } from './bwrap.js';
23
23
  import { detectSeatbelt as defaultDetectSeatbelt } from './seatbelt.js';
24
+ import { codexTrustedPerimeter } from './codex-perimeter.js';
24
25
  import { CLI } from '../cli-hint.js';
25
26
 
26
27
  // D245: the Windows opt-in (windows-unsandboxed.js re-exports it; defined here to avoid an import cycle).
@@ -121,6 +122,50 @@ export const bwrapRefusedMessage = (adapterName, { reason, apparmorRestricted, u
121
122
  ].join('\n');
122
123
  };
123
124
 
125
+ const CODEX_UNSANDBOXED_RUN_LINE = ` - In invite-only pods, run it without a sandbox: ${CLI} agent run <name> ${UNSANDBOXED_FLAG}`
126
+ + ' (in the foreground; the daemon takes this only on Windows).'
127
+ + ' Nothing confines it: it runs with your own access to files and commands, anyone in the pod,'
128
+ + ' people you invite later included, can direct it, and it gets no connector grants.';
129
+
130
+ /**
131
+ * F387, F444: a private Codex seat on Linux runs under Codex's own sandbox,
132
+ * which uses bubblewrap there. Where bubblewrap can't start one, the seat is
133
+ * refused before its first poll, with the fix for this host. The person can
134
+ * run it unconfined by their own choice, as on native Windows; it never falls
135
+ * back to that without being asked.
136
+ */
137
+ export const codexPrivateLinuxMessage = (bwrap = {}, { optedIn = false } = {}) => {
138
+ const refused = bwrap.namespaceRefused === true;
139
+ const offersProfile = refused && bwrap.apparmorRestricted === true && bwrap.ubuntuRelease === '24.04';
140
+ return [
141
+ 'A private Codex agent runs inside Codex\'s own sandbox, which keeps your other credentials out of its reach'
142
+ + ` and uses bubblewrap on Linux. ${refused
143
+ ? `This machine won't let bubblewrap start one (${bwrap.reason}).`
144
+ : (bwrap.error || 'bubblewrap was not found.')}`,
145
+ ...(refused && bwrap.apparmorRestricted === true
146
+ ? ['AppArmor on Ubuntu 24.04 and later restricts the user namespaces bubblewrap needs.']
147
+ : []),
148
+ ...(optedIn
149
+ ? ['A pod this agent answers in is publicly readable or open to join, or did not report whether it is,'
150
+ + ' so it cannot run without a sandbox either.']
151
+ : []),
152
+ 'So this agent cannot listen for @mentions here yet. You can:',
153
+ ...(refused ? [] : [' - Install bubblewrap (`sudo apt install bubblewrap`) and run the same command again.']),
154
+ ...(optedIn ? [] : [CODEX_UNSANDBOXED_RUN_LINE]),
155
+ HOSTED_LINE,
156
+ ...(offersProfile ? UBUNTU_BWRAP_PROFILE_LINES : []),
157
+ ].join('\n');
158
+ };
159
+
160
+ // The person opted in, and a pod rules it out, so the turn has no sandbox to
161
+ // fall back to on any platform. Naming the flag again would only send them
162
+ // round in a circle.
163
+ export const CODEX_OPTED_IN_PUBLIC_POD_MESSAGE = [
164
+ 'A pod this agent answers in is publicly readable or open to join, or did not report whether it is,',
165
+ 'so it cannot run without a sandbox. You can:',
166
+ HOSTED_LINE,
167
+ ].join('\n');
168
+
124
169
  /** What a person on native Windows can do instead. */
125
170
  export const windowsSandboxMessage = (adapterName) => {
126
171
  if (adapterName === 'codex') return CODEX_WINDOWS_MESSAGE;
@@ -158,6 +203,8 @@ export const hostSandboxRefusal = ({
158
203
  optedIn = false,
159
204
  detectBwrap = defaultDetectBwrap,
160
205
  detectSeatbelt = defaultDetectSeatbelt,
206
+ // F387: a cloud-codex pod declares itself here (codex-perimeter.js).
207
+ env = process.env,
161
208
  } = {}) => {
162
209
  if (adapterName === 'codex') {
163
210
  // Keyed on trust, not mode: Codex resolves no Seatbelt or bwrap mode of its
@@ -172,6 +219,19 @@ export const hostSandboxRefusal = ({
172
219
  const bwrap = detectBwrap();
173
220
  return bwrap.namespaceRefused === true ? bwrapRefusedMessage(adapterName, bwrap) : null;
174
221
  }
222
+ // F387, F444: a private seat outside a cloud-codex pod runs under the
223
+ // private permission profile, which Codex enforces with bubblewrap on Linux
224
+ // (walked on byo-linux.yml, walk=private-codex). Where bubblewrap can't
225
+ // start, every turn would fail at session start, so the seat is refused
226
+ // before its first poll, unless the person ran it unconfined by their own
227
+ // --unsandboxed (D245, as on Windows: only with every pod confirmed
228
+ // private). Never unconfined without being asked.
229
+ if (platform === 'linux' && trust !== 'workspace' && !codexTrustedPerimeter(env)) {
230
+ if (hostUnconfined === true) return null;
231
+ const bwrap = detectBwrap();
232
+ if (bwrap.available) return null;
233
+ return codexPrivateLinuxMessage(bwrap, { optedIn: optedIn === true });
234
+ }
175
235
  if (platform !== 'win32') return null;
176
236
  if (trust === 'workspace') return null;
177
237
  if (trust === 'public') return optedIn === true ? CODEX_WINDOWS_PUBLIC_MESSAGE : CODEX_WINDOWS_MESSAGE;
@@ -53,10 +53,19 @@ export { UNSANDBOXED_FLAG };
53
53
 
54
54
  export const unsandboxedMarkerPath = (home = homedir()) => join(home, '.commonly', 'daemon', 'unsandboxed.json');
55
55
 
56
- /** The flag is a Windows answer to a Windows gap; anywhere else it is refused. */
57
- export const unsandboxedFlagRefusal = (platform = process.platform) => (platform === 'win32'
58
- ? null
59
- : `${UNSANDBOXED_FLAG} is only for native Windows, which has no sandbox for agents yet. On this machine agents run in a sandbox.`);
56
+ /**
57
+ * The flag answers a gap in the sandbox: native Windows has none, and a private
58
+ * Codex agent on Linux has none where bubblewrap can't start (F387, F444). So
59
+ * on Linux it is accepted only for `agent run` of a Codex agent: pass `adapterName` once it is known,
60
+ * or `deferred` before the record is read (the run checks again after). The
61
+ * daemon's marker stays Windows-only.
62
+ */
63
+ export const unsandboxedFlagRefusal = (platform = process.platform, { adapterName = null, deferred = false } = {}) => {
64
+ if (platform === 'win32') return null;
65
+ if (platform === 'linux' && (adapterName === 'codex' || (deferred && adapterName === null))) return null;
66
+ return `${UNSANDBOXED_FLAG} is only for native Windows, which has no sandbox for agents yet, and for`
67
+ + ` \`agent run\` of a private Codex agent on Linux. On this machine this agent runs in a sandbox.`;
68
+ };
60
69
 
61
70
  export const loadUnsandboxedOptIn = ({
62
71
  platform = process.platform, home = homedir(), exists = existsSync, read = readFileSync,
@@ -114,8 +123,8 @@ export const hostUnconfinedForRun = ({
114
123
  };
115
124
 
116
125
  /**
117
- * Does this Codex run go unconfined? Only on win32, only by the user's own
118
- * opt-in, and only when every pod the seat answers in is confirmed private:
126
+ * Does this Codex run go unconfined? Only on win32, or on Linux (F387, F444),
127
+ * only by the user's own opt-in, and only when every pod the seat answers in is confirmed private:
119
128
  * `installations` is the server's read of them, and an empty or failed read is
120
129
  * a no. Workspace trust stays with Codex's own refusal. The caller removes the
121
130
  * sandbox block for this run only, so the saved record keeps its public trust
@@ -123,7 +132,7 @@ export const hostUnconfinedForRun = ({
123
132
  */
124
133
  export const codexUnconfinedForRun = ({
125
134
  optedIn, adapterName, environment, installations, platform = process.platform,
126
- }) => platform === 'win32' && optedIn === true && adapterName === 'codex'
135
+ }) => (platform === 'win32' || platform === 'linux') && optedIn === true && adapterName === 'codex'
127
136
  && effectiveSandboxTrust(environment?.sandbox?.trust) !== 'workspace'
128
137
  && allPodsConfirmedPrivate(installations);
129
138
 
@@ -142,6 +151,12 @@ export const UNSANDBOXED_NOTICE = 'unsandboxed (opted in): Windows has no sandbo
142
151
  /** Codex has no restricted tool settings to keep, so its line says what it costs instead. */
143
152
  export const CODEX_UNSANDBOXED_NOTICE = 'unsandboxed (opted in): Windows has no sandbox Codex can use here, so nothing confines this agent. It runs with your own access to files and commands, and anyone in its pods, people invited later included, can direct it. It gets no connector grants, and a turn is refused if a pod stops being invite-only.';
144
153
 
154
+ export const CODEX_LINUX_UNSANDBOXED_NOTICE = 'unsandboxed (opted in): you ran this Codex agent without its sandbox, so nothing confines this agent. It runs with your own access to files and commands, and anyone in its pods, people invited later included, can direct it. It gets no connector grants, and a turn is refused if a pod stops being invite-only.';
155
+
156
+ export const codexUnsandboxedNotice = (platform = process.platform) => (platform === 'linux'
157
+ ? CODEX_LINUX_UNSANDBOXED_NOTICE
158
+ : CODEX_UNSANDBOXED_NOTICE);
159
+
145
160
  // A 404 here is a server from before this route, which reads like a missing agent.
146
161
  export const hostReportFailureMessage = (err) => {
147
162
  const hint = err?.status === 404
@@ -151,7 +166,9 @@ export const hostReportFailureMessage = (err) => {
151
166
  };
152
167
 
153
168
  export default {
169
+ CODEX_LINUX_UNSANDBOXED_NOTICE,
154
170
  CODEX_UNSANDBOXED_NOTICE,
171
+ codexUnsandboxedNotice,
155
172
  UNSANDBOXED_FLAG,
156
173
  UNSANDBOXED_NOTICE,
157
174
  codexUnconfinedForRun,
@@ -134,13 +134,13 @@ export const workspaceTurnPlacement = ({
134
134
  };
135
135
 
136
136
  /**
137
- * Where one turn of a Windows Codex seat runs when the person opted in to
138
- * running it unsandboxed (windows-unsandboxed.js). A pod can turn public after
139
- * the run starts, so its rooms are re-read before every turn, as for a
140
- * `workspace` seat. With every pod confirmed private, the turn has no sandbox
141
- * block and Codex runs unconfined. Anything else, a failed read included, is
142
- * placed `public`, which host-check.js always refuses on native Windows, so
143
- * strangers can never reach an unconfined shell.
137
+ * Where one turn of a Codex seat runs when the person opted in to running it
138
+ * unsandboxed (windows-unsandboxed.js; native Windows, or Linux since F387). A
139
+ * pod can turn public after the run starts, so its rooms are re-read before
140
+ * every turn, as for a `workspace` seat. With every pod confirmed private, the
141
+ * turn has no sandbox block and Codex runs unconfined. Anything else, a failed
142
+ * read included, is placed `public`, and the run loop refuses that turn on
143
+ * every platform, so strangers can never reach an unconfined shell.
144
144
  */
145
145
  export const unconfinedTurnPlacement = ({ environment, installations, cwd } = {}) => {
146
146
  const { sandbox: _sandbox, ...unsandboxed } = environment || {};