@aisac/cli 0.4.0-beta.1 → 0.4.0-beta.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.
@@ -0,0 +1,206 @@
1
+ // @ts-check
2
+ /**
3
+ * A small POSIX-style shell word splitter for guardrail decisions. It never
4
+ * runs anything. It keeps quotes, escapes and command substitutions inside
5
+ * their word, splits commands on control operators, and marks redirection
6
+ * targets. When the text cannot be split (an unterminated quote), `ok` is
7
+ * false and callers fall back to a word-boundary scan of the raw text.
8
+ */
9
+
10
+ /**
11
+ * @typedef {object} ShellCommand
12
+ * @property {string[]} words Words of one simple command, without redirections.
13
+ * @property {string[]} targets File targets of its redirections (`>`, `>>`, `<`, `&>`, ...).
14
+ */
15
+
16
+ const CONTROL_OPERATORS = ['&&', '||', ';;', '|&', ';', '|', '&', '(', ')'];
17
+ const REDIRECTIONS = ['&>>', '&>', '>>', '>|', '<>', '<<<', '<<', '>', '<'];
18
+ const HEREDOC_OPERATORS = new Set(['<<', '<<<']);
19
+ const MAX_COMMAND_LENGTH = 64 * 1024;
20
+
21
+ /** @param {string} text @param {number} index @param {string[]} candidates */
22
+ function operatorAt(text, index, candidates) {
23
+ return candidates.find((candidate) => text.startsWith(candidate, index));
24
+ }
25
+
26
+ /**
27
+ * Read a `$(...)` or backtick substitution verbatim, so its text stays in the word.
28
+ * @param {string} text @param {number} start index of `$(` or the backtick
29
+ * @returns {number} index after the substitution, or -1 when it never closes
30
+ */
31
+ function substitutionEnd(text, start) {
32
+ if (text[start] === '`') {
33
+ const close = text.indexOf('`', start + 1);
34
+ return close === -1 ? -1 : close + 1;
35
+ }
36
+ let depth = 0;
37
+ for (let index = start; index < text.length; index += 1) {
38
+ if (text[index] === '(') depth += 1;
39
+ else if (text[index] === ')') {
40
+ depth -= 1;
41
+ if (depth === 0) return index + 1;
42
+ }
43
+ }
44
+ return -1;
45
+ }
46
+
47
+ /**
48
+ * Split a shell command line into simple commands.
49
+ * @param {string} text
50
+ * @returns {{ ok: boolean, commands: ShellCommand[] }}
51
+ */
52
+ export function splitShell(text) {
53
+ if (typeof text !== 'string' || text.length > MAX_COMMAND_LENGTH)
54
+ return { ok: false, commands: [] };
55
+ /** @type {ShellCommand[]} */
56
+ const commands = [];
57
+ /** @type {ShellCommand} */
58
+ let current = { words: [], targets: [] };
59
+ let word = '';
60
+ let inWord = false;
61
+ /** @type {string | null} */
62
+ let pendingRedirection = null;
63
+
64
+ const endWord = () => {
65
+ if (!inWord) return;
66
+ if (pendingRedirection !== null) {
67
+ if (!HEREDOC_OPERATORS.has(pendingRedirection)) current.targets.push(word);
68
+ pendingRedirection = null;
69
+ } else current.words.push(word);
70
+ word = '';
71
+ inWord = false;
72
+ };
73
+ const endCommand = () => {
74
+ endWord();
75
+ if (current.words.length > 0 || current.targets.length > 0) commands.push(current);
76
+ current = { words: [], targets: [] };
77
+ };
78
+
79
+ let index = 0;
80
+ while (index < text.length) {
81
+ const char = text[index];
82
+ if (char === ' ' || char === '\t') {
83
+ endWord();
84
+ index += 1;
85
+ } else if (char === '\n') {
86
+ endCommand();
87
+ index += 1;
88
+ } else if (char === '#' && !inWord) {
89
+ const newline = text.indexOf('\n', index);
90
+ index = newline === -1 ? text.length : newline;
91
+ } else if (char === "'") {
92
+ const close = text.indexOf("'", index + 1);
93
+ if (close === -1) return { ok: false, commands: [] };
94
+ word += text.slice(index + 1, close);
95
+ inWord = true;
96
+ index = close + 1;
97
+ } else if (char === '"') {
98
+ let cursor = index + 1;
99
+ let closed = false;
100
+ while (cursor < text.length) {
101
+ const inner = text[cursor];
102
+ if (
103
+ inner === '\\' &&
104
+ cursor + 1 < text.length &&
105
+ '"\\$`\n'.includes(text[cursor + 1] ?? '')
106
+ ) {
107
+ if (text[cursor + 1] !== '\n') word += text[cursor + 1];
108
+ cursor += 2;
109
+ } else if (inner === '"') {
110
+ closed = true;
111
+ cursor += 1;
112
+ break;
113
+ } else if (inner === '$' && text[cursor + 1] === '(') {
114
+ const end = substitutionEnd(text, cursor + 1);
115
+ if (end === -1) return { ok: false, commands: [] };
116
+ word += text.slice(cursor, end);
117
+ cursor = end;
118
+ } else {
119
+ word += inner;
120
+ cursor += 1;
121
+ }
122
+ }
123
+ if (!closed) return { ok: false, commands: [] };
124
+ inWord = true;
125
+ index = cursor;
126
+ } else if (char === '\\') {
127
+ if (text[index + 1] === '\n') index += 2;
128
+ else {
129
+ word += text[index + 1] ?? '';
130
+ inWord = true;
131
+ index += 2;
132
+ }
133
+ } else if ((char === '$' && text[index + 1] === '(') || char === '`') {
134
+ const end = substitutionEnd(text, char === '`' ? index : index + 1);
135
+ if (end === -1) return { ok: false, commands: [] };
136
+ word += text.slice(index, end);
137
+ inWord = true;
138
+ index = end;
139
+ } else {
140
+ const redirection = operatorAt(text, index, REDIRECTIONS);
141
+ const descriptorWord = inWord && /^\d+$/u.test(word);
142
+ if (redirection !== undefined && (!inWord || descriptorWord)) {
143
+ if (descriptorWord) {
144
+ word = '';
145
+ inWord = false;
146
+ } else endWord();
147
+ index += redirection.length;
148
+ // `2>&1` and `>&2` duplicate a descriptor; they name no file.
149
+ if (text[index] === '&' && /\d|-/u.test(text[index + 1] ?? '')) {
150
+ index += 2;
151
+ continue;
152
+ }
153
+ pendingRedirection = redirection;
154
+ continue;
155
+ }
156
+ const operator = operatorAt(text, index, CONTROL_OPERATORS);
157
+ if (operator !== undefined) {
158
+ endCommand();
159
+ index += operator.length;
160
+ continue;
161
+ }
162
+ word += char;
163
+ inWord = true;
164
+ index += 1;
165
+ }
166
+ }
167
+ endCommand();
168
+ return { ok: true, commands };
169
+ }
170
+
171
+ /** Basename of a program word (`/usr/bin/git` -> `git`). @param {string} word */
172
+ export function programName(word) {
173
+ const slash = word.lastIndexOf('/');
174
+ return slash === -1 ? word : word.slice(slash + 1);
175
+ }
176
+
177
+ const WRAPPERS = new Set([
178
+ 'sudo',
179
+ 'doas',
180
+ 'env',
181
+ 'command',
182
+ 'nice',
183
+ 'nohup',
184
+ 'time',
185
+ 'exec',
186
+ 'npx',
187
+ 'bunx',
188
+ ]);
189
+
190
+ /**
191
+ * The words of a command with leading `VAR=value` assignments and wrappers
192
+ * such as `sudo` or `env` removed, so `sudo rm -rf /` is seen as `rm -rf /`.
193
+ * @param {string[]} words
194
+ */
195
+ export function effectiveWords(words) {
196
+ let index = 0;
197
+ while (index < words.length) {
198
+ const word = words[index] ?? '';
199
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(word)) index += 1;
200
+ else if (WRAPPERS.has(programName(word))) {
201
+ index += 1;
202
+ while ((words[index] ?? '').startsWith('-')) index += 1;
203
+ } else break;
204
+ }
205
+ return words.slice(index);
206
+ }
@@ -0,0 +1,149 @@
1
+ // @ts-check
2
+ /**
3
+ * The session plugin `aisac-guardrails` (spec aisac-engineering-extensions
4
+ * FR5): written into the launch's private folder with only the enabled
5
+ * hooks, and deleted with that folder on exit. Every command is the absolute
6
+ * Node executable plus the dispatcher inside the installed package; nothing
7
+ * comes from the server (ADR-0048).
8
+ */
9
+ import { access, mkdir, writeFile } from 'node:fs/promises';
10
+ import { isAbsolute, join } from 'node:path';
11
+ import { hookById } from './extensions-catalog.mjs';
12
+ import { enabledHookIds, preferencesPath, readPreferences } from './extensions-preferences.mjs';
13
+ import { readStoredLocale, resolvePackLocale } from './engineering-pack.mjs';
14
+
15
+ export const GUARDRAILS_PLUGIN_NAME = 'aisac-guardrails';
16
+ const PLUGIN_VERSION = '1.0.0';
17
+ const PLUGIN_DIRECTORY = 'guardrails';
18
+ const STATE_DIRECTORY = 'guardrails-state';
19
+ const DISPATCHER = join('guardrails', 'run.mjs');
20
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
21
+ /** @type {Readonly<Record<string, number>>} */
22
+ const TIMEOUT_SECONDS = Object.freeze({
23
+ PreToolUse: 5,
24
+ PostToolUse: 5,
25
+ UserPromptSubmit: 5,
26
+ Stop: 5,
27
+ SessionStart: 10,
28
+ PreCompact: 10,
29
+ });
30
+
31
+ /** POSIX single-quote quoting for the host's shell. @param {string} value */
32
+ export function shellQuote(value) {
33
+ return `'${value.replaceAll("'", "'\\''")}'`;
34
+ }
35
+
36
+ /** @param {string} path */
37
+ function safeAbsolute(path) {
38
+ return isAbsolute(path) && !CONTROL_CHARACTERS.test(path);
39
+ }
40
+
41
+ /**
42
+ * The plugin's hooks.json for the enabled ids: one entry per event, whose
43
+ * matcher is the union of the enabled hooks' matchers for that event.
44
+ * @param {string[]} enabled
45
+ * @param {{ node: string, dispatcher: string, stateDir: string, prefsPath: string, locale: 'pt-BR' | 'en' }} paths
46
+ */
47
+ export function guardrailsHooks(enabled, paths) {
48
+ /** @type {Map<string, { ids: string[], matchers: Set<string>, unmatched: boolean }>} */
49
+ const events = new Map();
50
+ for (const id of enabled) {
51
+ for (const binding of hookById(id)?.bindings ?? []) {
52
+ const current = events.get(binding.event) ?? {
53
+ ids: [],
54
+ matchers: new Set(),
55
+ unmatched: false,
56
+ };
57
+ if (!current.ids.includes(id)) current.ids.push(id);
58
+ if (binding.matcher === undefined) current.unmatched = true;
59
+ else for (const name of binding.matcher.split('|')) current.matchers.add(name);
60
+ events.set(binding.event, current);
61
+ }
62
+ }
63
+ /** @type {Record<string, unknown[]>} */
64
+ const hooks = {};
65
+ for (const [event, group] of events) {
66
+ const command = [
67
+ shellQuote(paths.node),
68
+ shellQuote(paths.dispatcher),
69
+ '--event',
70
+ event,
71
+ '--hooks',
72
+ group.ids.join(','),
73
+ '--state',
74
+ shellQuote(paths.stateDir),
75
+ '--prefs',
76
+ shellQuote(paths.prefsPath),
77
+ '--locale',
78
+ paths.locale,
79
+ ].join(' ');
80
+ hooks[event] = [
81
+ {
82
+ ...(group.unmatched || group.matchers.size === 0
83
+ ? {}
84
+ : { matcher: [...group.matchers].join('|') }),
85
+ hooks: [{ type: 'command', command, timeout: TIMEOUT_SECONDS[event] ?? 5 }],
86
+ },
87
+ ];
88
+ }
89
+ return {
90
+ description: 'AISAC Engineering guardrails for this session (aisac hooks to change them).',
91
+ hooks,
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Write the plugin for a licensed launch. Null when no hook is enabled or the
97
+ * package lacks the dispatcher; the launch then goes on without it.
98
+ * @param {{ directory: string, root: string, packageRoot: string }} input
99
+ * @returns {Promise<{ pluginRoot: string, count: number, line: string } | null>}
100
+ */
101
+ export async function prepareGuardrails(input) {
102
+ const enabled = enabledHookIds(await readPreferences(input.root));
103
+ if (enabled.length === 0) return null;
104
+ const dispatcher = join(input.packageRoot, DISPATCHER);
105
+ const prefsPath = preferencesPath(input.root);
106
+ const pluginRoot = join(input.directory, PLUGIN_DIRECTORY);
107
+ const stateDir = join(input.directory, STATE_DIRECTORY);
108
+ if (![process.execPath, dispatcher, prefsPath, pluginRoot, stateDir].every(safeAbsolute))
109
+ return null;
110
+ if (
111
+ !(await access(dispatcher).then(
112
+ () => true,
113
+ () => false,
114
+ ))
115
+ )
116
+ return null;
117
+ const locale = resolvePackLocale(await readStoredLocale(input.root));
118
+ await mkdir(join(pluginRoot, '.claude-plugin'), { recursive: true, mode: 0o700 });
119
+ await mkdir(join(pluginRoot, 'hooks'), { mode: 0o700 });
120
+ await mkdir(stateDir, { mode: 0o700 });
121
+ const manifest = {
122
+ name: GUARDRAILS_PLUGIN_NAME,
123
+ version: PLUGIN_VERSION,
124
+ description: 'AISAC Engineering guardrail hooks, loaded for this session only.',
125
+ author: { name: 'AISAC' },
126
+ hooks: './hooks/hooks.json',
127
+ };
128
+ const hooks = guardrailsHooks(enabled, {
129
+ node: process.execPath,
130
+ dispatcher,
131
+ stateDir,
132
+ prefsPath,
133
+ locale,
134
+ });
135
+ await writeFile(
136
+ join(pluginRoot, '.claude-plugin', 'plugin.json'),
137
+ `${JSON.stringify(manifest, null, 2)}\n`,
138
+ { mode: 0o600, flag: 'wx' },
139
+ );
140
+ await writeFile(join(pluginRoot, 'hooks', 'hooks.json'), `${JSON.stringify(hooks, null, 2)}\n`, {
141
+ mode: 0o600,
142
+ flag: 'wx',
143
+ });
144
+ return {
145
+ pluginRoot,
146
+ count: enabled.length,
147
+ line: `AISAC Engineering: ${enabled.length} guardrail${enabled.length === 1 ? '' : 's'} on (aisac hooks to change them).`,
148
+ };
149
+ }
package/dist/launch.mjs CHANGED
@@ -13,6 +13,25 @@ import {
13
13
  telemetryConfigBinding,
14
14
  } from './state.mjs';
15
15
  import { codexPolicyJson, makePolicy } from './policy.mjs';
16
+ import {
17
+ prepareEngineeringPack,
18
+ sweepStaleLaunches,
19
+ writeLaunchMarker,
20
+ } from './engineering-pack.mjs';
21
+ import { prepareGuardrails } from './guardrails-plugin.mjs';
22
+ import {
23
+ CODEX_MCP_ENV,
24
+ claudeDenyRules,
25
+ claudeMcpEntries,
26
+ mcpLaunchLines,
27
+ sessionServers,
28
+ } from './mcp-servers.mjs';
29
+ import { enabledServerIds, readPreferences } from './extensions-preferences.mjs';
30
+ import {
31
+ CODEX_ENGINEERING_ENV,
32
+ CODEX_ENGINEERING_SKILLS_ROOT_ENV,
33
+ supportsCodexEngineering,
34
+ } from './codex-engineering.mjs';
16
35
  import {
17
36
  CODEX_LAUNCH_ENVELOPE,
18
37
  CODEX_MONITOR_CWD,
@@ -127,6 +146,9 @@ function childEnvironment(root) {
127
146
  delete environment.CODEX_CONTEXT_COMPACT_AT;
128
147
  delete environment[CODEX_LAUNCH_ENVELOPE];
129
148
  delete environment[CODEX_MONITOR_CWD];
149
+ delete environment[CODEX_ENGINEERING_ENV];
150
+ delete environment[CODEX_ENGINEERING_SKILLS_ROOT_ENV];
151
+ delete environment[CODEX_MCP_ENV];
130
152
  environment.AIBRAIN_STATE_DIR = resolve(root);
131
153
  return environment;
132
154
  }
@@ -361,14 +383,26 @@ async function assertClaudeCheckpointHelper(packageRoot) {
361
383
  return helperPath;
362
384
  }
363
385
 
364
- /** @param {string} root @param {string} prefix */
386
+ /**
387
+ * A fresh private directory for one launch. Directories left by launches whose
388
+ * processes are gone are swept first; this one records its launcher.
389
+ * @param {string} root @param {string} prefix
390
+ */
365
391
  async function launchDirectory(root, prefix) {
392
+ await sweepStaleLaunches(root);
366
393
  const parent = await privateDirectory(join(root, 'runtime'));
367
394
  const directory = await mkdtemp(join(parent, `${prefix}-`));
368
395
  await chmod(directory, 0o700);
396
+ await writeLaunchMarker(directory, { launcherPid: process.pid, childPid: null });
369
397
  return directory;
370
398
  }
371
399
 
400
+ /** @param {string} directory @param {number | undefined} childPid */
401
+ async function recordChild(directory, childPid) {
402
+ if (childPid === undefined) return;
403
+ await writeLaunchMarker(directory, { launcherPid: process.pid, childPid }).catch(() => undefined);
404
+ }
405
+
372
406
  /** @param {import('node:child_process').ChildProcess} child @param {string} directory */
373
407
  function waitForChild(child, directory) {
374
408
  return new Promise((resolvePromise) => {
@@ -401,8 +435,34 @@ function waitForChild(child, directory) {
401
435
  });
402
436
  }
403
437
 
404
- /** @param {LaunchConfig} config @param {string} root @param {string[]} args */
405
- export async function launchClaude(config, root, args) {
438
+ /**
439
+ * The catalog servers that join this session: the user's enabled choices from
440
+ * the preferences file. Called only after the license was confirmed.
441
+ * @param {string} root
442
+ * @param {'claude' | 'codex'} client
443
+ * @param {NodeJS.ProcessEnv} environment
444
+ */
445
+ export async function readSessionServers(root, client, environment) {
446
+ return sessionServers(enabledServerIds(await readPreferences(root)), client, environment);
447
+ }
448
+
449
+ /**
450
+ * @typedef {object} LaunchDependencies
451
+ * @property {typeof prepareEngineeringPack} [preparePack] AISAC Engineering pack loader (E4b)
452
+ * @property {typeof prepareGuardrails} [prepareGuardrails] Guardrail hooks plugin writer (E6a)
453
+ * @property {typeof readSessionServers} [readSessionServers] MCP catalog servers to load (E6c)
454
+ */
455
+
456
+ /**
457
+ * @param {LaunchConfig} config
458
+ * @param {string} root
459
+ * @param {string[]} args
460
+ * @param {LaunchDependencies} [dependencies]
461
+ */
462
+ export async function launchClaude(config, root, args, dependencies = {}) {
463
+ const preparePack = dependencies.preparePack ?? prepareEngineeringPack;
464
+ const writeGuardrails = dependencies.prepareGuardrails ?? prepareGuardrails;
465
+ const readServers = dependencies.readSessionServers ?? readSessionServers;
406
466
  const validated = assertConfig(config);
407
467
  const launchArgs = await parseClaudeLaunchArgs(args, process.cwd());
408
468
  assertClaudeArgs(launchArgs.args);
@@ -507,6 +567,14 @@ export async function launchClaude(config, root, args) {
507
567
  for (const rule of [...userAllow, ...requiredAllow]) {
508
568
  if (!mergedAllow.includes(rule)) mergedAllow.push(rule);
509
569
  }
570
+ // Catalog tools that spend money stay denied whatever the user allows or the
571
+ // permission mode is (spec aisac-engineering-extensions FR7.2).
572
+ const userDeny = Array.isArray(userPermissions.deny) ? userPermissions.deny : [];
573
+ /** @type {unknown[]} */
574
+ const mergedDeny = [];
575
+ for (const rule of [...userDeny, ...claudeDenyRules()]) {
576
+ if (!mergedDeny.includes(rule)) mergedDeny.push(rule);
577
+ }
510
578
  const settings = {
511
579
  ...(launchArgs.settings?.sandbox === undefined ? {} : { sandbox: launchArgs.settings.sandbox }),
512
580
  pluginConfigs: {
@@ -516,10 +584,43 @@ export async function launchClaude(config, root, args) {
516
584
  permissions: {
517
585
  ...userPermissions,
518
586
  allow: mergedAllow,
587
+ deny: mergedDeny,
519
588
  },
520
589
  };
590
+ try {
591
+ await privateJson(settingsPath, settings);
592
+ } catch (error) {
593
+ await rm(directory, { recursive: true, force: true });
594
+ throw error;
595
+ }
596
+ // The pack never blocks the launch: every failure starts Claude without it.
597
+ const engineering = await preparePack({
598
+ endpoint: validated.endpoint,
599
+ token: validated.token,
600
+ root,
601
+ directory,
602
+ packageRoot: validated.packageRoot,
603
+ }).catch(() => ({ pluginRoot: null, line: null }));
604
+ if (engineering.line !== null) process.stderr.write(`${engineering.line}\n`);
605
+ // Guardrails need the license this launch confirmed (the pack loaded), and
606
+ // like the pack they never block the launch (spec aisac-engineering-extensions FR5).
607
+ const guardrails =
608
+ engineering.pluginRoot === null
609
+ ? null
610
+ : await writeGuardrails({ directory, root, packageRoot: validated.packageRoot }).catch(
611
+ () => null,
612
+ );
613
+ if (guardrails !== null) process.stderr.write(`${guardrails.line}\n`);
614
+ // Catalog servers need the same confirmed license, and never block the launch.
615
+ const servers =
616
+ engineering.pluginRoot === null
617
+ ? null
618
+ : await readServers(root, 'claude', process.env).catch(() => null);
619
+ for (const line of servers === null ? [] : mcpLaunchLines(servers, 'claude'))
620
+ process.stderr.write(`${line}\n`);
521
621
  const mcp = {
522
622
  mcpServers: {
623
+ ...(servers === null ? {} : claudeMcpEntries(servers.ready)),
523
624
  [MCP_ALIAS]: {
524
625
  type: 'http',
525
626
  url: validated.endpoint,
@@ -528,7 +629,6 @@ export async function launchClaude(config, root, args) {
528
629
  },
529
630
  };
530
631
  try {
531
- await privateJson(settingsPath, settings);
532
632
  await privateJson(mcpPath, mcp);
533
633
  } catch (error) {
534
634
  await rm(directory, { recursive: true, force: true });
@@ -550,6 +650,8 @@ export async function launchClaude(config, root, args) {
550
650
  requiredAllow.join(','),
551
651
  '--plugin-dir',
552
652
  pluginRoot,
653
+ ...(engineering.pluginRoot === null ? [] : ['--plugin-dir', engineering.pluginRoot]),
654
+ ...(guardrails === null ? [] : ['--plugin-dir', guardrails.pluginRoot]),
553
655
  ...launchArgs.args,
554
656
  ],
555
657
  { cwd: process.cwd(), env: environment, stdio: 'inherit' },
@@ -558,15 +660,30 @@ export async function launchClaude(config, root, args) {
558
660
  await rm(directory, { recursive: true, force: true }).catch(() => undefined);
559
661
  throw error;
560
662
  }
561
- return waitForChild(child, directory);
663
+ // Listen for exit before any await, so a child that exits at once is not missed.
664
+ const finished = waitForChild(child, directory);
665
+ await recordChild(directory, child.pid);
666
+ return finished;
562
667
  }
563
668
 
564
- /** @param {LaunchConfig} config @param {string} root @param {string[]} args */
565
- export async function launchCodex(config, root, args) {
669
+ /**
670
+ * @param {LaunchConfig} config
671
+ * @param {string} root
672
+ * @param {string[]} args
673
+ * @param {LaunchDependencies} [dependencies]
674
+ */
675
+ export async function launchCodex(config, root, args, dependencies = {}) {
676
+ const preparePack = dependencies.preparePack ?? prepareEngineeringPack;
677
+ const readServers = dependencies.readSessionServers ?? readSessionServers;
566
678
  const validated = assertConfig(config);
567
679
  assertCodexArgs(args);
568
680
  const captureLockPlatform = captureLockPlatformCheck();
569
- if (!captureLockPlatform.ok) throw new Error(captureLockPlatform.code);
681
+ if (!captureLockPlatform.ok)
682
+ throw new Error(
683
+ captureLockPlatform.code === 'CODEX_MACOS_UNSUPPORTED'
684
+ ? `${captureLockPlatform.code}:${captureLockPlatform.message}`
685
+ : captureLockPlatform.code,
686
+ );
570
687
  const executable = resolveNative('codex');
571
688
  const node = resolveNative('node');
572
689
  if (!executable || !node) throw new Error('codex_or_node_not_found');
@@ -613,6 +730,26 @@ export async function launchCodex(config, root, args) {
613
730
  await rm(directory, { recursive: true, force: true });
614
731
  throw error;
615
732
  }
733
+ // The pack never blocks the launch: every failure starts Codex without it.
734
+ const engineering = await preparePack({
735
+ endpoint: validated.endpoint,
736
+ token: validated.token,
737
+ root,
738
+ directory,
739
+ packageRoot: validated.packageRoot,
740
+ client: 'codex',
741
+ hostSupported: supportsCodexEngineering(compatibility.version),
742
+ }).catch(() => ({ pluginRoot: null, codex: null, line: null }));
743
+ if (engineering.line !== null) process.stderr.write(`${engineering.line}\n`);
744
+ if (engineering.codex != null) {
745
+ environment[CODEX_ENGINEERING_ENV] = JSON.stringify(engineering.codex);
746
+ // Catalog servers need the license the pack confirmed (spec extensions FR6).
747
+ const servers = await readServers(root, 'codex', environment).catch(() => null);
748
+ for (const line of servers === null ? [] : mcpLaunchLines(servers, 'codex'))
749
+ process.stderr.write(`${line}\n`);
750
+ if (servers !== null && servers.ready.length > 0)
751
+ environment[CODEX_MCP_ENV] = JSON.stringify(servers.ready.map((entry) => entry.id));
752
+ }
616
753
  environment.AI_BRAIN_MCP_SERVER = MCP_ALIAS;
617
754
  environment.CODEX_BIN = executable;
618
755
  environment.CODEX_MONITOR_COMMAND = monitor;
@@ -640,7 +777,10 @@ export async function launchCodex(config, root, args) {
640
777
  env: environment,
641
778
  stdio: 'inherit',
642
779
  });
643
- return waitForChild(child, directory);
780
+ // Listen for exit before any await, so a child that exits at once is not missed.
781
+ const finished = waitForChild(child, directory);
782
+ await recordChild(directory, child.pid);
783
+ return finished;
644
784
  }
645
785
 
646
786
  export const launchInternals = { MCP_ALIAS, PLUGIN_NAME, PLUGIN_INLINE_NAME };