@bakers-build/addon-codex 0.10.1-next.1 → 0.10.1-next.3

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.
@@ -16,6 +16,13 @@ export interface CodexAgentOptions extends SecurityOptions {
16
16
  * read as one; switch to a TOML parser if that ever matters.
17
17
  */
18
18
  export declare function codexMcpServerIds(toml: string): string[];
19
+ /**
20
+ * Codex `prefix_rule`s allowing each entry, a literal command prefix of
21
+ * whitespace-separated argv tokens (`'ddev'`, `'git push'`, or `'ddev *'` as
22
+ * written for Claude). Throws on any entry Codex would not match literally,
23
+ * so none silently widens.
24
+ */
25
+ export declare function trustedCommandRules(entries: readonly string[]): string;
19
26
  export declare class CodexAgent implements BbAgent {
20
27
  private readonly home;
21
28
  readonly id = "codex";
@@ -25,6 +32,8 @@ export declare class CodexAgent implements BbAgent {
25
32
  private readonly overrides;
26
33
  readonly security: ResolvedSecurity;
27
34
  private readonly allowWrite;
35
+ /** This launch's `.rules` text, empty without trusted commands. */
36
+ private readonly trustedRules;
28
37
  readonly runEnvPolicy: RunEnvPolicy;
29
38
  readonly pluginsDisabled: boolean;
30
39
  /** The Codex home runs read and write: the agent home while plugins are on. */
package/dist/src/index.js CHANGED
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, symlinkSync } from 'node:fs';
3
3
  import { readdir, readFile, stat } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
6
7
  import { promisify } from 'node:util';
7
8
  import { CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOL_TIMEOUT_MS, CONDUCTOR_TOOLS_SERVER, ensureHome, homeKey, homePath, lastLine, resolveAgentCliOptions, resolveSecurityOptions, systemSandboxHost, validateOptionalBoolean, } from '@bakers-build/conductor/contract';
8
9
  import { gitSandboxPaths, shellQuote, withoutGitDirs, } from '@bakers-build/core';
@@ -106,6 +107,27 @@ export function codexMcpServerIds(toml) {
106
107
  }
107
108
  return [...ids];
108
109
  }
110
+ /** One literal argv token: no quoting, globbing, expansion or operator. */
111
+ const COMMAND_TOKEN = /^[A-Za-z0-9_./@%+=:,-]+$/;
112
+ /**
113
+ * Codex `prefix_rule`s allowing each entry, a literal command prefix of
114
+ * whitespace-separated argv tokens (`'ddev'`, `'git push'`, or `'ddev *'` as
115
+ * written for Claude). Throws on any entry Codex would not match literally,
116
+ * so none silently widens.
117
+ */
118
+ export function trustedCommandRules(entries) {
119
+ return entries
120
+ .map((entry) => {
121
+ const tokens = entry.trim().split(/\s+/);
122
+ // A Claude-style trailing ` *` means the same prefix; no other wildcard.
123
+ if (tokens.length > 1 && tokens.at(-1) === '*')
124
+ tokens.pop();
125
+ if (entry.trim() === '' || !tokens.every((t) => COMMAND_TOKEN.test(t)))
126
+ throw new Error(`sandbox.trusted_commands: ${JSON.stringify(entry)} is not a literal command prefix such as 'ddev' or 'git push'; Codex has no wildcards, quoting or shell syntax`);
127
+ return `prefix_rule(pattern=${JSON.stringify(tokens)}, decision="allow", justification="bakers.build sandbox.trusted_commands")\n`;
128
+ })
129
+ .join('');
130
+ }
109
131
  const CODEX_KNOWN = [
110
132
  { kind: 'model', flags: ['--model', '-m'], configKeys: ['model'] },
111
133
  { kind: 'effort', flags: [], configKeys: ['model_reasoning_effort'] },
@@ -119,6 +141,8 @@ export class CodexAgent {
119
141
  overrides;
120
142
  security;
121
143
  allowWrite;
144
+ /** This launch's `.rules` text, empty without trusted commands. */
145
+ trustedRules;
122
146
  runEnvPolicy;
123
147
  pluginsDisabled;
124
148
  /** The Codex home runs read and write: the agent home while plugins are on. */
@@ -131,21 +155,23 @@ export class CodexAgent {
131
155
  this.model = cli.model;
132
156
  this.effort = cli.effort;
133
157
  this.overrides = cli.overrides;
134
- // Shared deny_read and trusted_commands have nothing to map onto here.
158
+ // A shared deny_read has nothing to map onto here.
135
159
  this.security = resolveSecurityOptions(options, SANDBOX_DEFAULTS, {
136
- unsupported: ['deny_read', 'trusted_commands'],
160
+ unsupported: ['deny_read'],
137
161
  });
138
162
  this.runEnvPolicy = this.security.runEnvPolicy;
139
163
  this.allowWrite = withoutGitDirs(this.security.sandbox.allow_write);
140
164
  this.pluginsDisabled =
141
165
  validateOptionalBoolean(options.plugins, 'plugins') === false;
142
166
  this.configDir = this.userCodexHome();
143
- // Codex has no read deny or unsandboxed-command list to map these onto.
144
- for (const key of ['trusted_commands', 'deny_read']) {
145
- if (this.security.sandbox[key].length > 0) {
146
- throw new Error(`Codex does not support sandbox.${key}`);
147
- }
167
+ // Codex has no read deny to map this onto.
168
+ if (this.security.sandbox.deny_read.length > 0) {
169
+ throw new Error('Codex does not support sandbox.deny_read');
148
170
  }
171
+ this.trustedRules =
172
+ this.security.mode === 'sandbox'
173
+ ? trustedCommandRules(this.security.sandbox.trusted_commands)
174
+ : '';
149
175
  // `-c` takes a TOML value; a JSON object is not one.
150
176
  for (const [key, value] of Object.entries(this.security.config ?? {})) {
151
177
  if (value !== null &&
@@ -265,6 +291,8 @@ export class CodexAgent {
265
291
  const word = (t) => (/^[\w./=-]+$/.test(t) ? t : shellQuote(t));
266
292
  const parts = [
267
293
  'codex',
294
+ // A shared daemon would serve another home's rules.
295
+ ...(this.trustedRules ? ['--no-daemon'] : []),
268
296
  ...this.securityFlags(workspacePath, tools !== undefined, isolatedGit).map(word),
269
297
  ];
270
298
  for (const arg of pluginArgs)
@@ -295,6 +323,12 @@ export class CodexAgent {
295
323
  parts.push(shellQuote(prompt));
296
324
  parts.push(...this.args.map(shellQuote));
297
325
  }
326
+ if (this.trustedRules) {
327
+ const launcher = fileURLToPath(new URL(import.meta.url.endsWith('.ts')
328
+ ? './trusted-launch.ts'
329
+ : './trusted-launch.js', import.meta.url));
330
+ parts.unshift(shellQuote(process.execPath), shellQuote(launcher), shellQuote(this.trustedRules));
331
+ }
298
332
  return parts.join(' ');
299
333
  }
300
334
  async getRunLog(worktreePath, run) {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,83 @@
1
+ // Runs `codex` in a private CODEX_HOME whose `rules/` adds this launch's
2
+ // sandbox.trusted_commands to the operator's own rules; see docs/addons/codex.md.
3
+ import { execFile, spawn } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { cp, mkdir, readdir, readFile, rm, symlink, writeFile, } from 'node:fs/promises';
6
+ import { homedir, constants as osConstants } from 'node:os';
7
+ import { join, resolve } from 'node:path';
8
+ import { promisify } from 'node:util';
9
+ async function main() {
10
+ const [rules, executable, ...args] = process.argv.slice(2);
11
+ if (!rules || executable !== 'codex')
12
+ throw new Error('Invalid trusted Codex invocation');
13
+ const { stdout } = await promisify(execFile)('codex', ['--version'], {
14
+ timeout: 15000,
15
+ });
16
+ const [, major, minor, patch] = /(\d+)\.(\d+)\.(\d+)/.exec(stdout) ?? [];
17
+ if (Number(major) * 1e6 + Number(minor) * 1e3 + Number(patch) < 166_000 ||
18
+ !major)
19
+ throw new Error(`Codex 0.166.0 or newer is required, found ${stdout.trim()}`);
20
+ const source = resolve(process.env.CODEX_HOME || join(homedir(), '.codex'));
21
+ let config = '';
22
+ try {
23
+ config = await readFile(join(source, 'config.toml'), 'utf8');
24
+ }
25
+ catch (error) {
26
+ if (error.code !== 'ENOENT')
27
+ throw error;
28
+ }
29
+ // A keyring login is keyed by the home's path, so the private home would lose it.
30
+ if (/^\s*cli_auth_credentials_store\s*=\s*["'](keyring|auto)/m.test(config))
31
+ throw new Error('a file-backed login is required: set cli_auth_credentials_store = "file" and log in again');
32
+ // Transcripts land in the operator's home, where the conductor reads them.
33
+ await mkdir(join(source, 'sessions'), { recursive: true });
34
+ // A sibling keeps `../` paths in config.toml resolving as before.
35
+ const home = `${source}.bakers-${randomUUID()}`;
36
+ await mkdir(join(home, 'rules'), { recursive: true, mode: 0o700 });
37
+ try {
38
+ // shortcut: entries Codex creates later stay in the private home and are
39
+ // removed with it; link them ahead if one must persist.
40
+ for (const name of await readdir(source))
41
+ if (name !== 'rules')
42
+ await symlink(join(source, name), join(home, name));
43
+ // Codex skips linked .rules files, so the operator's rules are copied.
44
+ const inherited = await readdir(join(source, 'rules')).catch(() => []);
45
+ for (const name of inherited)
46
+ await cp(join(source, 'rules', name), join(home, 'rules', name), {
47
+ recursive: true,
48
+ dereference: true,
49
+ });
50
+ await writeFile(join(home, 'rules', 'bakers-trusted-commands.rules'), rules, {
51
+ flag: 'wx',
52
+ });
53
+ const child = spawn('codex', args, {
54
+ stdio: 'inherit',
55
+ env: { ...process.env, CODEX_HOME: home },
56
+ });
57
+ const handlers = ['SIGINT', 'SIGTERM', 'SIGHUP'].map((signal) => {
58
+ const forward = () => {
59
+ child.kill(signal);
60
+ };
61
+ process.on(signal, forward);
62
+ return { signal, forward };
63
+ });
64
+ try {
65
+ process.exitCode = await new Promise((resolveExit, reject) => {
66
+ child.once('error', reject);
67
+ child.once('exit', (code, signal) => resolveExit(code ?? (signal ? 128 + osConstants.signals[signal] : 1)));
68
+ });
69
+ }
70
+ finally {
71
+ for (const { signal, forward } of handlers)
72
+ process.off(signal, forward);
73
+ }
74
+ }
75
+ finally {
76
+ // Removes the links, never their targets.
77
+ await rm(home, { recursive: true, force: true });
78
+ }
79
+ }
80
+ main().catch((error) => {
81
+ console.error(`Cannot run Codex with sandbox.trusted_commands: ${error instanceof Error ? error.message : String(error)}`);
82
+ process.exitCode = 1;
83
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-codex",
3
- "version": "0.10.1-next.1",
3
+ "version": "0.10.1-next.3",
4
4
  "description": "bakers.build agent plugin for the Codex CLI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -22,11 +22,11 @@
22
22
  "directory": "bakers-cli/addons/codex"
23
23
  },
24
24
  "peerDependencies": {
25
- "@bakers-build/conductor": "^0.10.1-next.1",
26
- "@bakers-build/core": "^0.10.1-next.1"
25
+ "@bakers-build/conductor": "^0.10.1-next.3",
26
+ "@bakers-build/core": "^0.10.1-next.3"
27
27
  },
28
28
  "bakersBuild": {
29
- "commit": "f9cee7721df536cac94906e7278d60a13e202502",
29
+ "commit": "0eec088d2c0daf5127b57de523f251d83c497cc4",
30
30
  "channel": "next"
31
31
  }
32
32
  }