@aisac/cli 0.0.0-stage → 0.4.0-beta.2

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.
Files changed (35) hide show
  1. package/README.md +166 -2
  2. package/dist/assets/claude/.claude-plugin/plugin.json +147 -0
  3. package/dist/assets/claude/hooks/context-compaction.ts +6930 -0
  4. package/dist/assets/claude/hooks/hooks.json +3 -0
  5. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +18 -0
  6. package/dist/assets/claude/hooks/native-host-contract.test.ts +51 -0
  7. package/dist/assets/claude/hooks/provider-window.js +263 -0
  8. package/dist/assets/claude/hooks/state-fitting.d.mts +47 -0
  9. package/dist/assets/claude/hooks/state-fitting.mjs +324 -0
  10. package/dist/assets/codex-context-compaction.mjs +4689 -0
  11. package/dist/assets/context-selection-fitting.mjs +194 -0
  12. package/dist/assets/context-state-fitting.mjs +324 -0
  13. package/dist/assets/context-telemetry-reporter.mjs +305 -0
  14. package/dist/assets/jev-paid-pilot-terminal.mjs +1066 -0
  15. package/dist/claude-checkpoint.mjs +1338 -0
  16. package/dist/claude-compatibility.mjs +506 -0
  17. package/dist/claude-observation.mjs +1338 -0
  18. package/dist/cli.mjs +771 -0
  19. package/dist/codex-compatibility.mjs +481 -0
  20. package/dist/codex-diagnostics.mjs +447 -0
  21. package/dist/codex-permissions.mjs +590 -0
  22. package/dist/codex-protocol-fingerprint.json +131 -0
  23. package/dist/context-telemetry.mjs +257 -0
  24. package/dist/engineering-pack-public-key.json +10 -0
  25. package/dist/engineering-pack.mjs +722 -0
  26. package/dist/engineering.mjs +194 -0
  27. package/dist/launch.mjs +690 -0
  28. package/dist/mcp.mjs +962 -0
  29. package/dist/monitor.mjs +133 -0
  30. package/dist/package.json +5 -0
  31. package/dist/platform.mjs +126 -0
  32. package/dist/policy.mjs +218 -0
  33. package/dist/state.mjs +408 -0
  34. package/dist/telemetry-report.mjs +133 -0
  35. package/package.json +24 -4
@@ -0,0 +1,690 @@
1
+ // @ts-check
2
+
3
+ import { access, chmod, lstat, mkdir, mkdtemp, open, rm, writeFile } from 'node:fs/promises';
4
+ import { spawn } from 'node:child_process';
5
+ import { constants } from 'node:fs';
6
+ import { isAbsolute, join, resolve, sep } from 'node:path';
7
+ import { captureLockPlatformCheck, nativeVersion, resolveNative } from './platform.mjs';
8
+ import { claudeCompatibilityError, resolveClaudeCompatibility } from './claude-compatibility.mjs';
9
+ import { codexCompatibilityError, resolveCodexCompatibility } from './codex-compatibility.mjs';
10
+ import {
11
+ claudeCheckpointConfigBinding,
12
+ claudeObservationConfigBinding,
13
+ telemetryConfigBinding,
14
+ } from './state.mjs';
15
+ import { codexPolicyJson, makePolicy } from './policy.mjs';
16
+ import {
17
+ prepareEngineeringPack,
18
+ sweepStaleLaunches,
19
+ writeLaunchMarker,
20
+ } from './engineering-pack.mjs';
21
+ import {
22
+ CODEX_LAUNCH_ENVELOPE,
23
+ CODEX_MONITOR_CWD,
24
+ makeCodexLaunchEnvelope,
25
+ parseCodexLaunchArgs,
26
+ readEffectiveWritableRoots,
27
+ } from './codex-permissions.mjs';
28
+
29
+ const MCP_ALIAS = 'aibrain_context';
30
+ const PLUGIN_NAME = 'ai-brain-context-compaction';
31
+ const PLUGIN_INLINE_NAME = `${PLUGIN_NAME}@inline`;
32
+ const CLAUDE_HEADLESS_FLAGS = new Set([
33
+ '--print',
34
+ '-p',
35
+ '--output-format',
36
+ '--input-format',
37
+ '--output-style',
38
+ ]);
39
+ const RESERVED_CLAUDE_FLAGS = new Set(['--mcp-config', '--plugin-dir', '--allowedTools']);
40
+ const MAX_CLAUDE_SETTINGS_BYTES = 64 * 1024;
41
+ const MAX_CLAUDE_SETTINGS_DEPTH = 12;
42
+ const MAX_CLAUDE_SETTINGS_NODES = 512;
43
+ const MAX_CLAUDE_SETTINGS_STRING_LENGTH = 16 * 1024;
44
+ const MAX_CLAUDE_PERMISSION_LIST_ITEMS = 256;
45
+ const MAX_CLAUDE_PERMISSION_STRING_LENGTH = 4096;
46
+ const CLAUDE_SETTINGS_SECTIONS = new Set(['sandbox', 'permissions']);
47
+ const CLAUDE_PERMISSION_LISTS = new Set(['allow', 'ask', 'deny', 'additionalDirectories']);
48
+ const CLAUDE_SETTINGS_FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
49
+
50
+ /**
51
+ * @typedef {object} LaunchConfig
52
+ * @property {string} endpoint
53
+ * @property {string} token
54
+ * @property {string} packageRoot
55
+ * @property {string|null} claudeVersion
56
+ * @property {string|null} codexVersion
57
+ * @property {number} schemaVersion
58
+ * @property {import('./policy.mjs').ContextPolicy} [context]
59
+ * @property {{ enabled: boolean, disclosedAt?: string | null }} [telemetry]
60
+ * @property {{ shadowEnabled: boolean, diagnosticsEnabled: boolean, disclosedAt?: string | null }} [claudeObservation]
61
+ */
62
+
63
+ /** @param {LaunchConfig} config */
64
+ function assertConfig(config) {
65
+ if (config === null || typeof config !== 'object') throw new Error('setup_required');
66
+ if (typeof config.endpoint !== 'string' || typeof config.token !== 'string')
67
+ throw new Error('setup_config_invalid');
68
+ if (config.token.length === 0) throw new Error('setup_token_missing');
69
+ const endpoint = new URL(config.endpoint);
70
+ if (
71
+ endpoint.protocol !== 'https:' &&
72
+ !(
73
+ endpoint.protocol === 'http:' &&
74
+ ['127.0.0.1', 'localhost', '::1', '[::1]'].includes(endpoint.hostname)
75
+ )
76
+ )
77
+ throw new Error('endpoint_must_use_https');
78
+ if (endpoint.username || endpoint.password || endpoint.hash)
79
+ throw new Error('endpoint_credentials_or_fragment_rejected');
80
+ if (endpoint.search) throw new Error('endpoint_query_rejected');
81
+ if (typeof config.packageRoot !== 'string' || !isAbsolute(config.packageRoot))
82
+ throw new Error('package_root_invalid');
83
+ return { ...config, endpoint: endpoint.toString() };
84
+ }
85
+
86
+ /** @param {string} directory */
87
+ async function privateDirectory(directory) {
88
+ const target = resolve(directory);
89
+ const parts = target.split(sep);
90
+ let current = parts[0] === '' ? sep : parts[0];
91
+ for (const part of parts.slice(parts[0] === '' ? 1 : 0)) {
92
+ if (part.length === 0) continue;
93
+ current = current === sep ? `${sep}${part}` : join(current, part);
94
+ try {
95
+ const entry = await lstat(current);
96
+ if (entry.isSymbolicLink()) throw new Error('private_state_symlink_rejected');
97
+ if (!entry.isDirectory()) throw new Error('private_state_not_directory');
98
+ } catch (error) {
99
+ const errorCode =
100
+ error !== null && typeof error === 'object' && 'code' in error ? error.code : undefined;
101
+ if (errorCode !== 'ENOENT') throw error;
102
+ break;
103
+ }
104
+ }
105
+ await mkdir(target, { recursive: true, mode: 0o700 });
106
+ const entry = await lstat(target);
107
+ if (entry.isSymbolicLink() || !entry.isDirectory()) throw new Error('private_state_invalid');
108
+ if (
109
+ entry.uid !== undefined &&
110
+ typeof process.getuid === 'function' &&
111
+ entry.uid !== process.getuid()
112
+ )
113
+ throw new Error('private_state_owner_mismatch');
114
+ await chmod(target, 0o700);
115
+ return target;
116
+ }
117
+
118
+ /** @param {string} path @param {unknown} value */
119
+ async function privateJson(path, value) {
120
+ await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
121
+ await chmod(path, 0o600);
122
+ }
123
+
124
+ /** @param {string} root */
125
+ function childEnvironment(root) {
126
+ /** @type {NodeJS.ProcessEnv} */
127
+ const environment = { ...process.env, AIBRAIN_MCP_SERVER: MCP_ALIAS };
128
+ delete environment.JEV_API_KEY;
129
+ delete environment.TYPESAFE_API_KEY;
130
+ delete environment.AIBRAIN_TOKEN_FILE;
131
+ delete environment.CODEX_CONTEXT_POLICY_JSON;
132
+ delete environment.CODEX_CONTEXT_COMPACT_AT;
133
+ delete environment[CODEX_LAUNCH_ENVELOPE];
134
+ delete environment[CODEX_MONITOR_CWD];
135
+ environment.AIBRAIN_STATE_DIR = resolve(root);
136
+ return environment;
137
+ }
138
+
139
+ /** @param {string[]} args */
140
+ function assertClaudeArgs(args) {
141
+ for (const argument of args) {
142
+ if (argument === '--') break;
143
+ const option = argument.split('=', 1)[0];
144
+ if (CLAUDE_HEADLESS_FLAGS.has(option) || /^-p(?:=|[^-])/u.test(argument))
145
+ throw new Error('claude_headless_mode_unsupported');
146
+ if (RESERVED_CLAUDE_FLAGS.has(option)) throw new Error('claude_launch_flag_reserved');
147
+ }
148
+ }
149
+
150
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
151
+ function plainObject(value) {
152
+ return (
153
+ value !== null &&
154
+ typeof value === 'object' &&
155
+ !Array.isArray(value) &&
156
+ Object.getPrototypeOf(value) === Object.prototype
157
+ );
158
+ }
159
+
160
+ /** @param {unknown} value */
161
+ function validateClaudeSettingsValue(value, depth = 0, state = { nodes: 0 }) {
162
+ state.nodes += 1;
163
+ if (state.nodes > MAX_CLAUDE_SETTINGS_NODES || depth > MAX_CLAUDE_SETTINGS_DEPTH)
164
+ throw new Error('claude_settings_structure_invalid');
165
+ if (typeof value === 'string') {
166
+ if (value.length > MAX_CLAUDE_SETTINGS_STRING_LENGTH)
167
+ throw new Error('claude_settings_string_too_long');
168
+ return;
169
+ }
170
+ if (typeof value === 'number') {
171
+ if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER)
172
+ throw new Error('claude_settings_value_invalid');
173
+ return;
174
+ }
175
+ if (value === null || typeof value === 'boolean') return;
176
+ if (Array.isArray(value)) {
177
+ if (value.length > MAX_CLAUDE_SETTINGS_NODES)
178
+ throw new Error('claude_settings_structure_invalid');
179
+ for (const item of value) validateClaudeSettingsValue(item, depth + 1, state);
180
+ return;
181
+ }
182
+ if (!plainObject(value)) throw new Error('claude_settings_value_invalid');
183
+ for (const [key, item] of Object.entries(value)) {
184
+ if (CLAUDE_SETTINGS_FORBIDDEN_KEYS.has(key)) throw new Error('claude_settings_prototype_key');
185
+ if (key.length > 256) throw new Error('claude_settings_key_too_long');
186
+ validateClaudeSettingsValue(item, depth + 1, state);
187
+ }
188
+ }
189
+
190
+ /** @param {unknown} value */
191
+ function validateClaudeSettingsFragment(value) {
192
+ if (!plainObject(value)) throw new Error('claude_settings_root_invalid');
193
+ validateClaudeSettingsValue(value);
194
+ for (const key of Object.keys(value)) {
195
+ if (!CLAUDE_SETTINGS_SECTIONS.has(key)) throw new Error('claude_settings_section_unsupported');
196
+ const section = value[key];
197
+ if (!plainObject(section)) throw new Error('claude_settings_section_invalid');
198
+ }
199
+ const permissions = value.permissions;
200
+ if (permissions !== undefined) {
201
+ const permissionObject = /** @type {Record<string, unknown>} */ (permissions);
202
+ for (const key of CLAUDE_PERMISSION_LISTS) {
203
+ const list = permissionObject[key];
204
+ if (list === undefined) continue;
205
+ if (
206
+ !Array.isArray(list) ||
207
+ list.length > MAX_CLAUDE_PERMISSION_LIST_ITEMS ||
208
+ list.some(
209
+ (item) => typeof item !== 'string' || item.length > MAX_CLAUDE_PERMISSION_STRING_LENGTH,
210
+ )
211
+ )
212
+ throw new Error('claude_settings_permission_list_invalid');
213
+ }
214
+ }
215
+ return /** @type {{sandbox?: Record<string, unknown>, permissions?: Record<string, unknown>}} */ (
216
+ value
217
+ );
218
+ }
219
+
220
+ /** @param {string} text */
221
+ function parseClaudeSettingsText(text) {
222
+ const bytes = Buffer.byteLength(text, 'utf8');
223
+ if (bytes > MAX_CLAUDE_SETTINGS_BYTES) throw new Error('claude_settings_too_large');
224
+ let value;
225
+ try {
226
+ value = JSON.parse(text);
227
+ } catch {
228
+ throw new Error('claude_settings_invalid_json');
229
+ }
230
+ return validateClaudeSettingsFragment(value);
231
+ }
232
+
233
+ /** @param {string} path */
234
+ async function readClaudeSettingsFile(path) {
235
+ let handle;
236
+ try {
237
+ const link = await lstat(path);
238
+ if (link.isSymbolicLink() || !link.isFile()) throw new Error('claude_settings_file_invalid');
239
+ handle = await open(
240
+ path,
241
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
242
+ );
243
+ const entry = await handle.stat();
244
+ if (!entry.isFile()) throw new Error('claude_settings_file_invalid');
245
+ if (entry.size > MAX_CLAUDE_SETTINGS_BYTES) throw new Error('claude_settings_too_large');
246
+ const buffer = Buffer.alloc(MAX_CLAUDE_SETTINGS_BYTES + 1);
247
+ let offset = 0;
248
+ while (offset < buffer.length) {
249
+ const result = await handle.read(buffer, offset, buffer.length - offset, null);
250
+ if (result.bytesRead === 0) break;
251
+ offset += result.bytesRead;
252
+ }
253
+ if (offset > MAX_CLAUDE_SETTINGS_BYTES) throw new Error('claude_settings_too_large');
254
+ let text;
255
+ try {
256
+ text = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, offset));
257
+ } catch {
258
+ throw new Error('claude_settings_invalid_utf8');
259
+ }
260
+ return parseClaudeSettingsText(text);
261
+ } catch (error) {
262
+ if (error instanceof Error && error.message.startsWith('claude_settings_')) throw error;
263
+ throw new Error('claude_settings_file_invalid');
264
+ } finally {
265
+ await handle?.close().catch(() => undefined);
266
+ }
267
+ }
268
+
269
+ /** @param {string} value @param {string} cwd */
270
+ async function readClaudeSettings(value, cwd) {
271
+ const first = value.trimStart()[0];
272
+ const explicitPath = isAbsolute(value) || value.startsWith('./') || value.startsWith('../');
273
+ if (Buffer.byteLength(value, 'utf8') > MAX_CLAUDE_SETTINGS_BYTES)
274
+ throw new Error('claude_settings_too_large');
275
+ try {
276
+ return validateClaudeSettingsFragment(JSON.parse(value));
277
+ } catch (error) {
278
+ if (error instanceof Error && error.message.startsWith('claude_settings_')) throw error;
279
+ if (!explicitPath && (first === '{' || first === '[' || first === '"' || first === '-'))
280
+ throw new Error('claude_settings_invalid_json');
281
+ }
282
+ return readClaudeSettingsFile(resolve(cwd, value));
283
+ }
284
+
285
+ /**
286
+ * @param {string[]} args
287
+ * @param {string} cwd
288
+ * @returns {Promise<{args: string[], settings?: {sandbox?: Record<string, unknown>, permissions?: Record<string, unknown>}}>}
289
+ */
290
+ async function parseClaudeLaunchArgs(args, cwd) {
291
+ const forwarded = [];
292
+ let settingsValue;
293
+ let terminated = false;
294
+ for (let index = 0; index < args.length; index += 1) {
295
+ const argument = args[index];
296
+ if (terminated) {
297
+ forwarded.push(argument);
298
+ continue;
299
+ }
300
+ if (argument === '--') {
301
+ terminated = true;
302
+ forwarded.push(argument);
303
+ continue;
304
+ }
305
+ if (argument === '--settings' || argument.startsWith('--settings=')) {
306
+ if (settingsValue !== undefined) throw new Error('claude_settings_duplicate');
307
+ const value =
308
+ argument === '--settings' ? args[++index] : argument.slice('--settings='.length);
309
+ if (value === undefined || value === '' || value.startsWith('-'))
310
+ throw new Error('claude_settings_value_required');
311
+ settingsValue = value;
312
+ continue;
313
+ }
314
+ forwarded.push(argument);
315
+ }
316
+ return {
317
+ args: forwarded,
318
+ ...(settingsValue === undefined
319
+ ? {}
320
+ : { settings: await readClaudeSettings(settingsValue, cwd) }),
321
+ };
322
+ }
323
+
324
+ /** @param {string[]} args */
325
+ function assertCodexArgs(args) {
326
+ for (const argument of args) {
327
+ const option = argument.split('=', 1)[0];
328
+ if (option === '--remote' || option === '--listen' || option === 'app-server')
329
+ throw new Error('codex_launch_flag_reserved');
330
+ }
331
+ }
332
+
333
+ /** @param {string} packageRoot */
334
+ async function assertClaudeAssets(packageRoot) {
335
+ const pluginRoot = join(packageRoot, 'assets', 'claude');
336
+ const required = [
337
+ join(pluginRoot, '.claude-plugin', 'plugin.json'),
338
+ join(pluginRoot, 'hooks', 'hooks.json'),
339
+ join(pluginRoot, 'hooks', 'context-compaction.ts'),
340
+ join(pluginRoot, 'hooks', 'provider-window.js'),
341
+ join(pluginRoot, 'hooks', 'state-fitting.mjs'),
342
+ join(pluginRoot, 'hooks', 'state-fitting.d.mts'),
343
+ ];
344
+ await Promise.all(required.map((path) => access(path, constants.R_OK)));
345
+ return pluginRoot;
346
+ }
347
+
348
+ /** @param {string} packageRoot */
349
+ async function assertTelemetryHelper(packageRoot) {
350
+ const helperPath = join(packageRoot, 'telemetry-report.mjs');
351
+ await access(helperPath, constants.R_OK);
352
+ return helperPath;
353
+ }
354
+
355
+ /** @param {string} packageRoot */
356
+ async function assertClaudeObservationHelper(packageRoot) {
357
+ const helperPath = join(packageRoot, 'claude-observation.mjs');
358
+ await access(helperPath, constants.R_OK);
359
+ return helperPath;
360
+ }
361
+
362
+ /** @param {string} packageRoot */
363
+ async function assertClaudeCheckpointHelper(packageRoot) {
364
+ const helperPath = join(packageRoot, 'claude-checkpoint.mjs');
365
+ await access(helperPath, constants.R_OK);
366
+ return helperPath;
367
+ }
368
+
369
+ /**
370
+ * A fresh private directory for one launch. Directories left by launches whose
371
+ * processes are gone are swept first; this one records its launcher.
372
+ * @param {string} root @param {string} prefix
373
+ */
374
+ async function launchDirectory(root, prefix) {
375
+ await sweepStaleLaunches(root);
376
+ const parent = await privateDirectory(join(root, 'runtime'));
377
+ const directory = await mkdtemp(join(parent, `${prefix}-`));
378
+ await chmod(directory, 0o700);
379
+ await writeLaunchMarker(directory, { launcherPid: process.pid, childPid: null });
380
+ return directory;
381
+ }
382
+
383
+ /** @param {string} directory @param {number | undefined} childPid */
384
+ async function recordChild(directory, childPid) {
385
+ if (childPid === undefined) return;
386
+ await writeLaunchMarker(directory, { launcherPid: process.pid, childPid }).catch(() => undefined);
387
+ }
388
+
389
+ /** @param {import('node:child_process').ChildProcess} child @param {string} directory */
390
+ function waitForChild(child, directory) {
391
+ return new Promise((resolvePromise) => {
392
+ let settled = false;
393
+ /** @param {NodeJS.Signals} signal */
394
+ const forwardSignal = (signal) => {
395
+ if (child.exitCode === null) child.kill(signal);
396
+ };
397
+ const signalHandlers = {
398
+ SIGINT: () => forwardSignal('SIGINT'),
399
+ SIGTERM: () => forwardSignal('SIGTERM'),
400
+ SIGHUP: () => forwardSignal('SIGHUP'),
401
+ };
402
+ process.once('SIGINT', signalHandlers.SIGINT);
403
+ process.once('SIGTERM', signalHandlers.SIGTERM);
404
+ process.once('SIGHUP', signalHandlers.SIGHUP);
405
+ /** @param {number} code */
406
+ const finish = (code) => {
407
+ if (settled) return;
408
+ settled = true;
409
+ process.removeListener('SIGINT', signalHandlers.SIGINT);
410
+ process.removeListener('SIGTERM', signalHandlers.SIGTERM);
411
+ process.removeListener('SIGHUP', signalHandlers.SIGHUP);
412
+ void rm(directory, { recursive: true, force: true })
413
+ .catch(() => undefined)
414
+ .finally(() => resolvePromise(code));
415
+ };
416
+ child.once('error', () => finish(1));
417
+ child.once('close', (code, signal) => finish(signal === null ? (code ?? 1) : 1));
418
+ });
419
+ }
420
+
421
+ /**
422
+ * @typedef {object} LaunchDependencies
423
+ * @property {typeof prepareEngineeringPack} [preparePack] AISAC Engineering pack loader (E4b)
424
+ */
425
+
426
+ /**
427
+ * @param {LaunchConfig} config
428
+ * @param {string} root
429
+ * @param {string[]} args
430
+ * @param {LaunchDependencies} [dependencies]
431
+ */
432
+ export async function launchClaude(config, root, args, dependencies = {}) {
433
+ const preparePack = dependencies.preparePack ?? prepareEngineeringPack;
434
+ const validated = assertConfig(config);
435
+ const launchArgs = await parseClaudeLaunchArgs(args, process.cwd());
436
+ assertClaudeArgs(launchArgs.args);
437
+ const executable = resolveNative('claude');
438
+ if (!executable) throw new Error('claude_not_found');
439
+ const compatibility = await resolveClaudeCompatibility(executable, validated.packageRoot);
440
+ if (compatibility.status === 'rejected') throw new Error(claudeCompatibilityError(compatibility));
441
+ const pinnedExecutable = compatibility.executable ?? executable;
442
+ if (compatibility.status === 'host_checked')
443
+ process.stderr.write(
444
+ `aisac: Claude ${compatibility.version ?? 'unknown'} accepted by the local native host contract; end-to-end recovery remains separately qualified.\n`,
445
+ );
446
+ const currentVersion = compatibility.version ?? nativeVersion(pinnedExecutable);
447
+ const pluginRoot = await assertClaudeAssets(validated.packageRoot);
448
+ const telemetryActive =
449
+ validated.telemetry?.enabled === true && validated.telemetry?.disclosedAt != null;
450
+ const telemetryHelperPath = telemetryActive
451
+ ? await assertTelemetryHelper(validated.packageRoot)
452
+ : undefined;
453
+ const telemetryConfigDigest = telemetryActive ? telemetryConfigBinding(validated) : undefined;
454
+ const observationActive =
455
+ validated.claudeObservation?.shadowEnabled === true ||
456
+ validated.claudeObservation?.diagnosticsEnabled === true;
457
+ const observationHelperPath = observationActive
458
+ ? await assertClaudeObservationHelper(validated.packageRoot)
459
+ : undefined;
460
+ const observationConfigDigest = observationActive
461
+ ? claudeObservationConfigBinding(validated)
462
+ : undefined;
463
+ const checkpointHelperPath = await assertClaudeCheckpointHelper(validated.packageRoot);
464
+ const checkpointConfigDigest = claudeCheckpointConfigBinding(validated);
465
+ const checkpointStateDir = await privateDirectory(join(root, 'claude', 'checkpoints'));
466
+ const directory = await launchDirectory(root, 'claude');
467
+ const settingsPath = join(directory, 'settings.json');
468
+ const mcpPath = join(directory, 'mcp.json');
469
+ const context = validated.context;
470
+ const legacy = validated.schemaVersion !== 2 || context === undefined;
471
+ const v2Context = context ?? makePolicy('conservative');
472
+ /** @type {Record<string, unknown>} */
473
+ const options = {
474
+ brainServer: MCP_ALIAS,
475
+ ...(legacy
476
+ ? { compactAtPercent: 85 }
477
+ : {
478
+ policyVersion: 2,
479
+ compactAtPercent: v2Context.compactAtPercent,
480
+ keepThreshold: v2Context.keepThreshold,
481
+ preserveRecentMessages: v2Context.preserveRecentMessages,
482
+ minReductionRatio: v2Context.minReductionRatio,
483
+ truncateHeadChars: v2Context.truncateHeadChars,
484
+ maxStateTokens: v2Context.maxStateTokens,
485
+ maxRequestTokens: v2Context.maxRequestTokens,
486
+ toolPolicy: v2Context.toolPolicy,
487
+ }),
488
+ enabled: true,
489
+ disclosed: true,
490
+ compactionStrategy: 'native_summary_notes',
491
+ preservationMode: 'upstream_compatible',
492
+ diagnosticMode: false,
493
+ telemetryEnabled: validated.telemetry?.enabled === true,
494
+ telemetryDisclosed:
495
+ validated.telemetry?.enabled === true && validated.telemetry?.disclosedAt != null,
496
+ telemetryClientVersion: currentVersion.match(/\b\d+\.\d+\.\d+\b/u)?.[0] ?? '',
497
+ ...(telemetryActive
498
+ ? {
499
+ telemetryNodePath: process.execPath,
500
+ telemetryHelperPath,
501
+ telemetryStateDir: resolve(root),
502
+ telemetryConfigDigest,
503
+ }
504
+ : {}),
505
+ ...(observationActive
506
+ ? {
507
+ observationNodePath: process.execPath,
508
+ observationHelperPath,
509
+ observationStateDir: resolve(root),
510
+ observationConfigDigest,
511
+ observationShadowEnabled: validated.claudeObservation?.shadowEnabled === true,
512
+ observationDiagnosticsEnabled: validated.claudeObservation?.diagnosticsEnabled === true,
513
+ }
514
+ : {}),
515
+ checkpointNodePath: process.execPath,
516
+ checkpointHelperPath,
517
+ checkpointStateDir,
518
+ checkpointConfigDigest,
519
+ checkpointBinding: checkpointConfigDigest,
520
+ };
521
+ if (!legacy && context.goal !== undefined) options.goal = context.goal;
522
+ const requiredAllow = [
523
+ `mcp__${MCP_ALIAS}__brain_context_status`,
524
+ `mcp__${MCP_ALIAS}__brain_context_compact`,
525
+ `mcp__${MCP_ALIAS}__brain_context_select`,
526
+ `mcp__${MCP_ALIAS}__brain_context_budget`,
527
+ ...(options.telemetryEnabled && options.telemetryDisclosed
528
+ ? [`mcp__${MCP_ALIAS}__brain_context_report`]
529
+ : []),
530
+ ];
531
+ const userPermissions = launchArgs.settings?.permissions ?? {};
532
+ const userAllow = Array.isArray(userPermissions.allow) ? userPermissions.allow : [];
533
+ /** @type {string[]} */
534
+ const mergedAllow = [];
535
+ for (const rule of [...userAllow, ...requiredAllow]) {
536
+ if (!mergedAllow.includes(rule)) mergedAllow.push(rule);
537
+ }
538
+ const settings = {
539
+ ...(launchArgs.settings?.sandbox === undefined ? {} : { sandbox: launchArgs.settings.sandbox }),
540
+ pluginConfigs: {
541
+ [PLUGIN_NAME]: { options },
542
+ [PLUGIN_INLINE_NAME]: { options: { ...options } },
543
+ },
544
+ permissions: {
545
+ ...userPermissions,
546
+ allow: mergedAllow,
547
+ },
548
+ };
549
+ const mcp = {
550
+ mcpServers: {
551
+ [MCP_ALIAS]: {
552
+ type: 'http',
553
+ url: validated.endpoint,
554
+ headers: { Authorization: `Bearer ${validated.token}` },
555
+ },
556
+ },
557
+ };
558
+ try {
559
+ await privateJson(settingsPath, settings);
560
+ await privateJson(mcpPath, mcp);
561
+ } catch (error) {
562
+ await rm(directory, { recursive: true, force: true });
563
+ throw error;
564
+ }
565
+ // The pack never blocks the launch: every failure starts Claude without it.
566
+ const engineering = await preparePack({
567
+ endpoint: validated.endpoint,
568
+ token: validated.token,
569
+ root,
570
+ directory,
571
+ packageRoot: validated.packageRoot,
572
+ }).catch(() => ({ pluginRoot: null, line: null }));
573
+ if (engineering.line !== null) process.stderr.write(`${engineering.line}\n`);
574
+ const environment = childEnvironment(root);
575
+ environment.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = '1';
576
+ /** @type {import('node:child_process').ChildProcess} */
577
+ let child;
578
+ try {
579
+ child = spawn(
580
+ pinnedExecutable,
581
+ [
582
+ '--settings',
583
+ settingsPath,
584
+ '--mcp-config',
585
+ mcpPath,
586
+ '--allowedTools',
587
+ requiredAllow.join(','),
588
+ '--plugin-dir',
589
+ pluginRoot,
590
+ ...(engineering.pluginRoot === null ? [] : ['--plugin-dir', engineering.pluginRoot]),
591
+ ...launchArgs.args,
592
+ ],
593
+ { cwd: process.cwd(), env: environment, stdio: 'inherit' },
594
+ );
595
+ } catch (error) {
596
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
597
+ throw error;
598
+ }
599
+ // Listen for exit before any await, so a child that exits at once is not missed.
600
+ const finished = waitForChild(child, directory);
601
+ await recordChild(directory, child.pid);
602
+ return finished;
603
+ }
604
+
605
+ /** @param {LaunchConfig} config @param {string} root @param {string[]} args */
606
+ export async function launchCodex(config, root, args) {
607
+ const validated = assertConfig(config);
608
+ assertCodexArgs(args);
609
+ const captureLockPlatform = captureLockPlatformCheck();
610
+ if (!captureLockPlatform.ok) throw new Error(captureLockPlatform.code);
611
+ const executable = resolveNative('codex');
612
+ const node = resolveNative('node');
613
+ if (!executable || !node) throw new Error('codex_or_node_not_found');
614
+ const compatibility = await resolveCodexCompatibility(executable);
615
+ if (compatibility.status === 'rejected') throw new Error(codexCompatibilityError(compatibility));
616
+ if (compatibility.version === null) throw new Error('codex_version_unverified');
617
+ if (compatibility.status === 'protocol_match')
618
+ process.stderr.write(
619
+ `aisac: Codex ${compatibility.version} matched the local protocol contract; native behavioral qualification is not established.\n`,
620
+ );
621
+ const launchPlan = await parseCodexLaunchArgs(args, process.cwd());
622
+ const packageRoot = resolve(validated.packageRoot);
623
+ const terminal = join(packageRoot, 'assets', 'jev-paid-pilot-terminal.mjs');
624
+ const monitor = join(packageRoot, 'monitor.mjs');
625
+ const diagnosticModule = join(packageRoot, 'codex-diagnostics.mjs');
626
+ await Promise.all([
627
+ access(terminal, constants.R_OK),
628
+ access(monitor, constants.X_OK),
629
+ access(diagnosticModule, constants.R_OK),
630
+ ]);
631
+ const checkpoints = await privateDirectory(join(root, 'codex', 'checkpoints'));
632
+ const notes = await privateDirectory(join(root, 'codex', 'notes'));
633
+ const directory = await launchDirectory(root, 'codex');
634
+ const environment = childEnvironment(root);
635
+ try {
636
+ if (
637
+ launchPlan.additionalRoots.length > 0 ||
638
+ Object.keys(launchPlan.server).length > 0 ||
639
+ launchPlan.profile !== undefined
640
+ ) {
641
+ const configuredRoots =
642
+ launchPlan.additionalRoots.length > 0
643
+ ? await readEffectiveWritableRoots(
644
+ executable,
645
+ launchPlan.effectiveCwd,
646
+ launchPlan.profile,
647
+ environment,
648
+ )
649
+ : [];
650
+ const envelope = makeCodexLaunchEnvelope(launchPlan, configuredRoots);
651
+ environment[CODEX_LAUNCH_ENVELOPE] = JSON.stringify(envelope);
652
+ }
653
+ } catch (error) {
654
+ await rm(directory, { recursive: true, force: true });
655
+ throw error;
656
+ }
657
+ environment.AI_BRAIN_MCP_SERVER = MCP_ALIAS;
658
+ environment.CODEX_BIN = executable;
659
+ environment.CODEX_MONITOR_COMMAND = monitor;
660
+ environment[CODEX_MONITOR_CWD] = launchPlan.effectiveCwd;
661
+ environment.CODEX_CONTEXT_RECOVERY_ENABLED = '1';
662
+ environment.CODEX_CONTEXT_RECOVERY_DISCLOSED = '1';
663
+ environment.CODEX_CONTEXT_CHECKPOINT_DIR = checkpoints;
664
+ environment.CODEX_CONTEXT_RECOVERY_DIR = notes;
665
+ environment.CODEX_CONTEXT_DIAGNOSTICS_MODULE = diagnosticModule;
666
+ environment.CODEX_CONTEXT_DIAGNOSTICS_DIR = resolve(root);
667
+ environment.CODEX_CONTEXT_DIAGNOSTICS_ENABLED = '1';
668
+ environment.AIBRAIN_MCP_URL = validated.endpoint;
669
+ environment.AIBRAIN_MCP_TOKEN = validated.token;
670
+ environment.CODEX_CLIENT_VERSION = compatibility.version;
671
+ environment.CODEX_CONTEXT_TELEMETRY_ENABLED = validated.telemetry?.enabled === true ? '1' : '0';
672
+ environment.CODEX_CONTEXT_TELEMETRY_DISCLOSED =
673
+ validated.telemetry?.enabled === true && validated.telemetry?.disclosedAt != null ? '1' : '0';
674
+ if (validated.schemaVersion === 2 && validated.context !== undefined) {
675
+ environment.CODEX_CONTEXT_POLICY_JSON = codexPolicyJson(validated.context);
676
+ } else {
677
+ delete environment.CODEX_CONTEXT_POLICY_JSON;
678
+ }
679
+ const child = spawn(node, [terminal, '--', ...launchPlan.nativeArgs], {
680
+ cwd: process.cwd(),
681
+ env: environment,
682
+ stdio: 'inherit',
683
+ });
684
+ // Listen for exit before any await, so a child that exits at once is not missed.
685
+ const finished = waitForChild(child, directory);
686
+ await recordChild(directory, child.pid);
687
+ return finished;
688
+ }
689
+
690
+ export const launchInternals = { MCP_ALIAS, PLUGIN_NAME, PLUGIN_INLINE_NAME };