@commonlyai/cli 0.1.310 → 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.310",
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",
@@ -82,6 +82,7 @@ import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '..
82
82
  import { resolveSkillSource, skillsAsText } from '../skill-prompt.js';
83
83
  import { isLegacySandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
84
84
  import { contains, realpathOfNearest, refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
85
+ import { refuseCodeRunningGitSetup } from '../sandbox/workspace-git-config.js';
85
86
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
86
87
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
87
88
  import { startProviderProxy } from '../provider-proxy.js';
@@ -1099,6 +1100,12 @@ export default {
1099
1100
  const workspacePath = sandbox?.trust === 'public'
1100
1101
  ? await refuseWorkspaceHoldingTurnDirs({ workspace: ctx.cwd, seat: 'public Codex agents' })
1101
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
+ }
1102
1109
 
1103
1110
  // Per-spawn temp dir for --output-last-message. Cleaned up in `finally`
1104
1111
  // so a crash in the middle of the spawn doesn't leak files in $TMPDIR.
@@ -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 };