@shumkov/orchestra 0.6.0 → 0.7.0

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,1073 @@
1
+ 'use strict';
2
+
3
+ const { createHash } = require('node:crypto');
4
+ const path = require('node:path');
5
+
6
+ const {
7
+ CodexAppServerClient,
8
+ buildCodexAppServerEnv,
9
+ protocolSchema,
10
+ } = require('./app-server-client');
11
+
12
+ const MAX_PAGES = 16;
13
+ const MAX_ENTRIES = 1_000;
14
+ const PAGE_LIMIT = 100;
15
+ const MAX_STRING_BYTES = 64 * 1024;
16
+ const MAX_OBJECT_KEYS = 512;
17
+ const MAX_ARRAY_ITEMS = 1_024;
18
+ const MAX_NODES = 16_384;
19
+ const MAX_DEPTH = 16;
20
+ const POST_READ_SETTLE_MS = 25;
21
+ const SHA256_RE = /^[a-f0-9]{64}$/;
22
+ const EXPECTED_PROFILE_KEYS = new Set([
23
+ 'runtime',
24
+ 'binary',
25
+ 'binarySha256',
26
+ 'cliVersion',
27
+ 'protocolSchemaSha256',
28
+ 'codexHome',
29
+ 'cwd',
30
+ 'env',
31
+ 'allowlistedEnvironmentFingerprint',
32
+ 'ownedConfigSha256',
33
+ 'expectedConfigSha256',
34
+ 'expectedConfig',
35
+ 'expectedLayers',
36
+ 'expectedOriginsSha256',
37
+ 'expectedRequirements',
38
+ 'expectedPermissionProfiles',
39
+ 'permissionProfileId',
40
+ 'model',
41
+ 'effort',
42
+ ]);
43
+ const PREFLIGHT_RESULT_KEYS = new Set([
44
+ 'runtime',
45
+ 'runtimeVersion',
46
+ 'schemaVersion',
47
+ 'spawnProfileId',
48
+ 'auth',
49
+ 'attestation',
50
+ 'models',
51
+ 'efforts',
52
+ 'selected',
53
+ ]);
54
+ const SPAWN_PROFILE_KEYS = new Set([
55
+ 'runtime',
56
+ 'spawnProfileId',
57
+ 'expectedStaticProfile',
58
+ 'modelCatalog',
59
+ ]);
60
+ const SUCCESSFUL_PREFLIGHT_RESULTS = new WeakSet();
61
+ const SPAWN_PROFILE_RECEIPTS = new WeakSet();
62
+
63
+ class CodexPreflightError extends Error {
64
+ constructor(message, code, options) {
65
+ super(message, options);
66
+ this.name = 'CodexPreflightError';
67
+ this.code = code;
68
+ }
69
+ }
70
+
71
+ function deepFreeze(value) {
72
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) {
73
+ return value;
74
+ }
75
+ for (const child of Object.values(value)) deepFreeze(child);
76
+ return Object.freeze(value);
77
+ }
78
+
79
+ function isDeepFrozenPlainData(value, visiting = new Set()) {
80
+ if (value === null) return true;
81
+ if (typeof value !== 'object') {
82
+ return (
83
+ typeof value === 'string'
84
+ || typeof value === 'boolean'
85
+ || (typeof value === 'number' && Number.isFinite(value))
86
+ );
87
+ }
88
+ if (!Object.isFrozen(value) || visiting.has(value)) return false;
89
+ const prototype = Object.getPrototypeOf(value);
90
+ if (
91
+ !Array.isArray(value)
92
+ && prototype !== Object.prototype
93
+ && prototype !== null
94
+ ) {
95
+ return false;
96
+ }
97
+ if (Object.getOwnPropertySymbols(value).length > 0) return false;
98
+ visiting.add(value);
99
+ for (const descriptor of Object.values(
100
+ Object.getOwnPropertyDescriptors(value),
101
+ )) {
102
+ if (!('value' in descriptor)) return false;
103
+ if (!isDeepFrozenPlainData(descriptor.value, visiting)) return false;
104
+ }
105
+ visiting.delete(value);
106
+ return true;
107
+ }
108
+
109
+ function plainObject(value, label) {
110
+ if (
111
+ !value
112
+ || typeof value !== 'object'
113
+ || Array.isArray(value)
114
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))
115
+ ) {
116
+ throw new TypeError(`Codex preflight ${label} must be a plain object`);
117
+ }
118
+ return value;
119
+ }
120
+
121
+ function cloneBounded(value, label) {
122
+ let nodes = 0;
123
+ const clone = (current, depth) => {
124
+ nodes += 1;
125
+ if (nodes > MAX_NODES || depth > MAX_DEPTH) {
126
+ throw new TypeError(`Codex preflight ${label} exceeds structural bounds`);
127
+ }
128
+ if (
129
+ current === null
130
+ || typeof current === 'boolean'
131
+ || (
132
+ typeof current === 'number'
133
+ && Number.isFinite(current)
134
+ )
135
+ ) return current;
136
+ if (typeof current === 'string') {
137
+ if (Buffer.byteLength(current) > MAX_STRING_BYTES) {
138
+ throw new TypeError(`Codex preflight ${label} contains an oversized string`);
139
+ }
140
+ return current;
141
+ }
142
+ if (Array.isArray(current)) {
143
+ if (current.length > MAX_ARRAY_ITEMS) {
144
+ throw new TypeError(`Codex preflight ${label} contains an oversized array`);
145
+ }
146
+ return current.map((entry) => clone(entry, depth + 1));
147
+ }
148
+ const object = plainObject(current, label);
149
+ const entries = Object.entries(object);
150
+ if (entries.length > MAX_OBJECT_KEYS) {
151
+ throw new TypeError(`Codex preflight ${label} contains too many keys`);
152
+ }
153
+ return Object.fromEntries(entries.map(([key, entry]) => {
154
+ if (Buffer.byteLength(key) > MAX_STRING_BYTES) {
155
+ throw new TypeError(`Codex preflight ${label} contains an oversized key`);
156
+ }
157
+ return [key, clone(entry, depth + 1)];
158
+ }));
159
+ };
160
+ return clone(value, 0);
161
+ }
162
+
163
+ function canonical(value) {
164
+ if (Array.isArray(value)) return value.map(canonical);
165
+ if (value && typeof value === 'object') {
166
+ return Object.fromEntries(
167
+ Object.keys(value).sort().map((key) => [key, canonical(value[key])]),
168
+ );
169
+ }
170
+ return value;
171
+ }
172
+
173
+ function digest(value) {
174
+ const input = typeof value === 'string'
175
+ ? value
176
+ : JSON.stringify(canonical(value));
177
+ return createHash('sha256').update(input).digest('hex');
178
+ }
179
+
180
+ function requiredString(value, label) {
181
+ if (
182
+ typeof value !== 'string'
183
+ || value.length === 0
184
+ || Buffer.byteLength(value) > MAX_STRING_BYTES
185
+ ) {
186
+ throw new TypeError(`Codex preflight ${label} must be a non-empty string`);
187
+ }
188
+ return value;
189
+ }
190
+
191
+ function requiredSha256(value, label) {
192
+ if (typeof value !== 'string' || !SHA256_RE.test(value)) {
193
+ throw new TypeError(`Codex preflight ${label} must be a lowercase SHA-256`);
194
+ }
195
+ return value;
196
+ }
197
+
198
+ function exact(actual, expected, label) {
199
+ let left;
200
+ let right;
201
+ try {
202
+ left = JSON.stringify(canonical(cloneBounded(actual, label)));
203
+ right = JSON.stringify(canonical(expected));
204
+ } catch (error) {
205
+ if (error instanceof CodexPreflightError) throw error;
206
+ throw new CodexPreflightError(
207
+ `Codex ${label} was malformed`,
208
+ 'CODEX_STATIC_PROFILE_MISMATCH',
209
+ { cause: error },
210
+ );
211
+ }
212
+ if (left !== right) {
213
+ throw new CodexPreflightError(
214
+ `Codex ${label} did not match the expected static profile`,
215
+ 'CODEX_STATIC_PROFILE_MISMATCH',
216
+ );
217
+ }
218
+ }
219
+
220
+ function normalizeExpectedProfile(value) {
221
+ const source = plainObject(value, 'expectedStaticProfile');
222
+ for (const key of Object.keys(source)) {
223
+ if (!EXPECTED_PROFILE_KEYS.has(key)) {
224
+ throw new TypeError(`Codex preflight unexpected static profile field: ${key}`);
225
+ }
226
+ }
227
+ for (const key of EXPECTED_PROFILE_KEYS) {
228
+ if (!Object.hasOwn(source, key)) {
229
+ throw new TypeError(`Codex preflight missing static profile field: ${key}`);
230
+ }
231
+ }
232
+ if (source.runtime !== 'codex') {
233
+ throw new TypeError('Codex preflight runtime must be codex');
234
+ }
235
+ const binary = requiredString(source.binary, 'binary');
236
+ const codexHome = requiredString(source.codexHome, 'codexHome');
237
+ const cwd = requiredString(source.cwd, 'cwd');
238
+ if (
239
+ !path.isAbsolute(binary)
240
+ || !path.isAbsolute(codexHome)
241
+ || !path.isAbsolute(cwd)
242
+ ) {
243
+ throw new TypeError('Codex preflight runtime paths must be absolute');
244
+ }
245
+ const binarySha256 = requiredSha256(
246
+ source.binarySha256,
247
+ 'binarySha256',
248
+ );
249
+ const cliVersion = requiredString(source.cliVersion, 'cliVersion');
250
+ const protocolSchemaSha256 = requiredSha256(
251
+ source.protocolSchemaSha256,
252
+ 'protocolSchemaSha256',
253
+ );
254
+ if (
255
+ binarySha256 !== protocolSchema.binarySha256
256
+ || cliVersion !== protocolSchema.cliVersion
257
+ || protocolSchemaSha256
258
+ !== protocolSchema.generatedProtocolV2CanonicalSha256
259
+ ) {
260
+ throw new CodexPreflightError(
261
+ 'Codex runtime pin does not match the embedded protocol',
262
+ 'CODEX_RUNTIME_PIN_MISMATCH',
263
+ );
264
+ }
265
+
266
+ const suppliedEnv = cloneBounded(source.env, 'environment');
267
+ plainObject(suppliedEnv, 'environment');
268
+ const env = buildCodexAppServerEnv(codexHome, suppliedEnv);
269
+ const allowlistedEnvironmentFingerprint = requiredSha256(
270
+ source.allowlistedEnvironmentFingerprint,
271
+ 'allowlistedEnvironmentFingerprint',
272
+ );
273
+ const observedEnvironmentFingerprint = digest(
274
+ env,
275
+ );
276
+ if (
277
+ allowlistedEnvironmentFingerprint !== observedEnvironmentFingerprint
278
+ ) {
279
+ throw new CodexPreflightError(
280
+ 'Codex allowlisted environment fingerprint did not match',
281
+ 'CODEX_STATIC_PROFILE_MISMATCH',
282
+ );
283
+ }
284
+
285
+ const expectedConfig = cloneBounded(
286
+ source.expectedConfig,
287
+ 'expected config projection',
288
+ );
289
+ const expectedLayers = cloneBounded(
290
+ source.expectedLayers,
291
+ 'expected config layers',
292
+ );
293
+ const expectedRequirements = cloneBounded(
294
+ source.expectedRequirements,
295
+ 'expected config requirements',
296
+ );
297
+ const expectedPermissionProfiles = cloneBounded(
298
+ source.expectedPermissionProfiles,
299
+ 'expected permission profiles',
300
+ );
301
+ if (
302
+ !Array.isArray(expectedLayers)
303
+ || !Array.isArray(expectedPermissionProfiles)
304
+ || expectedLayers.length > 64
305
+ || expectedPermissionProfiles.length > MAX_ENTRIES
306
+ ) {
307
+ throw new TypeError(
308
+ 'Codex preflight expected layers or profiles exceeded their bounds',
309
+ );
310
+ }
311
+ const expectedProfileIds = new Set();
312
+ const normalizedExpectedPermissionProfiles = expectedPermissionProfiles
313
+ .map((entry) => {
314
+ const projected = validatePermissionProfile(entry).value;
315
+ if (expectedProfileIds.has(projected.id)) {
316
+ throw new CodexPreflightError(
317
+ 'Codex expected permission profiles contain a duplicate ID',
318
+ 'CODEX_PREFLIGHT_DUPLICATE',
319
+ );
320
+ }
321
+ expectedProfileIds.add(projected.id);
322
+ return projected;
323
+ })
324
+ .sort((left, right) => left.id.localeCompare(right.id));
325
+
326
+ const profile = {
327
+ runtime: 'codex',
328
+ binary,
329
+ binarySha256,
330
+ cliVersion,
331
+ protocolSchemaSha256,
332
+ codexHome,
333
+ cwd,
334
+ env,
335
+ allowlistedEnvironmentFingerprint,
336
+ ownedConfigSha256: requiredSha256(
337
+ source.ownedConfigSha256,
338
+ 'ownedConfigSha256',
339
+ ),
340
+ expectedConfigSha256: requiredSha256(
341
+ source.expectedConfigSha256,
342
+ 'expectedConfigSha256',
343
+ ),
344
+ expectedConfig,
345
+ expectedLayers,
346
+ expectedOriginsSha256: requiredSha256(
347
+ source.expectedOriginsSha256,
348
+ 'expectedOriginsSha256',
349
+ ),
350
+ expectedRequirements,
351
+ expectedPermissionProfiles: normalizedExpectedPermissionProfiles,
352
+ permissionProfileId: requiredString(
353
+ source.permissionProfileId,
354
+ 'permissionProfileId',
355
+ ),
356
+ model: requiredString(source.model, 'model'),
357
+ effort: requiredString(source.effort, 'effort'),
358
+ };
359
+
360
+ assertExpectedPolicy(profile);
361
+ return profile;
362
+ }
363
+
364
+ function assertExpectedPolicy(profile) {
365
+ const config = plainObject(profile.expectedConfig, 'expected config projection');
366
+ if (
367
+ config.sha256 !== profile.expectedConfigSha256
368
+ || config.modelProvider !== 'openai'
369
+ || config.defaultPermissions !== profile.permissionProfileId
370
+ || config.approvalPolicy !== 'never'
371
+ || config.approvalsReviewer !== 'user'
372
+ || config.webSearch !== 'disabled'
373
+ || config.allowLoginShell !== false
374
+ || config.shellEnvironmentInherit !== 'none'
375
+ || config.mcpServers?.count !== 0
376
+ || config.mcpServers?.keySha256?.length !== 0
377
+ || config.plugins?.count !== 0
378
+ || config.plugins?.keySha256?.length !== 0
379
+ || config.modelProviders?.count !== 1
380
+ || config.modelProviders?.keySha256?.length !== 1
381
+ || config.modelProviders.keySha256[0] !== digest('openai')
382
+ ) {
383
+ throw new CodexPreflightError(
384
+ 'Codex expected policy is outside the native beta contract',
385
+ 'CODEX_STATIC_PROFILE_MISMATCH',
386
+ );
387
+ }
388
+ if (!Array.isArray(config.permissionProfiles)) {
389
+ throw new TypeError(
390
+ 'Codex preflight expected config permission profiles must be an array',
391
+ );
392
+ }
393
+ const configured = config.permissionProfiles.filter(
394
+ (entry) => entry?.id === profile.permissionProfileId,
395
+ );
396
+ const listed = profile.expectedPermissionProfiles.filter(
397
+ (entry) => entry?.id === profile.permissionProfileId,
398
+ );
399
+ if (
400
+ configured.length !== 1
401
+ || listed.length !== 1
402
+ || configured[0].extends !== null
403
+ || configured[0].networkEnabled !== false
404
+ || listed[0].allowed !== true
405
+ ) {
406
+ throw new CodexPreflightError(
407
+ 'Codex expected permission profile is not uniquely allowed and isolated',
408
+ 'CODEX_STATIC_PROFILE_MISMATCH',
409
+ );
410
+ }
411
+ }
412
+
413
+ function paginationCursor(value) {
414
+ if (value == null) return null;
415
+ if (
416
+ typeof value !== 'string'
417
+ || value.length === 0
418
+ || Buffer.byteLength(value) > 512
419
+ ) {
420
+ throw new CodexPreflightError(
421
+ 'Codex preflight pagination cursor was malformed',
422
+ 'CODEX_PREFLIGHT_PAGINATION',
423
+ );
424
+ }
425
+ return value;
426
+ }
427
+
428
+ function projectClientFault(value) {
429
+ if (value == null) return null;
430
+ const outcome = plainObject(value, 'client fault outcome');
431
+ const projected = {
432
+ kind: outcome.kind,
433
+ boundary: outcome.boundary,
434
+ containment: outcome.containment,
435
+ cleanup: outcome.cleanup,
436
+ errorCode: outcome.errorCode,
437
+ cleanupErrorCode: outcome.cleanupErrorCode,
438
+ mutationOutcomeUnknown: outcome.mutationOutcomeUnknown,
439
+ };
440
+ if (
441
+ projected.kind !== 'codex-app-server-fault'
442
+ || !['pre-spawn', 'post-spawn'].includes(projected.boundary)
443
+ || !['safe', 'unverified'].includes(projected.containment)
444
+ || !['completed', 'failed'].includes(projected.cleanup)
445
+ || typeof projected.errorCode !== 'string'
446
+ || projected.errorCode.length === 0
447
+ || (
448
+ projected.cleanupErrorCode !== null
449
+ && (
450
+ typeof projected.cleanupErrorCode !== 'string'
451
+ || projected.cleanupErrorCode.length === 0
452
+ )
453
+ )
454
+ || typeof projected.mutationOutcomeUnknown !== 'boolean'
455
+ ) {
456
+ throw new CodexPreflightError(
457
+ 'Codex preflight client fault handoff was malformed',
458
+ 'CODEX_PREFLIGHT_FAULT_HANDOFF_FAILED',
459
+ );
460
+ }
461
+ return Object.freeze(projected);
462
+ }
463
+
464
+ function clientFaultError(outcome) {
465
+ const error = new CodexPreflightError(
466
+ 'Codex preflight app-server generation faulted',
467
+ 'CODEX_PREFLIGHT_CLIENT_FAULT',
468
+ );
469
+ error.clientFaultErrorCode = outcome.errorCode;
470
+ error.clientFaultBoundary = outcome.boundary;
471
+ error.clientFaultContainment = outcome.containment;
472
+ error.clientFaultCleanup = outcome.cleanup;
473
+ error.clientFaultCleanupErrorCode = outcome.cleanupErrorCode;
474
+ return error;
475
+ }
476
+
477
+ function annotateFailureWithClientFault(error, outcome) {
478
+ if (!error || !outcome) return;
479
+ try {
480
+ error.preflightClientFaultCode = outcome.errorCode;
481
+ error.preflightClientFaultBoundary = outcome.boundary;
482
+ error.preflightClientFaultContainment = outcome.containment;
483
+ } catch {}
484
+ }
485
+
486
+ async function collectPages(client, method, baseParams, validateEntry) {
487
+ const entries = [];
488
+ const seenCursors = new Set();
489
+ const seenKeys = new Map();
490
+ let cursor;
491
+
492
+ for (let page = 0; page < MAX_PAGES; page += 1) {
493
+ const params = cursor === undefined
494
+ ? { ...baseParams }
495
+ : { ...baseParams, cursor };
496
+ const result = plainObject(
497
+ await client.request(method, params),
498
+ `${method} result`,
499
+ );
500
+ if (!Array.isArray(result.data) || result.data.length > PAGE_LIMIT) {
501
+ throw new CodexPreflightError(
502
+ `Codex ${method} page exceeded the bounded result size`,
503
+ 'CODEX_PREFLIGHT_PAGINATION',
504
+ );
505
+ }
506
+ for (const rawEntry of result.data) {
507
+ const { value, keys } = validateEntry(rawEntry);
508
+ for (const [kind, key] of Object.entries(keys)) {
509
+ let seen = seenKeys.get(kind);
510
+ if (!seen) {
511
+ seen = new Set();
512
+ seenKeys.set(kind, seen);
513
+ }
514
+ if (seen.has(key)) {
515
+ throw new CodexPreflightError(
516
+ `Codex ${method} returned a duplicate ${kind}`,
517
+ 'CODEX_PREFLIGHT_DUPLICATE',
518
+ );
519
+ }
520
+ seen.add(key);
521
+ }
522
+ entries.push(value);
523
+ if (entries.length > MAX_ENTRIES) {
524
+ throw new CodexPreflightError(
525
+ `Codex ${method} catalog exceeded the bounded result size`,
526
+ 'CODEX_PREFLIGHT_PAGINATION',
527
+ );
528
+ }
529
+ }
530
+ const nextCursor = paginationCursor(result.nextCursor);
531
+ if (nextCursor === null) return entries;
532
+ if (seenCursors.has(nextCursor)) {
533
+ throw new CodexPreflightError(
534
+ `Codex ${method} pagination cursor repeated`,
535
+ 'CODEX_PREFLIGHT_PAGINATION',
536
+ );
537
+ }
538
+ seenCursors.add(nextCursor);
539
+ cursor = nextCursor;
540
+ }
541
+
542
+ throw new CodexPreflightError(
543
+ `Codex ${method} exceeded the page limit`,
544
+ 'CODEX_PREFLIGHT_PAGINATION',
545
+ );
546
+ }
547
+
548
+ function validatePermissionProfile(value) {
549
+ const profile = plainObject(value, 'permission profile');
550
+ const id = requiredString(profile.id, 'permission profile id');
551
+ if (
552
+ typeof profile.allowed !== 'boolean'
553
+ || (
554
+ profile.descriptionSha256 !== null
555
+ && !SHA256_RE.test(profile.descriptionSha256)
556
+ )
557
+ ) {
558
+ throw new CodexPreflightError(
559
+ 'Codex permission profile projection was malformed',
560
+ 'CODEX_STATIC_PROFILE_MISMATCH',
561
+ );
562
+ }
563
+ return {
564
+ value: {
565
+ id,
566
+ allowed: profile.allowed,
567
+ descriptionSha256: profile.descriptionSha256,
568
+ },
569
+ keys: { profileId: id },
570
+ };
571
+ }
572
+
573
+ function validateModel(value) {
574
+ const source = plainObject(value, 'model');
575
+ const projected = {
576
+ id: requiredString(source.id, 'model id'),
577
+ model: requiredString(source.model, 'model slug'),
578
+ displayName: requiredString(source.displayName, 'model display name'),
579
+ defaultReasoningEffort: requiredString(
580
+ source.defaultReasoningEffort,
581
+ 'model default reasoning effort',
582
+ ),
583
+ supportedReasoningEfforts: cloneBounded(
584
+ source.supportedReasoningEfforts,
585
+ 'model reasoning efforts',
586
+ ),
587
+ isDefault: source.isDefault,
588
+ };
589
+ requiredString(source.description, 'model description');
590
+ if (
591
+ source.hidden !== false
592
+ || typeof source.isDefault !== 'boolean'
593
+ || !Array.isArray(projected.supportedReasoningEfforts)
594
+ || projected.supportedReasoningEfforts.length === 0
595
+ || projected.supportedReasoningEfforts.length > 32
596
+ ) {
597
+ throw new CodexPreflightError(
598
+ 'Codex model projection was malformed',
599
+ 'CODEX_PREFLIGHT_CATALOG',
600
+ );
601
+ }
602
+ const efforts = new Set();
603
+ for (const effort of projected.supportedReasoningEfforts) {
604
+ requiredString(effort, 'model reasoning effort');
605
+ if (efforts.has(effort)) {
606
+ throw new CodexPreflightError(
607
+ 'Codex model returned a duplicate reasoning effort',
608
+ 'CODEX_PREFLIGHT_DUPLICATE',
609
+ );
610
+ }
611
+ efforts.add(effort);
612
+ }
613
+ if (!efforts.has(projected.defaultReasoningEffort)) {
614
+ throw new CodexPreflightError(
615
+ 'Codex model default effort was not supported',
616
+ 'CODEX_PREFLIGHT_CATALOG',
617
+ );
618
+ }
619
+ return {
620
+ value: projected,
621
+ keys: {
622
+ modelId: projected.id,
623
+ modelSlug: projected.model,
624
+ },
625
+ };
626
+ }
627
+
628
+ function staticAttestation(profile, configRead, requirements, profiles) {
629
+ const configuredProfile = configRead.config.permissionProfiles.find(
630
+ (entry) => entry.id === profile.permissionProfileId,
631
+ );
632
+ const listedProfile = profiles.find(
633
+ (entry) => entry.id === profile.permissionProfileId,
634
+ );
635
+ const requirementProjection = requirements.requirements;
636
+ const ids = profiles.map((entry) => digest(entry.id)).sort();
637
+ return {
638
+ binarySha256: profile.binarySha256,
639
+ binaryPathSha256: digest(profile.binary),
640
+ credentialHomeSha256: digest(profile.codexHome),
641
+ workspaceSha256: digest(profile.cwd),
642
+ allowlistedEnvironmentFingerprint:
643
+ profile.allowlistedEnvironmentFingerprint,
644
+ ownedConfigSha256: profile.ownedConfigSha256,
645
+ effectiveConfigSha256: configRead.config.sha256,
646
+ originsSha256: configRead.originsSha256,
647
+ layerCount: configRead.layers.length,
648
+ layerSetSha256: digest(configRead.layers),
649
+ requirements: requirementProjection === null
650
+ ? null
651
+ : {
652
+ sha256: requirementProjection.sha256,
653
+ keyCount: requirementProjection.keys.length,
654
+ keySetSha256: digest([...requirementProjection.keys].sort()),
655
+ },
656
+ policy: {
657
+ modelProvider: configRead.config.modelProvider,
658
+ defaultPermissionIdSha256: digest(
659
+ configRead.config.defaultPermissions,
660
+ ),
661
+ approvalPolicy: configRead.config.approvalPolicy,
662
+ approvalsReviewer: configRead.config.approvalsReviewer,
663
+ webSearch: configRead.config.webSearch,
664
+ allowLoginShell: configRead.config.allowLoginShell,
665
+ shellEnvironmentInherit:
666
+ configRead.config.shellEnvironmentInherit,
667
+ mcpServerCount: configRead.config.mcpServers.count,
668
+ mcpServerSetSha256: digest(
669
+ configRead.config.mcpServers.keySha256,
670
+ ),
671
+ pluginCount: configRead.config.plugins.count,
672
+ pluginSetSha256: digest(configRead.config.plugins.keySha256),
673
+ modelProviderCount: configRead.config.modelProviders.count,
674
+ modelProviderSetSha256: digest(
675
+ configRead.config.modelProviders.keySha256,
676
+ ),
677
+ },
678
+ permissionProfile: {
679
+ idSha256: digest(profile.permissionProfileId),
680
+ allowed: listedProfile.allowed,
681
+ extendsSha256: configuredProfile.extends === null
682
+ ? null
683
+ : digest(configuredProfile.extends),
684
+ networkEnabled: configuredProfile.networkEnabled,
685
+ filesystemSha256: configuredProfile.filesystemSha256,
686
+ filesystemRuleCount: configuredProfile.filesystem.length,
687
+ filesystemRuleSetSha256: digest(configuredProfile.filesystem),
688
+ descriptionSha256: listedProfile.descriptionSha256,
689
+ },
690
+ permissionProfileCatalog: {
691
+ count: profiles.length,
692
+ allowedCount: profiles.filter((entry) => entry.allowed).length,
693
+ idSetSha256: digest(ids),
694
+ },
695
+ };
696
+ }
697
+
698
+ function receiptInvalid(message) {
699
+ return new CodexPreflightError(
700
+ `Codex preflight receipt was invalid: ${message}`,
701
+ 'CODEX_PREFLIGHT_RECEIPT_INVALID',
702
+ );
703
+ }
704
+
705
+ function createCodexSpawnProfile(expectedStaticProfile, preflightResult) {
706
+ const profile = deepFreeze(normalizeExpectedProfile(expectedStaticProfile));
707
+ let result;
708
+ try {
709
+ result = plainObject(preflightResult, 'result');
710
+ } catch (error) {
711
+ throw receiptInvalid(error.message);
712
+ }
713
+ for (const key of Object.keys(result)) {
714
+ if (!PREFLIGHT_RESULT_KEYS.has(key)) {
715
+ throw new TypeError(
716
+ `Codex preflight unexpected preflight result field: ${key}`,
717
+ );
718
+ }
719
+ }
720
+ for (const key of PREFLIGHT_RESULT_KEYS) {
721
+ if (!Object.hasOwn(result, key)) {
722
+ throw new TypeError(`Codex preflight missing preflight result field: ${key}`);
723
+ }
724
+ }
725
+ if (!isDeepFrozenPlainData(result)) {
726
+ throw receiptInvalid('result must be deeply frozen plain data');
727
+ }
728
+ if (
729
+ result.runtime !== 'codex'
730
+ || result.runtimeVersion !== profile.cliVersion
731
+ || result.schemaVersion !== profile.protocolSchemaSha256
732
+ || !SHA256_RE.test(result.spawnProfileId)
733
+ ) {
734
+ throw receiptInvalid('runtime identity did not match the static profile');
735
+ }
736
+ let auth;
737
+ let selected;
738
+ try {
739
+ auth = plainObject(result.auth, 'result auth');
740
+ selected = plainObject(result.selected, 'result selection');
741
+ } catch (error) {
742
+ throw receiptInvalid(error.message);
743
+ }
744
+ if (
745
+ auth.authenticated !== true
746
+ || auth.accountType !== 'chatgpt'
747
+ || typeof auth.requiresOpenaiAuth !== 'boolean'
748
+ || selected.model !== profile.model
749
+ || selected.effort !== profile.effort
750
+ || !Array.isArray(result.models)
751
+ || !Array.isArray(result.efforts)
752
+ ) {
753
+ throw receiptInvalid('authenticated model selection did not match');
754
+ }
755
+ const selectedModels = result.models.filter(
756
+ (entry) => entry?.model === profile.model,
757
+ );
758
+ if (
759
+ selectedModels.length !== 1
760
+ || !Array.isArray(selectedModels[0].supportedReasoningEfforts)
761
+ || !selectedModels[0].supportedReasoningEfforts.includes(profile.effort)
762
+ || JSON.stringify(result.efforts)
763
+ !== JSON.stringify(selectedModels[0].supportedReasoningEfforts)
764
+ ) {
765
+ throw receiptInvalid('selected model catalog entry did not match');
766
+ }
767
+
768
+ const expectedAttestation = staticAttestation(
769
+ profile,
770
+ {
771
+ config: profile.expectedConfig,
772
+ layers: profile.expectedLayers,
773
+ originsSha256: profile.expectedOriginsSha256,
774
+ },
775
+ { requirements: profile.expectedRequirements },
776
+ profile.expectedPermissionProfiles,
777
+ );
778
+ if (
779
+ JSON.stringify(canonical(result.attestation))
780
+ !== JSON.stringify(canonical(expectedAttestation))
781
+ ) {
782
+ throw receiptInvalid('static attestation did not match');
783
+ }
784
+ const expectedSpawnProfileId = digest({
785
+ runtime: 'codex',
786
+ runtimeVersion: profile.cliVersion,
787
+ schemaVersion: profile.protocolSchemaSha256,
788
+ attestation: expectedAttestation,
789
+ accountType: 'chatgpt',
790
+ });
791
+ if (result.spawnProfileId !== expectedSpawnProfileId) {
792
+ throw receiptInvalid('spawn-profile identity did not match');
793
+ }
794
+ if (!SUCCESSFUL_PREFLIGHT_RESULTS.has(result)) {
795
+ throw receiptInvalid(
796
+ 'result was not produced by a successful preflight',
797
+ );
798
+ }
799
+
800
+ const receipt = deepFreeze({
801
+ runtime: 'codex',
802
+ spawnProfileId: expectedSpawnProfileId,
803
+ expectedStaticProfile: profile,
804
+ modelCatalog: result.models,
805
+ });
806
+ SPAWN_PROFILE_RECEIPTS.add(receipt);
807
+ return receipt;
808
+ }
809
+
810
+ function assertCodexSpawnProfile(receipt) {
811
+ if (
812
+ !receipt
813
+ || typeof receipt !== 'object'
814
+ || Array.isArray(receipt)
815
+ || !SPAWN_PROFILE_RECEIPTS.has(receipt)
816
+ || !isDeepFrozenPlainData(receipt)
817
+ || Object.keys(receipt).length !== SPAWN_PROFILE_KEYS.size
818
+ || Object.keys(receipt).some((key) => !SPAWN_PROFILE_KEYS.has(key))
819
+ ) {
820
+ throw receiptInvalid(
821
+ 'factory requires an intact createCodexSpawnProfile receipt',
822
+ );
823
+ }
824
+ return receipt;
825
+ }
826
+
827
+ async function readAndAssertStaticPolicy(profile, client) {
828
+ const configRead = await client.request('config/read', {
829
+ cwd: profile.cwd,
830
+ includeLayers: true,
831
+ });
832
+ const requirements = await client.request(
833
+ 'configRequirements/read',
834
+ undefined,
835
+ );
836
+ const permissionProfiles = await collectPages(
837
+ client,
838
+ 'permissionProfile/list',
839
+ { cwd: profile.cwd },
840
+ validatePermissionProfile,
841
+ );
842
+ permissionProfiles.sort((left, right) => left.id.localeCompare(right.id));
843
+
844
+ exact(configRead?.config, profile.expectedConfig, 'effective config');
845
+ exact(configRead?.layers, profile.expectedLayers, 'config layers');
846
+ exact(
847
+ configRead?.originsSha256,
848
+ profile.expectedOriginsSha256,
849
+ 'config origins',
850
+ );
851
+ exact(
852
+ requirements?.requirements,
853
+ profile.expectedRequirements,
854
+ 'config requirements',
855
+ );
856
+ exact(
857
+ permissionProfiles,
858
+ profile.expectedPermissionProfiles,
859
+ 'permission profile catalog',
860
+ );
861
+ return { configRead, requirements, permissionProfiles };
862
+ }
863
+
864
+ async function reattestCodexStaticPolicy(expectedStaticProfile, client) {
865
+ if (!client || typeof client.request !== 'function') {
866
+ throw new TypeError(
867
+ 'Codex static policy reattestation requires a live app-server client',
868
+ );
869
+ }
870
+ const profile = normalizeExpectedProfile(expectedStaticProfile);
871
+ await readAndAssertStaticPolicy(profile, client);
872
+ }
873
+
874
+ async function runPreflight(profile, client) {
875
+ await client.start();
876
+ const {
877
+ configRead,
878
+ requirements,
879
+ permissionProfiles,
880
+ } = await readAndAssertStaticPolicy(profile, client);
881
+
882
+ const account = plainObject(
883
+ await client.request('account/read', { refreshToken: false }),
884
+ 'account result',
885
+ );
886
+ if (account.account?.type !== 'chatgpt') {
887
+ throw new CodexPreflightError(
888
+ 'Codex ChatGPT authentication is unavailable',
889
+ 'CODEX_AUTH_UNAVAILABLE',
890
+ );
891
+ }
892
+ if (typeof account.requiresOpenaiAuth !== 'boolean') {
893
+ throw new CodexPreflightError(
894
+ 'Codex authentication projection was malformed',
895
+ 'CODEX_AUTH_UNAVAILABLE',
896
+ );
897
+ }
898
+
899
+ const models = await collectPages(
900
+ client,
901
+ 'model/list',
902
+ { includeHidden: false, limit: PAGE_LIMIT },
903
+ validateModel,
904
+ );
905
+ models.sort((left, right) => (
906
+ left.model.localeCompare(right.model)
907
+ || left.id.localeCompare(right.id)
908
+ ));
909
+ const selected = models.find((entry) => entry.model === profile.model);
910
+ if (!selected) {
911
+ throw new CodexPreflightError(
912
+ 'Requested Codex model is unavailable',
913
+ 'CODEX_MODEL_UNAVAILABLE',
914
+ );
915
+ }
916
+ if (!selected.supportedReasoningEfforts.includes(profile.effort)) {
917
+ throw new CodexPreflightError(
918
+ 'Requested Codex reasoning effort is unavailable',
919
+ 'CODEX_EFFORT_UNAVAILABLE',
920
+ );
921
+ }
922
+
923
+ const attestation = staticAttestation(
924
+ profile,
925
+ configRead,
926
+ requirements,
927
+ permissionProfiles,
928
+ );
929
+ const spawnProfileId = digest({
930
+ runtime: 'codex',
931
+ runtimeVersion: profile.cliVersion,
932
+ schemaVersion: profile.protocolSchemaSha256,
933
+ attestation,
934
+ accountType: account.account.type,
935
+ });
936
+ return deepFreeze({
937
+ runtime: 'codex',
938
+ runtimeVersion: profile.cliVersion,
939
+ schemaVersion: profile.protocolSchemaSha256,
940
+ spawnProfileId,
941
+ auth: {
942
+ authenticated: true,
943
+ accountType: account.account.type,
944
+ requiresOpenaiAuth: account.requiresOpenaiAuth,
945
+ },
946
+ attestation,
947
+ models,
948
+ efforts: [...selected.supportedReasoningEfforts],
949
+ selected: {
950
+ model: selected.model,
951
+ effort: profile.effort,
952
+ },
953
+ });
954
+ }
955
+
956
+ async function preflightCodexRuntime(
957
+ expectedStaticProfile,
958
+ {
959
+ clientFactory = (options) => new CodexAppServerClient(options),
960
+ } = {},
961
+ ) {
962
+ if (typeof clientFactory !== 'function') {
963
+ throw new TypeError('Codex preflight clientFactory must be a function');
964
+ }
965
+ const profile = normalizeExpectedProfile(expectedStaticProfile);
966
+ let latchedFault = null;
967
+ const client = clientFactory({
968
+ binary: profile.binary,
969
+ cwd: profile.cwd,
970
+ codexHome: profile.codexHome,
971
+ env: profile.env,
972
+ expectedConfigSha256: profile.ownedConfigSha256,
973
+ onNotification: async () => {
974
+ throw new CodexPreflightError(
975
+ 'Codex preflight received an unexpected state notification',
976
+ 'CODEX_PREFLIGHT_UNEXPECTED_NOTIFICATION',
977
+ );
978
+ },
979
+ onFault: (outcome) => {
980
+ outcome?.assertActive?.();
981
+ latchedFault = projectClientFault(outcome);
982
+ },
983
+ });
984
+ if (
985
+ !client
986
+ || typeof client.start !== 'function'
987
+ || typeof client.request !== 'function'
988
+ || typeof client.close !== 'function'
989
+ || typeof client.waitForFault !== 'function'
990
+ ) {
991
+ throw new TypeError('Codex preflight clientFactory returned an invalid client');
992
+ }
993
+
994
+ let result;
995
+ let failure = null;
996
+ try {
997
+ result = await runPreflight(profile, client);
998
+ } catch (error) {
999
+ failure = error;
1000
+ }
1001
+ if (!failure) {
1002
+ await new Promise((resolve) => setTimeout(resolve, POST_READ_SETTLE_MS));
1003
+ }
1004
+
1005
+ try {
1006
+ await client.close();
1007
+ } catch (error) {
1008
+ const closeFailure = new CodexPreflightError(
1009
+ 'Codex preflight client cleanup failed',
1010
+ 'CODEX_PREFLIGHT_CLOSE_FAILED',
1011
+ { cause: error },
1012
+ );
1013
+ closeFailure.preflightErrorCode = failure?.code ?? null;
1014
+ closeFailure.cleanupErrorCode = error?.code ?? null;
1015
+ throw closeFailure;
1016
+ }
1017
+
1018
+ let terminalFault;
1019
+ try {
1020
+ terminalFault = projectClientFault(await client.waitForFault());
1021
+ } catch (error) {
1022
+ if (failure) {
1023
+ try {
1024
+ failure.preflightFaultHandoffErrorCode = error?.code ?? null;
1025
+ } catch {}
1026
+ throw failure;
1027
+ }
1028
+ if (
1029
+ error instanceof CodexPreflightError
1030
+ && error.code === 'CODEX_PREFLIGHT_FAULT_HANDOFF_FAILED'
1031
+ ) {
1032
+ throw error;
1033
+ }
1034
+ throw new CodexPreflightError(
1035
+ 'Codex preflight client fault handoff failed',
1036
+ 'CODEX_PREFLIGHT_FAULT_HANDOFF_FAILED',
1037
+ { cause: error },
1038
+ );
1039
+ }
1040
+ if (
1041
+ latchedFault
1042
+ && terminalFault
1043
+ && JSON.stringify(latchedFault) !== JSON.stringify(terminalFault)
1044
+ ) {
1045
+ const mismatch = new CodexPreflightError(
1046
+ 'Codex preflight client fault handoff was inconsistent',
1047
+ 'CODEX_PREFLIGHT_FAULT_HANDOFF_FAILED',
1048
+ );
1049
+ if (failure) {
1050
+ try {
1051
+ failure.preflightFaultHandoffErrorCode = mismatch.code;
1052
+ } catch {}
1053
+ throw failure;
1054
+ }
1055
+ throw mismatch;
1056
+ }
1057
+ const observedFault = latchedFault ?? terminalFault;
1058
+ if (failure) {
1059
+ annotateFailureWithClientFault(failure, observedFault);
1060
+ throw failure;
1061
+ }
1062
+ if (observedFault) throw clientFaultError(observedFault);
1063
+ SUCCESSFUL_PREFLIGHT_RESULTS.add(result);
1064
+ return result;
1065
+ }
1066
+
1067
+ module.exports = {
1068
+ assertCodexSpawnProfile,
1069
+ CodexPreflightError,
1070
+ createCodexSpawnProfile,
1071
+ preflightCodexRuntime,
1072
+ reattestCodexStaticPolicy,
1073
+ };