@shumkov/orchestra 0.5.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,2814 @@
1
+ 'use strict';
2
+
3
+ const { randomUUID } = require('node:crypto');
4
+ const { isDeepStrictEqual } = require('node:util');
5
+
6
+ const { Process, UnsupportedOperationError } = require('./process');
7
+
8
+ const DEFAULT_QUEUE_CAP = 50;
9
+ const DEFAULT_TURN_START_TIMEOUT_MS = 20_000;
10
+ const DEFAULT_TURN_TIMEOUT_MS = 30 * 60_000;
11
+ const DEFAULT_INTERRUPT_TIMEOUT_MS = 20_000;
12
+ const DEFAULT_CLEANUP_TIMEOUT_MS = 20_000;
13
+ const DEFAULT_CLEANUP_POLL_MS = 100;
14
+ const DEFAULT_PROTOCOL_FAULT_THRESHOLD = 1;
15
+ const DEFAULT_MAX_TURN_TEXT_BYTES = 4 * 1024 * 1024;
16
+ const DEFAULT_STREAM_CHECKPOINT_BYTES = 64 * 1024;
17
+ const DEFAULT_MAX_TURN_ITEMS = 10_000;
18
+ const DEFAULT_MAX_TERMINAL_HISTORY = 1_024;
19
+ const DEFAULT_MAX_STEER_TEXT_BYTES = 256 * 1024;
20
+ const DEFAULT_MAX_PENDING_STEERS = 16;
21
+ const MAX_OPAQUE_ID_BYTES = 512;
22
+ const CONTROL_CHAR_RE = /[\x00-\x08\x0b-\x1f\x7f]/g;
23
+ const OPAQUE_ID_CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
24
+
25
+ class CodexProcessError extends Error {
26
+ constructor(message, code, options) {
27
+ super(message, options);
28
+ this.name = 'CodexProcessError';
29
+ this.code = code;
30
+ }
31
+ }
32
+
33
+ function makeDeferred() {
34
+ let resolve;
35
+ let reject;
36
+ const promise = new Promise((res, rej) => {
37
+ resolve = res;
38
+ reject = rej;
39
+ });
40
+ promise.catch(() => {});
41
+ return { promise, resolve, reject };
42
+ }
43
+
44
+ function nonEmptyString(value, label) {
45
+ if (typeof value !== 'string' || value.length === 0) {
46
+ throw new TypeError(`CodexProcess: ${label} (string) required`);
47
+ }
48
+ return value;
49
+ }
50
+
51
+ function optionalString(value, label) {
52
+ if (value == null) return null;
53
+ return nonEmptyString(value, label);
54
+ }
55
+
56
+ function boundedOpaqueId(value, label) {
57
+ if (
58
+ typeof value !== 'string'
59
+ || value.length === 0
60
+ || Buffer.byteLength(value, 'utf8') > MAX_OPAQUE_ID_BYTES
61
+ || OPAQUE_ID_CONTROL_CHAR_RE.test(value)
62
+ ) {
63
+ throw new TypeError(`CodexProcess: bounded ${label} required`);
64
+ }
65
+ return value;
66
+ }
67
+
68
+ function processError(message, code, options) {
69
+ return new CodexProcessError(message, code, options);
70
+ }
71
+
72
+ function modelSettings(model, effort, label = 'settings') {
73
+ return Object.freeze({
74
+ model: nonEmptyString(model, `${label}.model`),
75
+ effort: nonEmptyString(effort, `${label}.effort`),
76
+ });
77
+ }
78
+
79
+ function dynamicSettings(source) {
80
+ return modelSettings(
81
+ source?.model,
82
+ source?.reasoningEffort ?? source?.effort,
83
+ 'thread settings',
84
+ );
85
+ }
86
+
87
+ function staticThreadPolicy(source) {
88
+ return {
89
+ modelProvider: source?.modelProvider,
90
+ approvalPolicy: source?.approvalPolicy,
91
+ approvalsReviewer: source?.approvalsReviewer,
92
+ sandbox: source?.sandbox ?? source?.sandboxPolicy,
93
+ permissionProfile: source?.activePermissionProfile,
94
+ };
95
+ }
96
+
97
+ function isDeepFrozen(value) {
98
+ if (!value || typeof value !== 'object' || !Object.isFrozen(value)) {
99
+ return false;
100
+ }
101
+ return Object.values(value).every((entry) => (
102
+ !entry
103
+ || typeof entry !== 'object'
104
+ || isDeepFrozen(entry)
105
+ ));
106
+ }
107
+
108
+ function timeout(promise, timeoutMs, message, code) {
109
+ let timer;
110
+ return Promise.race([
111
+ promise,
112
+ new Promise((resolve, reject) => {
113
+ timer = setTimeout(() => reject(processError(message, code)), timeoutMs);
114
+ timer.unref?.();
115
+ }),
116
+ ]).finally(() => clearTimeout(timer));
117
+ }
118
+
119
+ function delay(timeoutMs) {
120
+ return new Promise((resolve) => {
121
+ const timer = setTimeout(resolve, timeoutMs);
122
+ timer.unref?.();
123
+ });
124
+ }
125
+
126
+ class CodexProcess extends Process {
127
+ get state() {
128
+ return this._state;
129
+ }
130
+
131
+ set state(next) {
132
+ if (
133
+ this._state === 'ContainmentFailed'
134
+ && next !== 'ContainmentFailed'
135
+ ) return;
136
+ if (
137
+ this._state === 'DurabilityBlocked'
138
+ && next !== 'DurabilityBlocked'
139
+ && next !== 'ContainmentFailed'
140
+ ) return;
141
+ if (
142
+ this._state === 'FailedAmbiguous'
143
+ && ![
144
+ 'FailedAmbiguous',
145
+ 'DurabilityBlocked',
146
+ 'ContainmentFailed',
147
+ ].includes(next)
148
+ ) return;
149
+ this._state = next;
150
+ }
151
+
152
+ constructor({
153
+ sessionKey,
154
+ chatId,
155
+ threadId,
156
+ label,
157
+ cwd,
158
+ clientFactory,
159
+ staticPolicyAttestor = async () => {},
160
+ checkpointSink,
161
+ hostIdentity,
162
+ bootSessionIdentity,
163
+ generationIdFactory = randomUUID,
164
+ clientUserMessageIdFactory = randomUUID,
165
+ mutationAttemptIdFactory = randomUUID,
166
+ expectedStaticPolicy,
167
+ expectedThreadPolicy,
168
+ modelCatalog,
169
+ queueCap = DEFAULT_QUEUE_CAP,
170
+ turnStartTimeoutMs = DEFAULT_TURN_START_TIMEOUT_MS,
171
+ turnTimeoutMs = DEFAULT_TURN_TIMEOUT_MS,
172
+ interruptTimeoutMs = DEFAULT_INTERRUPT_TIMEOUT_MS,
173
+ cleanupTimeoutMs = DEFAULT_CLEANUP_TIMEOUT_MS,
174
+ cleanupPollMs = DEFAULT_CLEANUP_POLL_MS,
175
+ protocolFaultThreshold = DEFAULT_PROTOCOL_FAULT_THRESHOLD,
176
+ maxTurnTextBytes = DEFAULT_MAX_TURN_TEXT_BYTES,
177
+ streamCheckpointBytes = DEFAULT_STREAM_CHECKPOINT_BYTES,
178
+ maxTurnItems = DEFAULT_MAX_TURN_ITEMS,
179
+ maxTerminalHistory = DEFAULT_MAX_TERMINAL_HISTORY,
180
+ maxSteerTextBytes = DEFAULT_MAX_STEER_TEXT_BYTES,
181
+ maxPendingSteers = DEFAULT_MAX_PENDING_STEERS,
182
+ logger = console,
183
+ } = {}) {
184
+ super({ sessionKey, chatId, threadId, label });
185
+ this.backend = 'codex';
186
+ this.cwd = nonEmptyString(cwd, 'cwd');
187
+ if (typeof clientFactory !== 'function') {
188
+ throw new TypeError('CodexProcess: clientFactory required');
189
+ }
190
+ if (typeof checkpointSink !== 'function') {
191
+ throw new TypeError('CodexProcess: checkpointSink required');
192
+ }
193
+ if (typeof staticPolicyAttestor !== 'function') {
194
+ throw new TypeError(
195
+ 'CodexProcess: staticPolicyAttestor must be a function',
196
+ );
197
+ }
198
+ if (typeof generationIdFactory !== 'function') {
199
+ throw new TypeError('CodexProcess: generationIdFactory must be a function');
200
+ }
201
+ if (typeof clientUserMessageIdFactory !== 'function') {
202
+ throw new TypeError(
203
+ 'CodexProcess: clientUserMessageIdFactory must be a function',
204
+ );
205
+ }
206
+ if (typeof mutationAttemptIdFactory !== 'function') {
207
+ throw new TypeError(
208
+ 'CodexProcess: mutationAttemptIdFactory must be a function',
209
+ );
210
+ }
211
+ for (const [value, name] of [
212
+ [queueCap, 'queueCap'],
213
+ [turnStartTimeoutMs, 'turnStartTimeoutMs'],
214
+ [turnTimeoutMs, 'turnTimeoutMs'],
215
+ [interruptTimeoutMs, 'interruptTimeoutMs'],
216
+ [cleanupTimeoutMs, 'cleanupTimeoutMs'],
217
+ [cleanupPollMs, 'cleanupPollMs'],
218
+ [protocolFaultThreshold, 'protocolFaultThreshold'],
219
+ [maxTurnTextBytes, 'maxTurnTextBytes'],
220
+ [streamCheckpointBytes, 'streamCheckpointBytes'],
221
+ [maxTurnItems, 'maxTurnItems'],
222
+ [maxTerminalHistory, 'maxTerminalHistory'],
223
+ [maxSteerTextBytes, 'maxSteerTextBytes'],
224
+ [maxPendingSteers, 'maxPendingSteers'],
225
+ ]) {
226
+ if (!Number.isSafeInteger(value) || value < 1) {
227
+ throw new TypeError(`CodexProcess: ${name} must be a positive integer`);
228
+ }
229
+ }
230
+
231
+ this.clientFactory = clientFactory;
232
+ this.staticPolicyAttestor = staticPolicyAttestor;
233
+ this.checkpointSink = checkpointSink;
234
+ this.hostIdentity = nonEmptyString(hostIdentity, 'hostIdentity');
235
+ this.bootSessionIdentity = nonEmptyString(
236
+ bootSessionIdentity,
237
+ 'bootSessionIdentity',
238
+ );
239
+ this.generationId = boundedOpaqueId(
240
+ generationIdFactory(),
241
+ 'generationId',
242
+ );
243
+ this.clientUserMessageIdFactory = clientUserMessageIdFactory;
244
+ this.mutationAttemptIdFactory = mutationAttemptIdFactory;
245
+ const legacyPolicy = expectedThreadPolicy;
246
+ const resolvedStaticPolicy = expectedStaticPolicy ?? (
247
+ legacyPolicy
248
+ ? Object.freeze({
249
+ modelProvider: legacyPolicy.modelProvider,
250
+ approvalPolicy: legacyPolicy.approvalPolicy,
251
+ approvalsReviewer: legacyPolicy.approvalsReviewer,
252
+ sandbox: legacyPolicy.sandbox,
253
+ permissionProfile: legacyPolicy.permissionProfile,
254
+ })
255
+ : null
256
+ );
257
+ if (!isDeepFrozen(resolvedStaticPolicy)) {
258
+ throw new TypeError(
259
+ 'CodexProcess: expectedStaticPolicy must be deeply frozen',
260
+ );
261
+ }
262
+ this.expectedStaticPolicy = resolvedStaticPolicy;
263
+ this.expectedPermissionProfileId = nonEmptyString(
264
+ resolvedStaticPolicy.permissionProfile?.id,
265
+ 'expectedStaticPolicy.permissionProfile.id',
266
+ );
267
+ const resolvedCatalog = modelCatalog ?? (
268
+ legacyPolicy?.model && legacyPolicy?.effort
269
+ ? [{
270
+ model: legacyPolicy.model,
271
+ supportedReasoningEfforts: [legacyPolicy.effort],
272
+ }]
273
+ : null
274
+ );
275
+ if (!Array.isArray(resolvedCatalog) || resolvedCatalog.length === 0) {
276
+ throw new TypeError('CodexProcess: modelCatalog required');
277
+ }
278
+ this.modelCatalog = Object.freeze(resolvedCatalog.map((entry) => {
279
+ const model = nonEmptyString(entry?.model, 'modelCatalog.model');
280
+ if (
281
+ !Array.isArray(entry.supportedReasoningEfforts)
282
+ || entry.supportedReasoningEfforts.length === 0
283
+ ) {
284
+ throw new TypeError(
285
+ 'CodexProcess: modelCatalog supportedReasoningEfforts required',
286
+ );
287
+ }
288
+ return Object.freeze({
289
+ model,
290
+ supportedReasoningEfforts: Object.freeze(
291
+ entry.supportedReasoningEfforts.map((effort) => (
292
+ nonEmptyString(effort, 'modelCatalog.effort')
293
+ )),
294
+ ),
295
+ });
296
+ }));
297
+ this.queueCap = queueCap;
298
+ this.streamCheckpointBytes = streamCheckpointBytes;
299
+ this.turnStartTimeoutMs = turnStartTimeoutMs;
300
+ this.turnTimeoutMs = turnTimeoutMs;
301
+ this.interruptTimeoutMs = interruptTimeoutMs;
302
+ this.cleanupTimeoutMs = cleanupTimeoutMs;
303
+ this.cleanupPollMs = cleanupPollMs;
304
+ this.protocolFaultThreshold = protocolFaultThreshold;
305
+ this.maxTurnTextBytes = maxTurnTextBytes;
306
+ this.maxTurnItems = maxTurnItems;
307
+ this.maxTerminalHistory = maxTerminalHistory;
308
+ this.maxSteerTextBytes = maxSteerTextBytes;
309
+ this.maxPendingSteers = maxPendingSteers;
310
+ this.logger = logger;
311
+
312
+ this.state = 'Spawning';
313
+ this.lifecycleEpoch = 0;
314
+ this.providerSessionId = null;
315
+ this.attachingThreadId = null;
316
+ this.activeTurnId = null;
317
+ this.lastTurnId = null;
318
+ this.lastTerminal = null;
319
+ this.threadStatusType = null;
320
+ this.desiredSettings = null;
321
+ this.observedThreadSettings = null;
322
+ this.admittingTurnSettings = null;
323
+ this.activeTurnSettings = null;
324
+ this.settingsGate = Promise.resolve();
325
+ this.settingsAdmissionClosed = false;
326
+ this.client = null;
327
+ this.current = null;
328
+ this.steerChain = Promise.resolve();
329
+ this.pendingSteerCount = 0;
330
+ this.startPromise = null;
331
+ this.killPromise = null;
332
+ this.interruptPromise = null;
333
+ this.backgroundSettlementPromise = null;
334
+ this.backgroundWatchdog = null;
335
+ this.backgroundWatchdogDeadlineAt = null;
336
+ this.backgroundWatchdogPromise = null;
337
+ this.backgroundCleanupProof = null;
338
+ this.cancellationFlushPromise = null;
339
+ this.pendingCancellations = [];
340
+ this.cancellationSequence = 0;
341
+ this.containmentClosePromise = null;
342
+ this.closeEmitted = false;
343
+ this.protocolFaultCount = 0;
344
+ this.containmentReason = null;
345
+ this.containmentError = null;
346
+ this.startupReleaseSafe = false;
347
+ this.stateChangingWriteCommitted = false;
348
+ this.terminalTurnIds = new Set();
349
+ this.terminalTurnOrder = [];
350
+ this.lastUsedTs = Date.now();
351
+ }
352
+
353
+ get cost() {
354
+ return 1;
355
+ }
356
+
357
+ _captureLifecycle() {
358
+ return Object.freeze({ epoch: this.lifecycleEpoch });
359
+ }
360
+
361
+ _advanceLifecycle() {
362
+ this.lifecycleEpoch += 1;
363
+ }
364
+
365
+ _assertLifecycle(fence) {
366
+ if (
367
+ fence?.epoch !== this.lifecycleEpoch
368
+ || this.state === 'ContainmentFailed'
369
+ || this.state === 'DurabilityBlocked'
370
+ || this.state === 'FailedAmbiguous'
371
+ ) {
372
+ throw this._lifecycleFenceError();
373
+ }
374
+ }
375
+
376
+ _lifecycleFenceError() {
377
+ if (this.state === 'ContainmentFailed') {
378
+ return processError(
379
+ 'Codex lifecycle was superseded by containment',
380
+ 'CODEX_CONTAINMENT_FAILED',
381
+ { cause: this.containmentError },
382
+ );
383
+ }
384
+ if (this.state === 'DurabilityBlocked') {
385
+ return processError(
386
+ 'Codex lifecycle was superseded by a durability fence',
387
+ 'CODEX_DURABILITY_FAILED',
388
+ );
389
+ }
390
+ return processError(
391
+ 'Codex lifecycle continuation was superseded',
392
+ 'CODEX_LIFECYCLE_SUPERSEDED',
393
+ );
394
+ }
395
+
396
+ start(options = {}) {
397
+ if (this.startPromise) return this.startPromise;
398
+ this.startPromise = this._start(options);
399
+ return this.startPromise;
400
+ }
401
+
402
+ async _start(options) {
403
+ const lifecycle = this._captureLifecycle();
404
+ const existingSessionId = optionalString(
405
+ options.existingSessionId
406
+ ?? options.providerSessionId
407
+ ?? options.codexThreadId,
408
+ 'existingSessionId',
409
+ );
410
+ this.desiredSettings = this._validatedModelSettings({
411
+ model: options.model ?? options.chatConfig?.model,
412
+ effort: options.effort ?? options.chatConfig?.effort,
413
+ });
414
+ this.state = 'Initializing';
415
+ const generationId = this.generationId;
416
+ let threadAccepted = false;
417
+ try {
418
+ this.client = this.clientFactory({
419
+ onNotification: (notification) => {
420
+ if (generationId !== this.generationId) return undefined;
421
+ return this._handleNotification(notification);
422
+ },
423
+ onFault: (outcome) => {
424
+ if (generationId !== this.generationId) return undefined;
425
+ return this._handleClientFault(outcome);
426
+ },
427
+ });
428
+ if (
429
+ !this.client
430
+ || typeof this.client.start !== 'function'
431
+ || typeof this.client.request !== 'function'
432
+ || typeof this.client.close !== 'function'
433
+ || typeof this.client.waitForFault !== 'function'
434
+ ) {
435
+ throw new TypeError(
436
+ 'CodexProcess: clientFactory returned an invalid client',
437
+ );
438
+ }
439
+ await this.client.start();
440
+ this._assertLifecycle(lifecycle);
441
+ this.state = 'AttachingThread';
442
+ this.attachingThreadId = existingSessionId;
443
+ const result = await this._withSettingsGate(async () => (
444
+ existingSessionId
445
+ ? this._mutation('thread/resume', {
446
+ threadId: existingSessionId,
447
+ }, { source: null })
448
+ : this._mutation('thread/start', {
449
+ cwd: this.cwd,
450
+ model: this.desiredSettings.model,
451
+ }, { source: null })
452
+ ));
453
+ this._assertLifecycle(lifecycle);
454
+ threadAccepted = true;
455
+ if (typeof result?.thread?.id === 'string' && result.thread.id.length > 0) {
456
+ this.providerSessionId = result.thread.id;
457
+ }
458
+ this._validateThreadResult(result, existingSessionId);
459
+ if (
460
+ this.attachingThreadId
461
+ && result.thread.id !== this.attachingThreadId
462
+ ) {
463
+ throw processError(
464
+ 'Codex thread notifications disagreed with the attached thread',
465
+ 'CODEX_PROTOCOL_ERROR',
466
+ );
467
+ }
468
+ this.attachingThreadId = null;
469
+ this.claudeSessionId = this.providerSessionId;
470
+ await this._checkpoint('thread-initialized', {
471
+ threadId: this.providerSessionId,
472
+ model: this.desiredSettings.model,
473
+ effort: this.desiredSettings.effort,
474
+ resumed: Boolean(existingSessionId),
475
+ });
476
+ this._assertLifecycle(lifecycle);
477
+ const init = {
478
+ type: 'system',
479
+ subtype: 'init',
480
+ session_id: this.providerSessionId,
481
+ providerSessionId: this.providerSessionId,
482
+ generationId: this.generationId,
483
+ backend: this.backend,
484
+ };
485
+ this.emit('init', init);
486
+ if (result.thread.status.type === 'active') {
487
+ this.state = 'RecoveryConflict';
488
+ this.emit('codex-lifecycle', this._lifecyclePayload(
489
+ 'recovery-conflict',
490
+ { reason: 'resumed-thread-active' },
491
+ ));
492
+ } else {
493
+ this.state = 'Idle';
494
+ this.emit('idle');
495
+ }
496
+ return this;
497
+ } catch (error) {
498
+ const durability = this._durabilityFailure(error);
499
+ if (
500
+ !threadAccepted
501
+ && !this.stateChangingWriteCommitted
502
+ && durability?.deliveryState === 'not-sent'
503
+ ) {
504
+ this._blockDurability(durability);
505
+ throw processError(
506
+ 'Codex startup durability failed before thread attachment',
507
+ 'CODEX_DURABILITY_FAILED',
508
+ { cause: durability },
509
+ );
510
+ }
511
+ if (
512
+ threadAccepted
513
+ || this.stateChangingWriteCommitted
514
+ || this.state === 'ContainmentFailed'
515
+ || this.state === 'DurabilityBlocked'
516
+ || this.state === 'FailedAmbiguous'
517
+ || error?.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
518
+ || error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
519
+ || error?.code === 'CODEX_DURABILITY_FAILED'
520
+ ) {
521
+ if (this.state !== 'ContainmentFailed') {
522
+ await this._enterContainment(
523
+ threadAccepted
524
+ ? 'thread-accepted-before-startup-failure'
525
+ : 'thread-attach-outcome-unknown',
526
+ error,
527
+ );
528
+ }
529
+ throw error;
530
+ }
531
+ try {
532
+ await this._verifyStartupRelease();
533
+ } catch (closeError) {
534
+ await this._enterContainment(
535
+ 'startup-close-unverified',
536
+ closeError,
537
+ );
538
+ }
539
+ throw error;
540
+ }
541
+ }
542
+
543
+ async _verifyStartupRelease() {
544
+ if (!this.client) {
545
+ this.startupReleaseSafe = true;
546
+ } else {
547
+ await this.client.close();
548
+ const terminalOutcome = await this.client.waitForFault();
549
+ const verifiedSafeFault = (
550
+ terminalOutcome?.boundary === 'pre-spawn'
551
+ && terminalOutcome?.containment === 'safe'
552
+ && terminalOutcome?.cleanup === 'completed'
553
+ && terminalOutcome?.mutationOutcomeUnknown !== true
554
+ );
555
+ if (terminalOutcome !== null && !verifiedSafeFault) {
556
+ throw processError(
557
+ 'Codex startup client did not prove a safe terminal close',
558
+ 'CODEX_STARTUP_CLOSE_UNVERIFIED',
559
+ );
560
+ }
561
+ this.startupReleaseSafe = true;
562
+ }
563
+ this.state = 'Closed';
564
+ this.closed = true;
565
+ this._emitClose(1);
566
+ }
567
+
568
+ _validateThreadResult(result, expectedThreadId) {
569
+ if (!result?.thread?.id) {
570
+ throw processError(
571
+ 'Codex thread response omitted the thread ID',
572
+ 'CODEX_PROTOCOL_ERROR',
573
+ );
574
+ }
575
+ if (expectedThreadId && result.thread.id !== expectedThreadId) {
576
+ throw processError(
577
+ 'Codex resumed a different provider thread',
578
+ 'CODEX_PROTOCOL_ERROR',
579
+ );
580
+ }
581
+ this._validateAndObserveThreadPolicy(result, { attaching: true });
582
+ }
583
+
584
+ _validateAndObserveThreadPolicy(source, { attaching = false } = {}) {
585
+ const actualStaticPolicy = staticThreadPolicy(source);
586
+ if (!isDeepStrictEqual(actualStaticPolicy, this.expectedStaticPolicy)) {
587
+ throw processError(
588
+ 'Codex thread did not attest the exact trusted static policy',
589
+ 'CODEX_THREAD_POLICY_MISMATCH',
590
+ );
591
+ }
592
+ let observed;
593
+ try {
594
+ observed = dynamicSettings(source);
595
+ } catch (cause) {
596
+ throw processError(
597
+ 'Codex thread omitted its dynamic settings',
598
+ 'CODEX_PROTOCOL_ERROR',
599
+ { cause },
600
+ );
601
+ }
602
+ const collaboration = source?.collaborationMode;
603
+ if (
604
+ collaboration != null
605
+ && (
606
+ collaboration.mode !== 'default'
607
+ || collaboration.model !== observed.model
608
+ || (
609
+ collaboration.reasoningEffort != null
610
+ && collaboration.reasoningEffort !== observed.effort
611
+ )
612
+ )
613
+ ) {
614
+ throw processError(
615
+ 'Codex collaboration settings disagreed with the observed turn settings',
616
+ 'CODEX_THREAD_POLICY_MISMATCH',
617
+ );
618
+ }
619
+ const accepted = [
620
+ this.observedThreadSettings,
621
+ this.admittingTurnSettings,
622
+ this.activeTurnSettings,
623
+ ].filter(Boolean);
624
+ if (
625
+ !attaching
626
+ && !accepted.some((candidate) => isDeepStrictEqual(candidate, observed))
627
+ ) {
628
+ throw processError(
629
+ 'Codex thread reported unexplained dynamic settings',
630
+ 'CODEX_THREAD_SETTINGS_MISMATCH',
631
+ );
632
+ }
633
+ if (
634
+ attaching
635
+ && this.observedThreadSettings
636
+ && !isDeepStrictEqual(this.observedThreadSettings, observed)
637
+ ) {
638
+ throw processError(
639
+ 'Codex thread attachment reported inconsistent dynamic settings',
640
+ 'CODEX_THREAD_SETTINGS_MISMATCH',
641
+ );
642
+ }
643
+ this.observedThreadSettings = observed;
644
+ }
645
+
646
+ _validatedModelSettings(settings) {
647
+ const selected = modelSettings(settings?.model, settings?.effort);
648
+ const catalogEntry = this.modelCatalog.find(
649
+ (entry) => entry.model === selected.model,
650
+ );
651
+ if (!catalogEntry) {
652
+ throw processError(
653
+ 'Codex model is unavailable in the authenticated catalog',
654
+ 'CODEX_MODEL_UNAVAILABLE',
655
+ );
656
+ }
657
+ if (!catalogEntry.supportedReasoningEfforts.includes(selected.effort)) {
658
+ throw processError(
659
+ 'Codex reasoning effort is unavailable for the selected model',
660
+ 'CODEX_EFFORT_UNAVAILABLE',
661
+ );
662
+ }
663
+ return selected;
664
+ }
665
+
666
+ _withSettingsGate(operation) {
667
+ const run = this.settingsGate
668
+ .catch(() => {})
669
+ .then(operation);
670
+ this.settingsGate = run.catch(() => {});
671
+ return run;
672
+ }
673
+
674
+ _closeSettingsAdmission() {
675
+ // Closing admission must be observable by a turn start that currently
676
+ // holds the gate so interruption can cancel it before transport dispatch.
677
+ this.settingsAdmissionClosed = true;
678
+ }
679
+
680
+ send(prompt, {
681
+ timeoutMs = this.turnTimeoutMs,
682
+ maxTurnMs = this.turnTimeoutMs,
683
+ context = {},
684
+ } = {}) {
685
+ if (typeof prompt !== 'string' || prompt.length === 0) {
686
+ return Promise.reject(new TypeError('CodexProcess.send: prompt required'));
687
+ }
688
+ const safePrompt = prompt.replace(CONTROL_CHAR_RE, '');
689
+ if (safePrompt.length !== prompt.length) {
690
+ this.emit('prompt-sanitized', {
691
+ stripped: prompt.length - safePrompt.length,
692
+ source: 'send',
693
+ });
694
+ prompt = safePrompt;
695
+ }
696
+ if (prompt.length === 0) {
697
+ return Promise.reject(new TypeError(
698
+ 'CodexProcess.send: prompt was empty after sanitization',
699
+ ));
700
+ }
701
+ const unavailable = this._newWorkError();
702
+ if (unavailable) return Promise.reject(unavailable);
703
+ if (
704
+ !Number.isSafeInteger(timeoutMs)
705
+ || timeoutMs < 1
706
+ || !Number.isSafeInteger(maxTurnMs)
707
+ || maxTurnMs < 1
708
+ ) {
709
+ return Promise.reject(new TypeError('CodexProcess.send: invalid timeout'));
710
+ }
711
+
712
+ this.lastUsedTs = Date.now();
713
+ const pending = {
714
+ prompt,
715
+ context,
716
+ timeoutMs: Math.min(timeoutMs, maxTurnMs),
717
+ maxTurnMs,
718
+ clientUserMessageId: nonEmptyString(
719
+ this.clientUserMessageIdFactory(),
720
+ 'generated clientUserMessageId',
721
+ ),
722
+ attemptId: boundedOpaqueId(
723
+ this.mutationAttemptIdFactory(),
724
+ 'mutation attemptId',
725
+ ),
726
+ turnId: null,
727
+ responseSeen: false,
728
+ startedSeen: false,
729
+ startDeliveryState: 'preparing',
730
+ startResponseOutcome: null,
731
+ startCancellationRequested: false,
732
+ startDisposition: makeDeferred(),
733
+ terminal: null,
734
+ terminalDeferred: makeDeferred(),
735
+ turnReady: makeDeferred(),
736
+ streamText: '',
737
+ streamTextBytes: 0,
738
+ uncheckpointedDeltaBytes: 0,
739
+ deltaCheckpointObserved: false,
740
+ lastStreamItemId: null,
741
+ itemText: new Map(),
742
+ completedItemText: new Map(),
743
+ itemIds: new Set(),
744
+ firstStreamFired: false,
745
+ startedAt: null,
746
+ deadlineAt: null,
747
+ settled: false,
748
+ cancelled: false,
749
+ resolve: null,
750
+ reject: null,
751
+ promise: null,
752
+ };
753
+ pending.promise = new Promise((resolve, reject) => {
754
+ pending.resolve = resolve;
755
+ pending.reject = reject;
756
+ });
757
+ pending.promise.catch(() => {});
758
+ this.pendingQueue.push(pending);
759
+
760
+ const waitingCount = this.pendingQueue.length - (this.current ? 1 : 0);
761
+ if (waitingCount > this.queueCap) {
762
+ this.pendingQueue.pop();
763
+ const error = processError(
764
+ `Codex send queue is full (cap ${this.queueCap})`,
765
+ 'QUEUE_OVERFLOW',
766
+ );
767
+ error.context = context;
768
+ pending.settled = true;
769
+ pending.reject(error);
770
+ this.emit('queue-drop', pending);
771
+ return pending.promise;
772
+ }
773
+ this._pump();
774
+ return pending.promise;
775
+ }
776
+
777
+ _pump() {
778
+ if (
779
+ this.current
780
+ || this.closed
781
+ || [
782
+ 'Quiescing',
783
+ 'Stopped',
784
+ 'ContainmentFailed',
785
+ 'FailedAmbiguous',
786
+ 'RecoveryConflict',
787
+ 'DurabilityBlocked',
788
+ 'Settling',
789
+ 'BackgroundWorking',
790
+ 'BackgroundSettling',
791
+ ]
792
+ .includes(this.state)
793
+ ) return;
794
+ const pending = this.pendingQueue[0];
795
+ if (!pending) {
796
+ this.inFlight = false;
797
+ if (this.state !== 'BackgroundWorking') this.state = 'Idle';
798
+ this.emit('idle');
799
+ return;
800
+ }
801
+ this.current = pending;
802
+ this.inFlight = true;
803
+ pending.startedAt = Date.now();
804
+ pending.deadlineAt = pending.startedAt + pending.maxTurnMs;
805
+ this.state = 'StartingTurn';
806
+ try {
807
+ pending.context?.onActivate?.();
808
+ } catch (error) {
809
+ this.logger.error?.(`[${this.label}] onActivate: ${error.message}`);
810
+ }
811
+ void this._runTurn(pending);
812
+ }
813
+
814
+ async _runTurn(pending) {
815
+ const lifecycle = this._captureLifecycle();
816
+ try {
817
+ const responseTurnId = await this._withSettingsGate(async () => {
818
+ if (this.settingsAdmissionClosed || this.state === 'Quiescing') {
819
+ throw processError(
820
+ 'Codex turn start was cancelled before admission',
821
+ 'CODEX_RPC_NOT_SENT',
822
+ );
823
+ }
824
+ const admittedSettings = this.desiredSettings;
825
+ pending.admittedSettings = admittedSettings;
826
+ this.admittingTurnSettings = admittedSettings;
827
+ const params = {
828
+ threadId: this.providerSessionId,
829
+ input: [{ type: 'text', text: pending.prompt }],
830
+ clientUserMessageId: pending.clientUserMessageId,
831
+ model: admittedSettings.model,
832
+ effort: admittedSettings.effort,
833
+ };
834
+ try {
835
+ try {
836
+ await this.staticPolicyAttestor(this.client);
837
+ } catch (cause) {
838
+ const error = processError(
839
+ 'Codex static policy changed before turn dispatch',
840
+ cause?.code ?? 'CODEX_STATIC_PROFILE_MISMATCH',
841
+ { cause },
842
+ );
843
+ error.deliveryState = 'not-sent';
844
+ throw error;
845
+ }
846
+ const result = await this._mutation('turn/start', params, {
847
+ source: pending.context?.sourceMsgId ?? null,
848
+ clientUserMessageId: pending.clientUserMessageId,
849
+ attemptId: pending.attemptId,
850
+ timeoutMs: this._remainingTurnBudget(pending),
851
+ onDeliveryState: (deliveryState, outcome = null) => {
852
+ pending.startDeliveryState = deliveryState;
853
+ if (deliveryState === 'response-observed') {
854
+ pending.startResponseOutcome = outcome;
855
+ }
856
+ },
857
+ assertCanWrite: () => {
858
+ if (
859
+ pending.startCancellationRequested
860
+ || this.settingsAdmissionClosed
861
+ || this.state === 'Quiescing'
862
+ ) {
863
+ if (pending.turnId) return;
864
+ throw processError(
865
+ 'Codex turn start was cancelled before dispatch',
866
+ 'CODEX_RPC_NOT_SENT',
867
+ );
868
+ }
869
+ },
870
+ });
871
+ this._assertLifecycle(lifecycle);
872
+ const turnId = result?.turn?.id;
873
+ if (!turnId) {
874
+ throw await this._runtimeProtocolFault(
875
+ 'turn-start-response-missing-id',
876
+ 'Codex turn/start response omitted its turn ID',
877
+ );
878
+ }
879
+ if (pending.turnId && pending.turnId !== turnId) {
880
+ throw await this._runtimeProtocolFault(
881
+ 'turn-start-id-mismatch',
882
+ 'Codex turn/start response disagreed with turn/started',
883
+ );
884
+ }
885
+ await this._checkpoint('turn-accepted', {
886
+ ...this._turnDetail(pending),
887
+ turnId,
888
+ model: admittedSettings.model,
889
+ effort: admittedSettings.effort,
890
+ });
891
+ this._assertLifecycle(lifecycle);
892
+ this.activeTurnSettings = admittedSettings;
893
+ return turnId;
894
+ } finally {
895
+ if (this.admittingTurnSettings === admittedSettings) {
896
+ this.admittingTurnSettings = null;
897
+ }
898
+ }
899
+ });
900
+ this._assertLifecycle(lifecycle);
901
+ pending.turnId = responseTurnId;
902
+ pending.responseSeen = true;
903
+ pending.startDeliveryState = 'accepted';
904
+ this.activeTurnId = responseTurnId;
905
+ this.lastTurnId = responseTurnId;
906
+ pending.startDisposition.resolve({
907
+ kind: 'accepted',
908
+ turnId: responseTurnId,
909
+ });
910
+ if (pending.startedSeen) pending.turnReady.resolve(responseTurnId);
911
+ await timeout(
912
+ pending.turnReady.promise,
913
+ Math.min(
914
+ this.turnStartTimeoutMs,
915
+ this._remainingTurnBudget(pending),
916
+ ),
917
+ 'Codex turn/started notification was not observed',
918
+ 'CODEX_TURN_START_TIMEOUT',
919
+ );
920
+ this._assertLifecycle(lifecycle);
921
+ if (this.state === 'StartingTurn') {
922
+ this.state = 'Active';
923
+ }
924
+
925
+ const terminal = await timeout(
926
+ pending.terminalDeferred.promise,
927
+ Math.min(pending.timeoutMs, this._remainingTurnBudget(pending)),
928
+ 'Codex turn did not reach a terminal state',
929
+ 'CODEX_TURN_TIMEOUT',
930
+ );
931
+ this._assertLifecycle(lifecycle);
932
+ if (pending.settled) return;
933
+ try {
934
+ await this._refreshBackgroundState(pending, lifecycle);
935
+ this._assertLifecycle(lifecycle);
936
+ } catch (error) {
937
+ if (this.state !== 'ContainmentFailed') {
938
+ await this._enterContainment(
939
+ 'background-probe-failed',
940
+ error,
941
+ pending,
942
+ );
943
+ }
944
+ throw error;
945
+ }
946
+ this._assertLifecycle(lifecycle);
947
+ this._resolveTurn(pending, terminal);
948
+ } catch (error) {
949
+ this._resolveStartDispositionFromError(pending, error);
950
+ if (pending.settled) return;
951
+ if (
952
+ this.state === 'ContainmentFailed'
953
+ || this.state === 'DurabilityBlocked'
954
+ || this.state === 'FailedAmbiguous'
955
+ ) {
956
+ const durability = this._durabilityFailure(error);
957
+ const rejection = (
958
+ error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
959
+ || durability
960
+ )
961
+ ? processError(
962
+ 'Codex durability checkpoint failed after dispatch',
963
+ 'CODEX_DURABILITY_FAILED',
964
+ { cause: error },
965
+ )
966
+ : this._lifecycleFenceError();
967
+ this._rejectPending(pending, rejection);
968
+ return;
969
+ }
970
+ const normalized = await this._classifyTurnFailure(error, pending);
971
+ this._rejectPending(pending, normalized);
972
+ } finally {
973
+ this._finishPending(pending);
974
+ }
975
+ }
976
+
977
+ _remainingTurnBudget(pending) {
978
+ const remaining = (pending.deadlineAt ?? Date.now()) - Date.now();
979
+ if (remaining < 1) {
980
+ throw processError(
981
+ 'Codex turn exceeded its activation deadline',
982
+ 'CODEX_TURN_TIMEOUT',
983
+ );
984
+ }
985
+ return remaining;
986
+ }
987
+
988
+ _resolveStartDispositionFromError(pending, error) {
989
+ if (pending.startDeliveryState === 'accepted') return;
990
+ const durability = this._durabilityFailure(error);
991
+ if (
992
+ error?.code === 'CODEX_RPC_NOT_SENT'
993
+ || durability?.deliveryState === 'not-sent'
994
+ ) {
995
+ pending.startDeliveryState = 'definitely-not-sent';
996
+ pending.startDisposition.resolve({ kind: 'definitely-not-sent' });
997
+ return;
998
+ }
999
+ if (
1000
+ error?.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
1001
+ || error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
1002
+ || durability?.deliveryState === 'ambiguous'
1003
+ || pending.startDeliveryState === 'write-attempted'
1004
+ || pending.startDeliveryState === 'response-observed'
1005
+ ) {
1006
+ pending.startDeliveryState = 'outcome-unknown';
1007
+ pending.startDisposition.resolve({ kind: 'outcome-unknown' });
1008
+ return;
1009
+ }
1010
+ pending.startDeliveryState = 'definitely-not-sent';
1011
+ pending.startDisposition.resolve({ kind: 'definitely-not-sent' });
1012
+ }
1013
+
1014
+ async _classifyTurnFailure(error, pending) {
1015
+ const durability = this._durabilityFailure(error);
1016
+ if (durability?.deliveryState === 'not-sent') {
1017
+ this._blockDurability(durability, pending);
1018
+ return processError(
1019
+ 'Codex durability checkpoint failed before dispatch',
1020
+ 'CODEX_DURABILITY_FAILED',
1021
+ { cause: durability },
1022
+ );
1023
+ }
1024
+ if (pending.startCancellationRequested && error?.code === 'CODEX_RPC_NOT_SENT') {
1025
+ return processError('Codex turn start was interrupted', 'INTERRUPTED', {
1026
+ cause: error,
1027
+ });
1028
+ }
1029
+ if (error?.code === 'CODEX_RPC_NOT_SENT') return error;
1030
+ if (
1031
+ (
1032
+ error?.code === 'CODEX_TURN_TIMEOUT'
1033
+ || error?.code === 'CODEX_TURN_START_TIMEOUT'
1034
+ )
1035
+ && pending.responseSeen
1036
+ ) {
1037
+ try {
1038
+ await this.interrupt();
1039
+ } catch (interruptError) {
1040
+ if (this.state !== 'ContainmentFailed') {
1041
+ await this._enterContainment(
1042
+ 'turn-timeout-cleanup-failed',
1043
+ interruptError,
1044
+ pending,
1045
+ );
1046
+ }
1047
+ }
1048
+ return error;
1049
+ }
1050
+ if (
1051
+ error?.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
1052
+ || error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
1053
+ || (
1054
+ error?.code === 'CODEX_RPC_ERROR'
1055
+ && pending.startResponseOutcome === 'error'
1056
+ )
1057
+ || (
1058
+ error?.code === 'CODEX_DURABILITY_FAILED'
1059
+ && error.deliveryState !== 'not-sent'
1060
+ )
1061
+ ) {
1062
+ const durability = error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
1063
+ || error?.code === 'CODEX_DURABILITY_FAILED';
1064
+ await this._enterFailedAmbiguous(
1065
+ durability ? 'durability-failed-after-dispatch' : 'turn-start-outcome-unknown',
1066
+ error,
1067
+ pending,
1068
+ );
1069
+ return durability
1070
+ ? processError(
1071
+ 'Codex durability checkpoint failed after dispatch',
1072
+ 'CODEX_DURABILITY_FAILED',
1073
+ { cause: error },
1074
+ )
1075
+ : error;
1076
+ }
1077
+ if (this.state === 'ContainmentFailed') return error;
1078
+ return error;
1079
+ }
1080
+
1081
+ _resolveTurn(pending, terminal) {
1082
+ const status = terminal.status;
1083
+ const text = this._finalTurnText(pending);
1084
+ const duration = Math.max(0, Date.now() - pending.startedAt);
1085
+ const result = {
1086
+ runtime: 'codex',
1087
+ backend: 'codex',
1088
+ text,
1089
+ sessionId: this.providerSessionId,
1090
+ providerSessionId: this.providerSessionId,
1091
+ providerTurnId: pending.turnId,
1092
+ generationId: this.generationId,
1093
+ cost: 0,
1094
+ duration,
1095
+ error: status === 'completed' ? null : status,
1096
+ metrics: {
1097
+ inputTokens: null,
1098
+ outputTokens: null,
1099
+ cacheCreationTokens: null,
1100
+ cacheReadTokens: null,
1101
+ numAssistantMessages: pending.completedItemText.size,
1102
+ numToolUses: 0,
1103
+ resultSubtype: status === 'completed' ? 'success' : status,
1104
+ },
1105
+ };
1106
+ Object.defineProperty(result, 'attemptId', {
1107
+ value: boundedOpaqueId(pending.attemptId, 'mutation attemptId'),
1108
+ enumerable: true,
1109
+ });
1110
+ this.emit('result', {
1111
+ subtype: result.metrics.resultSubtype,
1112
+ session_id: this.providerSessionId,
1113
+ turn_id: pending.turnId,
1114
+ generation_id: this.generationId,
1115
+ }, pending);
1116
+ this._settlePending(pending, 'resolve', result);
1117
+ }
1118
+
1119
+ _finalTurnText(pending) {
1120
+ const completed = [...pending.completedItemText.values()]
1121
+ .filter(Boolean)
1122
+ .join('\n\n');
1123
+ return completed || pending.streamText;
1124
+ }
1125
+
1126
+ _finishPending(pending) {
1127
+ const index = this.pendingQueue.indexOf(pending);
1128
+ if (index !== -1) this.pendingQueue.splice(index, 1);
1129
+ if (this.current === pending) this.current = null;
1130
+ if (this.activeTurnId === pending.turnId) this.activeTurnId = null;
1131
+ if (this.activeTurnSettings === pending.admittedSettings) {
1132
+ this.activeTurnSettings = null;
1133
+ }
1134
+ const backgroundOwned = (
1135
+ this.state === 'BackgroundWorking'
1136
+ || this.state === 'BackgroundSettling'
1137
+ );
1138
+ if (!backgroundOwned) this.inFlight = false;
1139
+ if (
1140
+ !this.closed
1141
+ && ![
1142
+ 'Quiescing',
1143
+ 'Stopped',
1144
+ 'ContainmentFailed',
1145
+ 'RecoveryConflict',
1146
+ 'DurabilityBlocked',
1147
+ 'BackgroundWorking',
1148
+ 'BackgroundSettling',
1149
+ ]
1150
+ .includes(this.state)
1151
+ ) {
1152
+ this.state = 'Idle';
1153
+ this._pump();
1154
+ }
1155
+ }
1156
+
1157
+ steerTurn(text, { context = {} } = {}) {
1158
+ if (
1159
+ typeof text === 'string'
1160
+ && Buffer.byteLength(text) > this.maxSteerTextBytes
1161
+ ) {
1162
+ return Promise.resolve({
1163
+ outcome: 'unavailable',
1164
+ reason: 'input-too-large',
1165
+ });
1166
+ }
1167
+ if (this.pendingSteerCount >= this.maxPendingSteers) {
1168
+ return Promise.reject(processError(
1169
+ 'Codex steer queue is full',
1170
+ 'CODEX_STEER_QUEUE_OVERFLOW',
1171
+ ));
1172
+ }
1173
+ this.pendingSteerCount += 1;
1174
+ const operation = this.steerChain.then(
1175
+ () => this._steerTurn(text, context),
1176
+ () => this._steerTurn(text, context),
1177
+ );
1178
+ const tracked = operation.finally(() => {
1179
+ this.pendingSteerCount -= 1;
1180
+ });
1181
+ this.steerChain = tracked.catch(() => {});
1182
+ return tracked;
1183
+ }
1184
+
1185
+ async _steerTurn(text, context) {
1186
+ const lifecycle = this._captureLifecycle();
1187
+ if (typeof text !== 'string' || text.length === 0) {
1188
+ return { outcome: 'unavailable', reason: 'empty-input' };
1189
+ }
1190
+ const unavailableReason = this._steerUnavailableReason();
1191
+ if (unavailableReason) {
1192
+ return { outcome: 'unavailable', reason: unavailableReason };
1193
+ }
1194
+
1195
+ let turnId = this.activeTurnId;
1196
+ const pending = this.current;
1197
+ if (pending && this.state === 'StartingTurn') {
1198
+ try {
1199
+ turnId = await timeout(
1200
+ pending.turnReady.promise,
1201
+ Math.min(
1202
+ this.turnStartTimeoutMs,
1203
+ this._remainingTurnBudget(pending),
1204
+ ),
1205
+ 'Codex turn ID was not observed before steering',
1206
+ 'CODEX_TURN_START_TIMEOUT',
1207
+ );
1208
+ this._assertLifecycle(lifecycle);
1209
+ } catch (error) {
1210
+ if (this.state === 'ContainmentFailed') throw error;
1211
+ return { outcome: 'unavailable', reason: 'turn-start-pending' };
1212
+ }
1213
+ }
1214
+ if (!turnId || !this.current || this.current.terminal) {
1215
+ return {
1216
+ outcome: 'queueable-not-active',
1217
+ turnId: turnId ?? this.lastTurnId,
1218
+ };
1219
+ }
1220
+
1221
+ const clientUserMessageId = nonEmptyString(
1222
+ this.clientUserMessageIdFactory(),
1223
+ 'generated clientUserMessageId',
1224
+ );
1225
+ const attemptId = boundedOpaqueId(
1226
+ this.mutationAttemptIdFactory(),
1227
+ 'mutation attemptId',
1228
+ );
1229
+ const targetAttemptId = boundedOpaqueId(
1230
+ pending.attemptId,
1231
+ 'target mutation attemptId',
1232
+ );
1233
+ try {
1234
+ const result = await this._mutation('turn/steer', {
1235
+ threadId: this.providerSessionId,
1236
+ expectedTurnId: turnId,
1237
+ input: [{ type: 'text', text }],
1238
+ clientUserMessageId,
1239
+ }, {
1240
+ source: context?.sourceMsgId ?? null,
1241
+ clientUserMessageId,
1242
+ turnId,
1243
+ attemptId,
1244
+ timeoutMs: this._remainingTurnBudget(pending),
1245
+ assertCanWrite: () => {
1246
+ const reason = this._steerUnavailableReason();
1247
+ if (reason) {
1248
+ throw processError(
1249
+ `Codex steering became unavailable: ${reason}`,
1250
+ 'CODEX_RPC_NOT_SENT',
1251
+ );
1252
+ }
1253
+ },
1254
+ });
1255
+ this._assertLifecycle(lifecycle);
1256
+ if (result.turnId !== turnId) {
1257
+ throw await this._runtimeProtocolFault(
1258
+ 'steer-turn-id-mismatch',
1259
+ 'Codex turn/steer acknowledged a different turn',
1260
+ );
1261
+ }
1262
+ await this._checkpoint('turn-steer-accepted', {
1263
+ threadId: this.providerSessionId,
1264
+ turnId,
1265
+ source: context?.sourceMsgId ?? null,
1266
+ clientUserMessageId,
1267
+ attemptId,
1268
+ });
1269
+ this._assertLifecycle(lifecycle);
1270
+ return Object.freeze({
1271
+ outcome: 'accepted',
1272
+ turnId: boundedOpaqueId(turnId, 'turnId'),
1273
+ generationId: this.generationId,
1274
+ attemptId,
1275
+ targetAttemptId,
1276
+ });
1277
+ } catch (error) {
1278
+ const durabilityFailure = this._durabilityFailure(error);
1279
+ if (durabilityFailure?.deliveryState === 'not-sent') {
1280
+ this._blockDurability(durabilityFailure, this.current);
1281
+ throw processError(
1282
+ 'Codex durability checkpoint failed before steering dispatch',
1283
+ 'CODEX_DURABILITY_FAILED',
1284
+ { cause: durabilityFailure },
1285
+ );
1286
+ }
1287
+ if (
1288
+ error?.code === 'CODEX_RPC_ERROR'
1289
+ && error.rpcMessage === 'no active turn to steer'
1290
+ ) {
1291
+ return { outcome: 'queueable-not-active', turnId };
1292
+ }
1293
+ if (
1294
+ error?.code === 'CODEX_RPC_NOT_SENT'
1295
+ && !this._steerUnavailableReason()
1296
+ ) {
1297
+ return { outcome: 'queueable-not-active', turnId };
1298
+ }
1299
+ if (
1300
+ error?.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
1301
+ || error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
1302
+ || error?.code === 'CODEX_DURABILITY_FAILED'
1303
+ || error?.code === 'CODEX_RPC_ERROR'
1304
+ ) {
1305
+ const reason = error.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
1306
+ ? 'steer-outcome-unknown'
1307
+ : error.code === 'CODEX_RPC_ERROR'
1308
+ ? 'steer-rpc-error-unclassified'
1309
+ : 'durability-failed-after-dispatch';
1310
+ await this._enterFailedAmbiguous(
1311
+ reason,
1312
+ error,
1313
+ );
1314
+ if (
1315
+ error.code === 'CODEX_RPC_CHECKPOINT_FAILED'
1316
+ || error.code === 'CODEX_DURABILITY_FAILED'
1317
+ ) {
1318
+ throw processError(
1319
+ 'Codex durability checkpoint failed after steering dispatch',
1320
+ 'CODEX_DURABILITY_FAILED',
1321
+ { cause: error },
1322
+ );
1323
+ }
1324
+ }
1325
+ throw error;
1326
+ }
1327
+ }
1328
+
1329
+ async interrupt() {
1330
+ if (this.interruptPromise) return this.interruptPromise;
1331
+ this.interruptPromise = this._interrupt();
1332
+ return this.interruptPromise;
1333
+ }
1334
+
1335
+ async _interrupt(controlDeadlineOverride = null) {
1336
+ if (this.closed) return false;
1337
+ if (this.state === 'ContainmentFailed') {
1338
+ throw processError(
1339
+ 'Codex generation is containment-failed',
1340
+ 'CODEX_CONTAINMENT_FAILED',
1341
+ );
1342
+ }
1343
+ if (this.state === 'FailedAmbiguous') {
1344
+ throw processError(
1345
+ 'Codex generation has an ambiguous mutation outcome',
1346
+ 'CODEX_RPC_OUTCOME_UNKNOWN',
1347
+ );
1348
+ }
1349
+ if (this.state === 'RecoveryConflict') {
1350
+ return false;
1351
+ }
1352
+ this._closeSettingsAdmission();
1353
+ const priorState = this.state;
1354
+ this._clearBackgroundWatchdog();
1355
+ const backgroundSettlement = this.backgroundSettlementPromise;
1356
+ const pending = this.current;
1357
+ const controlDeadline = controlDeadlineOverride
1358
+ ?? pending?.deadlineAt
1359
+ ?? this.lastTerminal?.deadlineAt
1360
+ ?? (Date.now() + this.interruptTimeoutMs + this.cleanupTimeoutMs);
1361
+ let turnId = this.activeTurnId
1362
+ ?? pending?.turnId
1363
+ ?? (
1364
+ (
1365
+ priorState === 'BackgroundWorking'
1366
+ || priorState === 'BackgroundSettling'
1367
+ )
1368
+ ? this.lastTerminal?.turnId
1369
+ : null
1370
+ );
1371
+ this.state = 'Quiescing';
1372
+ const lifecycle = this._captureLifecycle();
1373
+ this._drainWaiting('INTERRUPTED');
1374
+ await this.steerChain;
1375
+ this._assertLifecycle(lifecycle);
1376
+ await this._flushPendingCancellations();
1377
+ this._assertLifecycle(lifecycle);
1378
+ if (backgroundSettlement) {
1379
+ await backgroundSettlement;
1380
+ this._assertLifecycle(lifecycle);
1381
+ }
1382
+ let interruptEventEmitted = false;
1383
+ if (pending && priorState === 'StartingTurn') {
1384
+ pending.startCancellationRequested = true;
1385
+ let disposition;
1386
+ if (
1387
+ pending.startDeliveryState === 'preparing'
1388
+ || pending.startDeliveryState === 'prepared'
1389
+ ) {
1390
+ disposition = { kind: 'definitely-not-sent' };
1391
+ } else if (
1392
+ pending.startDeliveryState === 'write-checkpointing'
1393
+ ||
1394
+ pending.startDeliveryState === 'write-attempted'
1395
+ || pending.startDeliveryState === 'response-observed'
1396
+ ) {
1397
+ try {
1398
+ disposition = await timeout(
1399
+ pending.startDisposition.promise,
1400
+ Math.max(
1401
+ 1,
1402
+ Math.min(
1403
+ this.turnStartTimeoutMs,
1404
+ controlDeadline - Date.now(),
1405
+ ),
1406
+ ),
1407
+ 'Codex turn start disposition was not observed before interruption',
1408
+ 'CODEX_TURN_START_TIMEOUT',
1409
+ );
1410
+ this._assertLifecycle(lifecycle);
1411
+ } catch (error) {
1412
+ disposition = { kind: 'outcome-unknown', cause: error };
1413
+ }
1414
+ } else if (pending.startDeliveryState === 'accepted') {
1415
+ disposition = { kind: 'accepted', turnId: pending.turnId };
1416
+ } else {
1417
+ disposition = { kind: pending.startDeliveryState };
1418
+ }
1419
+ if (disposition.kind === 'accepted') {
1420
+ turnId = disposition.turnId ?? pending.turnId;
1421
+ } else if (disposition.kind === 'definitely-not-sent') {
1422
+ turnId = null;
1423
+ try {
1424
+ await this._checkpoint('active-start-cancelled', {
1425
+ ...this._turnDetail(pending),
1426
+ attemptId: pending.attemptId,
1427
+ deliveryState: 'definitely-not-sent',
1428
+ });
1429
+ this._assertLifecycle(lifecycle);
1430
+ } catch (error) {
1431
+ pending.cancelled = true;
1432
+ this._blockDurability(error);
1433
+ throw processError(
1434
+ 'Codex active-start cancellation was not durable',
1435
+ 'CODEX_DURABILITY_FAILED',
1436
+ { cause: error },
1437
+ );
1438
+ }
1439
+ const cancelled = processError(
1440
+ 'Codex turn start was interrupted before dispatch',
1441
+ 'INTERRUPTED',
1442
+ );
1443
+ pending.cancelled = true;
1444
+ this._rejectPending(pending, cancelled);
1445
+ this._finishPending(pending);
1446
+ } else {
1447
+ const error = disposition.cause ?? processError(
1448
+ 'Codex turn start delivery outcome is unknown',
1449
+ 'CODEX_RPC_OUTCOME_UNKNOWN',
1450
+ );
1451
+ await this._enterFailedAmbiguous(
1452
+ 'interrupt-turn-start-outcome-unknown',
1453
+ error,
1454
+ pending,
1455
+ );
1456
+ throw error;
1457
+ }
1458
+ }
1459
+
1460
+ try {
1461
+ const cleanupProof = this.backgroundCleanupProof;
1462
+ const reuseBackgroundCleanup = (
1463
+ cleanupProof?.turnId != null
1464
+ && cleanupProof.turnId === turnId
1465
+ );
1466
+ let terminal = pending?.terminal
1467
+ ?? (
1468
+ this.lastTerminal?.turnId === turnId
1469
+ ? this.lastTerminal
1470
+ : null
1471
+ );
1472
+ if (turnId && !terminal) {
1473
+ try {
1474
+ await this._mutation('turn/interrupt', {
1475
+ threadId: this.providerSessionId,
1476
+ turnId,
1477
+ }, {
1478
+ source: pending?.context?.sourceMsgId ?? null,
1479
+ turnId,
1480
+ timeoutMs: Math.max(1, controlDeadline - Date.now()),
1481
+ });
1482
+ this._assertLifecycle(lifecycle);
1483
+ this.emit('interrupt-applied', {
1484
+ backend: this.backend,
1485
+ generationId: this.generationId,
1486
+ turnId,
1487
+ });
1488
+ interruptEventEmitted = true;
1489
+ } catch (error) {
1490
+ const naturalRace = (
1491
+ error?.code === 'CODEX_RPC_ERROR'
1492
+ && error.rpcMessage === 'no active turn to interrupt'
1493
+ );
1494
+ if (!naturalRace) throw error;
1495
+ }
1496
+ terminal = pending?.terminal ?? await timeout(
1497
+ pending.terminalDeferred.promise,
1498
+ Math.max(
1499
+ 1,
1500
+ Math.min(this.interruptTimeoutMs, controlDeadline - Date.now()),
1501
+ ),
1502
+ 'Codex interrupted turn did not reach an exact terminal state',
1503
+ 'CODEX_INTERRUPT_TIMEOUT',
1504
+ );
1505
+ this._assertLifecycle(lifecycle);
1506
+ }
1507
+ if (turnId) {
1508
+ if (!terminal || terminal.turnId !== turnId) {
1509
+ throw processError(
1510
+ 'Codex interruption did not reconcile the exact turn',
1511
+ 'CODEX_INTERRUPT_UNMATCHED',
1512
+ );
1513
+ }
1514
+ if (reuseBackgroundCleanup) {
1515
+ await this._checkpoint('stop-background-cleanup-reused', {
1516
+ threadId: this.providerSessionId,
1517
+ turnId,
1518
+ terminalStatus: cleanupProof.terminalStatus,
1519
+ });
1520
+ } else {
1521
+ await this._checkpoint('stop-terminal-reconciled', {
1522
+ threadId: this.providerSessionId,
1523
+ turnId,
1524
+ terminalStatus: terminal.status,
1525
+ });
1526
+ }
1527
+ this._assertLifecycle(lifecycle);
1528
+ }
1529
+
1530
+ if (!reuseBackgroundCleanup) {
1531
+ await this._mutation('thread/backgroundTerminals/clean', {
1532
+ threadId: this.providerSessionId,
1533
+ }, {
1534
+ source: null,
1535
+ turnId,
1536
+ timeoutMs: Math.max(1, controlDeadline - Date.now()),
1537
+ });
1538
+ this._assertLifecycle(lifecycle);
1539
+ await this._checkpoint('stop-clean-accepted', {
1540
+ threadId: this.providerSessionId,
1541
+ turnId,
1542
+ });
1543
+ this._assertLifecycle(lifecycle);
1544
+ await this._waitForFreshEmptyRegistry(controlDeadline, lifecycle);
1545
+ this._assertLifecycle(lifecycle);
1546
+ await this._checkpoint('stop-empty-registry-observed', {
1547
+ threadId: this.providerSessionId,
1548
+ turnId,
1549
+ });
1550
+ this._assertLifecycle(lifecycle);
1551
+ }
1552
+ if (!interruptEventEmitted) {
1553
+ this.emit('interrupt-applied', {
1554
+ backend: this.backend,
1555
+ generationId: this.generationId,
1556
+ turnId,
1557
+ });
1558
+ }
1559
+ this.state = 'Stopped';
1560
+ this.inFlight = false;
1561
+ this.emit('codex-settled', this._lifecyclePayload('stopped', {
1562
+ turnId,
1563
+ terminalStatus: terminal?.status ?? null,
1564
+ trackedTerminalCleanupAccepted: true,
1565
+ freshRegistryObservedEmpty: true,
1566
+ }));
1567
+ return true;
1568
+ } catch (error) {
1569
+ if (
1570
+ this.state !== 'ContainmentFailed'
1571
+ && this.state !== 'DurabilityBlocked'
1572
+ ) {
1573
+ await this._enterContainment(
1574
+ error?.code === 'CODEX_DURABILITY_FAILED'
1575
+ || error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
1576
+ ? 'stop-checkpoint-failed'
1577
+ : 'stop-cleanup-failed',
1578
+ error,
1579
+ );
1580
+ }
1581
+ if (error?.code === 'CODEX_RPC_CHECKPOINT_FAILED') {
1582
+ throw processError(
1583
+ 'Codex durability checkpoint failed during stop',
1584
+ 'CODEX_DURABILITY_FAILED',
1585
+ { cause: error },
1586
+ );
1587
+ }
1588
+ throw error;
1589
+ }
1590
+ }
1591
+
1592
+ async _waitForFreshEmptyRegistry(
1593
+ deadline = Date.now() + this.cleanupTimeoutMs,
1594
+ lifecycle = this._captureLifecycle(),
1595
+ ) {
1596
+ do {
1597
+ const page = await this.client.request(
1598
+ 'thread/backgroundTerminals/list',
1599
+ { threadId: this.providerSessionId, limit: 100 },
1600
+ { timeoutMs: Math.max(1, deadline - Date.now()) },
1601
+ );
1602
+ this._assertLifecycle(lifecycle);
1603
+ if (page.count === 0 && page.nextCursor == null) return;
1604
+ if (Date.now() >= deadline) break;
1605
+ await delay(Math.min(this.cleanupPollMs, deadline - Date.now()));
1606
+ this._assertLifecycle(lifecycle);
1607
+ } while (Date.now() < deadline);
1608
+ throw processError(
1609
+ 'Codex background terminal registry did not become freshly empty',
1610
+ 'CODEX_TERMINAL_CLEANUP_TIMEOUT',
1611
+ );
1612
+ }
1613
+
1614
+ async _refreshBackgroundState(pending, lifecycle) {
1615
+ if (
1616
+ this.state === 'Quiescing'
1617
+ || this.state === 'ContainmentFailed'
1618
+ || this.state === 'FailedAmbiguous'
1619
+ || this.state === 'DurabilityBlocked'
1620
+ ) return;
1621
+ const page = await this.client.request(
1622
+ 'thread/backgroundTerminals/list',
1623
+ { threadId: this.providerSessionId, limit: 100 },
1624
+ {
1625
+ timeoutMs: Math.max(1, this._remainingTurnBudget(pending)),
1626
+ },
1627
+ );
1628
+ this._assertLifecycle(lifecycle);
1629
+ if (page.count > 0 || page.nextCursor != null) {
1630
+ this.state = 'BackgroundWorking';
1631
+ this._armBackgroundWatchdog(pending.deadlineAt);
1632
+ if (this.threadStatusType === 'idle') {
1633
+ this._scheduleBackgroundSettlement();
1634
+ }
1635
+ }
1636
+ }
1637
+
1638
+ async _mutation(method, params, detail) {
1639
+ const attemptId = boundedOpaqueId(
1640
+ detail.attemptId ?? this.mutationAttemptIdFactory(),
1641
+ 'mutation attemptId',
1642
+ );
1643
+ const prepared = {
1644
+ method,
1645
+ attemptId,
1646
+ threadId: params.threadId ?? this.providerSessionId,
1647
+ turnId: detail.turnId ?? params.turnId ?? params.expectedTurnId ?? null,
1648
+ source: detail.source ?? null,
1649
+ clientUserMessageId: detail.clientUserMessageId ?? null,
1650
+ };
1651
+ try {
1652
+ await this._checkpoint('request-prepared', prepared);
1653
+ } catch (error) {
1654
+ const durability = processError(
1655
+ `Codex ${method} prepared checkpoint failed`,
1656
+ 'CODEX_DURABILITY_FAILED',
1657
+ { cause: error },
1658
+ );
1659
+ durability.deliveryState = 'not-sent';
1660
+ throw durability;
1661
+ }
1662
+ detail.onDeliveryState?.('prepared');
1663
+ detail.assertCanWrite?.();
1664
+ return this.client.request(method, params, {
1665
+ timeoutMs: detail.timeoutMs,
1666
+ onWriteAttempted: async (transport) => {
1667
+ detail.assertCanWrite?.();
1668
+ detail.onDeliveryState?.('write-checkpointing');
1669
+ await this._transportCheckpoint(
1670
+ 'request-write-attempted',
1671
+ prepared,
1672
+ transport,
1673
+ () => {
1674
+ this.stateChangingWriteCommitted = true;
1675
+ detail.onDeliveryState?.('write-attempted');
1676
+ },
1677
+ );
1678
+ },
1679
+ onResponseObserved: async (transport) => {
1680
+ await this._transportCheckpoint(
1681
+ 'request-response-observed',
1682
+ { ...prepared, outcome: transport.outcome },
1683
+ transport,
1684
+ );
1685
+ detail.onDeliveryState?.('response-observed', transport.outcome);
1686
+ },
1687
+ });
1688
+ }
1689
+
1690
+ async _transportCheckpoint(kind, detail, transport, onCommitted = null) {
1691
+ transport.assertActive?.();
1692
+ const payload = this._checkpointPayload(kind, {
1693
+ ...detail,
1694
+ requestId: transport.id,
1695
+ });
1696
+ const properties = {
1697
+ signal: {
1698
+ value: transport.signal,
1699
+ enumerable: false,
1700
+ },
1701
+ assertActive: {
1702
+ value: transport.assertActive,
1703
+ enumerable: false,
1704
+ },
1705
+ };
1706
+ let writeCommitted = false;
1707
+ const markWriteCommitted = () => {
1708
+ transport.assertActive?.();
1709
+ if (writeCommitted) return;
1710
+ transport.markWriteCommitted?.();
1711
+ writeCommitted = true;
1712
+ onCommitted?.();
1713
+ };
1714
+ if (kind === 'request-write-attempted') {
1715
+ properties.markWriteCommitted = {
1716
+ value: markWriteCommitted,
1717
+ enumerable: false,
1718
+ };
1719
+ }
1720
+ Object.defineProperties(payload, properties);
1721
+ try {
1722
+ await this.checkpointSink(payload);
1723
+ if (kind === 'request-write-attempted') markWriteCommitted();
1724
+ transport.assertActive?.();
1725
+ } catch (error) {
1726
+ const durability = processError(
1727
+ `Codex checkpoint ${kind} failed`,
1728
+ 'CODEX_DURABILITY_FAILED',
1729
+ { cause: error },
1730
+ );
1731
+ durability.deliveryState = kind === 'request-write-attempted'
1732
+ ? writeCommitted ? 'ambiguous' : 'not-sent'
1733
+ : 'ambiguous';
1734
+ if (
1735
+ kind === 'request-response-observed'
1736
+ || (kind === 'request-write-attempted' && writeCommitted)
1737
+ ) {
1738
+ await this._enterFailedAmbiguous(
1739
+ kind === 'request-response-observed'
1740
+ ? 'response-checkpoint-failed-after-dispatch'
1741
+ : 'write-checkpoint-failed-after-commit',
1742
+ durability,
1743
+ this.current,
1744
+ );
1745
+ }
1746
+ throw durability;
1747
+ }
1748
+ }
1749
+
1750
+ async _checkpoint(kind, detail = {}, fence = null) {
1751
+ fence?.assertActive?.();
1752
+ const payload = this._checkpointPayload(kind, detail);
1753
+ if (fence) {
1754
+ Object.defineProperties(payload, {
1755
+ signal: {
1756
+ value: fence.signal,
1757
+ enumerable: false,
1758
+ },
1759
+ assertActive: {
1760
+ value: fence.assertActive,
1761
+ enumerable: false,
1762
+ },
1763
+ });
1764
+ }
1765
+ try {
1766
+ await this.checkpointSink(payload);
1767
+ } catch (error) {
1768
+ const durability = processError(
1769
+ `Codex checkpoint ${kind} failed`,
1770
+ 'CODEX_DURABILITY_FAILED',
1771
+ { cause: error },
1772
+ );
1773
+ durability.deliveryState = 'ambiguous';
1774
+ throw durability;
1775
+ }
1776
+ fence?.assertActive?.();
1777
+ }
1778
+
1779
+ _checkpointPayload(kind, detail) {
1780
+ return {
1781
+ kind,
1782
+ generationId: this.generationId,
1783
+ threadId: detail.threadId ?? this.providerSessionId,
1784
+ turnId: detail.turnId ?? null,
1785
+ source: detail.source ?? null,
1786
+ clientUserMessageId: detail.clientUserMessageId ?? null,
1787
+ hostIdentity: this.hostIdentity,
1788
+ bootSessionIdentity: this.bootSessionIdentity,
1789
+ ...detail,
1790
+ };
1791
+ }
1792
+
1793
+ async _handleNotification(notification) {
1794
+ const fence = {
1795
+ signal: notification?.signal,
1796
+ assertActive: notification?.assertActive,
1797
+ };
1798
+ fence.assertActive?.();
1799
+ try {
1800
+ return await this._handleNotificationWithFence(notification, fence);
1801
+ } catch (error) {
1802
+ const durability = this._durabilityFailure(error);
1803
+ if (
1804
+ durability
1805
+ && this.state !== 'ContainmentFailed'
1806
+ && this.state !== 'DurabilityBlocked'
1807
+ ) {
1808
+ await this._enterFailedAmbiguous(
1809
+ 'notification-checkpoint-failed',
1810
+ durability,
1811
+ );
1812
+ }
1813
+ throw error;
1814
+ } finally {
1815
+ fence.assertActive?.();
1816
+ }
1817
+ }
1818
+
1819
+ async _handleNotificationWithFence(notification, fence) {
1820
+ if (
1821
+ this.closed
1822
+ || this.state === 'Closed'
1823
+ || this.state === 'ContainmentFailed'
1824
+ ) return;
1825
+ const { method, params = {} } = notification ?? {};
1826
+ if (
1827
+ params.threadId
1828
+ && !this.providerSessionId
1829
+ && this.state === 'AttachingThread'
1830
+ && !this.attachingThreadId
1831
+ ) {
1832
+ this.attachingThreadId = params.threadId;
1833
+ }
1834
+ const ownedThreadId = this.providerSessionId ?? this.attachingThreadId;
1835
+ if (params.threadId && params.threadId !== ownedThreadId) {
1836
+ await this._notificationProtocolFault(
1837
+ 'cross-thread-notification',
1838
+ 'Codex emitted traffic for another provider thread',
1839
+ fence,
1840
+ );
1841
+ return;
1842
+ }
1843
+ if (method === 'thread/settings/updated') {
1844
+ try {
1845
+ this._validateAndObserveThreadPolicy(params.threadSettings, {
1846
+ attaching: this.state === 'AttachingThread',
1847
+ });
1848
+ } catch (error) {
1849
+ await this._enterContainment(
1850
+ 'thread-settings-drift',
1851
+ error,
1852
+ null,
1853
+ fence,
1854
+ );
1855
+ }
1856
+ fence.assertActive?.();
1857
+ return;
1858
+ }
1859
+ if (method === 'thread/status/changed') {
1860
+ const statusType = params.status?.type ?? null;
1861
+ await this._checkpoint('thread-status-changed', {
1862
+ threadId: ownedThreadId,
1863
+ statusType,
1864
+ }, fence);
1865
+ fence.assertActive?.();
1866
+ this.threadStatusType = statusType;
1867
+ if (
1868
+ statusType === 'active'
1869
+ && !this.current
1870
+ && this.state === 'Idle'
1871
+ ) {
1872
+ this.state = 'BackgroundWorking';
1873
+ } else if (
1874
+ statusType === 'idle'
1875
+ && this.state === 'BackgroundWorking'
1876
+ ) {
1877
+ this._scheduleBackgroundSettlement();
1878
+ }
1879
+ fence.assertActive?.();
1880
+ return;
1881
+ }
1882
+ if (method === 'error') {
1883
+ const pending = await this._notificationPending(params.turnId, fence);
1884
+ if (!pending) return;
1885
+ await this._checkpoint('turn-error-observed', {
1886
+ ...this._turnDetail(pending),
1887
+ willRetry: params.willRetry,
1888
+ }, fence);
1889
+ if (!params.willRetry) {
1890
+ pending.providerError = 'provider-error';
1891
+ }
1892
+ fence.assertActive?.();
1893
+ return;
1894
+ }
1895
+ if (method === 'turn/started') {
1896
+ const pending = this.current;
1897
+ const turnId = params.turn?.id;
1898
+ if (!pending) {
1899
+ if (!this.terminalTurnIds.has(turnId)) {
1900
+ await this._notificationProtocolFault(
1901
+ 'unexpected-turn-start',
1902
+ 'Codex started a turn without an owned send',
1903
+ fence,
1904
+ );
1905
+ }
1906
+ return;
1907
+ }
1908
+ if (pending.turnId && pending.turnId !== turnId) {
1909
+ throw await this._notificationProtocolFault(
1910
+ 'turn-start-id-mismatch',
1911
+ 'Codex turn/started disagreed with the owned turn',
1912
+ fence,
1913
+ );
1914
+ }
1915
+ await this._checkpoint('turn-started', {
1916
+ ...this._turnDetail(pending),
1917
+ turnId,
1918
+ }, fence);
1919
+ pending.turnId = turnId;
1920
+ pending.startedSeen = true;
1921
+ this.activeTurnId = turnId;
1922
+ this.lastTurnId = turnId;
1923
+ if (pending.admittedSettings) {
1924
+ this.activeTurnSettings = pending.admittedSettings;
1925
+ }
1926
+ if (pending.responseSeen) pending.turnReady.resolve(turnId);
1927
+ fence.assertActive?.();
1928
+ return;
1929
+ }
1930
+ if (method === 'item/agentMessage/delta') {
1931
+ const pending = await this._notificationPending(params.turnId, fence);
1932
+ if (!pending) return;
1933
+ if (!this._canTrackItem(pending, params.itemId)) {
1934
+ await this._notificationProtocolFault(
1935
+ 'turn-item-limit-exceeded',
1936
+ 'Codex turn exceeded its bounded item history',
1937
+ fence,
1938
+ );
1939
+ return;
1940
+ }
1941
+ const prior = pending.itemText.get(params.itemId) ?? '';
1942
+ const nextText = prior + params.delta;
1943
+ const deltaBytes = Buffer.byteLength(params.delta);
1944
+ const isNewItem = !pending.itemText.has(params.itemId);
1945
+ const separatorBytes = isNewItem && pending.itemText.size > 0 ? 2 : 0;
1946
+ const streamTextBytes = (
1947
+ pending.streamTextBytes
1948
+ + separatorBytes
1949
+ + deltaBytes
1950
+ );
1951
+ if (streamTextBytes > this.maxTurnTextBytes) {
1952
+ await this._notificationProtocolFault(
1953
+ 'turn-text-limit-exceeded',
1954
+ 'Codex turn exceeded its bounded text history',
1955
+ fence,
1956
+ );
1957
+ return;
1958
+ }
1959
+ const batchedDeltaBytes = (
1960
+ pending.uncheckpointedDeltaBytes
1961
+ + deltaBytes
1962
+ );
1963
+ if (
1964
+ !pending.deltaCheckpointObserved
1965
+ || batchedDeltaBytes >= this.streamCheckpointBytes
1966
+ ) {
1967
+ await this._checkpoint('item-delta-observed', {
1968
+ ...this._turnDetail(pending),
1969
+ itemId: params.itemId,
1970
+ deltaBytes,
1971
+ batchedDeltaBytes,
1972
+ }, fence);
1973
+ pending.deltaCheckpointObserved = true;
1974
+ pending.uncheckpointedDeltaBytes = 0;
1975
+ } else {
1976
+ pending.uncheckpointedDeltaBytes = batchedDeltaBytes;
1977
+ }
1978
+ let streamText;
1979
+ if (isNewItem) {
1980
+ streamText = pending.streamText
1981
+ + (pending.itemText.size > 0 ? '\n\n' : '')
1982
+ + params.delta;
1983
+ } else if (pending.lastStreamItemId === params.itemId) {
1984
+ streamText = pending.streamText + params.delta;
1985
+ } else {
1986
+ const nextItems = new Map(pending.itemText);
1987
+ nextItems.set(params.itemId, nextText);
1988
+ streamText = [...nextItems.values()].join('\n\n');
1989
+ }
1990
+ pending.itemIds.add(params.itemId);
1991
+ pending.itemText.set(params.itemId, nextText);
1992
+ pending.streamText = streamText;
1993
+ pending.streamTextBytes = streamTextBytes;
1994
+ if (isNewItem) pending.lastStreamItemId = params.itemId;
1995
+ this._fireFirstStream(pending);
1996
+ this.emit('stream-chunk', pending.streamText);
1997
+ fence.assertActive?.();
1998
+ return;
1999
+ }
2000
+ if (method === 'item/started' || method === 'item/completed') {
2001
+ const pending = await this._notificationPending(params.turnId, fence);
2002
+ if (!pending) return;
2003
+ const item = params.item;
2004
+ if (!item?.id || !this._canTrackItem(pending, item.id)) {
2005
+ await this._notificationProtocolFault(
2006
+ 'turn-item-limit-exceeded',
2007
+ 'Codex turn exceeded its bounded item history',
2008
+ fence,
2009
+ );
2010
+ return;
2011
+ }
2012
+ let authoritative = null;
2013
+ let authoritativeIsNew = false;
2014
+ if (
2015
+ method === 'item/completed'
2016
+ && item.type === 'agentMessage'
2017
+ && typeof item.text === 'string'
2018
+ ) {
2019
+ authoritativeIsNew = !pending.itemText.has(item.id);
2020
+ const nextItems = new Map(pending.itemText);
2021
+ nextItems.set(item.id, item.text);
2022
+ authoritative = [...nextItems.values()].join('\n\n');
2023
+ if (Buffer.byteLength(authoritative) > this.maxTurnTextBytes) {
2024
+ await this._notificationProtocolFault(
2025
+ 'turn-text-limit-exceeded',
2026
+ 'Codex turn exceeded its bounded text history',
2027
+ fence,
2028
+ );
2029
+ return;
2030
+ }
2031
+ }
2032
+ await this._checkpoint(
2033
+ method === 'item/started' ? 'item-started' : 'item-completed',
2034
+ {
2035
+ ...this._turnDetail(pending),
2036
+ itemId: item.id,
2037
+ itemType: item.type,
2038
+ },
2039
+ fence,
2040
+ );
2041
+ pending.itemIds.add(item.id);
2042
+ if (authoritative != null) {
2043
+ pending.completedItemText.set(item.id, item.text);
2044
+ pending.itemText.set(item.id, item.text);
2045
+ pending.streamTextBytes = Buffer.byteLength(authoritative);
2046
+ pending.uncheckpointedDeltaBytes = 0;
2047
+ if (authoritativeIsNew) pending.lastStreamItemId = item.id;
2048
+ if (authoritative !== pending.streamText) {
2049
+ pending.streamText = authoritative;
2050
+ this._fireFirstStream(pending);
2051
+ this.emit('stream-chunk', pending.streamText);
2052
+ }
2053
+ }
2054
+ fence.assertActive?.();
2055
+ return;
2056
+ }
2057
+ if (method === 'turn/completed') {
2058
+ const turnId = params.turn?.id;
2059
+ if (this.terminalTurnIds.has(turnId)) return;
2060
+ const pending = await this._notificationPending(turnId, fence);
2061
+ if (!pending) return;
2062
+ const status = params.turn.status;
2063
+ if (!['completed', 'interrupted', 'failed'].includes(status)) {
2064
+ throw await this._notificationProtocolFault(
2065
+ 'invalid-turn-terminal',
2066
+ 'Codex emitted a non-terminal turn/completed state',
2067
+ fence,
2068
+ );
2069
+ }
2070
+ const terminal = {
2071
+ turnId,
2072
+ status,
2073
+ deadlineAt: pending.deadlineAt,
2074
+ };
2075
+ await this._checkpoint('turn-terminal', {
2076
+ ...this._turnDetail(pending),
2077
+ terminalStatus: status,
2078
+ }, fence);
2079
+ pending.terminal = terminal;
2080
+ this.lastTerminal = terminal;
2081
+ this._rememberTerminal(turnId);
2082
+ if (
2083
+ this.state !== 'Quiescing'
2084
+ && this.state !== 'DurabilityBlocked'
2085
+ ) {
2086
+ this.state = 'Settling';
2087
+ }
2088
+ pending.terminalDeferred.resolve(terminal);
2089
+ fence.assertActive?.();
2090
+ }
2091
+ }
2092
+
2093
+ async _notificationPending(turnId, fence) {
2094
+ const pending = this.current;
2095
+ if (!pending || !turnId || pending.turnId !== turnId) {
2096
+ if (turnId && this.terminalTurnIds.has(turnId)) {
2097
+ return null;
2098
+ }
2099
+ await this._notificationProtocolFault(
2100
+ 'foreign-turn-notification',
2101
+ 'Codex emitted an event for a turn not owned by this generation',
2102
+ fence,
2103
+ );
2104
+ return null;
2105
+ }
2106
+ return pending;
2107
+ }
2108
+
2109
+ _canTrackItem(pending, itemId) {
2110
+ return (
2111
+ pending.itemIds.has(itemId)
2112
+ || pending.itemIds.size < this.maxTurnItems
2113
+ );
2114
+ }
2115
+
2116
+ _fireFirstStream(pending) {
2117
+ if (pending.firstStreamFired) return;
2118
+ pending.firstStreamFired = true;
2119
+ try {
2120
+ pending.context?.onFirstStream?.();
2121
+ } catch (error) {
2122
+ this.logger.error?.(`[${this.label}] onFirstStream: ${error.message}`);
2123
+ }
2124
+ }
2125
+
2126
+ _rememberTerminal(turnId) {
2127
+ this.terminalTurnIds.add(turnId);
2128
+ this.terminalTurnOrder.push(turnId);
2129
+ while (this.terminalTurnOrder.length > this.maxTerminalHistory) {
2130
+ this.terminalTurnIds.delete(this.terminalTurnOrder.shift());
2131
+ }
2132
+ }
2133
+
2134
+ async _notificationProtocolFault(reason, message, fence) {
2135
+ const error = this._protocolFault(reason, message, false);
2136
+ if (this.protocolFaultCount >= this.protocolFaultThreshold) {
2137
+ await this._enterContainment(reason, error, null, fence);
2138
+ }
2139
+ return error;
2140
+ }
2141
+
2142
+ async _runtimeProtocolFault(reason, message) {
2143
+ const error = this._protocolFault(reason, message, false);
2144
+ if (this.protocolFaultCount >= this.protocolFaultThreshold) {
2145
+ await this._enterContainment(reason, error);
2146
+ }
2147
+ return error;
2148
+ }
2149
+
2150
+ async _handleClientFault(outcome) {
2151
+ if (this.closed) return;
2152
+ if (
2153
+ outcome?.boundary === 'post-spawn'
2154
+ || outcome?.containment === 'unverified'
2155
+ ) {
2156
+ await this._enterContainment(
2157
+ outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
2158
+ ? 'rpc-outcome-unknown'
2159
+ : 'app-server-fault',
2160
+ processError(
2161
+ 'Codex app-server faulted after spawn',
2162
+ outcome?.errorCode ?? 'CODEX_PROCESS_EXITED',
2163
+ ),
2164
+ );
2165
+ }
2166
+ }
2167
+
2168
+ async _settleNaturalBackgroundWork() {
2169
+ const lifecycle = this._captureLifecycle();
2170
+ const terminal = this.lastTerminal;
2171
+ const deadline = terminal?.deadlineAt ?? Date.now();
2172
+ try {
2173
+ this._assertLifecycle(lifecycle);
2174
+ if (!terminal) {
2175
+ throw processError(
2176
+ 'Codex background work had no owned terminal turn',
2177
+ 'CODEX_BACKGROUND_OWNERSHIP_UNKNOWN',
2178
+ );
2179
+ }
2180
+ await this._checkpoint('background-terminal-reconciled', {
2181
+ threadId: this.providerSessionId,
2182
+ turnId: terminal.turnId,
2183
+ terminalStatus: terminal.status,
2184
+ });
2185
+ this._assertLifecycle(lifecycle);
2186
+ await this._mutation('thread/backgroundTerminals/clean', {
2187
+ threadId: this.providerSessionId,
2188
+ }, {
2189
+ source: null,
2190
+ turnId: terminal.turnId,
2191
+ timeoutMs: Math.max(1, deadline - Date.now()),
2192
+ });
2193
+ this._assertLifecycle(lifecycle);
2194
+ await this._checkpoint('background-clean-accepted', {
2195
+ threadId: this.providerSessionId,
2196
+ turnId: terminal.turnId,
2197
+ });
2198
+ this._assertLifecycle(lifecycle);
2199
+ await this._waitForFreshEmptyRegistry(deadline, lifecycle);
2200
+ this._assertLifecycle(lifecycle);
2201
+ await this._checkpoint('background-empty-registry-observed', {
2202
+ threadId: this.providerSessionId,
2203
+ turnId: terminal.turnId,
2204
+ });
2205
+ this._assertLifecycle(lifecycle);
2206
+ this.backgroundCleanupProof = Object.freeze({
2207
+ turnId: terminal.turnId,
2208
+ terminalStatus: terminal.status,
2209
+ deadlineAt: deadline,
2210
+ });
2211
+ this._clearBackgroundWatchdog();
2212
+ if (this.state === 'Quiescing') return this.backgroundCleanupProof;
2213
+ this.state = 'Idle';
2214
+ this.inFlight = false;
2215
+ this.emit('codex-settled', this._lifecyclePayload(
2216
+ 'background-settled',
2217
+ {
2218
+ turnId: terminal.turnId,
2219
+ terminalStatus: terminal.status,
2220
+ trackedTerminalCleanupAccepted: true,
2221
+ freshRegistryObservedEmpty: true,
2222
+ },
2223
+ ));
2224
+ this.emit('idle');
2225
+ this._pump();
2226
+ return this.backgroundCleanupProof;
2227
+ } catch (error) {
2228
+ if (this.state !== 'ContainmentFailed') {
2229
+ await this._enterContainment(
2230
+ error?.code === 'CODEX_DURABILITY_FAILED'
2231
+ || error?.code === 'CODEX_RPC_CHECKPOINT_FAILED'
2232
+ ? 'background-checkpoint-failed'
2233
+ : 'background-cleanup-failed',
2234
+ error,
2235
+ );
2236
+ }
2237
+ throw error;
2238
+ }
2239
+ }
2240
+
2241
+ _scheduleBackgroundSettlement() {
2242
+ if (this.backgroundSettlementPromise) return;
2243
+ this.state = 'BackgroundSettling';
2244
+ this.inFlight = true;
2245
+ this.backgroundSettlementPromise = Promise.resolve()
2246
+ .then(() => this._settleNaturalBackgroundWork())
2247
+ .finally(() => {
2248
+ this.backgroundSettlementPromise = null;
2249
+ });
2250
+ this.backgroundSettlementPromise.catch(() => {});
2251
+ }
2252
+
2253
+ _armBackgroundWatchdog(deadlineAt) {
2254
+ if (!Number.isFinite(deadlineAt)) return;
2255
+ if (
2256
+ this.backgroundWatchdog
2257
+ && this.backgroundWatchdogDeadlineAt === deadlineAt
2258
+ ) return;
2259
+ this._clearBackgroundWatchdog();
2260
+ this.backgroundWatchdogDeadlineAt = deadlineAt;
2261
+ this.backgroundWatchdog = setTimeout(() => {
2262
+ this.backgroundWatchdog = null;
2263
+ this.backgroundWatchdogDeadlineAt = null;
2264
+ if (
2265
+ this.state !== 'BackgroundWorking'
2266
+ && this.state !== 'BackgroundSettling'
2267
+ ) return;
2268
+ if (!this.interruptPromise) {
2269
+ this.interruptPromise = this._interrupt(
2270
+ Date.now() + this.interruptTimeoutMs + this.cleanupTimeoutMs,
2271
+ );
2272
+ }
2273
+ this.backgroundWatchdogPromise = this.interruptPromise
2274
+ .catch(async (error) => {
2275
+ if (
2276
+ this.state !== 'ContainmentFailed'
2277
+ && this.state !== 'DurabilityBlocked'
2278
+ ) {
2279
+ await this._enterContainment(
2280
+ 'background-deadline-stop-failed',
2281
+ error,
2282
+ );
2283
+ }
2284
+ })
2285
+ .finally(() => {
2286
+ this.backgroundWatchdogPromise = null;
2287
+ });
2288
+ }, Math.max(1, deadlineAt - Date.now()));
2289
+ this.backgroundWatchdog.unref?.();
2290
+ }
2291
+
2292
+ _clearBackgroundWatchdog() {
2293
+ if (this.backgroundWatchdog) clearTimeout(this.backgroundWatchdog);
2294
+ this.backgroundWatchdog = null;
2295
+ this.backgroundWatchdogDeadlineAt = null;
2296
+ }
2297
+
2298
+ _protocolFault(reason, message, enterContainment = true) {
2299
+ const error = processError(message, 'CODEX_PROTOCOL_ERROR');
2300
+ this.protocolFaultCount += 1;
2301
+ this.emit('protocol-security-fault', this._lifecyclePayload(
2302
+ 'protocol-security-fault',
2303
+ { reason, count: this.protocolFaultCount },
2304
+ ));
2305
+ if (enterContainment && this.protocolFaultCount >= this.protocolFaultThreshold) {
2306
+ void this._enterContainment(reason, error);
2307
+ }
2308
+ return error;
2309
+ }
2310
+
2311
+ async _enterFailedAmbiguous(reason, error, excludedPending = null) {
2312
+ if (
2313
+ this.state === 'ContainmentFailed'
2314
+ || this.state === 'FailedAmbiguous'
2315
+ ) return;
2316
+ this._advanceLifecycle();
2317
+ this.state = 'FailedAmbiguous';
2318
+ this.inFlight = false;
2319
+ try {
2320
+ await this._checkpoint('failed-ambiguous-entered', {
2321
+ reason,
2322
+ errorCode: error?.code ?? null,
2323
+ turnId: this.activeTurnId
2324
+ ?? this.current?.turnId
2325
+ ?? this.lastTurnId,
2326
+ });
2327
+ } catch (checkpointError) {
2328
+ this.containmentError = checkpointError;
2329
+ }
2330
+ this.emit('codex-lifecycle', this._lifecyclePayload(
2331
+ 'failed-ambiguous',
2332
+ {
2333
+ reason,
2334
+ errorCode: error?.code ?? null,
2335
+ },
2336
+ ));
2337
+ await this._enterContainment(reason, error, excludedPending);
2338
+ }
2339
+
2340
+ async _enterContainment(
2341
+ reason,
2342
+ error,
2343
+ excludedPending = null,
2344
+ fence = null,
2345
+ ) {
2346
+ if (this.state === 'ContainmentFailed') return;
2347
+ this._clearBackgroundWatchdog();
2348
+ const ownedTurnId = this.activeTurnId
2349
+ ?? this.current?.turnId
2350
+ ?? this.lastTurnId;
2351
+ this._advanceLifecycle();
2352
+ this.state = 'ContainmentFailed';
2353
+ this.containmentReason = reason;
2354
+ this.containmentError = error;
2355
+ this.inFlight = false;
2356
+ try {
2357
+ await this._checkpoint('containment-entered', {
2358
+ reason,
2359
+ errorCode: error?.code ?? null,
2360
+ turnId: ownedTurnId ?? null,
2361
+ }, fence);
2362
+ } catch (checkpointError) {
2363
+ this.containmentError = checkpointError;
2364
+ }
2365
+ const containment = processError(
2366
+ `Codex generation containment failed: ${reason}`,
2367
+ 'CODEX_CONTAINMENT_FAILED',
2368
+ { cause: error },
2369
+ );
2370
+ for (const pending of [...this.pendingQueue]) {
2371
+ if (pending !== excludedPending && !pending?.settled) {
2372
+ this._rejectPending(pending, containment);
2373
+ }
2374
+ }
2375
+ this.pendingQueue = excludedPending && this.pendingQueue.includes(excludedPending)
2376
+ ? [excludedPending]
2377
+ : [];
2378
+ if (this.current !== excludedPending) this.current = null;
2379
+ this.activeTurnId = null;
2380
+ this.admittingTurnSettings = null;
2381
+ this.activeTurnSettings = null;
2382
+ const payload = this._lifecyclePayload('containment-failed', {
2383
+ reason,
2384
+ errorCode: error?.code ?? null,
2385
+ turnId: ownedTurnId ?? null,
2386
+ });
2387
+ this.emit('containment-failed', payload);
2388
+ this.emit('codex-lifecycle', payload);
2389
+ this._scheduleContainedTransportClose();
2390
+ }
2391
+
2392
+ _scheduleContainedTransportClose() {
2393
+ if (this.containmentClosePromise) return;
2394
+ setImmediate(() => {
2395
+ if (this.containmentClosePromise) return;
2396
+ this.containmentClosePromise = timeout(
2397
+ Promise.resolve().then(() => this.client?.close()),
2398
+ this.cleanupTimeoutMs,
2399
+ 'Codex contained transport did not close in time',
2400
+ 'CODEX_CONTAINMENT_CLOSE_TIMEOUT',
2401
+ ).catch((closeError) => {
2402
+ this.logger.error?.(
2403
+ `[${this.label}] Codex containment close: ${closeError.message}`,
2404
+ );
2405
+ });
2406
+ });
2407
+ }
2408
+
2409
+ _durabilityFailure(error) {
2410
+ let current = error;
2411
+ for (let depth = 0; current && depth < 8; depth += 1) {
2412
+ if (current.code === 'CODEX_DURABILITY_FAILED') return current;
2413
+ current = current.cause;
2414
+ }
2415
+ return null;
2416
+ }
2417
+
2418
+ _blockDurability(error, excludedPending = null) {
2419
+ this._clearBackgroundWatchdog();
2420
+ if (this.state !== 'DurabilityBlocked') this._advanceLifecycle();
2421
+ this.state = 'DurabilityBlocked';
2422
+ this.inFlight = false;
2423
+ const blocked = processError(
2424
+ 'Codex durability is unavailable',
2425
+ 'CODEX_DURABILITY_FAILED',
2426
+ { cause: error },
2427
+ );
2428
+ for (const pending of [...this.pendingQueue]) {
2429
+ if (pending !== excludedPending && !pending?.settled) {
2430
+ this._rejectPending(pending, blocked);
2431
+ }
2432
+ }
2433
+ this.pendingQueue = excludedPending && this.pendingQueue.includes(excludedPending)
2434
+ ? [excludedPending]
2435
+ : [];
2436
+ if (this.current !== excludedPending) this.current = null;
2437
+ this.admittingTurnSettings = null;
2438
+ this.activeTurnSettings = null;
2439
+ this.emit('codex-lifecycle', this._lifecyclePayload(
2440
+ 'durability-blocked',
2441
+ { errorCode: error.code },
2442
+ ));
2443
+ }
2444
+
2445
+ blockDurability(error) {
2446
+ if (this.state === 'ContainmentFailed') return true;
2447
+ this._blockDurability(error);
2448
+ return true;
2449
+ }
2450
+
2451
+ _turnDetail(pending) {
2452
+ return {
2453
+ threadId: this.providerSessionId,
2454
+ turnId: pending.turnId,
2455
+ source: pending.context?.sourceMsgId ?? null,
2456
+ clientUserMessageId: pending.clientUserMessageId,
2457
+ attemptId: pending.attemptId,
2458
+ };
2459
+ }
2460
+
2461
+ _lifecyclePayload(kind, detail = {}) {
2462
+ return {
2463
+ kind,
2464
+ generationId: this.generationId,
2465
+ threadId: this.providerSessionId,
2466
+ hostIdentity: this.hostIdentity,
2467
+ bootSessionIdentity: this.bootSessionIdentity,
2468
+ ...detail,
2469
+ };
2470
+ }
2471
+
2472
+ _newWorkError() {
2473
+ if (this.closed || this.state === 'Closed') {
2474
+ return processError('Codex process is closed', 'CODEX_PROCESS_CLOSED');
2475
+ }
2476
+ if (this.state === 'ContainmentFailed') {
2477
+ return processError(
2478
+ 'Codex generation is containment-failed',
2479
+ 'CODEX_CONTAINMENT_FAILED',
2480
+ );
2481
+ }
2482
+ if (this.state === 'FailedAmbiguous') {
2483
+ return processError(
2484
+ 'Codex generation has an ambiguous mutation outcome',
2485
+ 'CODEX_RPC_OUTCOME_UNKNOWN',
2486
+ );
2487
+ }
2488
+ if (this.state === 'RecoveryConflict') {
2489
+ return processError(
2490
+ 'Codex resumed thread is already active',
2491
+ 'CODEX_RECOVERY_CONFLICT',
2492
+ );
2493
+ }
2494
+ if (this.state === 'Quiescing' || this.state === 'Stopped') {
2495
+ return processError(
2496
+ 'Codex process is quiescing',
2497
+ 'CODEX_PROCESS_QUIESCING',
2498
+ );
2499
+ }
2500
+ if (this.state === 'DurabilityBlocked') {
2501
+ return processError(
2502
+ 'Codex durability is unavailable',
2503
+ 'CODEX_DURABILITY_FAILED',
2504
+ );
2505
+ }
2506
+ if (this.state !== 'Idle' && this.state !== 'BackgroundWorking'
2507
+ && this.state !== 'BackgroundSettling'
2508
+ && this.state !== 'StartingTurn' && this.state !== 'Active'
2509
+ && this.state !== 'Settling') {
2510
+ return processError(
2511
+ 'Codex process is not ready',
2512
+ 'CODEX_PROCESS_NOT_READY',
2513
+ );
2514
+ }
2515
+ return null;
2516
+ }
2517
+
2518
+ _steerUnavailableReason() {
2519
+ if (this.closed || this.state === 'Closed') return 'closed';
2520
+ if (this.state === 'ContainmentFailed') return 'containment-failed';
2521
+ if (this.state === 'FailedAmbiguous') return 'outcome-unknown';
2522
+ if (this.state === 'RecoveryConflict') return 'recovery-conflict';
2523
+ if (this.state === 'Quiescing' || this.state === 'Stopped') {
2524
+ return 'quiescing';
2525
+ }
2526
+ if (this.state === 'DurabilityBlocked') return 'durability-blocked';
2527
+ return null;
2528
+ }
2529
+
2530
+ _settlePending(pending, action, value) {
2531
+ if (pending.settled) return false;
2532
+ pending.settled = true;
2533
+ if (action === 'resolve') pending.resolve(value);
2534
+ else pending.reject(value);
2535
+ return true;
2536
+ }
2537
+
2538
+ _rejectPending(pending, error) {
2539
+ pending.turnReady.reject(error);
2540
+ pending.terminalDeferred.reject(error);
2541
+ this._settlePending(pending, 'reject', error);
2542
+ }
2543
+
2544
+ _drainWaiting(code) {
2545
+ let count = 0;
2546
+ for (const pending of [...this.pendingQueue]) {
2547
+ if (pending === this.current) continue;
2548
+ this._reserveCancellation(pending, code);
2549
+ count += 1;
2550
+ }
2551
+ return count;
2552
+ }
2553
+
2554
+ drainQueue(code = 'INTERRUPTED') {
2555
+ if (this.current) return this._drainWaiting(code);
2556
+ return this._drainAll(code);
2557
+ }
2558
+
2559
+ _drainAll(code) {
2560
+ let count = 0;
2561
+ for (const pending of [...this.pendingQueue]) {
2562
+ this._reserveCancellation(pending, code);
2563
+ count += 1;
2564
+ }
2565
+ return count;
2566
+ }
2567
+
2568
+ _reserveCancellation(pending, code) {
2569
+ const index = this.pendingQueue.indexOf(pending);
2570
+ if (index !== -1) this.pendingQueue.splice(index, 1);
2571
+ try {
2572
+ pending.cancelled = true;
2573
+ pending.cancellationCode = code;
2574
+ } catch {}
2575
+ if (!this.pendingCancellations.some(({ pending: owned }) => owned === pending)) {
2576
+ this.cancellationSequence += 1;
2577
+ this.pendingCancellations.push({
2578
+ pending,
2579
+ code,
2580
+ attemptId: pending?.attemptId
2581
+ ?? `${this.generationId}:cancel:${this.cancellationSequence}`,
2582
+ });
2583
+ }
2584
+ }
2585
+
2586
+ async _flushPendingCancellations() {
2587
+ if (this.cancellationFlushPromise) return this.cancellationFlushPromise;
2588
+ this.cancellationFlushPromise = (async () => {
2589
+ while (this.pendingCancellations.length > 0) {
2590
+ const cancellation = this.pendingCancellations[0];
2591
+ const { pending } = cancellation;
2592
+ try {
2593
+ await this._checkpoint('queued-send-cancelled', {
2594
+ threadId: this.providerSessionId,
2595
+ turnId: pending.turnId ?? null,
2596
+ source: pending.context?.sourceMsgId ?? null,
2597
+ clientUserMessageId: pending.clientUserMessageId ?? null,
2598
+ attemptId: cancellation.attemptId,
2599
+ cancellationCode: cancellation.code,
2600
+ });
2601
+ } catch (error) {
2602
+ const durability = processError(
2603
+ 'Codex queued cancellation was not durably recorded',
2604
+ 'CODEX_DURABILITY_FAILED',
2605
+ { cause: error },
2606
+ );
2607
+ if (!cancellation.handlerSettled) {
2608
+ cancellation.handlerSettled = true;
2609
+ try {
2610
+ if (pending.turnReady) pending.turnReady.reject(durability);
2611
+ if (pending.terminalDeferred) {
2612
+ pending.terminalDeferred.reject(durability);
2613
+ }
2614
+ if (pending.settled === false) {
2615
+ this._settlePending(pending, 'reject', durability);
2616
+ } else if (typeof pending.reject === 'function') {
2617
+ pending.reject(durability);
2618
+ }
2619
+ } catch {}
2620
+ }
2621
+ this._blockDurability(error, this.current);
2622
+ throw durability;
2623
+ }
2624
+ this.pendingCancellations.shift();
2625
+ const error = processError(
2626
+ `drained:${cancellation.code}`,
2627
+ cancellation.code,
2628
+ );
2629
+ try {
2630
+ if (pending.turnReady) pending.turnReady.reject(error);
2631
+ if (pending.terminalDeferred) pending.terminalDeferred.reject(error);
2632
+ if (pending.settled === false) {
2633
+ this._settlePending(pending, 'reject', error);
2634
+ } else if (typeof pending.reject === 'function') {
2635
+ pending.reject(error);
2636
+ }
2637
+ } catch {}
2638
+ cancellation.handlerSettled = true;
2639
+ }
2640
+ })().finally(() => {
2641
+ this.cancellationFlushPromise = null;
2642
+ });
2643
+ return this.cancellationFlushPromise;
2644
+ }
2645
+
2646
+ async selectModelSettings(settings) {
2647
+ const selected = this._validatedModelSettings(settings);
2648
+ return this._withSettingsGate(() => {
2649
+ let reason = null;
2650
+ if (this.settingsAdmissionClosed || [
2651
+ 'Quiescing',
2652
+ 'Stopped',
2653
+ ].includes(this.state)) {
2654
+ reason = 'quiescing';
2655
+ } else if ([
2656
+ 'ContainmentFailed',
2657
+ 'FailedAmbiguous',
2658
+ 'DurabilityBlocked',
2659
+ ].includes(this.state)) {
2660
+ reason = 'containment';
2661
+ } else if (
2662
+ this.closed
2663
+ || this.state === 'Closed'
2664
+ || this.state === 'RecoveryConflict'
2665
+ ) {
2666
+ reason = 'stale-generation';
2667
+ }
2668
+ if (reason) {
2669
+ return {
2670
+ outcome: 'unavailable',
2671
+ reason,
2672
+ nextTurn: selected,
2673
+ };
2674
+ }
2675
+ this.desiredSettings = selected;
2676
+ return {
2677
+ outcome: 'updated-live',
2678
+ threadId: this.providerSessionId,
2679
+ generationId: this.generationId,
2680
+ currentTurn: this.activeTurnSettings ?? this.admittingTurnSettings,
2681
+ nextTurn: selected,
2682
+ };
2683
+ });
2684
+ }
2685
+
2686
+ injectUserMessage() {
2687
+ return false;
2688
+ }
2689
+
2690
+ steer() {
2691
+ return false;
2692
+ }
2693
+
2694
+ fireUserMessage() {
2695
+ return false;
2696
+ }
2697
+
2698
+ hasPendingDeliveryWork() {
2699
+ return Boolean(
2700
+ this.current
2701
+ || this.pendingQueue.length > 0
2702
+ || this.pendingCancellations.length > 0
2703
+ || this.cancellationFlushPromise
2704
+ || this.backgroundSettlementPromise
2705
+ || this.state === 'ContainmentFailed'
2706
+ || this.state === 'FailedAmbiguous'
2707
+ || this.state === 'DurabilityBlocked',
2708
+ );
2709
+ }
2710
+
2711
+ hasActiveBackgroundWork() {
2712
+ return (
2713
+ this.state === 'BackgroundWorking'
2714
+ || this.state === 'BackgroundSettling'
2715
+ );
2716
+ }
2717
+
2718
+ async getContextUsage() {
2719
+ throw new UnsupportedOperationError('getContextUsage', this.backend);
2720
+ }
2721
+
2722
+ async resetSession() {
2723
+ throw new UnsupportedOperationError('resetSession', this.backend);
2724
+ }
2725
+
2726
+ kill(reason = 'kill') {
2727
+ if (this.killPromise) return this.killPromise;
2728
+ this.killPromise = this._kill(reason);
2729
+ return this.killPromise;
2730
+ }
2731
+
2732
+ async _kill(reason) {
2733
+ if (this.closed) return;
2734
+ this._closeSettingsAdmission();
2735
+ this._clearBackgroundWatchdog();
2736
+ const lifecycle = this._captureLifecycle();
2737
+ if (this.state === 'RecoveryConflict') {
2738
+ await this._enterContainment(
2739
+ 'recovery-conflict-unresolved',
2740
+ processError(
2741
+ 'Codex resumed thread ownership remained unresolved',
2742
+ 'CODEX_RECOVERY_CONFLICT',
2743
+ ),
2744
+ );
2745
+ }
2746
+ if (this.state === 'ContainmentFailed') {
2747
+ this._scheduleContainedTransportClose();
2748
+ return;
2749
+ }
2750
+ if (this.state === 'DurabilityBlocked') {
2751
+ this._scheduleContainedTransportClose();
2752
+ return;
2753
+ }
2754
+
2755
+ this._drainWaiting('KILLED');
2756
+ if (!this.current) this._drainAll('KILLED');
2757
+ await this._flushPendingCancellations();
2758
+ this._assertLifecycle(lifecycle);
2759
+
2760
+ if (this.backgroundSettlementPromise) {
2761
+ await this.backgroundSettlementPromise;
2762
+ this._assertLifecycle(lifecycle);
2763
+ }
2764
+ if (
2765
+ this.current
2766
+ || this.state === 'BackgroundWorking'
2767
+ || this.state === 'Settling'
2768
+ ) {
2769
+ await this.interrupt();
2770
+ this._assertLifecycle(lifecycle);
2771
+ } else if (
2772
+ this.state !== 'Stopped'
2773
+ && this.state !== 'Idle'
2774
+ ) {
2775
+ await this.interrupt();
2776
+ this._assertLifecycle(lifecycle);
2777
+ }
2778
+
2779
+ this.state = 'Closing';
2780
+ try {
2781
+ await this.client?.close();
2782
+ } catch (error) {
2783
+ await this._enterContainment('app-server-close-unverified', error);
2784
+ }
2785
+ if (
2786
+ this.state === 'ContainmentFailed'
2787
+ || this.state === 'DurabilityBlocked'
2788
+ ) {
2789
+ // The transport may be closed, but this object remains the ownership
2790
+ // fence until containment or durability recovery is proved.
2791
+ return;
2792
+ }
2793
+ this._assertLifecycle(lifecycle);
2794
+ this.closed = true;
2795
+ this.state = 'Closed';
2796
+ this._emitClose(0, reason);
2797
+ }
2798
+
2799
+ _emitClose(code, reason = null) {
2800
+ if (this.closeEmitted) return;
2801
+ this.closeEmitted = true;
2802
+ this.emit('close', code, {
2803
+ backend: this.backend,
2804
+ generationId: this.generationId,
2805
+ reason,
2806
+ containmentReason: this.containmentReason,
2807
+ });
2808
+ }
2809
+ }
2810
+
2811
+ module.exports = {
2812
+ CodexProcess,
2813
+ CodexProcessError,
2814
+ };