@bakers-build/addon-codex 0.10.0 → 0.10.1-next.10

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.
@@ -1,4 +1,4 @@
1
- import { type AgentFootprint, type AgentPlugin, type AgentRunIdentity, type BbAgent, type MarketplaceDeclaration, type PluginLaunch, type ResolvedSecurity, type RunEnvPolicy, type SandboxHost, type SandboxPreflight, type SecurityOptions } from '@bakers-build/conductor/contract';
1
+ import { type AgentFootprint, type AgentPlugin, type AgentRunContext, type AgentRunIdentity, type BbAgent, type MarketplaceDeclaration, type PluginLaunch, type ResolvedSecurity, type RunEnvPolicy, type SandboxHost, type SandboxPreflight, type SecurityOptions } from '@bakers-build/conductor/contract';
2
2
  export { parseCodexTranscript } from './footprint.js';
3
3
  export interface CodexAgentOptions extends SecurityOptions {
4
4
  model?: string;
@@ -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. */
@@ -35,6 +44,7 @@ export declare class CodexAgent implements BbAgent {
35
44
  /** Point this agent at the agent home of the project's declared marketplaces. */
36
45
  useMarketplaces(marketplaces: readonly MarketplaceDeclaration[]): void;
37
46
  installPlugins(marketplaces: readonly MarketplaceDeclaration[], home: string): Promise<PluginLaunch>;
47
+ prepareRun(context: AgentRunContext): import("@bakers-build/conductor/contract").AgentRunPreparation;
38
48
  /** A `config.toml` server the conductor's own replaces, named once per dispatch. */
39
49
  get launchWarnings(): readonly string[];
40
50
  /** The launch flags a security mode owns (`docs/addons/codex.md`). */
package/dist/src/index.js CHANGED
@@ -3,10 +3,12 @@ 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';
9
10
  import { parseCodexTranscript } from './footprint.js';
11
+ import { prepareCodexRun } from './run.js';
10
12
  export { parseCodexTranscript } from './footprint.js';
11
13
  const run = promisify(execFile);
12
14
  /** Run `codex <args>` in `codexHome`; a failure names `what` and the CLI's output. */
@@ -106,6 +108,27 @@ export function codexMcpServerIds(toml) {
106
108
  }
107
109
  return [...ids];
108
110
  }
111
+ /** One literal argv token: no quoting, globbing, expansion or operator. */
112
+ const COMMAND_TOKEN = /^[A-Za-z0-9_./@%+=:,-]+$/;
113
+ /**
114
+ * Codex `prefix_rule`s allowing each entry, a literal command prefix of
115
+ * whitespace-separated argv tokens (`'ddev'`, `'git push'`, or `'ddev *'` as
116
+ * written for Claude). Throws on any entry Codex would not match literally,
117
+ * so none silently widens.
118
+ */
119
+ export function trustedCommandRules(entries) {
120
+ return entries
121
+ .map((entry) => {
122
+ const tokens = entry.trim().split(/\s+/);
123
+ // A Claude-style trailing ` *` means the same prefix; no other wildcard.
124
+ if (tokens.length > 1 && tokens.at(-1) === '*')
125
+ tokens.pop();
126
+ if (entry.trim() === '' || !tokens.every((t) => COMMAND_TOKEN.test(t)))
127
+ 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`);
128
+ return `prefix_rule(pattern=${JSON.stringify(tokens)}, decision="allow", justification="bakers.build sandbox.trusted_commands")\n`;
129
+ })
130
+ .join('');
131
+ }
109
132
  const CODEX_KNOWN = [
110
133
  { kind: 'model', flags: ['--model', '-m'], configKeys: ['model'] },
111
134
  { kind: 'effort', flags: [], configKeys: ['model_reasoning_effort'] },
@@ -119,6 +142,8 @@ export class CodexAgent {
119
142
  overrides;
120
143
  security;
121
144
  allowWrite;
145
+ /** This launch's `.rules` text, empty without trusted commands. */
146
+ trustedRules;
122
147
  runEnvPolicy;
123
148
  pluginsDisabled;
124
149
  /** The Codex home runs read and write: the agent home while plugins are on. */
@@ -131,21 +156,23 @@ export class CodexAgent {
131
156
  this.model = cli.model;
132
157
  this.effort = cli.effort;
133
158
  this.overrides = cli.overrides;
134
- // Shared deny_read and trusted_commands have nothing to map onto here.
159
+ // A shared deny_read has nothing to map onto here.
135
160
  this.security = resolveSecurityOptions(options, SANDBOX_DEFAULTS, {
136
- unsupported: ['deny_read', 'trusted_commands'],
161
+ unsupported: ['deny_read'],
137
162
  });
138
163
  this.runEnvPolicy = this.security.runEnvPolicy;
139
164
  this.allowWrite = withoutGitDirs(this.security.sandbox.allow_write);
140
165
  this.pluginsDisabled =
141
166
  validateOptionalBoolean(options.plugins, 'plugins') === false;
142
167
  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
- }
168
+ // Codex has no read deny to map this onto.
169
+ if (this.security.sandbox.deny_read.length > 0) {
170
+ throw new Error('Codex does not support sandbox.deny_read');
148
171
  }
172
+ this.trustedRules =
173
+ this.security.mode === 'sandbox'
174
+ ? trustedCommandRules(this.security.sandbox.trusted_commands)
175
+ : '';
149
176
  // `-c` takes a TOML value; a JSON object is not one.
150
177
  for (const [key, value] of Object.entries(this.security.config ?? {})) {
151
178
  if (value !== null &&
@@ -194,6 +221,9 @@ export class CodexAgent {
194
221
  trust_bypass: ['hook trust'],
195
222
  };
196
223
  }
224
+ prepareRun(context) {
225
+ return prepareCodexRun(context, this.configDir);
226
+ }
197
227
  /** A `config.toml` server the conductor's own replaces, named once per dispatch. */
198
228
  get launchWarnings() {
199
229
  return this.userMcpServers().includes(CONDUCTOR_TOOLS_SERVER)
@@ -265,6 +295,8 @@ export class CodexAgent {
265
295
  const word = (t) => (/^[\w./=-]+$/.test(t) ? t : shellQuote(t));
266
296
  const parts = [
267
297
  'codex',
298
+ // A shared daemon would serve another home's rules.
299
+ ...(this.trustedRules ? ['--no-daemon'] : []),
268
300
  ...this.securityFlags(workspacePath, tools !== undefined, isolatedGit).map(word),
269
301
  ];
270
302
  for (const arg of pluginArgs)
@@ -295,6 +327,12 @@ export class CodexAgent {
295
327
  parts.push(shellQuote(prompt));
296
328
  parts.push(...this.args.map(shellQuote));
297
329
  }
330
+ if (this.trustedRules) {
331
+ const launcher = fileURLToPath(new URL(import.meta.url.endsWith('.ts')
332
+ ? './trusted-launch.ts'
333
+ : './trusted-launch.js', import.meta.url));
334
+ parts.unshift(shellQuote(process.execPath), shellQuote(launcher), shellQuote(this.trustedRules));
335
+ }
298
336
  return parts.join(' ');
299
337
  }
300
338
  async getRunLog(worktreePath, run) {
@@ -0,0 +1,3 @@
1
+ import type { AgentRunContext, AgentRunPreparation } from '@bakers-build/conductor/contract';
2
+ /** Prepare Codex's files in the home supplied by any execution backend. */
3
+ export declare function prepareCodexRun(context: AgentRunContext, configDir: string, hostEnv?: Readonly<Record<string, string | undefined>>): AgentRunPreparation;
@@ -0,0 +1,64 @@
1
+ import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, realpathSync, symlinkSync, writeFileSync, } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ /**
4
+ * Source directories shared read-only; everything else starts fresh and
5
+ * writable in the private home, since Codex writes leftovers such as
6
+ * thread-writer-locks at startup. Marketplace clones live in .tmp/marketplaces.
7
+ */
8
+ const SHARED = ['plugins', 'skills', 'packages', '.tmp/marketplaces'];
9
+ /** Prepare Codex's files in the home supplied by any execution backend. */
10
+ export function prepareCodexRun(context, configDir, hostEnv = process.env) {
11
+ const source = context.env.CODEX_HOME ?? configDir;
12
+ const home = join(context.homePath, '.codex');
13
+ mkdirSync(home, { recursive: true });
14
+ // Transcripts land in the source home, where the conductor reads them.
15
+ const sessions = join(source, 'sessions');
16
+ mkdirSync(sessions, { recursive: true });
17
+ symlinkSync(sessions, join(home, 'sessions'));
18
+ // Writable copies: Codex records project trust in config.toml, skips linked
19
+ // .rules files, and the trusted-commands launcher adds a rule beside them.
20
+ if (existsSync(join(source, 'config.toml')))
21
+ copyFileSync(join(source, 'config.toml'), join(home, 'config.toml'));
22
+ if (existsSync(join(source, 'rules')))
23
+ cpSync(join(source, 'rules'), join(home, 'rules'), {
24
+ recursive: true,
25
+ dereference: true,
26
+ });
27
+ // Shared directories are linked each on its own: the runtimes refuse a
28
+ // write path inside a read path.
29
+ // shortcut: files such as the state DB and history start empty in the
30
+ // private home and are discarded with it; link one if it must persist.
31
+ const readPaths = [];
32
+ for (const name of SHARED) {
33
+ const path = join(source, name);
34
+ if (!existsSync(path) || !lstatSync(path).isDirectory())
35
+ continue;
36
+ mkdirSync(dirname(join(home, name)), { recursive: true });
37
+ symlinkSync(path, join(home, name));
38
+ readPaths.push(path);
39
+ }
40
+ const keys = ['CODEX_API_KEY', 'OPENAI_API_KEY'];
41
+ const env = { CODEX_HOME: home };
42
+ const bindPaths = [];
43
+ if (!keys.some((key) => context.env[key])) {
44
+ const key = keys.find((name) => hostEnv[name]);
45
+ if (key)
46
+ env[key] = hostEnv[key];
47
+ else if (existsSync(join(source, 'auth.json'))) {
48
+ // The run shares the host's login file, never a copy: a refresh in one
49
+ // copy rotates the token and logs every other copy out.
50
+ const login = join(home, 'auth.json');
51
+ writeFileSync(login, '', { mode: 0o600 });
52
+ bindPaths.push({
53
+ source: realpathSync(join(source, 'auth.json')),
54
+ target: login,
55
+ });
56
+ }
57
+ }
58
+ return {
59
+ env,
60
+ readPaths,
61
+ writePaths: [sessions],
62
+ ...(bindPaths.length ? { bindPaths } : {}),
63
+ };
64
+ }
@@ -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.0",
3
+ "version": "0.10.1-next.10",
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.0",
26
- "@bakers-build/core": "^0.10.0"
25
+ "@bakers-build/conductor": "^0.10.1-next.10",
26
+ "@bakers-build/core": "^0.10.1-next.10"
27
27
  },
28
28
  "bakersBuild": {
29
- "commit": "5857b00008bc0926fd52fdc8d9366d6d52444e35",
30
- "channel": "latest"
29
+ "commit": "d0f650fbe4c44eda2a26be62d28d30c22c56c386",
30
+ "channel": "next"
31
31
  }
32
32
  }