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

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