@commonlyai/cli 0.1.309 → 0.1.311

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.309",
3
+ "version": "0.1.311",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -77,7 +77,6 @@ import { homedir, tmpdir } from 'os';
77
77
  import {
78
78
  delimiter, dirname, isAbsolute, join,
79
79
  } from 'path';
80
- import { fileURLToPath } from 'url';
81
80
 
82
81
  import {
83
82
  isLegacySandboxTrust,
@@ -95,6 +94,7 @@ import {
95
94
  } from '../sandbox/seatbelt.js';
96
95
  import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
97
96
  import { supportedGitHooks } from '../commit-attribution.js';
97
+ import { workspaceGitAttachment } from '../workspace-git.js';
98
98
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
99
99
  import {
100
100
  prepareMcpSpawn, PUBLIC_MCP_UNAVAILABLE_CODE, publicMcpUnavailableError, selectedMcpVersionDir,
@@ -180,44 +180,23 @@ const workspaceGrants = (sandbox) => (
180
180
  sandbox?.trust === 'workspace' && Array.isArray(sandbox.allow) ? sandbox.allow : []
181
181
  );
182
182
  // A workspace seat reads its project's history through one read-only git tool
183
- // (git-readonly-server.js). The server runs inside the jail, so the jail must
184
- // admit its code (cli/src/lib, plus package.json for the module type) and the
185
- // git binary it runs.
186
- const WORKSPACE_GIT_SERVER = fileURLToPath(new URL('../git-readonly-server.js', import.meta.url));
187
- const WORKSPACE_GIT_PACKAGE_JSON = fileURLToPath(new URL('../../../package.json', import.meta.url));
188
- // macOS's /usr/bin/git is an xcrun shim, and it fails inside Seatbelt ("No
189
- // developer tools were found"). So the jail gets the binary git itself runs:
190
- // `git --exec-path`, resolved here on the host, holds a `git` that links to it.
191
- const resolveRealGit = () => {
192
- const result = spawnSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 5000 });
193
- const execDir = result?.status === 0 ? String(result.stdout || '').trim() : '';
194
- if (!execDir) return null;
195
- try {
196
- return realpathSync(join(execDir, 'git'));
197
- } catch {
198
- return null;
199
- }
200
- };
183
+ // (git-readonly-server.js, attached by workspace-git.js). The server runs
184
+ // inside the jail, so the jail admits its code and the real git binary.
201
185
  const withWorkspaceGit = (ctx) => {
202
186
  if (ctx.environment?.sandbox?.trust !== 'workspace' || !ctx.cwd) return ctx;
203
- const git = resolveRealGit();
204
- if (!git) {
187
+ const attachment = workspaceGitAttachment(ctx.cwd);
188
+ if (!attachment) {
205
189
  // eslint-disable-next-line no-console
206
190
  console.warn('[claude] git was not found on this machine, so this workspace seat has no git tool');
207
191
  return ctx;
208
192
  }
209
- const server = {
210
- name: 'workspace_git',
211
- transport: 'stdio',
212
- command: [process.execPath, WORKSPACE_GIT_SERVER, '--root', ctx.cwd, '--git', git],
213
- };
214
193
  return {
215
194
  ...ctx,
216
- environment: { ...ctx.environment, mcp: [...(ctx.environment.mcp || []), server] },
195
+ environment: { ...ctx.environment, mcp: [...(ctx.environment.mcp || []), attachment.server] },
217
196
  workspaceGit: {
218
- executable: git,
219
- readDirectories: [dirname(WORKSPACE_GIT_SERVER)],
220
- readPaths: [WORKSPACE_GIT_PACKAGE_JSON],
197
+ executable: attachment.executable,
198
+ readDirectories: attachment.readDirectories,
199
+ readPaths: attachment.readPaths,
221
200
  },
222
201
  };
223
202
  };
@@ -75,12 +75,14 @@ import { isOurGrantBroker } from '../grant-broker-guard.js';
75
75
  import { BRIDGE_PATH } from './codex-broker-bridge.mjs';
76
76
  import { brokerBridgeEntry } from './broker-bridge-entry.js';
77
77
  import { supportedGitHooks } from '../commit-attribution.js';
78
+ import { WORKSPACE_GIT_SERVER_NAME, confinedWorkspaceGitServer } from '../workspace-git.js';
78
79
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
79
80
  import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
80
81
  import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '../memory-bridge.js';
81
82
  import { resolveSkillSource, skillsAsText } from '../skill-prompt.js';
82
83
  import { isLegacySandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
83
84
  import { contains, realpathOfNearest, refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
85
+ import { refuseCodeRunningGitSetup } from '../sandbox/workspace-git-config.js';
84
86
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
85
87
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
86
88
  import { startProviderProxy } from '../provider-proxy.js';
@@ -1098,6 +1100,12 @@ export default {
1098
1100
  const workspacePath = sandbox?.trust === 'public'
1099
1101
  ? await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'public Codex agents' })
1100
1102
  : null;
1103
+ // Codex runs git in the workspace outside the seat's profile, so a
1104
+ // repository set up to run programs is refused before anything starts
1105
+ // (sandbox/workspace-git-config.js).
1106
+ if (workspacePath) {
1107
+ (ctx._refuseCodeRunningGitSetup || refuseCodeRunningGitSetup)(workspacePath, { seat: 'This public Codex agent' });
1108
+ }
1101
1109
 
1102
1110
  // Per-spawn temp dir for --output-last-message. Cleaned up in `finally`
1103
1111
  // so a crash in the middle of the spawn doesn't leak files in $TMPDIR.
@@ -1114,7 +1122,38 @@ export default {
1114
1122
 
1115
1123
  let providerProxy = null;
1116
1124
  try {
1117
- const mcp = buildMcpOverrideArgs(ctx.environment?.mcp, {
1125
+ // A public seat can't run git from its shell on macOS: Homebrew's git is
1126
+ // outside the profile and /usr/bin/git is an xcrun shim that fails there.
1127
+ // So it reads its workspace's history through the read-only git tool a
1128
+ // Claude workspace seat has. Codex starts MCP servers outside the seat's
1129
+ // profile, so this one runs under a Seatbelt of its own
1130
+ // (confinedWorkspaceGitServer). An entry the environment declares under
1131
+ // the same name would run unconfined, so on a public seat it is replaced.
1132
+ const declaredMcp = ctx.environment?.mcp || [];
1133
+ let seatMcp = declaredMcp;
1134
+ if (workspacePath) {
1135
+ const declaresGit = declaredMcp.some((server) => server?.name === WORKSPACE_GIT_SERVER_NAME);
1136
+ if (declaresGit) {
1137
+ // eslint-disable-next-line no-console
1138
+ console.warn(`[codex] this public seat's environment declares ${WORKSPACE_GIT_SERVER_NAME}; `
1139
+ + 'Codex would run it outside the sandbox, so the confined one replaces it');
1140
+ }
1141
+ const stateDir = join(dir, 'git-tool');
1142
+ await mkdir(stateDir, { mode: 0o700 });
1143
+ const workspaceGit = (ctx._workspaceGitServer || confinedWorkspaceGitServer)(workspacePath, {
1144
+ stateDir,
1145
+ platform: ctx._platform || process.platform,
1146
+ });
1147
+ if (!workspaceGit) {
1148
+ // eslint-disable-next-line no-console
1149
+ console.warn('[codex] the read-only git tool needs macOS and git on this machine, so this public seat has none');
1150
+ }
1151
+ seatMcp = [
1152
+ ...declaredMcp.filter((server) => server?.name !== WORKSPACE_GIT_SERVER_NAME),
1153
+ ...(workspaceGit ? [workspaceGit] : []),
1154
+ ];
1155
+ }
1156
+ const mcp = buildMcpOverrideArgs(seatMcp, {
1118
1157
  runtimeToken: ctx.runtimeToken,
1119
1158
  instanceUrl: ctx.instanceUrl,
1120
1159
  credentialFile: credential?.path || null,
@@ -1186,6 +1225,9 @@ export default {
1186
1225
  prompt: fullPrompt,
1187
1226
  outputFile,
1188
1227
  mcpFlags: mcp.flags,
1228
+ // Nothing is added for the git tool, which has a Seatbelt of its own:
1229
+ // admitting the git binary here would let the shell run git directly,
1230
+ // around the read-only server.
1189
1231
  mcpReadDirectories: mcp.mcpReadDirectories,
1190
1232
  publicSandboxMode,
1191
1233
  model: seatModel,
@@ -42,9 +42,12 @@
42
42
  * no transport is allowed, which covers git older than 2.44, where
43
43
  * GIT_NO_LAZY_FETCH does nothing.
44
44
  * 5. Outside this module, the seat's sandbox (Seatbelt or bwrap) mounts the
45
- * workspace read-only.
45
+ * workspace read-only. A public Codex seat starts its MCP servers outside
46
+ * its own profile, so the codex adapter runs this server under a Seatbelt
47
+ * of its own (workspace-git.js): workspace read-only, no network.
46
48
  * 6. A committed `.env` or `.env.*` stays as far out of reach as the file
47
- * itself, which the sandbox denies at any depth. An argument naming one
49
+ * itself, which the sandbox denies at any depth. So do `.npmrc`,
50
+ * `.yarnrc*`, `.commonly` and `.codex`, which a sandbox also denies. An argument naming one
48
51
  * (`.env`, `HEAD:.env`, `:0:sub/.env.local`, `-L1,5:.env`) is refused, and
49
52
  * status, log, diff and show run with pathspecs excluding them, so no patch,
50
53
  * pickaxe match or blob id comes from one whatever path or glob the caller
@@ -154,13 +157,27 @@ const checkFormat = (arg) => {
154
157
  return `${arg} is refused: name a built-in format (${BUILTIN_FORMATS.join(', ')}) or give format:<placeholders>`;
155
158
  };
156
159
 
157
- // Mirrors the names sandbox/seatbelt.js denies at any depth.
160
+ // The names a seat's sandbox denies at any depth: sandbox/seatbelt.js denies
161
+ // .env files, .commonly and .codex, and a public Codex seat's profile
162
+ // (adapters/codex.js) also denies .npmrc and .yarnrc*. They are kept out of
163
+ // git's results too, since the objects git reads hold them whatever the
164
+ // sandbox says about the file.
158
165
  const ENV_FILE_SEGMENT = /^\.env(\..*)?$/;
159
- const namesEnvFile = (arg) => arg.split(':')
160
- .some((part) => part.split('/').some((segment) => ENV_FILE_SEGMENT.test(segment)));
166
+ const OTHER_PROTECTED_SEGMENT = /^(?:\.npmrc|\.yarnrc.*|\.commonly|\.codex)$/;
167
+ const segmentsOf = (arg) => arg.split(':').flatMap((part) => part.split('/'));
168
+ const namesEnvFile = (arg) => segmentsOf(arg).some((segment) => ENV_FILE_SEGMENT.test(segment));
169
+ const namesOtherProtected = (arg) => segmentsOf(arg).some((segment) => OTHER_PROTECTED_SEGMENT.test(segment));
161
170
  const NAMES_ENV_FILE = 'it names a .env file, which the workspace keeps out of reach';
171
+ const NAMES_OTHER_PROTECTED = 'it names a file the workspace keeps out of reach (.npmrc, .yarnrc, .commonly or .codex)';
172
+ const protectedNameReason = (arg) => {
173
+ if (namesEnvFile(arg)) return NAMES_ENV_FILE;
174
+ if (namesOtherProtected(arg)) return NAMES_OTHER_PROTECTED;
175
+ return null;
176
+ };
162
177
  const ENV_EXCLUDES = Object.freeze([
163
178
  ':(exclude,glob)**/.env', ':(exclude,glob)**/.env.*', ':(exclude,glob)**/.env/**', ':(exclude,glob)**/.env.*/**',
179
+ ':(exclude,glob)**/.npmrc', ':(exclude,glob)**/.npmrc/**', ':(exclude,glob)**/.yarnrc*', ':(exclude,glob)**/.yarnrc*/**',
180
+ ':(exclude,glob)**/.commonly', ':(exclude,glob)**/.commonly/**', ':(exclude,glob)**/.codex', ':(exclude,glob)**/.codex/**',
164
181
  ]);
165
182
  // blame takes one literal file, so the name check above covers it. A
166
183
  // blob-to-blob diff (`diff A:f B:f`) takes no pathspec and is refused by git
@@ -254,14 +271,16 @@ export const readonlyGitArgv = ({ subcommand, args = [], root }) => {
254
271
  if (arg.length > MAX_ARG_LENGTH || arg.includes('\0')) return refuse('an argument is too long or contains NUL');
255
272
  if (pathsOnly || arg === '-' || !arg.startsWith('-')) {
256
273
  if (escapesRoot(root, arg)) return refuse(`${arg} is refused: it is outside the workspace`);
257
- if (namesEnvFile(arg)) return refuse(`${arg} is refused: ${NAMES_ENV_FILE}`);
274
+ const protectedReason = protectedNameReason(arg);
275
+ if (protectedReason) return refuse(`${arg} is refused: ${protectedReason}`);
258
276
  } else if (arg === '--') {
259
277
  pathsOnly = true;
260
278
  } else {
261
279
  const reason = arg.startsWith('--') ? checkLongOption(arg) || checkFormat(arg) : checkShortOption(arg, subcommand);
262
280
  if (reason) return refuse(reason);
263
281
  if (arg.startsWith('-L')) {
264
- if (namesEnvFile(arg.slice(2))) return refuse(`${arg} is refused: ${NAMES_ENV_FILE}`);
282
+ const rangeReason = protectedNameReason(arg.slice(2));
283
+ if (rangeReason) return refuse(`${arg} is refused: ${rangeReason}`);
265
284
  if (PATHSPEC_SUBCOMMANDS.has(subcommand)) {
266
285
  const lineRangeReason = checkLineRange(arg, index, subcommand);
267
286
  if (lineRangeReason) return refuse(lineRangeReason);
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Refuses a public Codex seat's workspace when its repository is set up to run
3
+ * programs.
4
+ *
5
+ * Codex runs git itself (status and diff of the workspace) outside the seat's
6
+ * permission profile, so whatever the repository's own git setup tells git to
7
+ * run, runs as the operator. `git clone` never copies a remote's config or
8
+ * hooks, so a repository the operator cloned carries none of this. A folder
9
+ * that was copied, unpacked or handed over can, and nothing about the folder
10
+ * says which it was.
11
+ *
12
+ * So before a turn, git itself is asked which repository it would open from the
13
+ * workspace and what config that repository gives it. Asking git rather than
14
+ * walking for `.git` matters: git also accepts a bare layout, skips a `.git` it
15
+ * can't use, and follows `.git` files and symlinks. The questions asked
16
+ * (`rev-parse`, `config --list`, `ls-files`) parse and print, and run with
17
+ * fsmonitor and hooks forced off on the command line, so the check can't be
18
+ * turned against the host. The same is done for every submodule recorded in
19
+ * the index that is checked out, since `git status` recurses into them.
20
+ *
21
+ * The turn is refused when any of these repositories sets a key that names a
22
+ * program or another config file, or holds a hook. The names are reported,
23
+ * never the values. When git's answer can't be read, the turn is refused too.
24
+ *
25
+ * Hook managers (husky's `core.hooksPath`, lefthook, pre-commit, git-lfs's
26
+ * hooks) are refused like any other: a later commit would run them as the
27
+ * operator. A seat that needs one of those repositories needs that setup
28
+ * removed from its copy.
29
+ */
30
+ import { spawnSync } from 'child_process';
31
+ import { existsSync, readdirSync } from 'fs';
32
+ import { isAbsolute, join, resolve } from 'path';
33
+
34
+ // Keys whose value names a program git may run, or another file whose keys it
35
+ // would then read. Matched on the key as git prints it: section and key lower
36
+ // case, subsection as written. Bare-boolean keys are in BOOLEAN_KEYS below.
37
+ const PROGRAM_KEYS = [
38
+ /^filter\..+\.(clean|smudge|process)$/i,
39
+ /^core\.(sshcommand|pager|editor|askpass|hookspath|gitproxy|alternaterefscommand|worktree)$/i,
40
+ /^diff\.external$/i,
41
+ /^diff\..+\.(command|textconv)$/i,
42
+ /^merge\..+\.driver$/i,
43
+ /^(mergetool|difftool)\..+\.(cmd|path)$/i,
44
+ /^pager\./i,
45
+ /^gpg\.(program|.+\.program)$/i,
46
+ /^gpg\.ssh\.defaultkeycommand$/i,
47
+ /^credential\.(helper|.+\.helper)$/i,
48
+ /^sequence\.editor$/i,
49
+ /^interactive\.difffilter$/i,
50
+ /^include\.path$/i,
51
+ /^includeif\..+\.path$/i,
52
+ /^hook\./i,
53
+ /^gc\.recentobjectshook$/i,
54
+ /^remote\..+\.(uploadpack|receivepack|proxy|vcs)$/i,
55
+ /^uploadpack\.packobjectshook$/i,
56
+ /^protocol\.allow$/i,
57
+ /^protocol\..+\.allow$/i,
58
+ /^sendemail\.(.+\.)?(smtpserver|tocmd|cccmd|sendmailcmd|headercmd)$/i,
59
+ /^imap\.tunnel$/i,
60
+ /^guitool\..+\.cmd$/i,
61
+ /^instaweb\.httpd$/i,
62
+ /^(web|help)\.browser$/i,
63
+ /^(browser|man)\..+\.(cmd|path)$/i,
64
+ /^trailer\..+\.(command|cmd)$/i,
65
+ /^lfs\.extension\..+\.(clean|smudge)$/i,
66
+ /^lfs\.customtransfer\..+\.path$/i,
67
+ ];
68
+ // core.fsmonitor is a program unless it is a boolean (true starts git's own
69
+ // daemon, which runs nothing from the repository).
70
+ const BOOLEAN_KEYS = [/^core\.fsmonitor$/i];
71
+ const BOOLEAN_VALUES = new Set(['', 'true', 'false', 'yes', 'no', 'on', 'off', '1', '0']);
72
+ // Keys that run a program only when their value says so.
73
+ const BANG_VALUE_KEYS = [/^alias\./i, /^submodule\..+\.update$/i];
74
+ const EXT_URL = /^ext::/i;
75
+
76
+ export const codeRunningKey = (key, value = '') => {
77
+ if (PROGRAM_KEYS.some((pattern) => pattern.test(key))) return true;
78
+ if (BOOLEAN_KEYS.some((pattern) => pattern.test(key))) return !BOOLEAN_VALUES.has(String(value).trim().toLowerCase());
79
+ if (BANG_VALUE_KEYS.some((pattern) => pattern.test(key))) return String(value).trim().startsWith('!');
80
+ if (/^(remote|submodule)\..+\.(url|pushurl)$/i.test(key)) return EXT_URL.test(String(value).trim());
81
+ if (/^url\..+\.(insteadof|pushinsteadof)$/i.test(key)) return EXT_URL.test(key.slice(4));
82
+ return false;
83
+ };
84
+
85
+ // What git reads from the environment to pick a repository. Passed through, so
86
+ // the check opens the repository Codex's git would.
87
+ const DISCOVERY_ENV = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_CEILING_DIRECTORIES', 'GIT_DISCOVERY_ACROSS_FILESYSTEM'];
88
+ // On the command line, ahead of anything the repository says: nothing these
89
+ // commands do may start fsmonitor or a hook.
90
+ const SAFE_FLAGS = ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-c', 'core.untrackedCache=false'];
91
+ const MAX_DEPTH = 8;
92
+
93
+ const gitEnv = (baseEnv) => {
94
+ const env = { PATH: baseEnv.PATH || process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' };
95
+ for (const name of DISCOVERY_ENV) if (baseEnv[name] !== undefined) env[name] = baseEnv[name];
96
+ return env;
97
+ };
98
+
99
+ const runGit = (run, cwd, env, args, { flags = SAFE_FLAGS } = {}) => run('git', [...flags, ...args], {
100
+ cwd, env, encoding: 'utf8', timeout: 10_000, maxBuffer: 16 * 1024 * 1024,
101
+ });
102
+
103
+ // The repository git opens from `dir`, as git reports it: null when `dir` is in
104
+ // none, or `{ unreadable }` when git could not say.
105
+ const describeRepository = (dir, { run, env }) => {
106
+ const result = runGit(run, dir, env, ['rev-parse', '--path-format=absolute', '--absolute-git-dir', '--git-common-dir', '--git-path', 'hooks']);
107
+ if (result?.status !== 0) {
108
+ // No git on the host means Codex can't run git either.
109
+ if (result?.error?.code === 'ENOENT') return null;
110
+ // Only git's "nothing here or above" answer means no repository. A `.git`
111
+ // file pointing nowhere also says "not a git repository", with the path.
112
+ if (/not a git repository \(or any/i.test(String(result?.stderr || ''))) return null;
113
+ return { unreadable: `git could not read the repository (${String(result?.stderr || result?.error?.message || 'no answer').trim().split('\n')[0]})` };
114
+ }
115
+ const [gitDir, commonDir, hooksDirRaw] = String(result.stdout).trim().split('\n');
116
+ if (!gitDir || !commonDir || !hooksDirRaw) return { unreadable: 'git gave no repository path' };
117
+ // --git-path answers with core.hooksPath forced to /dev/null above, so the
118
+ // repository's own hooks folder is read without it.
119
+ const hooksDir = hooksDirRaw === '/dev/null' ? join(commonDir, 'hooks') : hooksDirRaw;
120
+ return { gitDir, commonDir, hooksDir: isAbsolute(hooksDir) ? hooksDir : resolve(dir, hooksDir) };
121
+ };
122
+
123
+ // Every config entry git applies in this repository, with the system and
124
+ // global files off: the repository's own config, its worktree config, and
125
+ // whatever they include.
126
+ const repositoryConfig = (dir, { run, env }) => {
127
+ const result = runGit(run, dir, env, ['config', '--list', '--includes', '-z', '--show-origin']);
128
+ if (result?.status !== 0) return null;
129
+ // With --show-origin and -z each entry is "origin\0key\nvalue\0".
130
+ const parts = String(result.stdout || '').split('\0');
131
+ const entries = [];
132
+ for (let i = 0; i + 1 < parts.length; i += 2) {
133
+ const origin = parts[i];
134
+ const entry = parts[i + 1];
135
+ // The safe flags this check passes come back as "command line:" entries.
136
+ if (!entry || origin.startsWith('command line:')) continue;
137
+ const at = entry.indexOf('\n');
138
+ entries.push({
139
+ origin: origin.replace(/^file:/, ''),
140
+ key: at < 0 ? entry : entry.slice(0, at),
141
+ value: at < 0 ? '' : entry.slice(at + 1),
142
+ });
143
+ }
144
+ return entries;
145
+ };
146
+
147
+ // Hook names in `dir`, or null when it exists but can't be listed.
148
+ const hooksIn = (dir) => {
149
+ if (!existsSync(dir)) return [];
150
+ try {
151
+ return readdirSync(dir).filter((name) => !name.endsWith('.sample'));
152
+ } catch {
153
+ return null;
154
+ }
155
+ };
156
+
157
+ // Checked-out submodules recorded in the index, as paths below `top`.
158
+ const submodulesOf = (top, { run, env }) => {
159
+ const result = runGit(run, top, env, ['ls-files', '--stage', '-z']);
160
+ if (result?.status !== 0) return null;
161
+ return String(result.stdout || '').split('\0').filter((line) => line.startsWith('160000 '))
162
+ .map((line) => line.slice(line.indexOf('\t') + 1))
163
+ .map((path) => join(top, path))
164
+ .filter((path) => existsSync(join(path, '.git')));
165
+ };
166
+
167
+ const topLevelOf = (dir, { run, env }) => {
168
+ const result = runGit(run, dir, env, ['rev-parse', '--show-toplevel']);
169
+ return result?.status === 0 ? String(result.stdout).trim() || null : null;
170
+ };
171
+
172
+ const inspect = (dir, context, findings, seen, depth) => {
173
+ const repo = describeRepository(dir, context);
174
+ if (!repo) return;
175
+ if (repo.unreadable) {
176
+ findings.push({ file: dir, key: repo.unreadable });
177
+ return;
178
+ }
179
+ if (seen.has(repo.gitDir)) return;
180
+ seen.add(repo.gitDir);
181
+ if (depth > MAX_DEPTH) {
182
+ findings.push({ file: dir, key: `submodules nested deeper than ${MAX_DEPTH}` });
183
+ return;
184
+ }
185
+ const entries = repositoryConfig(dir, context);
186
+ if (!entries) {
187
+ findings.push({ file: join(repo.commonDir, 'config'), key: 'unreadable config' });
188
+ } else {
189
+ for (const { origin, key, value } of entries) {
190
+ if (codeRunningKey(key, value)) findings.push({ file: origin, key });
191
+ }
192
+ }
193
+ for (const hooksDir of new Set([repo.hooksDir, join(repo.gitDir, 'hooks'), join(repo.commonDir, 'hooks')])) {
194
+ const hooks = hooksIn(hooksDir);
195
+ if (!hooks) findings.push({ file: hooksDir, key: 'unreadable hooks folder' });
196
+ else for (const hook of hooks) findings.push({ file: join(hooksDir, hook), hook });
197
+ }
198
+ const top = topLevelOf(dir, context);
199
+ if (!top) return; // a bare repository has no work tree, so no submodules are checked out
200
+ const submodules = submodulesOf(top, context);
201
+ if (!submodules) {
202
+ findings.push({ file: top, key: 'unreadable index' });
203
+ return;
204
+ }
205
+ for (const sub of submodules) inspect(sub, context, findings, seen, depth + 1);
206
+ };
207
+
208
+ /**
209
+ * What would make git run a program in the workspace's repository or its
210
+ * checked-out submodules: each a `{ file, key }` (never the value), or a
211
+ * `{ file, hook }`. Empty when the workspace is in no repository, or nothing
212
+ * is set. `env` is the environment Codex will get; only the variables git uses
213
+ * to pick a repository are taken from it.
214
+ */
215
+ export const codeRunningGitSetup = (workspace, { run = spawnSync, env = process.env } = {}) => {
216
+ const findings = [];
217
+ inspect(resolve(workspace), { run, env: gitEnv(env) }, findings, new Set(), 0);
218
+ return findings;
219
+ };
220
+
221
+ export const refuseCodeRunningGitSetup = (workspace, { seat = 'this agent', run, env } = {}) => {
222
+ const findings = codeRunningGitSetup(workspace, { run, env });
223
+ if (!findings.length) return;
224
+ const named = findings.slice(0, 8).map((f) => (f.hook ? `hook ${f.hook} (${f.file})` : `${f.key} (${f.file})`)).join('; ');
225
+ const more = findings.length > 8 ? ` and ${findings.length - 8} more` : '';
226
+ const error = new Error(
227
+ `${seat} won't work in ${workspace}: its git repository is set to run programs, or git couldn't `
228
+ + `say (${named}${more}). Codex runs git outside the sandbox, so these would run as you. Remove that setup from the `
229
+ + 'agent\'s copy (unset the keys, delete the hooks), or give it a fresh `git clone` that no hook '
230
+ + 'manager has been installed into.',
231
+ );
232
+ error.code = 'workspace_git_runs_programs';
233
+ throw error;
234
+ };
235
+
236
+ export default { codeRunningGitSetup, codeRunningKey, refuseCodeRunningGitSetup };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The read-only `workspace_git` MCP server (git-readonly-server.js), as an
3
+ * adapter attaches it to a sandboxed seat. Shared by the claude adapter (for a
4
+ * workspace-trust seat) and the codex adapter (for a public seat), so both
5
+ * give the model the same one git tool, run against the same real binary.
6
+ */
7
+ import { spawnSync } from 'child_process';
8
+ import { realpathSync } from 'fs';
9
+ import { dirname, join } from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import { wrapArgvWithSeatbelt } from './sandbox/seatbelt.js';
12
+
13
+ // The name git-readonly-server.js serves under. Kept here, not imported: the
14
+ // server module pulls in git-readonly.js and its execFile, which an adapter has
15
+ // no use for (git-readonly-server.test.mjs checks the two names agree).
16
+ export const WORKSPACE_GIT_SERVER_NAME = 'workspace_git';
17
+
18
+ // The server runs inside the sandbox, so the sandbox must admit its code
19
+ // (cli/src/lib, plus package.json for the module type) and the git binary it runs.
20
+ export const WORKSPACE_GIT_SERVER = fileURLToPath(new URL('./git-readonly-server.js', import.meta.url));
21
+ export const WORKSPACE_GIT_PACKAGE_JSON = fileURLToPath(new URL('../../package.json', import.meta.url));
22
+
23
+ // macOS's /usr/bin/git is an xcrun shim, and it fails inside a sandbox ("No
24
+ // developer tools were found"). So the sandbox gets the binary git itself runs:
25
+ // `git --exec-path`, resolved here on the host, holds a `git` that links to it.
26
+ export const resolveRealGit = ({ run = spawnSync } = {}) => {
27
+ const result = run('git', ['--exec-path'], { encoding: 'utf8', timeout: 5000 });
28
+ const execDir = result?.status === 0 ? String(result.stdout || '').trim() : '';
29
+ if (!execDir) return null;
30
+ try {
31
+ return realpathSync(join(execDir, 'git'));
32
+ } catch {
33
+ return null;
34
+ }
35
+ };
36
+
37
+ // The MCP server entry and the paths the sandbox has to let it read, for a
38
+ // seat whose workspace is `root`. Null when this machine has no git.
39
+ export const workspaceGitAttachment = (root, { git = resolveRealGit() } = {}) => {
40
+ if (!root || !git) return null;
41
+ return {
42
+ server: {
43
+ name: WORKSPACE_GIT_SERVER_NAME,
44
+ transport: 'stdio',
45
+ command: [process.execPath, WORKSPACE_GIT_SERVER, '--root', root, '--git', git],
46
+ },
47
+ executable: git,
48
+ readDirectories: [dirname(WORKSPACE_GIT_SERVER)],
49
+ readPaths: [WORKSPACE_GIT_PACKAGE_JSON],
50
+ };
51
+ };
52
+
53
+ // For a public Codex seat. Codex starts its MCP servers outside the seat's
54
+ // permission profile, so a bare server would run git as the operator, with the
55
+ // network on and every file the profile denies in reach. This one runs under a
56
+ // Seatbelt of its own: the workspace read-only, no network, its code and git
57
+ // readable, and nothing writable but `stateDir`, an empty folder of its own (not
58
+ // the folder that holds the seat's credential). macOS only: elsewhere there is
59
+ // no wrapper here yet, so the seat gets no tool rather than an unconfined one.
60
+ export const confinedWorkspaceGitServer = (root, {
61
+ stateDir,
62
+ platform = process.platform,
63
+ git = platform === 'darwin' ? resolveRealGit() : null,
64
+ wrap = wrapArgvWithSeatbelt,
65
+ } = {}) => {
66
+ if (platform !== 'darwin' || !root || !stateDir || !git) return null;
67
+ const attachment = workspaceGitAttachment(root, { git });
68
+ const command = wrap(attachment.server.command, {
69
+ workspacePath: root,
70
+ workspaceAccess: 'read',
71
+ executablePath: git,
72
+ statePath: stateDir,
73
+ readOnlyDirectories: attachment.readDirectories,
74
+ readOnlyPaths: attachment.readPaths,
75
+ network: 'loopback',
76
+ processInfo: 'self',
77
+ });
78
+ return { ...attachment.server, command };
79
+ };