@commonlyai/cli 0.1.331 → 0.1.333

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.331",
3
+ "version": "0.1.333",
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_PRIVATE_LINUX_OPTED_IN_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';
@@ -145,7 +145,14 @@ import {
145
145
  refusedItemRef,
146
146
  sanitizeHandoffAgent,
147
147
  } from '../lib/content-refusal.js';
148
- import { CANT_ANSWER_NOTICE_WINDOW_MS, CUT_OFF_NOTICE, cantAnswerNotice } from '../lib/turn-failure-notice.js';
148
+ import {
149
+ CANT_ANSWER_NOTICE_WINDOW_MS,
150
+ CLAUDE_SIGNED_OUT_FIX,
151
+ CUT_OFF_NOTICE,
152
+ cantAnswerNotice,
153
+ claudeSignedOutResult,
154
+ isClaudeSignedOut,
155
+ } from '../lib/turn-failure-notice.js';
149
156
  import {
150
157
  ADDRESSED_EVENT_TYPES,
151
158
  isPersonMention,
@@ -2861,13 +2868,17 @@ export const performRun = ({
2861
2868
  // failed read is not: it throws, so the event stays unacked and comes back
2862
2869
  // through the spawn-retry backoff instead of being refused for good.
2863
2870
  if (placement.reason) {
2864
- 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({
2865
2876
  environment: placement.environment,
2866
2877
  adapterName: adapter.name,
2867
2878
  hostUnconfined,
2868
2879
  optedIn: codexUnconfined,
2869
2880
  ...(detectBwrapImpl ? { detectBwrap: detectBwrapImpl } : {}),
2870
- });
2881
+ }) || (codexUnconfined ? CODEX_PRIVATE_LINUX_OPTED_IN_MESSAGE : null));
2871
2882
  if (turnRefusal && placement.readError) {
2872
2883
  throw Object.assign(
2873
2884
  new Error(`turn deferred, because its pods could not be read: ${placement.readError.message}`, {
@@ -3166,8 +3177,11 @@ export const performRun = ({
3166
3177
  // A public seat's Commonly server writes nothing once Commonly is
3167
3178
  // unreachable in its process (lib/public-seat-mcp-flag.js).
3168
3179
  environment: publicSeat ? withPublicSeatMcpFlag(placement.environment) : placement.environment,
3169
- // Only when set, so every other spawn context stays as it was.
3170
- ...(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 } : {}),
3171
3185
  ...(publicSeat && !memoryWithheld && opened.ownerWoken === true ? { ownerWoken: true } : {}),
3172
3186
  onSkillsLinked: ({ mounted, conflicted }) => {
3173
3187
  skillMount = {
@@ -4254,6 +4268,15 @@ export const performRun = ({
4254
4268
  }
4255
4269
  }
4256
4270
  } catch (err) {
4271
+ // F436: a signed-out Claude Code fails every turn the same way until
4272
+ // someone signs in. Held, the event sat behind the 15-minute circuit;
4273
+ // acked, the pod hears why now and the next event is the re-probe.
4274
+ if (isClaudeSignedOut(err)) {
4275
+ for (const entry of actionEntries) entry.result = claudeSignedOutResult();
4276
+ log(`[inbox.batch] ${CLAUDE_SIGNED_OUT_FIX}`);
4277
+ await noticeCantAnswer(err, actionEntries.map((entry) => entry.event));
4278
+ return { entries };
4279
+ }
4257
4280
  if (!isContentRefusal(err)) throw err;
4258
4281
  // Ambient text anyone wrote can draw the refusal, and no waking item
4259
4282
  // should pay for that. So the same items run once more with counts
@@ -4702,6 +4725,11 @@ export const performRun = ({
4702
4725
  // pod to post into, and its sender's ask expires on its own.
4703
4726
  result = contentRefusedResult();
4704
4727
  log(`[${event.type}] the model provider refused the content of event ${event._id} (content_refused) — acked as refused, not retried`);
4728
+ } else if (isClaudeSignedOut(err)) {
4729
+ // F436, as in the batch path. A pod-less or private item has no
4730
+ // pod to tell, so the log line is the whole notice.
4731
+ result = claudeSignedOutResult();
4732
+ log(`[${event.type}] ${CLAUDE_SIGNED_OUT_FIX}`);
4705
4733
  } else {
4706
4734
  // Do not record or ack: the kernel must retain the event for
4707
4735
  // at-least-once delivery. Stop this fetched batch immediately —
@@ -5468,7 +5496,7 @@ Docs:
5468
5496
  .option('--cascade-reset <ms>', `Silence window that clears the streak (env ${CASCADE_ENV_VARS.resetMs}, default ${CASCADE_DEFAULTS.resetMs})`)
5469
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')
5470
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.')
5471
- .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.')
5472
5500
  .action(async (typedName, opts) => {
5473
5501
  // F306: the seat this run is. `name` is the local key (the token file,
5474
5502
  // the log label, the daemon's plist); the server identity is the record's.
@@ -5483,7 +5511,9 @@ Docs:
5483
5511
  const named = instanceId !== null;
5484
5512
  let name = named ? seatKey(agentArg, instanceId) : agentArg;
5485
5513
  if (opts.unsandboxed) {
5486
- 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 });
5487
5517
  if (flagRefusal) {
5488
5518
  console.error(`${stamp()} [${name}] ${flagRefusal}`);
5489
5519
  process.exit(1);
@@ -5559,6 +5589,13 @@ Docs:
5559
5589
  // marker is read only by the seats that daemon spawns). Nothing from the
5560
5590
  // server decides this, and the environment never carries it: the seat
5561
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
+ }
5562
5599
  const optedIn = runOptedInUnsandboxed({ flag: opts.unsandboxed === true });
5563
5600
  const hostUnconfined = hostUnconfinedForRun({
5564
5601
  optedIn,
@@ -5572,7 +5609,7 @@ Docs:
5572
5609
  // the saved record, loses its sandbox block. A read that fails stays
5573
5610
  // refused: nothing here may assume a pod is private.
5574
5611
  let codexUnconfined = false;
5575
- if (optedIn && record.adapter === 'codex' && process.platform === 'win32') {
5612
+ if (optedIn && record.adapter === 'codex' && (process.platform === 'win32' || process.platform === 'linux')) {
5576
5613
  const seatClient = createClient({ instance: record.instanceUrl, token: record.runtimeToken });
5577
5614
  let installations = null;
5578
5615
  try {
@@ -5597,7 +5634,7 @@ Docs:
5597
5634
  }
5598
5635
  }
5599
5636
  }
5600
- if (codexUnconfined) console.warn(`${stamp()} [${name}] ${CODEX_UNSANDBOXED_NOTICE}`);
5637
+ if (codexUnconfined) console.warn(`${stamp()} [${name}] ${codexUnsandboxedNotice(process.platform)}`);
5601
5638
  let runEnvironment = record.environment;
5602
5639
  if (codexUnconfined && runEnvironment) {
5603
5640
  const { sandbox: _sandbox, ...unsandboxed } = runEnvironment;
@@ -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, 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 {
@@ -626,20 +632,9 @@ const parseCodexVersion = (stdout) => (
626
632
  /^codex-cli (\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\s*$/m.exec(String(stdout))?.[1] || null
627
633
  );
628
634
 
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';
635
+ // The commit-attribution hooks a profile has to let the shell read: the hooks
636
+ // folder Commonly installs, and each executable hook the repository already had.
637
+ const commitHookReadPaths = (commitAttributionEnv) => {
643
638
  const commitHooksPath = commitAttributionEnv?.COMMONLY_AGENT_HOOKS_PATH || null;
644
639
  const originalHooksPath = commitAttributionEnv?.COMMONLY_AGENT_ORIGINAL_HOOKS_PATH || null;
645
640
  const originalHookPaths = originalHooksPath
@@ -654,14 +649,37 @@ const publicPermissionProfileFlags = (
654
649
  }
655
650
  })
656
651
  : [];
652
+ return { commitHooksPath, originalHookPaths };
653
+ };
654
+
655
+ // Codex's default name filter treats GIT_CONFIG_KEY_n as sensitive, so the
656
+ // attribution keys are set again after filtering. Their values stay in the
657
+ // environment instead of riding argv.
658
+ const gitConfigKeyShellSet = (commitAttributionEnv) => Object.entries(commitAttributionEnv || {})
659
+ .filter(([name]) => /^GIT_CONFIG_KEY_\d+$/.test(name))
660
+ .map(([name, value]) => `${toml(name)}=${toml(value)}`);
661
+
662
+ const publicPermissionProfileFlags = (
663
+ mode,
664
+ commitAttributionEnv = null,
665
+ mcpReadDirectories = [],
666
+ codexHelperReadPaths = [],
667
+ platform = process.platform,
668
+ workspacePath = null,
669
+ ) => {
670
+ if (!PUBLIC_SANDBOX_MODES.has(mode)) {
671
+ throw new Error(
672
+ `public codex agents require sandbox.mode=workspace or read-only, got ${mode || 'unset'}`,
673
+ );
674
+ }
675
+ const workspaceAccess = mode === 'read-only' ? 'read' : 'write';
676
+ const { commitHooksPath, originalHookPaths } = commitHookReadPaths(commitAttributionEnv);
657
677
  // Preserve caller-supplied git config entries alongside the appended
658
678
  // hooksPath entry. The explicit allowlist below admits only these concrete
659
679
  // variable names, not arbitrary environment variables.
660
680
  const gitConfigEnv = Object.keys(commitAttributionEnv || {})
661
681
  .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)}`);
682
+ const gitConfigKeySet = gitConfigKeyShellSet(commitAttributionEnv);
665
683
  // The profile denies $TMPDIR and /tmp, so a shell heredoc fails. Set for the
666
684
  // model's shell alone: codex, its MCP child and the per-turn folder keep the
667
685
  // host's temp root, which spawn refuses to find in the workspace. The
@@ -725,6 +743,141 @@ const publicPermissionProfileFlags = (
725
743
  ];
726
744
  };
727
745
 
746
+ // Host secrets a private seat's shell never reads. ~/.commonly holds every
747
+ // seat's tokens and state; the seat's own workspace sits under it and is
748
+ // admitted by the more specific workspace rule. gh keeps working: on macOS its
749
+ // login is in the keychain, which a credential the seat itself uses has to be.
750
+ const PRIVATE_SECRET_DENIES = Object.freeze([
751
+ '~/.commonly', '~/.claude', '~/.codex', '~/.ssh', '~/.aws', '~/.gnupg',
752
+ '~/.kube', '~/.docker', '~/.netrc', '~/.config/gcloud',
753
+ ]);
754
+
755
+ const realOrSelf = (path) => {
756
+ try {
757
+ return realpathSync(path);
758
+ } catch {
759
+ return path;
760
+ }
761
+ };
762
+
763
+ // What a commit writes, and nothing that runs code. Codex keeps a workspace's
764
+ // `.git` read-only even inside a writable root, and only an explicit absolute
765
+ // key opens it (measured with `codex sandbox` on 0.162.1: the same key inside
766
+ // :workspace_roots did not). `config` and `hooks` stay read-only, because a
767
+ // hook or a config-defined program (core.fsmonitor, a filter) would run as the
768
+ // person in every later git command there, outside any sandbox; renaming over
769
+ // them is refused too (measured). A git worktree keeps its admin folder
770
+ // outside the workspace (`.git` is a file naming it), and a commit there also
771
+ // writes the shared repository's objects, refs and logs, and packed-refs when
772
+ // git repacks them. Read from the files git leaves, without running git.
773
+ // Measured: a worktree whose repository lies under the denied ~/.commonly
774
+ // can't commit (git can't resolve the path), whatever these keys are.
775
+ const gitAdminKeys = (workspace) => {
776
+ if (!workspace) return [];
777
+ const dotGit = join(workspace, '.git');
778
+ const ownRepository = (dir) => {
779
+ const real = realOrSelf(dir);
780
+ return [
781
+ [real, 'write'],
782
+ [join(real, 'config'), 'read'],
783
+ [join(real, 'config.worktree'), 'read'],
784
+ [join(real, 'hooks'), 'read'],
785
+ ];
786
+ };
787
+ try {
788
+ if (statSync(dotGit).isDirectory()) return ownRepository(dotGit);
789
+ } catch {
790
+ return [];
791
+ }
792
+ try {
793
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, 'utf8'))?.[1]?.trim();
794
+ if (!pointer) return [];
795
+ const gitDir = pathResolve(workspace, pointer);
796
+ let commonDir = null;
797
+ try {
798
+ commonDir = pathResolve(gitDir, readFileSync(join(gitDir, 'commondir'), 'utf8').trim());
799
+ } catch {
800
+ // A linked gitdir that is a whole repository of its own.
801
+ return ownRepository(gitDir);
802
+ }
803
+ const realGitDir = realOrSelf(gitDir);
804
+ const realCommon = realOrSelf(commonDir);
805
+ return [
806
+ [realGitDir, 'write'],
807
+ [join(realGitDir, 'config.worktree'), 'read'],
808
+ ...['objects', 'refs', 'logs', 'packed-refs', 'packed-refs.lock']
809
+ .map((name) => [join(realCommon, name), 'write']),
810
+ ];
811
+ } catch {
812
+ // An unreadable `.git` file.
813
+ return [];
814
+ }
815
+ };
816
+
817
+ // F387: the profile for a private Codex seat outside a cloud-codex pod. It is
818
+ // the seat owner's own agent doing dev work, so the disk stays readable, the
819
+ // network is on and the environment is inherited (with Codex's secret-name
820
+ // filter on); what it removes is every host secret the seat doesn't use
821
+ // itself. It is not a sandbox for untrusted input: public seats keep
822
+ // commonly_public.
823
+ const privatePermissionProfileFlags = ({
824
+ commitAttributionEnv = null,
825
+ mcpReadDirectories = [],
826
+ codexHelperReadPaths = [],
827
+ platform = process.platform,
828
+ workspace = null,
829
+ tempRoots = [],
830
+ shellTempDir = null,
831
+ } = {}) => {
832
+ const { commitHooksPath, originalHookPaths } = commitHookReadPaths(commitAttributionEnv);
833
+ const posix = platform !== 'win32';
834
+ // The temp roots hold every seat's per-turn folder: its runtime token and the
835
+ // reply file Codex posts from. So they are denied whole, and the shell gets
836
+ // one folder of its own inside this turn's, as TMPDIR (and TMPPREFIX, which
837
+ // zsh takes its heredoc files from). Codex, and the MCP child that reads the
838
+ // token, run outside the profile. On Windows these keys have no drive.
839
+ const deniedTemp = posix
840
+ ? [...new Set(['/private/tmp', ...tempRoots.filter(Boolean).map(realOrSelf)])]
841
+ : [];
842
+ const shellTemp = posix && shellTempDir ? realOrSelf(shellTempDir) : null;
843
+ const filesystem = [
844
+ // Codex reads every key as a path for its own platform; on Windows "/" has
845
+ // no drive and Codex would refuse the whole profile (as with /private/tmp
846
+ // in publicPermissionProfileFlags).
847
+ posix ? '"/"="read"' : '":minimal"="read"',
848
+ ...PRIVATE_SECRET_DENIES.map((path) => `${toml(path)}="deny"`),
849
+ ...deniedTemp.map((path) => `${toml(path)}="deny"`),
850
+ ...(shellTemp ? [`${toml(shellTemp)}="write"`] : []),
851
+ '":workspace_roots"={"."="write",".commonly/**"="deny",".codex/**"="deny"}',
852
+ ...gitAdminKeys(workspace).map(([path, mode]) => `${toml(path)}=${toml(mode)}`),
853
+ ...(commitHooksPath ? [`${toml(commitHooksPath)}="read"`] : []),
854
+ ...originalHookPaths.map((hookPath) => `${toml(hookPath)}="read"`),
855
+ ...mcpReadDirectories.map((path) => `${toml(path)}="read"`),
856
+ ...codexHelperReadPaths.map((path) => `${toml(path)}="read"`),
857
+ ].join(',');
858
+ const shellSet = [
859
+ ...gitConfigKeyShellSet(commitAttributionEnv),
860
+ ...(shellTemp
861
+ ? [
862
+ `${toml('TMPDIR')}=${toml(shellTemp)}`,
863
+ `${toml('TMPPREFIX')}=${toml(join(shellTemp, 'zsh'))}`,
864
+ // macOS's /usr/bin tools are xcrun shims, which keep a cache in the
865
+ // user temp root (denied above) and print an error on every call
866
+ // without this.
867
+ `${toml('xcrun_db')}=${toml(join(shellTemp, 'xcrun_db'))}`,
868
+ ]
869
+ : []),
870
+ ];
871
+ return [
872
+ '-c', `default_permissions=${toml(PRIVATE_PERMISSION_PROFILE)}`,
873
+ '-c', `permissions.${PRIVATE_PERMISSION_PROFILE}.filesystem={${filesystem}}`,
874
+ '-c', `permissions.${PRIVATE_PERMISSION_PROFILE}.network.enabled=true`,
875
+ '-c', 'shell_environment_policy.inherit="all"',
876
+ '-c', 'shell_environment_policy.ignore_default_excludes=false',
877
+ ...(shellSet.length ? ['-c', `shell_environment_policy.set={${shellSet.join(',')}}`] : []),
878
+ ];
879
+ };
880
+
728
881
  // F188: the host's OpenAI-compatible model route, for a public seat. That seat
729
882
  // runs with `--ignore-user-config`, so config.toml's `openai_base_url` never
730
883
  // loads, and codex-cli 0.162.1 does not read the OPENAI_BASE_URL env either
@@ -836,8 +989,18 @@ const buildArgs = ({
836
989
  providerProxy = null,
837
990
  platform = process.platform,
838
991
  workspacePath = null,
992
+ trustedContainerPerimeter = false,
993
+ operatorUnconfined = false,
994
+ privateWorkspace = null,
995
+ tempRoots = [],
996
+ shellTempDir = null,
839
997
  }) => {
840
998
  const publicSandbox = publicSandboxMode !== null;
999
+ // F387: a private seat keeps the flag below only in a cloud-codex pod, or
1000
+ // when its operator opted this run out of the OS sandbox (D245, native
1001
+ // Windows only: Codex can't enforce a profile's read denies there).
1002
+ const keepsOwnPolicy = trustedContainerPerimeter || operatorUnconfined;
1003
+ const privateProfile = !publicSandbox && !keepsOwnPolicy;
841
1004
  // `--dangerously-bypass-approvals-and-sandbox` disables codex CLI's
842
1005
  // bubblewrap (bwrap) sandbox + approval prompts. bwrap needs CAP_SYS_ADMIN
843
1006
  // or unprivileged user-namespaces — neither available to standard k8s
@@ -852,6 +1015,15 @@ const buildArgs = ({
852
1015
  // versions spawn admits (PUBLIC_CODEX_MIN_VERSION). Do not
853
1016
  // pass legacy `--sandbox` alongside them: Codex documents that the legacy
854
1017
  // mode disables permission-profile composition.
1018
+ //
1019
+ // F387 (TASK-280): the flag above belongs to a cloud-codex k8s pod, where
1020
+ // bwrap cannot run and the pod is the boundary, or to a run its operator
1021
+ // opted out (keepsOwnPolicy). Every other private seat gets
1022
+ // privatePermissionProfileFlags: readable disk, network on, host secret dirs
1023
+ // denied. It keeps the seat's own config and route (no --ignore-user-config),
1024
+ // since a private seat relies on its config.toml; the -c profile still wins
1025
+ // over config defaults (checked against sandbox_mode, default_permissions and
1026
+ // a user [permissions.*] table on codex-cli 0.162.1).
855
1027
  const executionPolicy = publicSandbox
856
1028
  ? [
857
1029
  '--ignore-user-config',
@@ -867,7 +1039,17 @@ const buildArgs = ({
867
1039
  ...providerRouteFlags(providerProxy),
868
1040
  ...PUBLIC_BUILTIN_TOOL_FLAGS,
869
1041
  ]
870
- : ['--dangerously-bypass-approvals-and-sandbox'];
1042
+ : keepsOwnPolicy
1043
+ ? ['--dangerously-bypass-approvals-and-sandbox']
1044
+ : privatePermissionProfileFlags({
1045
+ commitAttributionEnv,
1046
+ mcpReadDirectories,
1047
+ codexHelperReadPaths,
1048
+ platform,
1049
+ workspace: privateWorkspace,
1050
+ tempRoots,
1051
+ shellTempDir,
1052
+ });
871
1053
  const common = [
872
1054
  '--json',
873
1055
  '--skip-git-repo-check',
@@ -884,8 +1066,9 @@ const buildArgs = ({
884
1066
  ];
885
1067
  // Approval policy is a global option in Codex 0.144, so it must precede
886
1068
  // 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'] : [];
1069
+ // non-interactive agents never hang waiting for an operator. A private seat
1070
+ // under its profile keeps its own config.toml, which may ask for approvals.
1071
+ const prefix = publicSandbox || privateProfile ? ['--ask-for-approval', 'never'] : [];
889
1072
  if (sessionId) {
890
1073
  // Place <sessionId> immediately after the `exec resume` subcommand so a
891
1074
  // future codex parser change can't accidentally consume it as the value
@@ -1212,16 +1395,32 @@ export default {
1212
1395
  if (routeNames.has(name.toUpperCase())) delete childEnv[name];
1213
1396
  }
1214
1397
  }
1398
+ // F387: only a cloud-codex pod sets the perimeter env
1399
+ // (sandbox/codex-perimeter.js), and only the operator's own D245 opt-in
1400
+ // sets hostUnconfined. Every other private seat runs under the private
1401
+ // permission profile.
1402
+ const trustedContainerPerimeter = codexTrustedPerimeter(ctx.env || process.env);
1403
+ const operatorUnconfined = ctx.hostUnconfined === true;
1404
+ const privateProfile = publicSandboxMode === null && !trustedContainerPerimeter && !operatorUnconfined;
1215
1405
  // Before the public home is prepared, so a refused seat changes nothing.
1216
- if (publicSandboxMode !== null) {
1406
+ // A private profile uses the same permission keys, tested to the same bar.
1407
+ if (publicSandboxMode !== null || privateProfile) {
1217
1408
  const codexVersion = await readCodexVersion(ctx, childEnv);
1218
1409
  if (!meetsMinimumVersion(codexVersion, PUBLIC_CODEX_MIN_VERSION)) {
1219
- throw publicCodexVersionError({ found: codexVersion, required: PUBLIC_CODEX_MIN_VERSION });
1410
+ throw publicCodexVersionError({
1411
+ found: codexVersion,
1412
+ required: PUBLIC_CODEX_MIN_VERSION,
1413
+ seat: publicSandboxMode !== null ? 'public seat' : 'private seat',
1414
+ });
1220
1415
  }
1221
1416
  }
1222
1417
  const publicCodexHome = publicSandboxMode !== null
1223
1418
  ? await preparePublicCodexHome(ctx, childEnv, { login: !route })
1224
1419
  : null;
1420
+ // The private shell's TMPDIR: inside this turn's folder, which `finally`
1421
+ // removes, and beside (not over) the token's folder.
1422
+ const privateShellTemp = privateProfile ? join(dir, 'shell-tmp') : null;
1423
+ if (privateShellTemp) await mkdir(privateShellTemp, { mode: 0o700 });
1225
1424
  if (route) {
1226
1425
  providerProxy = await (ctx._startProviderProxy || startProviderProxy)({
1227
1426
  provider: { baseURL: route.baseURL },
@@ -1249,6 +1448,13 @@ export default {
1249
1448
  providerProxy,
1250
1449
  platform: ctx._platform || process.platform,
1251
1450
  workspacePath,
1451
+ trustedContainerPerimeter,
1452
+ operatorUnconfined,
1453
+ privateWorkspace: privateProfile && ctx.cwd ? pathResolve(ctx.cwd) : null,
1454
+ // Both roots: this process's, where every seat's per-turn folder
1455
+ // lives, and the one the shell would inherit.
1456
+ tempRoots: privateProfile ? [tmpdir(), childEnv.TMPDIR] : [],
1457
+ shellTempDir: privateShellTemp,
1252
1458
  });
1253
1459
  // childEnv is derived from the process environment, so the bootstrap export has to be
1254
1460
  // 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,31 @@ export const bwrapRefusedMessage = (adapterName, { reason, apparmorRestricted, u
121
122
  ].join('\n');
122
123
  };
123
124
 
125
+ /**
126
+ * F387: a private Codex seat on Linux is refused by default until a Linux
127
+ * permission profile is walked (see hostSandboxRefusal). The person can run it
128
+ * unconfined by their own choice, as on native Windows; it never falls back
129
+ * to that without being asked.
130
+ */
131
+ export const CODEX_PRIVATE_LINUX_MESSAGE = [
132
+ 'A private Codex agent runs inside a sandbox that keeps your other credentials out of its reach, and that sandbox is not ready on Linux yet,',
133
+ 'so by default this agent cannot listen for @mentions here. You can:',
134
+ ` - In invite-only pods, run it without a sandbox: ${CLI} agent run <name> ${UNSANDBOXED_FLAG}.`
135
+ + ' Nothing confines it: it runs with your own access to files and commands, anyone in the pod,'
136
+ + ' people you invite later included, can direct it, and it gets no connector grants.',
137
+ ' - Run it on a Mac, where the sandbox is ready.',
138
+ HOSTED_LINE,
139
+ ].join('\n');
140
+
141
+ // The person opted in, and a pod rules it out. Naming the flag again would
142
+ // only send them round in a circle.
143
+ export const CODEX_PRIVATE_LINUX_OPTED_IN_MESSAGE = [
144
+ 'A pod this agent answers in is publicly readable or open to join, or did not report whether it is,',
145
+ 'so it cannot run without a sandbox, and the sandbox for a private Codex agent is not ready on Linux yet. You can:',
146
+ ' - Run it on a Mac, where the sandbox is ready.',
147
+ HOSTED_LINE,
148
+ ].join('\n');
149
+
124
150
  /** What a person on native Windows can do instead. */
125
151
  export const windowsSandboxMessage = (adapterName) => {
126
152
  if (adapterName === 'codex') return CODEX_WINDOWS_MESSAGE;
@@ -158,6 +184,8 @@ export const hostSandboxRefusal = ({
158
184
  optedIn = false,
159
185
  detectBwrap = defaultDetectBwrap,
160
186
  detectSeatbelt = defaultDetectSeatbelt,
187
+ // F387: a cloud-codex pod declares itself here (codex-perimeter.js).
188
+ env = process.env,
161
189
  } = {}) => {
162
190
  if (adapterName === 'codex') {
163
191
  // Keyed on trust, not mode: Codex resolves no Seatbelt or bwrap mode of its
@@ -172,6 +200,18 @@ export const hostSandboxRefusal = ({
172
200
  const bwrap = detectBwrap();
173
201
  return bwrap.namespaceRefused === true ? bwrapRefusedMessage(adapterName, bwrap) : null;
174
202
  }
203
+ // F387: a private seat outside a cloud-codex pod runs under the private
204
+ // permission profile. On Linux, Codex runs its sandbox helper from
205
+ // CODEX_HOME (~/.codex), and a denied ancestor always wins there (see the
206
+ // public Codex home in adapters/codex.js), so the profile's denies would
207
+ // fail every turn at bootstrap. Until a Linux key set is walked, the seat
208
+ // is refused before its first poll, unless the person ran it unconfined
209
+ // by their own --unsandboxed (D245, as on Windows: only with every pod
210
+ // confirmed private). Never unconfined without being asked.
211
+ if (platform === 'linux' && trust !== 'workspace' && !codexTrustedPerimeter(env)) {
212
+ if (hostUnconfined === true) return null;
213
+ return optedIn === true ? CODEX_PRIVATE_LINUX_OPTED_IN_MESSAGE : CODEX_PRIVATE_LINUX_MESSAGE;
214
+ }
175
215
  if (platform !== 'win32') return null;
176
216
  if (trust === 'workspace') return null;
177
217
  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 ready yet (F387). So on Linux it is accepted
59
+ * 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,7 +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
126
+ * Does this Codex run go unconfined? Only on win32, or on Linux where a private
127
+ * Codex agent has no sandbox ready yet (F387), only by the user's own
118
128
  * opt-in, and only when every pod the seat answers in is confirmed private:
119
129
  * `installations` is the server's read of them, and an empty or failed read is
120
130
  * a no. Workspace trust stays with Codex's own refusal. The caller removes the
@@ -123,7 +133,7 @@ export const hostUnconfinedForRun = ({
123
133
  */
124
134
  export const codexUnconfinedForRun = ({
125
135
  optedIn, adapterName, environment, installations, platform = process.platform,
126
- }) => platform === 'win32' && optedIn === true && adapterName === 'codex'
136
+ }) => (platform === 'win32' || platform === 'linux') && optedIn === true && adapterName === 'codex'
127
137
  && effectiveSandboxTrust(environment?.sandbox?.trust) !== 'workspace'
128
138
  && allPodsConfirmedPrivate(installations);
129
139
 
@@ -142,6 +152,12 @@ export const UNSANDBOXED_NOTICE = 'unsandboxed (opted in): Windows has no sandbo
142
152
  /** Codex has no restricted tool settings to keep, so its line says what it costs instead. */
143
153
  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
154
 
155
+ export const CODEX_LINUX_UNSANDBOXED_NOTICE = 'unsandboxed (opted in): the sandbox for a private Codex agent is not ready on Linux yet, 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.';
156
+
157
+ export const codexUnsandboxedNotice = (platform = process.platform) => (platform === 'linux'
158
+ ? CODEX_LINUX_UNSANDBOXED_NOTICE
159
+ : CODEX_UNSANDBOXED_NOTICE);
160
+
145
161
  // A 404 here is a server from before this route, which reads like a missing agent.
146
162
  export const hostReportFailureMessage = (err) => {
147
163
  const hint = err?.status === 404
@@ -151,7 +167,9 @@ export const hostReportFailureMessage = (err) => {
151
167
  };
152
168
 
153
169
  export default {
170
+ CODEX_LINUX_UNSANDBOXED_NOTICE,
154
171
  CODEX_UNSANDBOXED_NOTICE,
172
+ codexUnsandboxedNotice,
155
173
  UNSANDBOXED_FLAG,
156
174
  UNSANDBOXED_NOTICE,
157
175
  codexUnconfinedForRun,
@@ -29,12 +29,22 @@ const LOGIN_FAILED_WORDINGS = [
29
29
  /\bupstream refused 401\b/, // the same refusal, read from pi's stream
30
30
  /^\w+ exited(?: with code)? \d+: 401\b/, // pi's text, which names no upstream
31
31
  /workspace routing discovery unauthorized/,
32
+ // Any other text carrying Claude Code's wording keeps this general line.
32
33
  /(?:^|: | \| )Not logged in · Please run \/login/,
33
34
  /API Error: 400 This API key is not scoped to a workspace/,
34
35
  // The wrapper's own refusals of a Claude login (adapters/claude.js).
35
36
  /the Claude login on this machine expires in/,
36
37
  /refusing a Claude login/,
37
38
  ];
39
+ // F436: what Claude Code prints, and exits 1 on, when it has no login on the
40
+ // computer (2.1.318, walked on windows-latest). No key is wrong and no allowance
41
+ // is spent: someone signs in to Claude Code there, and the next turn works.
42
+ // Anchored on the claude adapter's own exit line, first in its tail or after
43
+ // the stderr | stdout join, because this match acks the message unanswered:
44
+ // the same words from another adapter or a tool keep the general login line.
45
+ const CLAUDE_SIGNED_OUT_WORDINGS = [
46
+ /^claude exited(?: with code)? \d+: (?:[^\n]*? \| )?Not logged in · Please run \/login/,
47
+ ];
38
48
  const WONT_START_WORDINGS = [
39
49
  /^spawn \S+ ENOENT/,
40
50
  /^\w+ adapter: \S+ (?:is not set|is missing)/, // the seat has no provider key
@@ -75,6 +85,11 @@ const AGAIN = 'After that, send your message again if I still haven’t answered
75
85
 
76
86
  export const LOGIN_NOTICE = 'I can’t answer right now: the key or login on the computer I run on isn’t working. '
77
87
  + `Whoever runs me needs to fix it and start me again. ${AGAIN}`;
88
+ export const CLAUDE_SIGNED_OUT_NOTICE = 'I can’t answer right now: Claude Code isn’t signed in on the computer I run on. '
89
+ + `Whoever runs me needs to open Claude Code there and sign in. ${AGAIN}`;
90
+ // What the seat's own log says, for whoever runs it.
91
+ export const CLAUDE_SIGNED_OUT_FIX = 'Claude Code is not signed in on this computer: open Claude Code here and sign in '
92
+ + '(/login). The waiting message was acked, not held, so the next message starts a turn at once.';
78
93
  export const WONT_START_NOTICE = 'I can’t answer right now: the tool I run on wouldn’t start on my computer. '
79
94
  + `Whoever runs me needs to fix that and start me again. ${AGAIN}`;
80
95
  export const OUT_OF_ALLOWANCE_NOTICE = 'I can’t answer right now: the AI account I run on has used up its allowance. '
@@ -113,6 +128,8 @@ export const cantAnswerNotice = (error) => {
113
128
  // claudeFailureTail drops tool and assistant JSON. This cut is for what can
114
129
  // still arrive: a torn stream line, or an error event after stderr.
115
130
  const text = String(error?.message ?? '').split(/(?:^|: | \| |\n)\{"type":/)[0];
131
+ // Before the general login line: this one names its own fix.
132
+ if (matches(CLAUDE_SIGNED_OUT_WORDINGS, text)) return { cause: 'claude-signed-out', text: CLAUDE_SIGNED_OUT_NOTICE };
116
133
  // Before the allowance check: a 401 is settled, whatever else its body says.
117
134
  if (matches(LOGIN_FAILED_WORDINGS, text)) return { cause: 'login', text: LOGIN_NOTICE };
118
135
  if (matches(WONT_START_WORDINGS, text)) return { cause: 'wont-start', text: WONT_START_NOTICE };
@@ -121,3 +138,21 @@ export const cantAnswerNotice = (error) => {
121
138
  }
122
139
  return null;
123
140
  };
141
+
142
+ /**
143
+ * A turn that failed because Claude Code is signed out on this computer (F436).
144
+ * It is a setup fault, not an outage: retrying cannot fix it, and holding the
145
+ * event behind the 15-minute circuit kept the person waiting with no answer.
146
+ * The run loop acks it instead and posts CLAUDE_SIGNED_OUT_NOTICE, and the
147
+ * next event spawns at once, which is the re-probe.
148
+ */
149
+ export const isClaudeSignedOut = (error) => cantAnswerNotice(error)?.cause === 'claude-signed-out';
150
+
151
+ /** The turn result a signed-out turn is acked with: a person's message is handed to another listener. */
152
+ export const CLAUDE_SIGNED_OUT_REASON = 'claude-signed-out';
153
+ export const claudeSignedOutResult = () => ({
154
+ outcome: 'error',
155
+ refused: { reason: 'delivery-refused' },
156
+ reason: CLAUDE_SIGNED_OUT_REASON,
157
+ details: { failureClass: 'configuration' },
158
+ });
@@ -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 || {};