@shumkov/orchestra 0.6.0 → 0.7.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.
@@ -0,0 +1,2874 @@
1
+ 'use strict';
2
+
3
+ const { execFile, spawn } = require('node:child_process');
4
+ const { createHash } = require('node:crypto');
5
+ const { EventEmitter } = require('node:events');
6
+ const {
7
+ createReadStream,
8
+ lstatSync,
9
+ realpathSync,
10
+ statSync,
11
+ } = require('node:fs');
12
+ const os = require('node:os');
13
+ const path = require('node:path');
14
+ const { StringDecoder } = require('node:string_decoder');
15
+ const { promisify } = require('node:util');
16
+
17
+ function deepFreeze(value) {
18
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
19
+ for (const child of Object.values(value)) deepFreeze(child);
20
+ return Object.freeze(value);
21
+ }
22
+
23
+ const protocolSchema = deepFreeze(
24
+ JSON.parse(JSON.stringify(require('./protocol-schema.json'))),
25
+ );
26
+ const execFileAsync = promisify(execFile);
27
+
28
+ const CONTROLLED_PATH = '/usr/bin:/bin';
29
+ const SUPERVISOR_PATH = path.join(__dirname, 'app-server-supervisor.mjs');
30
+ const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
31
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
32
+ const DEFAULT_CLOSE_GRACE_MS = 1_000;
33
+ const DEFAULT_CLOSE_KILL_MS = 1_000;
34
+ const DEFAULT_MAX_LINE_BYTES = 1024 * 1024;
35
+ const DEFAULT_MAX_STDERR_BYTES = 64 * 1024;
36
+ const DEFAULT_MAX_PENDING_REQUESTS = 64;
37
+ const DEFAULT_MAX_USED_REQUEST_IDS = 65_536;
38
+ const DEFAULT_MAX_QUEUED_LINES = 256;
39
+ const DEFAULT_MAX_QUEUED_BYTES = 4 * 1024 * 1024;
40
+ const DEFAULT_SINK_TIMEOUT_MS = 5_000;
41
+ const MAX_ID_BYTES = 512;
42
+ const MAX_TEXT_BYTES = 64 * 1024;
43
+ const MAX_COMPLETED_ITEMS = 512;
44
+ const MAX_RESPONSE_ARRAY_ITEMS = 512;
45
+ const MAX_RESPONSE_OBJECT_KEYS = 512;
46
+ const MAX_RESPONSE_NODES = 8_192;
47
+ const MAX_RESPONSE_DEPTH = 12;
48
+ const SAFE_METHOD_PATTERN = /^[A-Za-z][A-Za-z0-9]*(?:\/[A-Za-z][A-Za-z0-9]*)*$/;
49
+ const FORBIDDEN_REQUEST_FIELDS = new Set([
50
+ 'sandbox_mode',
51
+ 'sandbox_workspace_write',
52
+ 'sandbox',
53
+ 'sandboxPolicy',
54
+ 'permissions',
55
+ 'permissionProfile',
56
+ 'config',
57
+ ]);
58
+ const CONSTRUCTOR_KEYS = new Set([
59
+ 'binary',
60
+ 'cwd',
61
+ 'codexHome',
62
+ 'env',
63
+ 'spawnFn',
64
+ 'killFn',
65
+ 'setTimer',
66
+ 'clearTimer',
67
+ 'requestIdFactory',
68
+ 'onNotification',
69
+ 'onFault',
70
+ 'attestBinaryFn',
71
+ 'attestCodexHomeFn',
72
+ 'expectedConfigSha256',
73
+ 'requestTimeoutMs',
74
+ 'sinkTimeoutMs',
75
+ 'closeGraceMs',
76
+ 'closeKillMs',
77
+ 'maxLineBytes',
78
+ 'maxStderrBytes',
79
+ 'maxPendingRequests',
80
+ 'maxUsedRequestIds',
81
+ 'maxQueuedLines',
82
+ 'maxQueuedBytes',
83
+ ]);
84
+
85
+ const CLIENT_REQUESTS = new Map(Object.entries(protocolSchema.clientRequests));
86
+ const CLIENT_NOTIFICATIONS = new Set(protocolSchema.clientNotifications);
87
+ const DENIED_CLIENT_REQUESTS = new Set(protocolSchema.deniedClientRequests);
88
+ const DELIVERED_NOTIFICATIONS = new Set(
89
+ protocolSchema.deliveredServerNotifications,
90
+ );
91
+ const DROPPED_NOTIFICATIONS = new Set(
92
+ protocolSchema.droppedServerNotifications,
93
+ );
94
+ const DENIED_SERVER_REQUESTS = new Map(
95
+ Object.entries(protocolSchema.deniedServerRequests),
96
+ );
97
+ const RECOGNIZED_RPC_ERRORS = new Map(
98
+ Object.entries(protocolSchema.recognizedRpcErrors)
99
+ .map(([method, messages]) => [method, new Set(messages)]),
100
+ );
101
+
102
+ function assertProtocolSchema() {
103
+ const experimental = [...CLIENT_REQUESTS]
104
+ .filter(([, spec]) => spec.experimental)
105
+ .map(([method]) => method)
106
+ .sort();
107
+ if (
108
+ JSON.stringify(experimental) !== JSON.stringify([
109
+ 'thread/backgroundTerminals/clean',
110
+ 'thread/backgroundTerminals/list',
111
+ ])
112
+ || !CLIENT_NOTIFICATIONS.has('initialized')
113
+ || CLIENT_NOTIFICATIONS.size !== 1
114
+ || protocolSchema.requestIdTypes.join(',') !== 'integer,string'
115
+ || typeof protocolSchema.generatedProtocolV2CanonicalSha256 !== 'string'
116
+ || !/^[a-f0-9]{64}$/.test(protocolSchema.generatedProtocolV2CanonicalSha256)
117
+ ) {
118
+ throw new Error('Codex app-server protocol pin is inconsistent');
119
+ }
120
+ for (const method of DELIVERED_NOTIFICATIONS) {
121
+ if (DROPPED_NOTIFICATIONS.has(method)) {
122
+ throw new Error('Codex app-server notification classes overlap');
123
+ }
124
+ }
125
+ if (
126
+ CLIENT_REQUESTS.has('thread/backgroundTerminals/terminate')
127
+ || CLIENT_REQUESTS.has('command/exec')
128
+ || !DENIED_CLIENT_REQUESTS.has('command/exec')
129
+ ) {
130
+ throw new Error('Codex app-server privileged method policy drifted');
131
+ }
132
+ }
133
+
134
+ assertProtocolSchema();
135
+
136
+ class CodexAppServerError extends Error {
137
+ constructor(message, code, options) {
138
+ super(message, options);
139
+ this.name = 'CodexAppServerError';
140
+ this.code = code;
141
+ }
142
+ }
143
+
144
+ function buildCodexAppServerEnv(codexHome, hostEnv = process.env) {
145
+ return Object.fromEntries(
146
+ Object.entries({
147
+ HOME: hostEnv.HOME,
148
+ PATH: CONTROLLED_PATH,
149
+ TMPDIR: hostEnv.TMPDIR,
150
+ LANG: hostEnv.LANG,
151
+ LC_ALL: hostEnv.LC_ALL,
152
+ CODEX_HOME: codexHome,
153
+ }).filter(([, value]) => value !== undefined),
154
+ );
155
+ }
156
+
157
+ function binaryFingerprint(binary) {
158
+ const stat = statSync(binary, { bigint: true });
159
+ if (!stat.isFile()) {
160
+ throw new CodexAppServerError(
161
+ 'pinned Codex binary is not a regular file',
162
+ 'CODEX_BINARY_MISMATCH',
163
+ );
164
+ }
165
+ return {
166
+ dev: stat.dev.toString(),
167
+ ino: stat.ino.toString(),
168
+ size: stat.size.toString(),
169
+ mtimeNs: stat.mtimeNs.toString(),
170
+ ctimeNs: stat.ctimeNs.toString(),
171
+ mode: Number(stat.mode),
172
+ uid: Number(stat.uid),
173
+ nlink: Number(stat.nlink),
174
+ };
175
+ }
176
+
177
+ async function hashFile(binary) {
178
+ const hash = createHash('sha256');
179
+ await new Promise((resolve, reject) => {
180
+ const stream = createReadStream(binary);
181
+ stream.on('data', (chunk) => hash.update(chunk));
182
+ stream.once('error', reject);
183
+ stream.once('end', resolve);
184
+ });
185
+ return hash.digest('hex');
186
+ }
187
+
188
+ async function attestPinnedCodexBinary(binary) {
189
+ if (realpathSync(binary) !== binary) {
190
+ throw new CodexAppServerError(
191
+ 'pinned Codex binary path is not canonical',
192
+ 'CODEX_BINARY_MISMATCH',
193
+ );
194
+ }
195
+ const root = path.parse(binary).root;
196
+ let component = root;
197
+ for (const part of binary.slice(root.length).split('/').filter(Boolean)) {
198
+ component = path.join(component, part);
199
+ const stat = lstatSync(component);
200
+ if (
201
+ stat.isSymbolicLink()
202
+ || ![0, process.getuid?.()].includes(stat.uid)
203
+ || (stat.mode & 0o022) !== 0
204
+ ) {
205
+ throw new CodexAppServerError(
206
+ 'pinned Codex binary path ownership or mode is unsafe',
207
+ 'CODEX_BINARY_MISMATCH',
208
+ );
209
+ }
210
+ }
211
+ const fingerprint = binaryFingerprint(binary);
212
+ if (
213
+ (fingerprint.mode & 0o022) !== 0
214
+ || (process.platform !== 'win32' && (fingerprint.mode & 0o111) === 0)
215
+ || ![0, process.getuid?.()].includes(fingerprint.uid)
216
+ || fingerprint.nlink !== 1
217
+ ) {
218
+ throw new CodexAppServerError(
219
+ 'pinned Codex binary ownership or mode is unsafe',
220
+ 'CODEX_BINARY_MISMATCH',
221
+ );
222
+ }
223
+ const sha256 = await hashFile(binary);
224
+ if (sha256 !== protocolSchema.binarySha256) {
225
+ throw new CodexAppServerError(
226
+ 'pinned Codex binary hash mismatch',
227
+ 'CODEX_BINARY_MISMATCH',
228
+ );
229
+ }
230
+ let stdout;
231
+ try {
232
+ ({ stdout } = await execFileAsync(binary, ['--version'], {
233
+ encoding: 'utf8',
234
+ timeout: 10_000,
235
+ maxBuffer: 4 * 1024,
236
+ env: { PATH: CONTROLLED_PATH },
237
+ }));
238
+ } catch {
239
+ throw new CodexAppServerError(
240
+ 'pinned Codex binary version probe failed',
241
+ 'CODEX_BINARY_MISMATCH',
242
+ );
243
+ }
244
+ if (stdout.trim() !== protocolSchema.cliVersion) {
245
+ throw new CodexAppServerError(
246
+ 'pinned Codex binary version mismatch',
247
+ 'CODEX_BINARY_MISMATCH',
248
+ );
249
+ }
250
+ return {
251
+ path: binary,
252
+ sha256,
253
+ version: stdout.trim(),
254
+ fingerprint,
255
+ };
256
+ }
257
+
258
+ function pathFingerprint(target) {
259
+ const stat = lstatSync(target, { bigint: true });
260
+ return {
261
+ dev: stat.dev.toString(),
262
+ ino: stat.ino.toString(),
263
+ size: stat.size.toString(),
264
+ mtimeNs: stat.mtimeNs.toString(),
265
+ ctimeNs: stat.ctimeNs.toString(),
266
+ mode: Number(stat.mode),
267
+ uid: Number(stat.uid),
268
+ nlink: Number(stat.nlink),
269
+ };
270
+ }
271
+
272
+ function canonicalTemporaryRoots() {
273
+ const roots = new Set();
274
+ for (const candidate of [
275
+ os.tmpdir(),
276
+ '/tmp',
277
+ '/private/tmp',
278
+ '/var/tmp',
279
+ '/private/var/folders',
280
+ ]) {
281
+ try {
282
+ roots.add(realpathSync(candidate));
283
+ } catch {}
284
+ }
285
+ return [...roots];
286
+ }
287
+
288
+ function assertSecureOwnedPath(target, {
289
+ kind,
290
+ expectedMode,
291
+ temporaryRoots = canonicalTemporaryRoots(),
292
+ }) {
293
+ if (realpathSync(target) !== target) {
294
+ throw new CodexAppServerError(
295
+ `pinned Codex ${kind} path is not canonical`,
296
+ 'CODEX_CONFIG_MISMATCH',
297
+ );
298
+ }
299
+ if (temporaryRoots.some((root) => isWithin(root, target))) {
300
+ throw new CodexAppServerError(
301
+ `pinned Codex ${kind} cannot be stored in a temporary directory`,
302
+ 'CODEX_CONFIG_MISMATCH',
303
+ );
304
+ }
305
+ const root = path.parse(target).root;
306
+ let component = root;
307
+ for (const part of target.slice(root.length).split('/').filter(Boolean)) {
308
+ component = path.join(component, part);
309
+ const stat = lstatSync(component);
310
+ const isTarget = component === target;
311
+ if (
312
+ stat.isSymbolicLink()
313
+ || ![0, process.getuid?.()].includes(stat.uid)
314
+ || (stat.mode & 0o022) !== 0
315
+ || (
316
+ isTarget
317
+ && expectedMode !== undefined
318
+ && (stat.mode & 0o777) !== expectedMode
319
+ )
320
+ ) {
321
+ throw new CodexAppServerError(
322
+ `pinned Codex ${kind} ownership or mode is unsafe`,
323
+ 'CODEX_CONFIG_MISMATCH',
324
+ );
325
+ }
326
+ }
327
+ }
328
+
329
+ function assertSecureCredentialFile(file, label) {
330
+ const stat = lstatSync(file);
331
+ if (
332
+ stat.isSymbolicLink()
333
+ || !stat.isFile()
334
+ || (
335
+ typeof process.getuid === 'function'
336
+ && stat.uid !== process.getuid()
337
+ )
338
+ || (stat.mode & 0o777) !== 0o600
339
+ || stat.nlink !== 1
340
+ ) {
341
+ throw new CodexAppServerError(
342
+ `pinned Codex ${label} ownership or mode is unsafe`,
343
+ 'CODEX_CONFIG_MISMATCH',
344
+ );
345
+ }
346
+ return pathFingerprint(file);
347
+ }
348
+
349
+ async function attestPinnedCodexHome(
350
+ codexHome,
351
+ expectedConfigSha256,
352
+ { temporaryRoots = canonicalTemporaryRoots() } = {},
353
+ ) {
354
+ if (
355
+ typeof expectedConfigSha256 !== 'string'
356
+ || !/^[a-f0-9]{64}$/.test(expectedConfigSha256)
357
+ ) {
358
+ throw new TypeError(
359
+ 'CodexAppServerClient: expectedConfigSha256 must be a lowercase SHA-256',
360
+ );
361
+ }
362
+ assertSecureOwnedPath(codexHome, {
363
+ kind: 'credential home',
364
+ expectedMode: 0o700,
365
+ temporaryRoots,
366
+ });
367
+ const homeStat = lstatSync(codexHome);
368
+ if (!homeStat.isDirectory() || homeStat.nlink < 1) {
369
+ throw new CodexAppServerError(
370
+ 'pinned Codex credential home is not a directory',
371
+ 'CODEX_CONFIG_MISMATCH',
372
+ );
373
+ }
374
+
375
+ const configPath = path.join(codexHome, 'config.toml');
376
+ const configFingerprint = assertSecureCredentialFile(
377
+ configPath,
378
+ 'config.toml',
379
+ );
380
+ const configSha256 = await hashFile(configPath);
381
+ if (configSha256 !== expectedConfigSha256) {
382
+ throw new CodexAppServerError(
383
+ 'pinned Codex config.toml hash mismatch',
384
+ 'CODEX_CONFIG_MISMATCH',
385
+ );
386
+ }
387
+
388
+ const authPath = path.join(codexHome, 'auth.json');
389
+ let authFingerprint = null;
390
+ try {
391
+ authFingerprint = assertSecureCredentialFile(authPath, 'auth.json');
392
+ } catch (error) {
393
+ if (error?.code !== 'ENOENT') throw error;
394
+ }
395
+ return {
396
+ path: codexHome,
397
+ configSha256,
398
+ configFingerprint,
399
+ authFingerprint,
400
+ };
401
+ }
402
+
403
+ function assertAbsolute(value, label) {
404
+ if (typeof value !== 'string' || !path.isAbsolute(value)) {
405
+ throw new TypeError(`CodexAppServerClient: ${label} must be an absolute path`);
406
+ }
407
+ }
408
+
409
+ function assertPositiveInteger(value, label) {
410
+ if (!Number.isSafeInteger(value) || value <= 0) {
411
+ throw new TypeError(`CodexAppServerClient: ${label} must be a positive integer`);
412
+ }
413
+ }
414
+
415
+ // Beyond this a delay silently collapses to ~1ms instead of waiting, which
416
+ // would turn a long close budget into no budget at all.
417
+ function assertTimerDelay(value, label) {
418
+ assertPositiveInteger(value, label);
419
+ if (value > MAX_TIMER_DELAY_MS) {
420
+ throw new TypeError(
421
+ `CodexAppServerClient: ${label} must not exceed ${MAX_TIMER_DELAY_MS}`,
422
+ );
423
+ }
424
+ }
425
+
426
+ function isWithin(root, candidate) {
427
+ const relative = path.relative(root, candidate);
428
+ return (
429
+ relative === ''
430
+ || (!relative.startsWith('..') && !path.isAbsolute(relative))
431
+ );
432
+ }
433
+
434
+ function assertRequestId(id) {
435
+ if (
436
+ !(typeof id === 'string' && id.length > 0 && Buffer.byteLength(id) <= MAX_ID_BYTES)
437
+ && !Number.isSafeInteger(id)
438
+ ) {
439
+ throw new CodexAppServerError(
440
+ 'app-server request ID was outside the pinned schema',
441
+ 'CODEX_PROTOCOL_ERROR',
442
+ );
443
+ }
444
+ }
445
+
446
+ function boundedString(value, label, maxBytes = MAX_ID_BYTES) {
447
+ if (value == null) return undefined;
448
+ if (typeof value !== 'string' || Buffer.byteLength(value) > maxBytes) {
449
+ throw new CodexAppServerError(
450
+ `app-server ${label} exceeded the size limit`,
451
+ 'CODEX_PROTOCOL_ERROR',
452
+ );
453
+ }
454
+ return value;
455
+ }
456
+
457
+ function protocolString(value, label, maxBytes = MAX_ID_BYTES) {
458
+ const projected = boundedString(value, label, maxBytes);
459
+ if (projected === undefined) {
460
+ throw new CodexAppServerError(
461
+ `app-server ${label} must be a string`,
462
+ 'CODEX_PROTOCOL_ERROR',
463
+ );
464
+ }
465
+ return projected;
466
+ }
467
+
468
+ function projectThreadStatus(value, label) {
469
+ const status = protocolObject(value, label);
470
+ const type = protocolRequiredString(status.type, `${label} type`);
471
+ if (!['notLoaded', 'idle', 'systemError', 'active'].includes(type)) {
472
+ throw new CodexAppServerError(
473
+ `app-server ${label} is unsupported`,
474
+ 'CODEX_PROTOCOL_ERROR',
475
+ );
476
+ }
477
+ if (type !== 'active') return { type };
478
+ if (
479
+ !Array.isArray(status.activeFlags)
480
+ || status.activeFlags.length > 32
481
+ || status.activeFlags.some((flag) => (
482
+ !['waitingOnApproval', 'waitingOnUserInput'].includes(flag)
483
+ ))
484
+ ) {
485
+ throw new CodexAppServerError(
486
+ `app-server ${label} active flags are malformed`,
487
+ 'CODEX_PROTOCOL_ERROR',
488
+ );
489
+ }
490
+ return { type, activeFlags: [...status.activeFlags] };
491
+ }
492
+
493
+ function projectCollaborationMode(value) {
494
+ const collaboration = protocolObject(value, 'collaboration mode');
495
+ const mode = protocolRequiredString(collaboration.mode, 'collaboration mode');
496
+ if (!['plan', 'default'].includes(mode)) {
497
+ throw new CodexAppServerError(
498
+ 'app-server collaboration mode is unsupported',
499
+ 'CODEX_PROTOCOL_ERROR',
500
+ );
501
+ }
502
+ const settings = protocolObject(
503
+ collaboration.settings,
504
+ 'collaboration mode settings',
505
+ );
506
+ const projected = {
507
+ mode,
508
+ model: protocolRequiredString(
509
+ settings.model,
510
+ 'collaboration mode model',
511
+ ),
512
+ };
513
+ if (settings.reasoning_effort != null) {
514
+ projected.reasoningEffort = protocolRequiredString(
515
+ settings.reasoning_effort,
516
+ 'collaboration mode reasoning effort',
517
+ );
518
+ }
519
+ if (
520
+ settings.developer_instructions !== undefined
521
+ && settings.developer_instructions !== null
522
+ ) {
523
+ protocolString(
524
+ settings.developer_instructions,
525
+ 'collaboration mode developer instructions',
526
+ MAX_TEXT_BYTES,
527
+ );
528
+ }
529
+ return projected;
530
+ }
531
+
532
+ function projectNotification(message, ownedCwd) {
533
+ const source = protocolObject(
534
+ message.params ?? {},
535
+ `${message.method} notification parameters`,
536
+ );
537
+ const params = {};
538
+ const requiredIds = new Set();
539
+ if (
540
+ message.method === 'thread/status/changed'
541
+ || message.method === 'thread/settings/updated'
542
+ || message.method === 'turn/started'
543
+ || message.method === 'turn/completed'
544
+ ) requiredIds.add('threadId');
545
+ if (
546
+ message.method === 'error'
547
+ || message.method === 'item/started'
548
+ || message.method === 'item/completed'
549
+ || message.method === 'item/agentMessage/delta'
550
+ ) {
551
+ requiredIds.add('threadId');
552
+ requiredIds.add('turnId');
553
+ }
554
+ if (message.method === 'item/agentMessage/delta') requiredIds.add('itemId');
555
+ for (const key of ['threadId', 'turnId', 'itemId']) {
556
+ const value = requiredIds.has(key)
557
+ ? protocolRequiredString(source[key], `notification ${key}`)
558
+ : boundedString(source[key], `notification ${key}`);
559
+ if (value !== undefined) params[key] = value;
560
+ }
561
+
562
+ if (message.method === 'error') {
563
+ if (typeof source.willRetry !== 'boolean' || source.error == null) {
564
+ throw new CodexAppServerError(
565
+ 'app-server error notification omitted retry ownership',
566
+ 'CODEX_PROTOCOL_ERROR',
567
+ );
568
+ }
569
+ protocolObject(source.error, 'error notification payload');
570
+ params.willRetry = source.willRetry;
571
+ params.error = { present: source.error != null };
572
+ } else if (message.method === 'thread/status/changed') {
573
+ params.status = projectThreadStatus(source.status, 'thread status');
574
+ } else if (message.method === 'thread/settings/updated') {
575
+ const settings = protocolObject(
576
+ source.threadSettings,
577
+ 'thread settings',
578
+ );
579
+ if (settings.cwd !== ownedCwd) {
580
+ throw new CodexAppServerError(
581
+ 'app-server thread settings changed the owned workspace',
582
+ 'CODEX_PROTOCOL_ERROR',
583
+ );
584
+ }
585
+ const reviewer = protocolRequiredString(
586
+ settings.approvalsReviewer,
587
+ 'thread settings approvals reviewer',
588
+ );
589
+ if (!['user', 'auto_review', 'guardian_subagent'].includes(reviewer)) {
590
+ throw new CodexAppServerError(
591
+ 'app-server thread settings approvals reviewer is unsupported',
592
+ 'CODEX_PROTOCOL_ERROR',
593
+ );
594
+ }
595
+ params.threadSettings = {
596
+ model: protocolRequiredString(settings.model, 'thread settings model'),
597
+ modelProvider: protocolRequiredString(
598
+ settings.modelProvider,
599
+ 'thread settings model provider',
600
+ ),
601
+ approvalPolicy: projectApprovalPolicy(settings.approvalPolicy),
602
+ approvalsReviewer: reviewer,
603
+ collaborationMode: projectCollaborationMode(
604
+ settings.collaborationMode,
605
+ ),
606
+ sandboxPolicy: projectSandbox(settings.sandboxPolicy, ownedCwd),
607
+ };
608
+ if (settings.effort != null) {
609
+ params.threadSettings.effort = protocolRequiredString(
610
+ settings.effort,
611
+ 'thread settings effort',
612
+ );
613
+ }
614
+ const profile = settings.activePermissionProfile;
615
+ if (profile != null) {
616
+ params.threadSettings.activePermissionProfile = {
617
+ id: protocolRequiredString(profile.id, 'permission profile id'),
618
+ extends: profile.extends == null
619
+ ? null
620
+ : boundedString(profile.extends, 'permission profile parent'),
621
+ };
622
+ }
623
+ } else if (
624
+ message.method === 'turn/started'
625
+ || message.method === 'turn/completed'
626
+ ) {
627
+ const turn = projectTurn(source.turn, 'notification turn');
628
+ params.turn = {
629
+ id: turn.id,
630
+ status: turn.status,
631
+ };
632
+ if (message.method === 'turn/completed') {
633
+ params.turn.error = turn.error;
634
+ params.turn.items = turn.items;
635
+ }
636
+ } else if (
637
+ message.method === 'item/started'
638
+ || message.method === 'item/completed'
639
+ ) {
640
+ const timestamp = message.method === 'item/started'
641
+ ? source.startedAtMs
642
+ : source.completedAtMs;
643
+ if (!Number.isSafeInteger(timestamp)) {
644
+ throw new CodexAppServerError(
645
+ 'app-server item notification timestamp is malformed',
646
+ 'CODEX_PROTOCOL_ERROR',
647
+ );
648
+ }
649
+ const item = protocolObject(source.item, 'notification item');
650
+ params.item = {
651
+ id: protocolRequiredString(item.id, 'item id'),
652
+ type: protocolRequiredString(item.type, 'item type'),
653
+ };
654
+ const clientId = boundedString(item.clientId, 'item client id');
655
+ if (clientId !== undefined) params.item.clientId = clientId;
656
+ if (item.type === 'agentMessage') {
657
+ const text = boundedString(item.text, 'agent message', MAX_TEXT_BYTES);
658
+ if (text !== undefined) params.item.text = text;
659
+ }
660
+ } else if (message.method === 'item/agentMessage/delta') {
661
+ params.delta = protocolString(
662
+ source.delta,
663
+ 'agent message delta',
664
+ MAX_TEXT_BYTES,
665
+ );
666
+ }
667
+ return { method: message.method, params };
668
+ }
669
+
670
+ function plainObject(value, label) {
671
+ if (
672
+ !value
673
+ || typeof value !== 'object'
674
+ || Array.isArray(value)
675
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))
676
+ ) {
677
+ throw new CodexAppServerError(
678
+ `app-server ${label} must be a plain object`,
679
+ 'CODEX_RPC_REJECTED',
680
+ );
681
+ }
682
+ return value;
683
+ }
684
+
685
+ function protocolObject(value, label) {
686
+ try {
687
+ return plainObject(value, label);
688
+ } catch (error) {
689
+ throw new CodexAppServerError(
690
+ `app-server ${label} must be a plain object`,
691
+ 'CODEX_PROTOCOL_ERROR',
692
+ { cause: error },
693
+ );
694
+ }
695
+ }
696
+
697
+ function boundedRequiredString(value, label, maxBytes = MAX_ID_BYTES) {
698
+ const projected = boundedString(value, label, maxBytes);
699
+ if (projected === undefined || projected.length === 0) {
700
+ throw new CodexAppServerError(
701
+ `app-server ${label} is required`,
702
+ 'CODEX_RPC_REJECTED',
703
+ );
704
+ }
705
+ return projected;
706
+ }
707
+
708
+ function protocolRequiredString(value, label, maxBytes = MAX_ID_BYTES) {
709
+ const projected = boundedString(value, label, maxBytes);
710
+ if (projected === undefined || projected.length === 0) {
711
+ throw new CodexAppServerError(
712
+ `app-server ${label} is required`,
713
+ 'CODEX_PROTOCOL_ERROR',
714
+ );
715
+ }
716
+ return projected;
717
+ }
718
+
719
+ function protocolOptionalCursor(value, label = 'pagination cursor') {
720
+ if (value == null) return null;
721
+ return protocolRequiredString(value, label);
722
+ }
723
+
724
+ function cloneBoundedJson(value, label) {
725
+ let nodes = 0;
726
+ const clone = (current, depth) => {
727
+ nodes += 1;
728
+ if (nodes > MAX_RESPONSE_NODES || depth > MAX_RESPONSE_DEPTH) {
729
+ throw new CodexAppServerError(
730
+ `app-server ${label} exceeded structural bounds`,
731
+ 'CODEX_PROTOCOL_ERROR',
732
+ );
733
+ }
734
+ if (current === null || typeof current === 'boolean') return current;
735
+ if (typeof current === 'string') {
736
+ return protocolString(current, label, MAX_TEXT_BYTES);
737
+ }
738
+ if (typeof current === 'number' && Number.isFinite(current)) return current;
739
+ if (Array.isArray(current)) {
740
+ if (current.length > MAX_RESPONSE_ARRAY_ITEMS) {
741
+ throw new CodexAppServerError(
742
+ `app-server ${label} array exceeded the size limit`,
743
+ 'CODEX_PROTOCOL_ERROR',
744
+ );
745
+ }
746
+ return current.map((entry) => clone(entry, depth + 1));
747
+ }
748
+ const object = protocolObject(current, label);
749
+ const entries = Object.entries(object);
750
+ if (entries.length > MAX_RESPONSE_OBJECT_KEYS) {
751
+ throw new CodexAppServerError(
752
+ `app-server ${label} object exceeded the size limit`,
753
+ 'CODEX_PROTOCOL_ERROR',
754
+ );
755
+ }
756
+ return Object.fromEntries(entries.map(([key, entry]) => [
757
+ protocolString(key, `${label} key`),
758
+ clone(entry, depth + 1),
759
+ ]));
760
+ };
761
+ return clone(value, 0);
762
+ }
763
+
764
+ function canonicalJson(value) {
765
+ if (Array.isArray(value)) return value.map(canonicalJson);
766
+ if (value && typeof value === 'object') {
767
+ return Object.fromEntries(
768
+ Object.keys(value)
769
+ .sort()
770
+ .map((key) => [key, canonicalJson(value[key])]),
771
+ );
772
+ }
773
+ return value;
774
+ }
775
+
776
+ function jsonDigest(value) {
777
+ return createHash('sha256')
778
+ .update(JSON.stringify(canonicalJson(value)))
779
+ .digest('hex');
780
+ }
781
+
782
+ function projectedOptionalString(value, label, maxBytes = MAX_ID_BYTES) {
783
+ if (value == null) return null;
784
+ return protocolString(value, label, maxBytes);
785
+ }
786
+
787
+ function objectKeys(value, label) {
788
+ if (value == null) return [];
789
+ return Object.keys(protocolObject(value, label))
790
+ .map((key) => protocolString(key, `${label} key`))
791
+ .sort();
792
+ }
793
+
794
+ function projectedObjectIndex(value, label) {
795
+ const keys = objectKeys(value, label);
796
+ return {
797
+ count: keys.length,
798
+ keySha256: keys
799
+ .map((key) => createHash('sha256').update(key).digest('hex'))
800
+ .sort(),
801
+ };
802
+ }
803
+
804
+ function projectEffectiveConfig(value) {
805
+ const config = cloneBoundedJson(value, 'config');
806
+ const profileSource = config.permissions == null
807
+ ? {}
808
+ : protocolObject(config.permissions, 'permission profiles');
809
+ const permissionProfiles = Object.entries(profileSource)
810
+ .map(([id, rawProfile]) => {
811
+ const profile = protocolObject(rawProfile, 'permission profile config');
812
+ const filesystem = profile.filesystem == null
813
+ ? {}
814
+ : protocolObject(profile.filesystem, 'permission profile filesystem');
815
+ const network = profile.network == null
816
+ ? {}
817
+ : protocolObject(profile.network, 'permission profile network');
818
+ if (
819
+ network.enabled !== undefined
820
+ && typeof network.enabled !== 'boolean'
821
+ ) {
822
+ throw new CodexAppServerError(
823
+ 'app-server permission profile network policy is malformed',
824
+ 'CODEX_PROTOCOL_ERROR',
825
+ );
826
+ }
827
+ return {
828
+ id: protocolRequiredString(id, 'permission profile id'),
829
+ extends: projectedOptionalString(
830
+ profile.extends,
831
+ 'permission profile parent',
832
+ ),
833
+ networkEnabled: network.enabled ?? null,
834
+ filesystemSha256: jsonDigest(filesystem),
835
+ filesystem: Object.entries(filesystem)
836
+ .filter(([, access]) => typeof access === 'string')
837
+ .map(([root, access]) => ({
838
+ rootSha256: createHash('sha256').update(root).digest('hex'),
839
+ access: protocolRequiredString(
840
+ access,
841
+ 'permission profile filesystem access',
842
+ ),
843
+ }))
844
+ .sort((left, right) => (
845
+ left.rootSha256.localeCompare(right.rootSha256)
846
+ )),
847
+ };
848
+ })
849
+ .sort((left, right) => left.id.localeCompare(right.id));
850
+ const shellEnvironment = config.shell_environment_policy == null
851
+ ? {}
852
+ : protocolObject(
853
+ config.shell_environment_policy,
854
+ 'shell environment policy',
855
+ );
856
+ if (
857
+ config.allow_login_shell !== undefined
858
+ && typeof config.allow_login_shell !== 'boolean'
859
+ ) {
860
+ throw new CodexAppServerError(
861
+ 'app-server login shell policy is malformed',
862
+ 'CODEX_PROTOCOL_ERROR',
863
+ );
864
+ }
865
+ return {
866
+ sha256: jsonDigest(config),
867
+ model: projectedOptionalString(config.model, 'configured model'),
868
+ modelProvider: projectedOptionalString(
869
+ config.model_provider,
870
+ 'configured model provider',
871
+ ),
872
+ defaultPermissions: projectedOptionalString(
873
+ config.default_permissions,
874
+ 'default permission profile',
875
+ ),
876
+ approvalPolicy: config.approval_policy == null
877
+ ? null
878
+ : projectApprovalPolicy(config.approval_policy),
879
+ approvalsReviewer: projectedOptionalString(
880
+ config.approvals_reviewer,
881
+ 'configured approvals reviewer',
882
+ ),
883
+ webSearch: projectedOptionalString(config.web_search, 'web search policy'),
884
+ allowLoginShell: config.allow_login_shell ?? null,
885
+ shellEnvironmentInherit: projectedOptionalString(
886
+ shellEnvironment.inherit,
887
+ 'shell environment inheritance',
888
+ ),
889
+ permissionProfiles,
890
+ mcpServers: projectedObjectIndex(config.mcp_servers, 'MCP servers'),
891
+ plugins: projectedObjectIndex(config.plugins, 'plugins'),
892
+ modelProviders: projectedObjectIndex(
893
+ config.model_providers,
894
+ 'model providers',
895
+ ),
896
+ };
897
+ }
898
+
899
+ function projectConfigLayer(value) {
900
+ const layer = protocolObject(value, 'config layer');
901
+ const name = (
902
+ typeof layer.name === 'string'
903
+ ? { type: layer.name }
904
+ : protocolObject(layer.name, 'config layer source')
905
+ );
906
+ return {
907
+ type: protocolRequiredString(name.type, 'config layer source type'),
908
+ version: protocolString(layer.version, 'config layer version'),
909
+ disabled: layer.disabledReason != null,
910
+ configSha256: jsonDigest(cloneBoundedJson(layer.config, 'config layer')),
911
+ };
912
+ }
913
+
914
+ function projectTurn(value, label) {
915
+ const turn = protocolObject(value, label);
916
+ if (!Array.isArray(turn.items) || turn.items.length > MAX_COMPLETED_ITEMS) {
917
+ throw new CodexAppServerError(
918
+ `app-server ${label} item list exceeded the size limit`,
919
+ 'CODEX_PROTOCOL_ERROR',
920
+ );
921
+ }
922
+ const status = protocolRequiredString(turn.status, `${label} status`);
923
+ if (!['completed', 'interrupted', 'failed', 'inProgress'].includes(status)) {
924
+ throw new CodexAppServerError(
925
+ `app-server ${label} status is unsupported`,
926
+ 'CODEX_PROTOCOL_ERROR',
927
+ );
928
+ }
929
+ return {
930
+ id: protocolRequiredString(turn.id, `${label} id`),
931
+ status,
932
+ items: turn.items.map((item) => {
933
+ const projected = protocolObject(item, `${label} item`);
934
+ return {
935
+ id: protocolRequiredString(projected.id, `${label} item id`),
936
+ type: protocolRequiredString(projected.type, `${label} item type`),
937
+ };
938
+ }),
939
+ error: turn.error == null ? null : { present: true },
940
+ };
941
+ }
942
+
943
+ function projectThread(value, label, ownedCwd, modelProvider) {
944
+ const thread = protocolObject(value, label);
945
+ const status = projectThreadStatus(thread.status, `${label} status`);
946
+ if (!Array.isArray(thread.turns) || thread.turns.length > MAX_COMPLETED_ITEMS) {
947
+ throw new CodexAppServerError(
948
+ `app-server ${label} turn list exceeded the size limit`,
949
+ 'CODEX_PROTOCOL_ERROR',
950
+ );
951
+ }
952
+ for (const [key, maxBytes] of [
953
+ ['cliVersion', MAX_ID_BYTES],
954
+ ['cwd', MAX_TEXT_BYTES],
955
+ ['id', MAX_ID_BYTES],
956
+ ['modelProvider', MAX_ID_BYTES],
957
+ ['preview', MAX_TEXT_BYTES],
958
+ ['sessionId', MAX_ID_BYTES],
959
+ ['source', MAX_ID_BYTES],
960
+ ]) {
961
+ protocolString(thread[key], `${label} ${key}`, maxBytes);
962
+ }
963
+ if (
964
+ !Number.isSafeInteger(thread.createdAt)
965
+ || !Number.isSafeInteger(thread.updatedAt)
966
+ || typeof thread.ephemeral !== 'boolean'
967
+ || thread.cwd !== ownedCwd
968
+ || thread.modelProvider !== modelProvider
969
+ ) {
970
+ throw new CodexAppServerError(
971
+ `app-server ${label} metadata is malformed`,
972
+ 'CODEX_PROTOCOL_ERROR',
973
+ );
974
+ }
975
+ return {
976
+ id: protocolRequiredString(thread.id, `${label} id`),
977
+ status,
978
+ turns: thread.turns.map((turn) => projectTurn(turn, `${label} turn`)),
979
+ };
980
+ }
981
+
982
+ function projectApprovalPolicy(value) {
983
+ if (typeof value === 'string') {
984
+ if (!['untrusted', 'on-request', 'never'].includes(value)) {
985
+ throw new CodexAppServerError(
986
+ 'app-server approval policy is unsupported',
987
+ 'CODEX_PROTOCOL_ERROR',
988
+ );
989
+ }
990
+ return value;
991
+ }
992
+ const policy = protocolObject(value, 'approval policy');
993
+ const granular = protocolObject(policy.granular, 'granular approval policy');
994
+ for (const key of ['mcp_elicitations', 'rules', 'sandbox_approval']) {
995
+ if (typeof granular[key] !== 'boolean') {
996
+ throw new CodexAppServerError(
997
+ 'app-server granular approval policy is malformed',
998
+ 'CODEX_PROTOCOL_ERROR',
999
+ );
1000
+ }
1001
+ }
1002
+ return {
1003
+ granular: {
1004
+ mcp_elicitations: granular.mcp_elicitations,
1005
+ rules: granular.rules,
1006
+ sandbox_approval: granular.sandbox_approval,
1007
+ request_permissions: granular.request_permissions === true,
1008
+ skill_approval: granular.skill_approval === true,
1009
+ },
1010
+ };
1011
+ }
1012
+
1013
+ function projectSandbox(value, ownedCwd) {
1014
+ const sandbox = protocolObject(value, 'sandbox policy');
1015
+ const type = protocolRequiredString(sandbox.type, 'sandbox policy type');
1016
+ if (
1017
+ ![
1018
+ 'dangerFullAccess',
1019
+ 'readOnly',
1020
+ 'externalSandbox',
1021
+ 'workspaceWrite',
1022
+ ].includes(type)
1023
+ ) {
1024
+ throw new CodexAppServerError(
1025
+ 'app-server sandbox policy is unsupported',
1026
+ 'CODEX_PROTOCOL_ERROR',
1027
+ );
1028
+ }
1029
+ const projected = { type };
1030
+ if (sandbox.networkAccess !== undefined) {
1031
+ if (
1032
+ typeof sandbox.networkAccess !== 'boolean'
1033
+ && !['restricted', 'enabled'].includes(sandbox.networkAccess)
1034
+ ) {
1035
+ throw new CodexAppServerError(
1036
+ 'app-server sandbox network policy is malformed',
1037
+ 'CODEX_PROTOCOL_ERROR',
1038
+ );
1039
+ }
1040
+ projected.networkAccess = sandbox.networkAccess;
1041
+ }
1042
+ if (type === 'workspaceWrite') {
1043
+ if (
1044
+ sandbox.writableRoots !== undefined
1045
+ && !Array.isArray(sandbox.writableRoots)
1046
+ ) {
1047
+ throw new CodexAppServerError(
1048
+ 'app-server writable root list is malformed',
1049
+ 'CODEX_PROTOCOL_ERROR',
1050
+ );
1051
+ }
1052
+ const roots = sandbox.writableRoots ?? [];
1053
+ if (roots.length > 64) {
1054
+ throw new CodexAppServerError(
1055
+ 'app-server writable root list is malformed',
1056
+ 'CODEX_PROTOCOL_ERROR',
1057
+ );
1058
+ }
1059
+ const validatedRoots = roots.map((root) => (
1060
+ protocolRequiredString(root, 'sandbox writable root', MAX_TEXT_BYTES)
1061
+ ));
1062
+ if (validatedRoots.some((root) => (
1063
+ !path.isAbsolute(root)
1064
+ || path.normalize(root) !== root
1065
+ || !isWithin(ownedCwd, root)
1066
+ ))) {
1067
+ throw new CodexAppServerError(
1068
+ 'app-server writable root escaped the owned workspace',
1069
+ 'CODEX_PROTOCOL_ERROR',
1070
+ );
1071
+ }
1072
+ projected.writableRootCount = validatedRoots.length;
1073
+ projected.writableRootSha256 = validatedRoots
1074
+ .map((root) => createHash('sha256').update(root).digest('hex'))
1075
+ .sort();
1076
+ }
1077
+ return projected;
1078
+ }
1079
+
1080
+ function projectRpcResult(method, value, ownedCwd) {
1081
+ const result = protocolObject(value, `${method} result`);
1082
+ if (method === 'initialize') {
1083
+ return {
1084
+ codexHome: protocolRequiredString(
1085
+ result.codexHome,
1086
+ 'initialized credential home',
1087
+ MAX_TEXT_BYTES,
1088
+ ),
1089
+ platformFamily: protocolRequiredString(
1090
+ result.platformFamily,
1091
+ 'server platform family',
1092
+ ),
1093
+ platformOs: protocolRequiredString(result.platformOs, 'server platform OS'),
1094
+ userAgent: protocolRequiredString(
1095
+ result.userAgent,
1096
+ 'server user agent',
1097
+ 4_096,
1098
+ ),
1099
+ };
1100
+ }
1101
+ if (method === 'config/read') {
1102
+ if (
1103
+ !Array.isArray(result.layers)
1104
+ || result.layers.length > 64
1105
+ ) {
1106
+ throw new CodexAppServerError(
1107
+ 'app-server config layers must be an array',
1108
+ 'CODEX_PROTOCOL_ERROR',
1109
+ );
1110
+ }
1111
+ const origins = cloneBoundedJson(result.origins, 'config origins');
1112
+ return {
1113
+ config: projectEffectiveConfig(result.config),
1114
+ layers: result.layers.map(projectConfigLayer),
1115
+ originsSha256: jsonDigest(origins),
1116
+ };
1117
+ }
1118
+ if (method === 'configRequirements/read') {
1119
+ const requirements = result.requirements == null
1120
+ ? null
1121
+ : cloneBoundedJson(result.requirements, 'config requirements');
1122
+ return {
1123
+ requirements: requirements == null
1124
+ ? null
1125
+ : {
1126
+ sha256: jsonDigest(requirements),
1127
+ keys: objectKeys(requirements, 'config requirements'),
1128
+ },
1129
+ };
1130
+ }
1131
+ if (method === 'permissionProfile/list') {
1132
+ if (!Array.isArray(result.data) || result.data.length > 100) {
1133
+ throw new CodexAppServerError(
1134
+ 'app-server permission profile page exceeded the size limit',
1135
+ 'CODEX_PROTOCOL_ERROR',
1136
+ );
1137
+ }
1138
+ return {
1139
+ data: result.data.map((profile) => {
1140
+ const source = protocolObject(profile, 'permission profile');
1141
+ if (typeof source.allowed !== 'boolean') {
1142
+ throw new CodexAppServerError(
1143
+ 'app-server permission profile allowed flag is malformed',
1144
+ 'CODEX_PROTOCOL_ERROR',
1145
+ );
1146
+ }
1147
+ return {
1148
+ id: protocolRequiredString(source.id, 'permission profile id'),
1149
+ allowed: source.allowed,
1150
+ descriptionSha256: source.description == null
1151
+ ? null
1152
+ : createHash('sha256')
1153
+ .update(protocolString(
1154
+ source.description,
1155
+ 'permission profile description',
1156
+ MAX_TEXT_BYTES,
1157
+ ))
1158
+ .digest('hex'),
1159
+ };
1160
+ }),
1161
+ nextCursor: protocolOptionalCursor(result.nextCursor),
1162
+ };
1163
+ }
1164
+ if (method === 'account/read') {
1165
+ if (typeof result.requiresOpenaiAuth !== 'boolean') {
1166
+ throw new CodexAppServerError(
1167
+ 'app-server account auth requirement is malformed',
1168
+ 'CODEX_PROTOCOL_ERROR',
1169
+ );
1170
+ }
1171
+ if (result.account == null) {
1172
+ return {
1173
+ account: null,
1174
+ requiresOpenaiAuth: result.requiresOpenaiAuth,
1175
+ };
1176
+ }
1177
+ const account = protocolObject(result.account, 'account');
1178
+ const type = protocolRequiredString(account.type, 'account type');
1179
+ if (!['apiKey', 'chatgpt', 'amazonBedrock'].includes(type)) {
1180
+ throw new CodexAppServerError(
1181
+ 'app-server account type is unsupported',
1182
+ 'CODEX_PROTOCOL_ERROR',
1183
+ );
1184
+ }
1185
+ if (type === 'chatgpt') {
1186
+ if (account.email !== null) {
1187
+ protocolString(account.email, 'ChatGPT account email', MAX_TEXT_BYTES);
1188
+ }
1189
+ const planType = protocolRequiredString(
1190
+ account.planType,
1191
+ 'ChatGPT plan type',
1192
+ );
1193
+ if (![
1194
+ 'free',
1195
+ 'go',
1196
+ 'plus',
1197
+ 'pro',
1198
+ 'prolite',
1199
+ 'team',
1200
+ 'self_serve_business_usage_based',
1201
+ 'business',
1202
+ 'enterprise_cbp_usage_based',
1203
+ 'enterprise',
1204
+ 'edu',
1205
+ 'unknown',
1206
+ ].includes(planType)) {
1207
+ throw new CodexAppServerError(
1208
+ 'app-server ChatGPT plan type is unsupported',
1209
+ 'CODEX_PROTOCOL_ERROR',
1210
+ );
1211
+ }
1212
+ }
1213
+ if (
1214
+ type === 'amazonBedrock'
1215
+ && account.usesCodexManagedCredentials !== undefined
1216
+ && typeof account.usesCodexManagedCredentials !== 'boolean'
1217
+ ) {
1218
+ throw new CodexAppServerError(
1219
+ 'app-server Bedrock credential flag is malformed',
1220
+ 'CODEX_PROTOCOL_ERROR',
1221
+ );
1222
+ }
1223
+ return {
1224
+ account: { type },
1225
+ requiresOpenaiAuth: result.requiresOpenaiAuth,
1226
+ };
1227
+ }
1228
+ if (method === 'model/list') {
1229
+ if (!Array.isArray(result.data) || result.data.length > 100) {
1230
+ throw new CodexAppServerError(
1231
+ 'app-server model page exceeded the size limit',
1232
+ 'CODEX_PROTOCOL_ERROR',
1233
+ );
1234
+ }
1235
+ return {
1236
+ data: result.data.map((model) => {
1237
+ const source = protocolObject(model, 'model');
1238
+ if (
1239
+ typeof source.hidden !== 'boolean'
1240
+ || typeof source.isDefault !== 'boolean'
1241
+ || !Array.isArray(source.supportedReasoningEfforts)
1242
+ || source.supportedReasoningEfforts.length > 32
1243
+ ) {
1244
+ throw new CodexAppServerError(
1245
+ 'app-server model catalog entry is malformed',
1246
+ 'CODEX_PROTOCOL_ERROR',
1247
+ );
1248
+ }
1249
+ const projected = {
1250
+ id: protocolRequiredString(source.id, 'model id'),
1251
+ model: protocolRequiredString(source.model, 'model slug'),
1252
+ description: protocolString(
1253
+ source.description,
1254
+ 'model description',
1255
+ MAX_TEXT_BYTES,
1256
+ ),
1257
+ displayName: protocolString(source.displayName, 'model display name'),
1258
+ defaultReasoningEffort: protocolRequiredString(
1259
+ source.defaultReasoningEffort,
1260
+ 'model default reasoning effort',
1261
+ ),
1262
+ hidden: source.hidden,
1263
+ isDefault: source.isDefault,
1264
+ };
1265
+ projected.supportedReasoningEfforts = source.supportedReasoningEfforts
1266
+ .map((entry) => {
1267
+ const effort = protocolObject(entry, 'model reasoning effort');
1268
+ protocolString(
1269
+ effort.description,
1270
+ 'model reasoning effort description',
1271
+ MAX_TEXT_BYTES,
1272
+ );
1273
+ return protocolRequiredString(
1274
+ effort.reasoningEffort,
1275
+ 'model reasoning effort',
1276
+ );
1277
+ });
1278
+ if (
1279
+ new Set(projected.supportedReasoningEfforts).size
1280
+ !== projected.supportedReasoningEfforts.length
1281
+ ||
1282
+ !projected.supportedReasoningEfforts
1283
+ .includes(projected.defaultReasoningEffort)
1284
+ ) {
1285
+ throw new CodexAppServerError(
1286
+ 'app-server model default reasoning effort is unsupported',
1287
+ 'CODEX_PROTOCOL_ERROR',
1288
+ );
1289
+ }
1290
+ return projected;
1291
+ }),
1292
+ nextCursor: protocolOptionalCursor(result.nextCursor),
1293
+ };
1294
+ }
1295
+ if (method === 'thread/start' || method === 'thread/resume') {
1296
+ if (
1297
+ result.cwd !== ownedCwd
1298
+ || !['user', 'auto_review', 'guardian_subagent']
1299
+ .includes(result.approvalsReviewer)
1300
+ ) {
1301
+ throw new CodexAppServerError(
1302
+ 'app-server thread policy response is inconsistent',
1303
+ 'CODEX_PROTOCOL_ERROR',
1304
+ );
1305
+ }
1306
+ const projected = {
1307
+ cwd: ownedCwd,
1308
+ model: protocolRequiredString(result.model, 'thread model'),
1309
+ modelProvider: protocolRequiredString(
1310
+ result.modelProvider,
1311
+ 'thread model provider',
1312
+ ),
1313
+ approvalPolicy: projectApprovalPolicy(result.approvalPolicy),
1314
+ approvalsReviewer: result.approvalsReviewer,
1315
+ sandbox: projectSandbox(result.sandbox, ownedCwd),
1316
+ };
1317
+ projected.thread = projectThread(
1318
+ result.thread,
1319
+ 'thread',
1320
+ ownedCwd,
1321
+ projected.modelProvider,
1322
+ );
1323
+ if (result.reasoningEffort != null) {
1324
+ projected.reasoningEffort = protocolRequiredString(
1325
+ result.reasoningEffort,
1326
+ 'thread reasoning effort',
1327
+ );
1328
+ }
1329
+ if (result.activePermissionProfile != null) {
1330
+ const profile = protocolObject(
1331
+ result.activePermissionProfile,
1332
+ 'active permission profile',
1333
+ );
1334
+ projected.activePermissionProfile = {
1335
+ id: protocolRequiredString(profile.id, 'permission profile id'),
1336
+ extends: profile.extends == null
1337
+ ? null
1338
+ : protocolRequiredString(profile.extends, 'permission profile parent'),
1339
+ };
1340
+ }
1341
+ return projected;
1342
+ }
1343
+ if (method === 'turn/start') {
1344
+ return { turn: projectTurn(result.turn, 'started turn') };
1345
+ }
1346
+ if (method === 'turn/steer') {
1347
+ return {
1348
+ turnId: protocolRequiredString(result.turnId, 'steered turn id'),
1349
+ };
1350
+ }
1351
+ if (
1352
+ method === 'turn/interrupt'
1353
+ || method === 'thread/backgroundTerminals/clean'
1354
+ ) {
1355
+ if (Object.keys(result).length !== 0) {
1356
+ throw new CodexAppServerError(
1357
+ `app-server ${method} returned an unexpected result`,
1358
+ 'CODEX_PROTOCOL_ERROR',
1359
+ );
1360
+ }
1361
+ return {};
1362
+ }
1363
+ if (method === 'thread/backgroundTerminals/list') {
1364
+ if (!Array.isArray(result.data) || result.data.length > 100) {
1365
+ throw new CodexAppServerError(
1366
+ 'app-server terminal page exceeded the size limit',
1367
+ 'CODEX_PROTOCOL_ERROR',
1368
+ );
1369
+ }
1370
+ return {
1371
+ count: result.data.length,
1372
+ nextCursor: protocolOptionalCursor(result.nextCursor),
1373
+ };
1374
+ }
1375
+ throw new CodexAppServerError(
1376
+ 'app-server result projection is missing',
1377
+ 'CODEX_PROTOCOL_ERROR',
1378
+ );
1379
+ }
1380
+
1381
+ function projectRpcError(value) {
1382
+ const error = protocolObject(value, 'RPC error');
1383
+ if (
1384
+ !Number.isSafeInteger(error.code)
1385
+ || Object.keys(error).some((key) => !['code', 'message', 'data'].includes(key))
1386
+ ) {
1387
+ throw new CodexAppServerError(
1388
+ 'app-server returned a malformed RPC error',
1389
+ 'CODEX_PROTOCOL_ERROR',
1390
+ );
1391
+ }
1392
+ return {
1393
+ code: error.code,
1394
+ message: protocolRequiredString(error.message, 'RPC error message', 4_096),
1395
+ };
1396
+ }
1397
+
1398
+ function projectTextInput(input) {
1399
+ if (!Array.isArray(input) || input.length === 0 || input.length > 64) {
1400
+ throw new CodexAppServerError(
1401
+ 'app-server input list exceeded the supported bounds',
1402
+ 'CODEX_RPC_REJECTED',
1403
+ );
1404
+ }
1405
+ return input.map((item) => {
1406
+ plainObject(item, 'input item');
1407
+ if (
1408
+ Object.keys(item).some((key) => !['type', 'text'].includes(key))
1409
+ || item.type !== 'text'
1410
+ ) {
1411
+ throw new CodexAppServerError(
1412
+ 'app-server input item type is unsupported',
1413
+ 'CODEX_RPC_REJECTED',
1414
+ );
1415
+ }
1416
+ return {
1417
+ type: 'text',
1418
+ text: boundedRequiredString(item.text, 'input text', 256 * 1024),
1419
+ };
1420
+ });
1421
+ }
1422
+
1423
+ function projectRequestParams(method, params, spec, ownedCwd) {
1424
+ if (spec.params === 'omitted') {
1425
+ if (params !== undefined) {
1426
+ throw new CodexAppServerError(
1427
+ `app-server ${method} parameters must be omitted`,
1428
+ 'CODEX_RPC_REJECTED',
1429
+ );
1430
+ }
1431
+ return undefined;
1432
+ }
1433
+ plainObject(params, `${method} parameters`);
1434
+ const allowed = new Set([...spec.required, ...spec.optional]);
1435
+ for (const key of Object.keys(params)) {
1436
+ if (FORBIDDEN_REQUEST_FIELDS.has(key)) {
1437
+ throw new CodexAppServerError(
1438
+ `app-server ${method} forbids ${key}`,
1439
+ 'CODEX_RPC_REJECTED',
1440
+ );
1441
+ }
1442
+ if (!allowed.has(key)) {
1443
+ throw new CodexAppServerError(
1444
+ `app-server ${method} received an unexpected parameter`,
1445
+ 'CODEX_RPC_REJECTED',
1446
+ );
1447
+ }
1448
+ }
1449
+ for (const key of spec.required) {
1450
+ if (!Object.hasOwn(params, key)) {
1451
+ throw new CodexAppServerError(
1452
+ `app-server ${method} omitted a required parameter`,
1453
+ 'CODEX_RPC_REJECTED',
1454
+ );
1455
+ }
1456
+ }
1457
+ const cursor = () => {
1458
+ if (!Object.hasOwn(params, 'cursor')) return {};
1459
+ return { cursor: boundedRequiredString(params.cursor, 'pagination cursor') };
1460
+ };
1461
+ const threadId = () => boundedRequiredString(params.threadId, 'thread id');
1462
+ const clientMessageId = () => (
1463
+ Object.hasOwn(params, 'clientUserMessageId')
1464
+ ? {
1465
+ clientUserMessageId: boundedRequiredString(
1466
+ params.clientUserMessageId,
1467
+ 'client user message id',
1468
+ ),
1469
+ }
1470
+ : {}
1471
+ );
1472
+ if (method === 'initialize') {
1473
+ plainObject(params.clientInfo, 'initialize clientInfo');
1474
+ plainObject(params.capabilities, 'initialize capabilities');
1475
+ if (
1476
+ params.capabilities.experimentalApi !== true
1477
+ || Object.keys(params.capabilities).length !== 1
1478
+ ) {
1479
+ throw new CodexAppServerError(
1480
+ 'app-server initialize capabilities changed',
1481
+ 'CODEX_RPC_REJECTED',
1482
+ );
1483
+ }
1484
+ return {
1485
+ clientInfo: {
1486
+ name: boundedRequiredString(params.clientInfo.name, 'client name'),
1487
+ title: boundedRequiredString(params.clientInfo.title, 'client title'),
1488
+ version: boundedRequiredString(params.clientInfo.version, 'client version'),
1489
+ },
1490
+ capabilities: { experimentalApi: true },
1491
+ };
1492
+ }
1493
+ if (method === 'config/read') {
1494
+ if (params.cwd !== ownedCwd || params.includeLayers !== true) {
1495
+ throw new CodexAppServerError(
1496
+ 'app-server config read must target the owned workspace and layers',
1497
+ 'CODEX_RPC_REJECTED',
1498
+ );
1499
+ }
1500
+ return { cwd: ownedCwd, includeLayers: true };
1501
+ }
1502
+ if (method === 'permissionProfile/list') {
1503
+ if (params.cwd !== ownedCwd) {
1504
+ throw new CodexAppServerError(
1505
+ 'app-server permission profile list changed workspace',
1506
+ 'CODEX_RPC_REJECTED',
1507
+ );
1508
+ }
1509
+ return { cwd: ownedCwd, ...cursor() };
1510
+ }
1511
+ if (method === 'account/read') {
1512
+ if (params.refreshToken !== false) {
1513
+ throw new CodexAppServerError(
1514
+ 'app-server account read cannot refresh credentials',
1515
+ 'CODEX_RPC_REJECTED',
1516
+ );
1517
+ }
1518
+ return { refreshToken: false };
1519
+ }
1520
+ if (method === 'model/list') {
1521
+ if (
1522
+ params.includeHidden !== false
1523
+ || !Number.isSafeInteger(params.limit)
1524
+ || params.limit < 1
1525
+ || params.limit > 100
1526
+ ) {
1527
+ throw new CodexAppServerError(
1528
+ 'app-server model list parameters are outside policy',
1529
+ 'CODEX_RPC_REJECTED',
1530
+ );
1531
+ }
1532
+ return { includeHidden: false, limit: params.limit, ...cursor() };
1533
+ }
1534
+ if (method === 'thread/start') {
1535
+ if (params.cwd !== ownedCwd) {
1536
+ throw new CodexAppServerError(
1537
+ 'app-server thread start changed workspace',
1538
+ 'CODEX_RPC_REJECTED',
1539
+ );
1540
+ }
1541
+ return {
1542
+ cwd: ownedCwd,
1543
+ model: boundedRequiredString(params.model, 'model'),
1544
+ };
1545
+ }
1546
+ if (method === 'thread/resume') return { threadId: threadId() };
1547
+ if (method === 'turn/start') {
1548
+ const projected = {
1549
+ threadId: threadId(),
1550
+ input: projectTextInput(params.input),
1551
+ ...clientMessageId(),
1552
+ };
1553
+ if (Object.hasOwn(params, 'model')) {
1554
+ projected.model = boundedRequiredString(params.model, 'model');
1555
+ }
1556
+ if (Object.hasOwn(params, 'effort')) {
1557
+ const effort = boundedRequiredString(params.effort, 'reasoning effort');
1558
+ if (!['low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(effort)) {
1559
+ throw new CodexAppServerError(
1560
+ 'app-server reasoning effort is unsupported',
1561
+ 'CODEX_RPC_REJECTED',
1562
+ );
1563
+ }
1564
+ projected.effort = effort;
1565
+ }
1566
+ return projected;
1567
+ }
1568
+ if (method === 'turn/steer') {
1569
+ return {
1570
+ threadId: threadId(),
1571
+ expectedTurnId: boundedRequiredString(
1572
+ params.expectedTurnId,
1573
+ 'expected turn id',
1574
+ ),
1575
+ input: projectTextInput(params.input),
1576
+ ...clientMessageId(),
1577
+ };
1578
+ }
1579
+ if (method === 'turn/interrupt') {
1580
+ return {
1581
+ threadId: threadId(),
1582
+ turnId: boundedRequiredString(params.turnId, 'turn id'),
1583
+ };
1584
+ }
1585
+ if (method === 'thread/backgroundTerminals/list') {
1586
+ const projected = { threadId: threadId(), ...cursor() };
1587
+ if (Object.hasOwn(params, 'limit')) {
1588
+ if (
1589
+ !Number.isSafeInteger(params.limit)
1590
+ || params.limit < 1
1591
+ || params.limit > 100
1592
+ ) {
1593
+ throw new CodexAppServerError(
1594
+ 'app-server terminal page limit is outside policy',
1595
+ 'CODEX_RPC_REJECTED',
1596
+ );
1597
+ }
1598
+ projected.limit = params.limit;
1599
+ }
1600
+ return projected;
1601
+ }
1602
+ if (method === 'thread/backgroundTerminals/clean') {
1603
+ return { threadId: threadId() };
1604
+ }
1605
+ throw new CodexAppServerError(
1606
+ 'app-server request projection is missing',
1607
+ 'CODEX_RPC_REJECTED',
1608
+ );
1609
+ }
1610
+
1611
+ function mutationDeliveryError(pending, cause) {
1612
+ const code = pending.writeAttempted
1613
+ ? 'CODEX_RPC_OUTCOME_UNKNOWN'
1614
+ : 'CODEX_RPC_NOT_SENT';
1615
+ const message = pending.writeAttempted
1616
+ ? `app-server ${pending.method} outcome is unknown`
1617
+ : `app-server ${pending.method} was not sent`;
1618
+ return new CodexAppServerError(message, code, { cause });
1619
+ }
1620
+
1621
+ function sameFingerprint(left, right) {
1622
+ return Boolean(
1623
+ left
1624
+ && right
1625
+ && Object.keys(left).every((key) => left[key] === right[key])
1626
+ && Object.keys(right).every((key) => left[key] === right[key]),
1627
+ );
1628
+ }
1629
+
1630
+ function sameOptionalFingerprint(left, right) {
1631
+ return (
1632
+ (left === null && right === null)
1633
+ || sameFingerprint(left, right)
1634
+ );
1635
+ }
1636
+
1637
+ class CodexAppServerClient extends EventEmitter {
1638
+ constructor(options = {}) {
1639
+ super();
1640
+ for (const key of Object.keys(options)) {
1641
+ if (!CONSTRUCTOR_KEYS.has(key)) {
1642
+ throw new TypeError(`CodexAppServerClient: unknown option ${key}`);
1643
+ }
1644
+ }
1645
+ const {
1646
+ binary,
1647
+ cwd,
1648
+ codexHome,
1649
+ env = process.env,
1650
+ spawnFn = spawn,
1651
+ killFn = process.kill.bind(process),
1652
+ setTimer = setTimeout,
1653
+ clearTimer = clearTimeout,
1654
+ requestIdFactory = null,
1655
+ onNotification = async () => {},
1656
+ onFault,
1657
+ attestBinaryFn = attestPinnedCodexBinary,
1658
+ attestCodexHomeFn = attestPinnedCodexHome,
1659
+ expectedConfigSha256,
1660
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
1661
+ sinkTimeoutMs = DEFAULT_SINK_TIMEOUT_MS,
1662
+ closeGraceMs = DEFAULT_CLOSE_GRACE_MS,
1663
+ closeKillMs = DEFAULT_CLOSE_KILL_MS,
1664
+ maxLineBytes = DEFAULT_MAX_LINE_BYTES,
1665
+ maxStderrBytes = DEFAULT_MAX_STDERR_BYTES,
1666
+ maxPendingRequests = DEFAULT_MAX_PENDING_REQUESTS,
1667
+ maxUsedRequestIds = DEFAULT_MAX_USED_REQUEST_IDS,
1668
+ maxQueuedLines = DEFAULT_MAX_QUEUED_LINES,
1669
+ maxQueuedBytes = DEFAULT_MAX_QUEUED_BYTES,
1670
+ } = options;
1671
+ assertAbsolute(binary, 'binary');
1672
+ assertAbsolute(cwd, 'cwd');
1673
+ assertAbsolute(codexHome, 'codexHome');
1674
+ if (
1675
+ typeof expectedConfigSha256 !== 'string'
1676
+ || !/^[a-f0-9]{64}$/.test(expectedConfigSha256)
1677
+ ) {
1678
+ throw new TypeError(
1679
+ 'CodexAppServerClient: expectedConfigSha256 must be a lowercase SHA-256',
1680
+ );
1681
+ }
1682
+ if (process.platform === 'win32') {
1683
+ throw new CodexAppServerError(
1684
+ 'The native Codex app-server beta does not support Windows',
1685
+ 'CODEX_UNSUPPORTED_PLATFORM',
1686
+ );
1687
+ }
1688
+ for (const [value, label] of [
1689
+ [cwd, 'cwd'],
1690
+ [codexHome, 'codexHome'],
1691
+ ]) {
1692
+ if (realpathSync(value) !== value) {
1693
+ throw new TypeError(
1694
+ `CodexAppServerClient: ${label} must be a canonical path`,
1695
+ );
1696
+ }
1697
+ }
1698
+ const workspaceStat = lstatSync(cwd);
1699
+ const credentialStat = lstatSync(codexHome);
1700
+ if (!workspaceStat.isDirectory()) {
1701
+ throw new TypeError('CodexAppServerClient: cwd must be a directory');
1702
+ }
1703
+ if (
1704
+ !credentialStat.isDirectory()
1705
+ || credentialStat.isSymbolicLink()
1706
+ || (
1707
+ typeof process.getuid === 'function'
1708
+ && credentialStat.uid !== process.getuid()
1709
+ )
1710
+ || (credentialStat.mode & 0o777) !== 0o700
1711
+ || isWithin(cwd, codexHome)
1712
+ || isWithin(codexHome, cwd)
1713
+ ) {
1714
+ throw new TypeError(
1715
+ 'CodexAppServerClient: codexHome must be a separate owned 0700 directory',
1716
+ );
1717
+ }
1718
+ for (const [value, label] of [
1719
+ [spawnFn, 'spawnFn'],
1720
+ [killFn, 'killFn'],
1721
+ [setTimer, 'setTimer'],
1722
+ [clearTimer, 'clearTimer'],
1723
+ [onNotification, 'onNotification'],
1724
+ [onFault, 'onFault'],
1725
+ [attestBinaryFn, 'attestBinaryFn'],
1726
+ [attestCodexHomeFn, 'attestCodexHomeFn'],
1727
+ ]) {
1728
+ if (typeof value !== 'function') {
1729
+ throw new TypeError(`CodexAppServerClient: ${label} must be a function`);
1730
+ }
1731
+ }
1732
+ if (requestIdFactory !== null && typeof requestIdFactory !== 'function') {
1733
+ throw new TypeError('CodexAppServerClient: requestIdFactory must be a function');
1734
+ }
1735
+ for (const [value, label] of [
1736
+ [requestTimeoutMs, 'requestTimeoutMs'],
1737
+ [sinkTimeoutMs, 'sinkTimeoutMs'],
1738
+ [closeGraceMs, 'closeGraceMs'],
1739
+ [closeKillMs, 'closeKillMs'],
1740
+ ]) {
1741
+ assertTimerDelay(value, label);
1742
+ }
1743
+ // close waits out the supervisor's whole escalation in one timer.
1744
+ if (closeGraceMs + closeKillMs > MAX_TIMER_DELAY_MS) {
1745
+ throw new TypeError(
1746
+ 'CodexAppServerClient: closeGraceMs + closeKillMs must not exceed '
1747
+ + `${MAX_TIMER_DELAY_MS}`,
1748
+ );
1749
+ }
1750
+ for (const [value, label] of [
1751
+ [maxLineBytes, 'maxLineBytes'],
1752
+ [maxStderrBytes, 'maxStderrBytes'],
1753
+ [maxPendingRequests, 'maxPendingRequests'],
1754
+ [maxUsedRequestIds, 'maxUsedRequestIds'],
1755
+ [maxQueuedLines, 'maxQueuedLines'],
1756
+ [maxQueuedBytes, 'maxQueuedBytes'],
1757
+ ]) {
1758
+ assertPositiveInteger(value, label);
1759
+ }
1760
+
1761
+ Object.assign(this, {
1762
+ binary,
1763
+ cwd,
1764
+ codexHome,
1765
+ spawnFn,
1766
+ killFn,
1767
+ setTimer,
1768
+ clearTimer,
1769
+ requestIdFactory,
1770
+ onNotification,
1771
+ onFault,
1772
+ attestBinaryFn,
1773
+ attestCodexHomeFn,
1774
+ expectedConfigSha256,
1775
+ requestTimeoutMs,
1776
+ sinkTimeoutMs,
1777
+ closeGraceMs,
1778
+ closeKillMs,
1779
+ maxLineBytes,
1780
+ maxStderrBytes,
1781
+ maxPendingRequests,
1782
+ maxUsedRequestIds,
1783
+ maxQueuedLines,
1784
+ maxQueuedBytes,
1785
+ });
1786
+ this.env = buildCodexAppServerEnv(codexHome, env);
1787
+ this.state = 'new';
1788
+ this.child = null;
1789
+ this.startPromise = null;
1790
+ this.closePromise = null;
1791
+ this.exitPromise = null;
1792
+ this.exitInfo = null;
1793
+ this.protocolError = null;
1794
+ this.faultPromise = null;
1795
+ this.faultOutcome = null;
1796
+ this.faultWaitPromise = new Promise((resolve, reject) => {
1797
+ this.resolveFaultWait = resolve;
1798
+ this.rejectFaultWait = reject;
1799
+ });
1800
+ this.faultWaitPromise.catch(() => {});
1801
+ this.sinkGeneration = 0;
1802
+ this.activeSinkControllers = new Set();
1803
+ this.pending = new Map();
1804
+ this.usedRequestIds = new Set();
1805
+ this.nextRequestId = 1;
1806
+ this.stdoutBuffer = '';
1807
+ this.stdoutDecoder = new StringDecoder('utf8');
1808
+ this.stderrBytes = 0;
1809
+ this.messageChain = Promise.resolve();
1810
+ this.queuedLineCount = 0;
1811
+ this.queuedLineBytes = 0;
1812
+ this.stdoutPaused = false;
1813
+ }
1814
+
1815
+ start() {
1816
+ if (this.startPromise) return this.startPromise;
1817
+ this.startPromise = this._start();
1818
+ return this.startPromise;
1819
+ }
1820
+
1821
+ async _start() {
1822
+ if (this.state !== 'new') {
1823
+ throw new CodexAppServerError(
1824
+ 'app-server start is only valid once',
1825
+ 'CODEX_CLIENT_STATE',
1826
+ );
1827
+ }
1828
+ this.state = 'starting';
1829
+ const args = ['app-server', '--strict-config', '--stdio'];
1830
+ const command = process.execPath;
1831
+ const commandArgs = [
1832
+ SUPERVISOR_PATH,
1833
+ `--group-term-grace-ms=${this.closeGraceMs}`,
1834
+ this.binary,
1835
+ ...args,
1836
+ ];
1837
+ try {
1838
+ const [attestation, homeAttestation] = await Promise.all([
1839
+ this.attestBinaryFn(this.binary),
1840
+ this.attestCodexHomeFn(
1841
+ this.codexHome,
1842
+ this.expectedConfigSha256,
1843
+ ),
1844
+ ]);
1845
+ if (
1846
+ !attestation
1847
+ || attestation.path !== this.binary
1848
+ || attestation.sha256 !== protocolSchema.binarySha256
1849
+ || attestation.version !== protocolSchema.cliVersion
1850
+ ) {
1851
+ throw new CodexAppServerError(
1852
+ 'pinned Codex binary attestation was inconsistent',
1853
+ 'CODEX_BINARY_MISMATCH',
1854
+ );
1855
+ }
1856
+ if (
1857
+ !homeAttestation
1858
+ || homeAttestation.path !== this.codexHome
1859
+ || homeAttestation.configSha256 !== this.expectedConfigSha256
1860
+ || !homeAttestation.configFingerprint
1861
+ ) {
1862
+ throw new CodexAppServerError(
1863
+ 'pinned Codex credential home attestation was inconsistent',
1864
+ 'CODEX_CONFIG_MISMATCH',
1865
+ );
1866
+ }
1867
+ if (this.state !== 'starting') {
1868
+ throw new CodexAppServerError(
1869
+ 'app-server start was cancelled before spawn',
1870
+ 'CODEX_CLIENT_CLOSED',
1871
+ );
1872
+ }
1873
+ this.child = this.spawnFn(command, commandArgs, {
1874
+ cwd: this.cwd,
1875
+ env: this.env,
1876
+ detached: process.platform !== 'win32',
1877
+ stdio: ['pipe', 'pipe', 'pipe'],
1878
+ });
1879
+ this._attachChild();
1880
+ if (
1881
+ attestation.fingerprint
1882
+ && !sameFingerprint(attestation.fingerprint, binaryFingerprint(this.binary))
1883
+ ) {
1884
+ throw new CodexAppServerError(
1885
+ 'pinned Codex binary changed during spawn',
1886
+ 'CODEX_BINARY_MISMATCH',
1887
+ );
1888
+ }
1889
+ const afterSpawnHome = await this.attestCodexHomeFn(
1890
+ this.codexHome,
1891
+ this.expectedConfigSha256,
1892
+ );
1893
+ if (
1894
+ !afterSpawnHome
1895
+ || afterSpawnHome.path !== this.codexHome
1896
+ || afterSpawnHome.configSha256 !== this.expectedConfigSha256
1897
+ || !sameFingerprint(
1898
+ homeAttestation.configFingerprint,
1899
+ afterSpawnHome.configFingerprint,
1900
+ )
1901
+ || !sameOptionalFingerprint(
1902
+ homeAttestation.authFingerprint,
1903
+ afterSpawnHome.authFingerprint,
1904
+ )
1905
+ ) {
1906
+ throw new CodexAppServerError(
1907
+ 'pinned Codex credential state changed during spawn',
1908
+ 'CODEX_CONFIG_MISMATCH',
1909
+ );
1910
+ }
1911
+ this.state = 'initializing';
1912
+ const result = await this._request('initialize', {
1913
+ clientInfo: {
1914
+ name: 'orchestra',
1915
+ title: 'Orchestra',
1916
+ version: '0.5.0',
1917
+ },
1918
+ capabilities: { experimentalApi: true },
1919
+ }, { internal: true });
1920
+ if (result?.codexHome !== this.codexHome) {
1921
+ throw new CodexAppServerError(
1922
+ 'app-server initialized with an unexpected credential home',
1923
+ 'CODEX_CONFIG_MISMATCH',
1924
+ );
1925
+ }
1926
+ await this._writeMessage({ method: 'initialized' });
1927
+ this.state = 'ready';
1928
+ return this;
1929
+ } catch (error) {
1930
+ this._fault(error);
1931
+ throw error;
1932
+ }
1933
+ }
1934
+
1935
+ _attachChild() {
1936
+ const child = this.child;
1937
+ if (
1938
+ !child
1939
+ || !child.stdin
1940
+ || !child.stdout
1941
+ || !child.stderr
1942
+ || typeof child.once !== 'function'
1943
+ ) {
1944
+ throw new TypeError('CodexAppServerClient: spawnFn returned an invalid child');
1945
+ }
1946
+ this.exitPromise = new Promise((resolve) => {
1947
+ let observed = false;
1948
+ const observeExit = (code, signal) => {
1949
+ if (observed) return;
1950
+ observed = true;
1951
+ this.exitInfo = { code, signal };
1952
+ try { this.emit('exit', this.exitInfo); } catch {}
1953
+ };
1954
+ child.once('exit', observeExit);
1955
+ child.once('close', (code, signal) => {
1956
+ observeExit(code, signal);
1957
+ resolve(this.exitInfo);
1958
+ if (this.state !== 'closing' && this.state !== 'closed') {
1959
+ this._enqueueTerminalFault(new CodexAppServerError(
1960
+ 'app-server exited unexpectedly',
1961
+ 'CODEX_PROCESS_EXITED',
1962
+ ));
1963
+ }
1964
+ });
1965
+ });
1966
+ child.stdout.on('data', (chunk) => this._onStdoutData(chunk));
1967
+ child.stdout.once('end', () => this._onStdoutEnd());
1968
+ child.stdout.once('error', (error) => this._transportFault(
1969
+ 'app-server stdout failed',
1970
+ error,
1971
+ ));
1972
+ child.stderr.on('data', (chunk) => this._onStderrData(chunk));
1973
+ child.stderr.once('error', (error) => this._transportFault(
1974
+ 'app-server stderr failed',
1975
+ error,
1976
+ ));
1977
+ child.stdin.on('error', (error) => {
1978
+ this._transportFault('app-server stdin failed', error);
1979
+ });
1980
+ child.once('error', (error) => {
1981
+ if (this.state !== 'closing' && this.state !== 'closed') {
1982
+ this._fault(new CodexAppServerError(
1983
+ 'app-server process failed',
1984
+ 'CODEX_PROCESS_ERROR',
1985
+ { cause: error },
1986
+ ));
1987
+ }
1988
+ });
1989
+ }
1990
+
1991
+ request(method, params, {
1992
+ timeoutMs = this.requestTimeoutMs,
1993
+ onWriteAttempted,
1994
+ onResponseObserved,
1995
+ } = {}) {
1996
+ return this._request(method, params, {
1997
+ timeoutMs,
1998
+ onWriteAttempted,
1999
+ onResponseObserved,
2000
+ });
2001
+ }
2002
+
2003
+ _request(method, params, {
2004
+ internal = false,
2005
+ timeoutMs = this.requestTimeoutMs,
2006
+ onWriteAttempted,
2007
+ onResponseObserved,
2008
+ } = {}) {
2009
+ const spec = CLIENT_REQUESTS.get(method);
2010
+ if (
2011
+ !spec
2012
+ || DENIED_CLIENT_REQUESTS.has(method)
2013
+ || (spec.internal && !internal)
2014
+ ) {
2015
+ return Promise.reject(new CodexAppServerError(
2016
+ 'app-server request method is not allowlisted',
2017
+ 'CODEX_RPC_REJECTED',
2018
+ ));
2019
+ }
2020
+ if (this.protocolError) return Promise.reject(this.protocolError);
2021
+ if (
2022
+ (!internal && this.state !== 'ready')
2023
+ || (internal && method === 'initialize' && this.state !== 'initializing')
2024
+ ) {
2025
+ return Promise.reject(new CodexAppServerError(
2026
+ 'app-server client is not ready',
2027
+ 'CODEX_CLIENT_STATE',
2028
+ ));
2029
+ }
2030
+ let projectedParams;
2031
+ try {
2032
+ projectedParams = projectRequestParams(method, params, spec, this.cwd);
2033
+ assertPositiveInteger(timeoutMs, 'request timeout');
2034
+ } catch (error) {
2035
+ return Promise.reject(error);
2036
+ }
2037
+ if (
2038
+ spec.stateChanging
2039
+ && (
2040
+ typeof onWriteAttempted !== 'function'
2041
+ || typeof onResponseObserved !== 'function'
2042
+ )
2043
+ ) {
2044
+ return Promise.reject(new CodexAppServerError(
2045
+ `app-server ${method} requires delivery checkpoints`,
2046
+ 'CODEX_RPC_REJECTED',
2047
+ ));
2048
+ }
2049
+ if (!this._stdinWritable()) {
2050
+ const cause = new CodexAppServerError(
2051
+ 'app-server stdin is not writable',
2052
+ 'CODEX_TRANSPORT_ERROR',
2053
+ );
2054
+ return Promise.reject(
2055
+ spec.stateChanging
2056
+ ? mutationDeliveryError({ method, writeAttempted: false }, cause)
2057
+ : cause,
2058
+ );
2059
+ }
2060
+ if (this.pending.size >= this.maxPendingRequests) {
2061
+ return Promise.reject(new CodexAppServerError(
2062
+ 'app-server pending request limit reached',
2063
+ 'CODEX_RPC_REJECTED',
2064
+ ));
2065
+ }
2066
+ if (this.usedRequestIds.size >= this.maxUsedRequestIds) {
2067
+ const error = new CodexAppServerError(
2068
+ 'app-server request ID space is exhausted for this generation',
2069
+ 'CODEX_REQUEST_ID_EXHAUSTED',
2070
+ );
2071
+ this._fault(error);
2072
+ return Promise.reject(error);
2073
+ }
2074
+
2075
+ let id;
2076
+ try {
2077
+ id = this.requestIdFactory
2078
+ ? this.requestIdFactory(this.nextRequestId)
2079
+ : this.nextRequestId;
2080
+ this.nextRequestId += 1;
2081
+ assertRequestId(id);
2082
+ if (this.usedRequestIds.has(id)) {
2083
+ throw new CodexAppServerError(
2084
+ 'app-server request ID was reused',
2085
+ 'CODEX_PROTOCOL_ERROR',
2086
+ );
2087
+ }
2088
+ this.usedRequestIds.add(id);
2089
+ } catch (error) {
2090
+ return Promise.reject(error);
2091
+ }
2092
+
2093
+ return new Promise((resolve, reject) => {
2094
+ const pending = {
2095
+ id,
2096
+ method,
2097
+ stateChanging: spec.stateChanging,
2098
+ writeAttempted: false,
2099
+ onWriteAttempted,
2100
+ onResponseObserved,
2101
+ resolve,
2102
+ reject,
2103
+ timer: null,
2104
+ sinkController: null,
2105
+ };
2106
+ pending.timer = this.setTimer(() => {
2107
+ if (this.pending.get(id) !== pending) return;
2108
+ const timeoutError = new CodexAppServerError(
2109
+ `app-server ${method} timed out`,
2110
+ 'CODEX_RPC_TIMEOUT',
2111
+ );
2112
+ if (pending.stateChanging && pending.writeAttempted) {
2113
+ this._fault(timeoutError);
2114
+ return;
2115
+ }
2116
+ pending.sinkController?.abort(timeoutError);
2117
+ this.pending.delete(id);
2118
+ reject(
2119
+ pending.stateChanging
2120
+ ? mutationDeliveryError(pending, timeoutError)
2121
+ : timeoutError,
2122
+ );
2123
+ }, timeoutMs);
2124
+ this.pending.set(id, pending);
2125
+ void this._dispatchRequest(pending, projectedParams);
2126
+ });
2127
+ }
2128
+
2129
+ async _dispatchRequest(pending, params) {
2130
+ try {
2131
+ const message = { id: pending.id, method: pending.method };
2132
+ if (params !== undefined) message.params = params;
2133
+ const line = this._serializeMessage(message);
2134
+ if (pending.stateChanging) {
2135
+ const controller = new AbortController();
2136
+ pending.sinkController = controller;
2137
+ try {
2138
+ await this._runSink(
2139
+ pending.onWriteAttempted,
2140
+ {
2141
+ id: pending.id,
2142
+ method: pending.method,
2143
+ },
2144
+ 'write checkpoint',
2145
+ controller,
2146
+ {
2147
+ markWriteCommitted: () => {
2148
+ pending.writeAttempted = true;
2149
+ },
2150
+ },
2151
+ );
2152
+ } finally {
2153
+ if (pending.sinkController === controller) {
2154
+ pending.sinkController = null;
2155
+ }
2156
+ }
2157
+ if (this.pending.get(pending.id) !== pending) return;
2158
+ pending.writeAttempted = true;
2159
+ }
2160
+ await this._writeLine(line);
2161
+ } catch (error) {
2162
+ if (this.pending.get(pending.id) !== pending) return;
2163
+ if (pending.stateChanging && pending.writeAttempted) {
2164
+ this._fault(error);
2165
+ return;
2166
+ }
2167
+ this.pending.delete(pending.id);
2168
+ this.clearTimer(pending.timer);
2169
+ pending.reject(
2170
+ pending.stateChanging
2171
+ ? mutationDeliveryError(pending, error)
2172
+ : error,
2173
+ );
2174
+ }
2175
+ }
2176
+
2177
+ _serializeMessage(message) {
2178
+ let line;
2179
+ try {
2180
+ line = `${JSON.stringify(message)}\n`;
2181
+ } catch (error) {
2182
+ throw new CodexAppServerError(
2183
+ 'app-server client message was not serializable',
2184
+ 'CODEX_RPC_REJECTED',
2185
+ { cause: error },
2186
+ );
2187
+ }
2188
+ if (Buffer.byteLength(line) > this.maxLineBytes) {
2189
+ throw new CodexAppServerError(
2190
+ 'app-server client message exceeded the size limit',
2191
+ 'CODEX_RPC_REJECTED',
2192
+ );
2193
+ }
2194
+ return line;
2195
+ }
2196
+
2197
+ _writeMessage(message) {
2198
+ return this._writeLine(this._serializeMessage(message));
2199
+ }
2200
+
2201
+ _writeLine(line) {
2202
+ if (this.protocolError) throw this.protocolError;
2203
+ if (!this._stdinWritable()) {
2204
+ throw new CodexAppServerError(
2205
+ 'app-server stdin is not writable',
2206
+ 'CODEX_TRANSPORT_ERROR',
2207
+ );
2208
+ }
2209
+ return this._awaitBounded(
2210
+ new Promise((resolve, reject) => {
2211
+ try {
2212
+ this.child.stdin.write(line, (error) => {
2213
+ if (error) reject(error);
2214
+ else resolve();
2215
+ });
2216
+ } catch (error) {
2217
+ reject(error);
2218
+ }
2219
+ }),
2220
+ 'transport write',
2221
+ );
2222
+ }
2223
+
2224
+ _awaitBounded(value, label) {
2225
+ let timer;
2226
+ return Promise.race([
2227
+ Promise.resolve(value),
2228
+ new Promise((resolve, reject) => {
2229
+ timer = this.setTimer(() => reject(new CodexAppServerError(
2230
+ `app-server ${label} timed out`,
2231
+ 'CODEX_SINK_TIMEOUT',
2232
+ )), this.sinkTimeoutMs);
2233
+ }),
2234
+ ]).finally(() => {
2235
+ if (timer !== undefined) this.clearTimer(timer);
2236
+ });
2237
+ }
2238
+
2239
+ _runSink(
2240
+ callback,
2241
+ payload,
2242
+ label,
2243
+ controller = new AbortController(),
2244
+ capabilities = {},
2245
+ ) {
2246
+ const generation = this.sinkGeneration;
2247
+ let active = true;
2248
+ const sinkPayload = { ...payload };
2249
+ const assertSinkActive = () => {
2250
+ if (
2251
+ !active
2252
+ || controller.signal.aborted
2253
+ || generation !== this.sinkGeneration
2254
+ ) {
2255
+ throw new CodexAppServerError(
2256
+ `app-server ${label} is no longer active`,
2257
+ 'CODEX_SINK_ABORTED',
2258
+ );
2259
+ }
2260
+ };
2261
+ const properties = {
2262
+ signal: {
2263
+ value: controller.signal,
2264
+ enumerable: false,
2265
+ },
2266
+ assertActive: {
2267
+ value: assertSinkActive,
2268
+ enumerable: false,
2269
+ },
2270
+ };
2271
+ for (const [name, capability] of Object.entries(capabilities)) {
2272
+ properties[name] = {
2273
+ value: (...args) => {
2274
+ assertSinkActive();
2275
+ return capability(...args);
2276
+ },
2277
+ enumerable: false,
2278
+ };
2279
+ }
2280
+ Object.defineProperties(sinkPayload, properties);
2281
+ this.activeSinkControllers.add(controller);
2282
+ let timer;
2283
+ let sinkPromise;
2284
+ try {
2285
+ sinkPromise = Promise.resolve(callback(sinkPayload));
2286
+ } catch (error) {
2287
+ sinkPromise = Promise.reject(error);
2288
+ }
2289
+ return Promise.race([
2290
+ sinkPromise,
2291
+ new Promise((resolve, reject) => {
2292
+ controller.signal.addEventListener('abort', () => {
2293
+ active = false;
2294
+ reject(
2295
+ controller.signal.reason instanceof Error
2296
+ ? controller.signal.reason
2297
+ : new CodexAppServerError(
2298
+ `app-server ${label} was aborted`,
2299
+ 'CODEX_SINK_ABORTED',
2300
+ ),
2301
+ );
2302
+ }, { once: true });
2303
+ }),
2304
+ new Promise((resolve, reject) => {
2305
+ timer = this.setTimer(() => {
2306
+ active = false;
2307
+ const timeoutError = new CodexAppServerError(
2308
+ `app-server ${label} timed out`,
2309
+ 'CODEX_SINK_TIMEOUT',
2310
+ );
2311
+ controller.abort(timeoutError);
2312
+ reject(timeoutError);
2313
+ }, this.sinkTimeoutMs);
2314
+ }),
2315
+ ]).finally(() => {
2316
+ active = false;
2317
+ controller.abort();
2318
+ this.activeSinkControllers.delete(controller);
2319
+ if (timer !== undefined) this.clearTimer(timer);
2320
+ });
2321
+ }
2322
+
2323
+ _invalidateSinks() {
2324
+ this.sinkGeneration += 1;
2325
+ for (const controller of this.activeSinkControllers) {
2326
+ controller.abort(new CodexAppServerError(
2327
+ 'app-server sink generation was invalidated',
2328
+ 'CODEX_SINK_ABORTED',
2329
+ ));
2330
+ }
2331
+ this.activeSinkControllers.clear();
2332
+ }
2333
+
2334
+ _stdinWritable() {
2335
+ return (
2336
+ this.child
2337
+ && this.state !== 'closing'
2338
+ && this.state !== 'closed'
2339
+ && !this.exitInfo
2340
+ && this.child.stdin.writable !== false
2341
+ && this.child.stdin.destroyed !== true
2342
+ );
2343
+ }
2344
+
2345
+ _onStdoutData(chunk) {
2346
+ if (
2347
+ this.state === 'closing'
2348
+ || this.state === 'closed'
2349
+ || this.protocolError
2350
+ ) return;
2351
+ this.stdoutBuffer += typeof chunk === 'string'
2352
+ ? chunk
2353
+ : this.stdoutDecoder.write(chunk);
2354
+ let newline;
2355
+ while ((newline = this.stdoutBuffer.indexOf('\n')) !== -1) {
2356
+ let line = this.stdoutBuffer.slice(0, newline);
2357
+ this.stdoutBuffer = this.stdoutBuffer.slice(newline + 1);
2358
+ if (line.endsWith('\r')) line = line.slice(0, -1);
2359
+ if (Buffer.byteLength(line) > this.maxLineBytes) {
2360
+ this._fault(new CodexAppServerError(
2361
+ 'app-server line exceeded the size limit',
2362
+ 'CODEX_PROTOCOL_ERROR',
2363
+ ));
2364
+ return;
2365
+ }
2366
+ const lineBytes = Buffer.byteLength(line);
2367
+ if (
2368
+ this.queuedLineCount + 1 > this.maxQueuedLines
2369
+ || this.queuedLineBytes + lineBytes > this.maxQueuedBytes
2370
+ ) {
2371
+ this._fault(new CodexAppServerError(
2372
+ 'app-server inbound message queue exceeded the size limit',
2373
+ 'CODEX_PROTOCOL_ERROR',
2374
+ ));
2375
+ return;
2376
+ }
2377
+ this.queuedLineCount += 1;
2378
+ this.queuedLineBytes += lineBytes;
2379
+ if (
2380
+ !this.stdoutPaused
2381
+ && this.child?.stdout
2382
+ && typeof this.child.stdout.pause === 'function'
2383
+ && (
2384
+ this.queuedLineCount >= Math.ceil(this.maxQueuedLines / 2)
2385
+ || this.queuedLineBytes >= Math.ceil(this.maxQueuedBytes / 2)
2386
+ )
2387
+ ) {
2388
+ this.child.stdout.pause();
2389
+ this.stdoutPaused = true;
2390
+ }
2391
+ this.messageChain = this.messageChain
2392
+ .then(async () => {
2393
+ this.queuedLineCount -= 1;
2394
+ this.queuedLineBytes -= lineBytes;
2395
+ this._resumeStdoutIfSafe();
2396
+ if (
2397
+ this.protocolError
2398
+ || this.state === 'closing'
2399
+ || this.state === 'closed'
2400
+ ) return;
2401
+ await this._handleLine(line);
2402
+ })
2403
+ .catch((error) => this._fault(error));
2404
+ }
2405
+ if (Buffer.byteLength(this.stdoutBuffer) > this.maxLineBytes) {
2406
+ this._fault(new CodexAppServerError(
2407
+ 'app-server partial line exceeded the size limit',
2408
+ 'CODEX_PROTOCOL_ERROR',
2409
+ ));
2410
+ }
2411
+ }
2412
+
2413
+ _onStdoutEnd() {
2414
+ const trailing = this.stdoutBuffer + this.stdoutDecoder.end();
2415
+ this.stdoutBuffer = '';
2416
+ this._enqueueTerminalFault(new CodexAppServerError(
2417
+ trailing.length > 0
2418
+ ? 'app-server output ended with a partial message'
2419
+ : 'app-server output closed unexpectedly',
2420
+ 'CODEX_PROTOCOL_ERROR',
2421
+ ));
2422
+ }
2423
+
2424
+ _resumeStdoutIfSafe() {
2425
+ if (
2426
+ !this.stdoutPaused
2427
+ || this.protocolError
2428
+ || this.state === 'closing'
2429
+ || this.state === 'closed'
2430
+ ) return;
2431
+ if (
2432
+ this.queuedLineCount < Math.ceil(this.maxQueuedLines / 2)
2433
+ && this.queuedLineBytes < Math.ceil(this.maxQueuedBytes / 2)
2434
+ ) {
2435
+ this.child?.stdout?.resume?.();
2436
+ this.stdoutPaused = false;
2437
+ }
2438
+ }
2439
+
2440
+ _enqueueTerminalFault(error) {
2441
+ if (
2442
+ this.state === 'closing'
2443
+ || this.state === 'closed'
2444
+ || this.protocolError
2445
+ ) return;
2446
+ this.messageChain = this.messageChain
2447
+ .then(() => {
2448
+ if (
2449
+ this.state !== 'closing'
2450
+ && this.state !== 'closed'
2451
+ && !this.protocolError
2452
+ ) this._fault(error);
2453
+ })
2454
+ .catch((cause) => this._fault(cause));
2455
+ }
2456
+
2457
+ _transportFault(message, cause) {
2458
+ if (this.state === 'closing' || this.state === 'closed') return;
2459
+ this._enqueueTerminalFault(new CodexAppServerError(
2460
+ message,
2461
+ 'CODEX_TRANSPORT_ERROR',
2462
+ { cause },
2463
+ ));
2464
+ }
2465
+
2466
+ _onStderrData(chunk) {
2467
+ this.stderrBytes += Buffer.isBuffer(chunk)
2468
+ ? chunk.length
2469
+ : Buffer.byteLength(String(chunk));
2470
+ if (this.stderrBytes > this.maxStderrBytes) {
2471
+ this._fault(new CodexAppServerError(
2472
+ 'app-server stderr exceeded the size limit',
2473
+ 'CODEX_PROTOCOL_ERROR',
2474
+ ));
2475
+ }
2476
+ }
2477
+
2478
+ async _handleLine(line) {
2479
+ let message;
2480
+ try {
2481
+ message = JSON.parse(line);
2482
+ } catch {
2483
+ throw new CodexAppServerError(
2484
+ 'app-server emitted malformed JSON',
2485
+ 'CODEX_PROTOCOL_ERROR',
2486
+ );
2487
+ }
2488
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
2489
+ throw new CodexAppServerError(
2490
+ 'app-server emitted a malformed message',
2491
+ 'CODEX_PROTOCOL_ERROR',
2492
+ );
2493
+ }
2494
+ if (Object.hasOwn(message, 'jsonrpc')) {
2495
+ throw new CodexAppServerError(
2496
+ 'app-server emitted unsupported JSON-RPC framing',
2497
+ 'CODEX_PROTOCOL_ERROR',
2498
+ );
2499
+ }
2500
+ const hasId = Object.hasOwn(message, 'id');
2501
+ const hasMethod = Object.hasOwn(message, 'method');
2502
+ const hasResult = Object.hasOwn(message, 'result');
2503
+ const hasError = Object.hasOwn(message, 'error');
2504
+ const keysAllowed = (allowed) => (
2505
+ Object.keys(message).every((key) => allowed.includes(key))
2506
+ );
2507
+ if (hasId) assertRequestId(message.id);
2508
+ if (
2509
+ hasMethod
2510
+ && (
2511
+ typeof message.method !== 'string'
2512
+ || !SAFE_METHOD_PATTERN.test(message.method)
2513
+ )
2514
+ ) {
2515
+ throw new CodexAppServerError(
2516
+ 'app-server emitted a malformed method',
2517
+ 'CODEX_PROTOCOL_ERROR',
2518
+ );
2519
+ }
2520
+
2521
+ if (hasId && hasMethod) {
2522
+ if (hasResult || hasError || !keysAllowed(['id', 'method', 'params'])) {
2523
+ throw new CodexAppServerError(
2524
+ 'app-server emitted an ambiguous server request',
2525
+ 'CODEX_PROTOCOL_ERROR',
2526
+ );
2527
+ }
2528
+ const denial = DENIED_SERVER_REQUESTS.get(message.method);
2529
+ if (!denial) {
2530
+ throw new CodexAppServerError(
2531
+ 'app-server sent an unknown server request',
2532
+ 'CODEX_PROTOCOL_ERROR',
2533
+ );
2534
+ }
2535
+ await this._writeMessage({ id: message.id, ...denial });
2536
+ try { this.emit('server-request-denied', { known: true }); } catch {}
2537
+ throw new CodexAppServerError(
2538
+ 'app-server sent a disabled server request',
2539
+ 'CODEX_SERVER_REQUEST_DENIED',
2540
+ );
2541
+ }
2542
+
2543
+ if (hasId) {
2544
+ if (
2545
+ hasMethod
2546
+ || hasResult === hasError
2547
+ || !keysAllowed(hasResult ? ['id', 'result'] : ['id', 'error'])
2548
+ ) {
2549
+ return this._handleMalformedResponse(message.id);
2550
+ }
2551
+ const pending = this.pending.get(message.id);
2552
+ if (!pending) {
2553
+ throw new CodexAppServerError(
2554
+ 'app-server returned an unexpected response ID',
2555
+ 'CODEX_PROTOCOL_ERROR',
2556
+ );
2557
+ }
2558
+ let projectedResult;
2559
+ let projectedError;
2560
+ try {
2561
+ if (hasResult) {
2562
+ projectedResult = projectRpcResult(
2563
+ pending.method,
2564
+ message.result,
2565
+ this.cwd,
2566
+ );
2567
+ } else {
2568
+ projectedError = projectRpcError(message.error);
2569
+ }
2570
+ } catch (error) {
2571
+ this._fault(error);
2572
+ return;
2573
+ }
2574
+ this.clearTimer(pending.timer);
2575
+ try {
2576
+ if (pending.stateChanging) {
2577
+ const controller = new AbortController();
2578
+ pending.sinkController = controller;
2579
+ try {
2580
+ await this._runSink(
2581
+ pending.onResponseObserved,
2582
+ {
2583
+ id: pending.id,
2584
+ method: pending.method,
2585
+ outcome: hasResult ? 'result' : 'error',
2586
+ },
2587
+ 'response checkpoint',
2588
+ controller,
2589
+ );
2590
+ } finally {
2591
+ if (pending.sinkController === controller) {
2592
+ pending.sinkController = null;
2593
+ }
2594
+ }
2595
+ }
2596
+ } catch (error) {
2597
+ if (this.pending.get(message.id) === pending) {
2598
+ this.pending.delete(message.id);
2599
+ const checkpointError = new CodexAppServerError(
2600
+ 'app-server response checkpoint failed',
2601
+ 'CODEX_RPC_CHECKPOINT_FAILED',
2602
+ { cause: error },
2603
+ );
2604
+ pending.reject(checkpointError);
2605
+ this._fault(checkpointError);
2606
+ }
2607
+ return;
2608
+ }
2609
+ if (this.pending.get(message.id) !== pending) return;
2610
+ this.pending.delete(message.id);
2611
+ if (hasError) {
2612
+ const error = new CodexAppServerError(
2613
+ `app-server ${pending.method} failed`,
2614
+ 'CODEX_RPC_ERROR',
2615
+ );
2616
+ error.rpcCode = projectedError.code;
2617
+ if (
2618
+ RECOGNIZED_RPC_ERRORS.get(pending.method)
2619
+ ?.has(projectedError.message)
2620
+ ) {
2621
+ error.rpcMessage = projectedError.message;
2622
+ }
2623
+ pending.reject(error);
2624
+ } else {
2625
+ pending.resolve(projectedResult);
2626
+ }
2627
+ return;
2628
+ }
2629
+
2630
+ if (
2631
+ !hasMethod
2632
+ || hasResult
2633
+ || hasError
2634
+ || !keysAllowed(['method', 'params'])
2635
+ ) {
2636
+ throw new CodexAppServerError(
2637
+ 'app-server emitted a malformed notification',
2638
+ 'CODEX_PROTOCOL_ERROR',
2639
+ );
2640
+ }
2641
+ if (DROPPED_NOTIFICATIONS.has(message.method)) return;
2642
+ if (!DELIVERED_NOTIFICATIONS.has(message.method)) {
2643
+ throw new CodexAppServerError(
2644
+ 'app-server sent an unexpected server notification',
2645
+ 'CODEX_PROTOCOL_ERROR',
2646
+ );
2647
+ }
2648
+ await this._runSink(
2649
+ this.onNotification,
2650
+ projectNotification(message, this.cwd),
2651
+ 'notification sink',
2652
+ );
2653
+ }
2654
+
2655
+ _handleMalformedResponse(id) {
2656
+ const pending = this.pending.get(id);
2657
+ if (!pending) {
2658
+ throw new CodexAppServerError(
2659
+ 'app-server returned an unexpected response ID',
2660
+ 'CODEX_PROTOCOL_ERROR',
2661
+ );
2662
+ }
2663
+ this.clearTimer(pending.timer);
2664
+ const malformed = new CodexAppServerError(
2665
+ `app-server ${pending.method} returned a malformed response`,
2666
+ 'CODEX_PROTOCOL_ERROR',
2667
+ );
2668
+ this._fault(malformed);
2669
+ }
2670
+
2671
+ _fault(error) {
2672
+ if (this.protocolError || this.state === 'closed') return;
2673
+ const fault = error instanceof Error
2674
+ ? error
2675
+ : new CodexAppServerError(
2676
+ 'app-server protocol failed',
2677
+ 'CODEX_PROTOCOL_ERROR',
2678
+ );
2679
+ const ambiguousMutation = this._rejectAll(fault);
2680
+ this.protocolError = ambiguousMutation ?? fault;
2681
+ this._invalidateSinks();
2682
+ try { this.emit('protocol-error', this.protocolError); } catch {}
2683
+ if (this.state !== 'closing') this.state = 'faulted';
2684
+ const postSpawn = Boolean(this.child);
2685
+ this.faultPromise = this._settleFault(postSpawn);
2686
+ this.faultPromise.then(this.resolveFaultWait, this.rejectFaultWait);
2687
+ this.faultPromise.catch(() => {});
2688
+ }
2689
+
2690
+ async _settleFault(postSpawn) {
2691
+ let cleanupError = null;
2692
+ try {
2693
+ await this.close();
2694
+ } catch (error) {
2695
+ cleanupError = error;
2696
+ }
2697
+ const outcome = Object.freeze({
2698
+ kind: 'codex-app-server-fault',
2699
+ boundary: postSpawn ? 'post-spawn' : 'pre-spawn',
2700
+ containment: postSpawn ? 'unverified' : 'safe',
2701
+ cleanup: cleanupError ? 'failed' : 'completed',
2702
+ errorCode: this.protocolError?.code ?? 'CODEX_PROTOCOL_ERROR',
2703
+ cleanupErrorCode: cleanupError?.code ?? null,
2704
+ mutationOutcomeUnknown:
2705
+ this.protocolError?.code === 'CODEX_RPC_OUTCOME_UNKNOWN',
2706
+ });
2707
+ try {
2708
+ await this._runSink(this.onFault, outcome, 'fault checkpoint');
2709
+ } catch (error) {
2710
+ const handoffError = new CodexAppServerError(
2711
+ 'app-server fault checkpoint failed',
2712
+ 'CODEX_FAULT_CHECKPOINT_FAILED',
2713
+ { cause: error },
2714
+ );
2715
+ try { this.emit('fault-checkpoint-error', handoffError); } catch {}
2716
+ throw handoffError;
2717
+ }
2718
+ this.faultOutcome = outcome;
2719
+ try { this.emit('fault-outcome', outcome); } catch {}
2720
+ return outcome;
2721
+ }
2722
+
2723
+ waitForFault() {
2724
+ return this.faultWaitPromise;
2725
+ }
2726
+
2727
+ _rejectAll(cause) {
2728
+ let ambiguousMutation = null;
2729
+ for (const pending of this.pending.values()) {
2730
+ this.clearTimer(pending.timer);
2731
+ pending.sinkController?.abort(cause);
2732
+ const requestError = pending.stateChanging
2733
+ ? mutationDeliveryError(pending, cause)
2734
+ : cause;
2735
+ if (
2736
+ requestError.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
2737
+ && ambiguousMutation === null
2738
+ ) ambiguousMutation = requestError;
2739
+ pending.reject(requestError);
2740
+ }
2741
+ this.pending.clear();
2742
+ return ambiguousMutation;
2743
+ }
2744
+
2745
+ assertHealthy() {
2746
+ if (this.protocolError) throw this.protocolError;
2747
+ if (this.state !== 'ready') {
2748
+ throw new CodexAppServerError(
2749
+ 'app-server client is not ready',
2750
+ 'CODEX_CLIENT_STATE',
2751
+ );
2752
+ }
2753
+ }
2754
+
2755
+ _childAlive() {
2756
+ return Boolean(
2757
+ this.child
2758
+ && !this.exitInfo
2759
+ && this.child.exitCode == null
2760
+ && this.child.signalCode == null,
2761
+ );
2762
+ }
2763
+
2764
+ _waitForExit(timeoutMs) {
2765
+ let timer;
2766
+ return Promise.race([
2767
+ this.exitPromise,
2768
+ new Promise((resolve) => {
2769
+ timer = this.setTimer(() => resolve(null), timeoutMs);
2770
+ }),
2771
+ ]).finally(() => {
2772
+ if (timer !== undefined) this.clearTimer(timer);
2773
+ });
2774
+ }
2775
+
2776
+ _delay(timeoutMs) {
2777
+ return new Promise((resolve) => {
2778
+ this.setTimer(resolve, timeoutMs);
2779
+ });
2780
+ }
2781
+
2782
+ _ownsProcessGroup() {
2783
+ return Number.isSafeInteger(this.child?.pid) && this.child.pid >= 2;
2784
+ }
2785
+
2786
+ _cleanupUnverified(message, cause) {
2787
+ return new CodexAppServerError(
2788
+ message,
2789
+ 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
2790
+ cause ? { cause } : undefined,
2791
+ );
2792
+ }
2793
+
2794
+ // Runs only after the supervisor has exited, and only ever reads: a group id
2795
+ // whose leader is gone may be recycled, so signalling it could reach an
2796
+ // unrelated process group. ESRCH is the sole proof that the group is empty.
2797
+ async _proveOwnedGroupEmpty(timeoutMs) {
2798
+ if (!this._ownsProcessGroup()) {
2799
+ throw this._cleanupUnverified(
2800
+ 'could not prove the owned app-server process group is empty',
2801
+ );
2802
+ }
2803
+ const deadline = Date.now() + timeoutMs;
2804
+ for (;;) {
2805
+ try {
2806
+ this.killFn(-this.child.pid, 0);
2807
+ } catch (error) {
2808
+ if (error?.code === 'ESRCH') return;
2809
+ throw this._cleanupUnverified(
2810
+ 'could not read the owned app-server process group',
2811
+ error,
2812
+ );
2813
+ }
2814
+ if (Date.now() >= deadline) {
2815
+ throw this._cleanupUnverified(
2816
+ 'the owned app-server process group still holds processes',
2817
+ );
2818
+ }
2819
+ await this._delay(Math.min(20, Math.max(1, deadline - Date.now())));
2820
+ }
2821
+ }
2822
+
2823
+ close() {
2824
+ if (this.closePromise) return this.closePromise;
2825
+ this.closePromise = this._close();
2826
+ return this.closePromise;
2827
+ }
2828
+
2829
+ async _close() {
2830
+ if (this.state === 'closed') return;
2831
+ this.state = 'closing';
2832
+ this._invalidateSinks();
2833
+ this._rejectAll(new CodexAppServerError(
2834
+ 'app-server client closed',
2835
+ 'CODEX_CLIENT_CLOSED',
2836
+ ));
2837
+ let cleanupError = null;
2838
+ if (this._childAlive()) {
2839
+ // Ending stdin is the whole shutdown request. Terminating the owned group
2840
+ // belongs to the supervisor: only the group's live leader can signal it
2841
+ // without racing its own exit and hitting a recycled group id.
2842
+ try { this.child.stdin.end(); } catch {}
2843
+ await this._waitForExit(this.closeGraceMs + this.closeKillMs);
2844
+ }
2845
+ if (this._childAlive()) {
2846
+ throw new CodexAppServerError(
2847
+ 'app-server supervisor did not terminate the owned process group',
2848
+ 'CODEX_PROCESS_CLOSE_TIMEOUT',
2849
+ );
2850
+ }
2851
+ // Nothing was ever spawned before a pre-spawn fault, so there is no owned
2852
+ // group to account for.
2853
+ if (this.child) {
2854
+ try {
2855
+ await this._proveOwnedGroupEmpty(this.closeKillMs);
2856
+ } catch (error) {
2857
+ cleanupError ??= error;
2858
+ }
2859
+ }
2860
+ this.stdoutBuffer = '';
2861
+ this.state = 'closed';
2862
+ if (!this.protocolError) this.resolveFaultWait(null);
2863
+ if (cleanupError) throw cleanupError;
2864
+ }
2865
+ }
2866
+
2867
+ module.exports = {
2868
+ CodexAppServerClient,
2869
+ CodexAppServerError,
2870
+ attestPinnedCodexBinary,
2871
+ attestPinnedCodexHome,
2872
+ buildCodexAppServerEnv,
2873
+ protocolSchema,
2874
+ };