@shumkov/orchestra 0.10.14 → 0.10.15

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.
@@ -40,6 +40,39 @@ const DEFAULT_MAX_USED_REQUEST_IDS = 65_536;
40
40
  const DEFAULT_MAX_QUEUED_LINES = 256;
41
41
  const DEFAULT_MAX_QUEUED_BYTES = 4 * 1024 * 1024;
42
42
  const DEFAULT_SINK_TIMEOUT_MS = 5_000;
43
+ const CLIENT_ROOT_ERROR_CODES = Object.freeze([
44
+ 'CODEX_PROTOCOL_ERROR',
45
+ 'CODEX_TRANSPORT_ERROR',
46
+ 'CODEX_PROCESS_EXITED',
47
+ 'CODEX_PROCESS_ERROR',
48
+ 'CODEX_RPC_TIMEOUT',
49
+ 'CODEX_SINK_TIMEOUT',
50
+ 'CODEX_PROCESS_CLOSE_TIMEOUT',
51
+ 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
52
+ 'unknown',
53
+ ]);
54
+ const CLIENT_FAULT_CLASSES = Object.freeze([
55
+ 'stderr-limit',
56
+ 'transport',
57
+ 'protocol',
58
+ 'process-exit',
59
+ 'rpc-timeout',
60
+ 'sink',
61
+ 'cleanup',
62
+ 'unknown',
63
+ ]);
64
+ const CLIENT_ROOT_ERROR_CODE_SET = new Set(CLIENT_ROOT_ERROR_CODES);
65
+ const CLIENT_FAULT_CLASS_SET = new Set(CLIENT_FAULT_CLASSES);
66
+ const CLIENT_FAULT_CLASS_BY_CODE = Object.freeze({
67
+ CODEX_PROTOCOL_ERROR: 'protocol',
68
+ CODEX_TRANSPORT_ERROR: 'transport',
69
+ CODEX_PROCESS_EXITED: 'process-exit',
70
+ CODEX_PROCESS_ERROR: 'process-exit',
71
+ CODEX_RPC_TIMEOUT: 'rpc-timeout',
72
+ CODEX_SINK_TIMEOUT: 'sink',
73
+ CODEX_PROCESS_CLOSE_TIMEOUT: 'cleanup',
74
+ CODEX_PROCESS_CLEANUP_UNVERIFIED: 'cleanup',
75
+ });
43
76
  const MAX_ID_BYTES = 512;
44
77
  const MAX_TEXT_BYTES = 64 * 1024;
45
78
  const MAX_COMPLETED_ITEMS = 512;
@@ -104,6 +137,115 @@ const RECOGNIZED_RPC_ERRORS = new Map(
104
137
  .map(([method, messages]) => [method, new Set(messages)]),
105
138
  );
106
139
 
140
+ function faultProvenanceFrom(error) {
141
+ const seen = new Set();
142
+ let current = error;
143
+ for (let depth = 0; current && depth < 8; depth += 1) {
144
+ if (
145
+ (typeof current !== 'object' && typeof current !== 'function')
146
+ || seen.has(current)
147
+ ) {
148
+ break;
149
+ }
150
+ seen.add(current);
151
+ const rootDescriptor = Object.getOwnPropertyDescriptor(
152
+ current,
153
+ 'clientRootErrorCode',
154
+ );
155
+ const classDescriptor = Object.getOwnPropertyDescriptor(
156
+ current,
157
+ 'clientFaultClass',
158
+ );
159
+ const codeDescriptor = Object.getOwnPropertyDescriptor(current, 'code');
160
+ const rootCode = rootDescriptor?.value;
161
+ const code = codeDescriptor?.value;
162
+ const faultClass = classDescriptor?.value;
163
+ if (
164
+ typeof rootCode === 'string'
165
+ && CLIENT_ROOT_ERROR_CODE_SET.has(rootCode)
166
+ && rootCode !== 'unknown'
167
+ ) {
168
+ return Object.freeze({
169
+ clientRootErrorCode: rootCode,
170
+ clientFaultClass: CLIENT_FAULT_CLASS_SET.has(faultClass)
171
+ ? faultClass
172
+ : (CLIENT_FAULT_CLASS_BY_CODE[rootCode] ?? 'unknown'),
173
+ });
174
+ }
175
+ if (
176
+ typeof code === 'string'
177
+ && CLIENT_ROOT_ERROR_CODE_SET.has(code)
178
+ && code !== 'unknown'
179
+ ) {
180
+ return Object.freeze({
181
+ clientRootErrorCode: code,
182
+ clientFaultClass: CLIENT_FAULT_CLASS_SET.has(faultClass)
183
+ ? faultClass
184
+ : (CLIENT_FAULT_CLASS_BY_CODE[code] ?? 'unknown'),
185
+ });
186
+ }
187
+ const causeDescriptor = Object.getOwnPropertyDescriptor(current, 'cause');
188
+ current = causeDescriptor?.value;
189
+ }
190
+ return Object.freeze({
191
+ clientRootErrorCode: 'unknown',
192
+ clientFaultClass: 'unknown',
193
+ });
194
+ }
195
+
196
+ function defineFaultProvenance(error, provenance) {
197
+ const properties = {
198
+ clientRootErrorCode: {
199
+ value: provenance.clientRootErrorCode,
200
+ enumerable: true,
201
+ writable: false,
202
+ configurable: false,
203
+ },
204
+ clientFaultClass: {
205
+ value: provenance.clientFaultClass,
206
+ enumerable: true,
207
+ writable: false,
208
+ configurable: false,
209
+ },
210
+ };
211
+ try {
212
+ Object.defineProperties(error, properties);
213
+ return error;
214
+ } catch {
215
+ const safeCode = provenance.clientRootErrorCode === 'unknown'
216
+ ? 'CODEX_PROTOCOL_ERROR'
217
+ : provenance.clientRootErrorCode;
218
+ const replacement = new CodexAppServerError(
219
+ 'app-server fault could not be annotated',
220
+ safeCode,
221
+ { cause: error },
222
+ );
223
+ Object.defineProperties(replacement, properties);
224
+ return replacement;
225
+ }
226
+ }
227
+
228
+ function faultWithClass(error, clientFaultClass) {
229
+ Object.defineProperty(error, 'clientFaultClass', {
230
+ value: clientFaultClass,
231
+ enumerable: true,
232
+ writable: false,
233
+ configurable: false,
234
+ });
235
+ return error;
236
+ }
237
+
238
+ function transportWriteError(cause) {
239
+ if (cause instanceof CodexAppServerError && cause.code === 'CODEX_TRANSPORT_ERROR') {
240
+ return cause;
241
+ }
242
+ return new CodexAppServerError(
243
+ 'app-server transport write failed',
244
+ 'CODEX_TRANSPORT_ERROR',
245
+ { cause },
246
+ );
247
+ }
248
+
107
249
  function assertProtocolSchema() {
108
250
  const experimental = [...CLIENT_REQUESTS]
109
251
  .filter(([, spec]) => spec.experimental)
@@ -1794,14 +1936,19 @@ function projectRequestParams(method, params, spec, ownedCwd) {
1794
1936
  );
1795
1937
  }
1796
1938
 
1797
- function mutationDeliveryError(pending, cause) {
1939
+ function mutationDeliveryError(
1940
+ pending,
1941
+ cause,
1942
+ provenance = faultProvenanceFrom(cause),
1943
+ ) {
1798
1944
  const code = pending.writeAttempted
1799
1945
  ? 'CODEX_RPC_OUTCOME_UNKNOWN'
1800
1946
  : 'CODEX_RPC_NOT_SENT';
1801
1947
  const message = pending.writeAttempted
1802
1948
  ? `app-server ${pending.method} outcome is unknown`
1803
1949
  : `app-server ${pending.method} was not sent`;
1804
- return new CodexAppServerError(message, code, { cause });
1950
+ const error = new CodexAppServerError(message, code, { cause });
1951
+ return defineFaultProvenance(error, provenance);
1805
1952
  }
1806
1953
 
1807
1954
  function sameFingerprint(left, right) {
@@ -1994,6 +2141,7 @@ class CodexAppServerClient extends EventEmitter {
1994
2141
  this.protocolError = null;
1995
2142
  this.faultPromise = null;
1996
2143
  this.faultOutcome = null;
2144
+ this.faultProvenance = null;
1997
2145
  this.faultWaitPromise = new Promise((resolve, reject) => {
1998
2146
  this.resolveFaultWait = resolve;
1999
2147
  this.rejectFaultWait = reject;
@@ -2463,7 +2611,10 @@ class CodexAppServerClient extends EventEmitter {
2463
2611
  }
2464
2612
  }),
2465
2613
  'transport write',
2466
- );
2614
+ ).catch((error) => {
2615
+ if (error?.code === 'CODEX_SINK_TIMEOUT') throw error;
2616
+ throw transportWriteError(error);
2617
+ });
2467
2618
  }
2468
2619
 
2469
2620
  _awaitBounded(value, label) {
@@ -2713,10 +2864,10 @@ class CodexAppServerClient extends EventEmitter {
2713
2864
  ? chunk.length
2714
2865
  : Buffer.byteLength(String(chunk));
2715
2866
  if (this.stderrBytes > this.maxStderrBytes) {
2716
- this._fault(new CodexAppServerError(
2867
+ this._fault(faultWithClass(new CodexAppServerError(
2717
2868
  'app-server stderr exceeded the size limit',
2718
2869
  'CODEX_PROTOCOL_ERROR',
2719
- ));
2870
+ ), 'stderr-limit'));
2720
2871
  }
2721
2872
  }
2722
2873
 
@@ -2922,13 +3073,16 @@ class CodexAppServerClient extends EventEmitter {
2922
3073
 
2923
3074
  _fault(error) {
2924
3075
  if (this.protocolError || this.state === 'closed') return;
2925
- const fault = error instanceof Error
3076
+ let fault = error instanceof Error
2926
3077
  ? error
2927
3078
  : new CodexAppServerError(
2928
3079
  'app-server protocol failed',
2929
3080
  'CODEX_PROTOCOL_ERROR',
2930
3081
  );
2931
- const ambiguousMutation = this._rejectAll(fault);
3082
+ const provenance = faultProvenanceFrom(fault);
3083
+ this.faultProvenance = provenance;
3084
+ fault = defineFaultProvenance(fault, provenance);
3085
+ const ambiguousMutation = this._rejectAll(fault, provenance);
2932
3086
  this.protocolError = ambiguousMutation ?? fault;
2933
3087
  this._invalidateSinks();
2934
3088
  try { this.emit('protocol-error', this.protocolError); } catch {}
@@ -2953,6 +3107,8 @@ class CodexAppServerClient extends EventEmitter {
2953
3107
  cleanup: cleanupError ? 'failed' : 'completed',
2954
3108
  errorCode: this.protocolError?.code ?? 'CODEX_PROTOCOL_ERROR',
2955
3109
  cleanupErrorCode: cleanupError?.code ?? null,
3110
+ clientRootErrorCode: this.faultProvenance?.clientRootErrorCode ?? 'unknown',
3111
+ clientFaultClass: this.faultProvenance?.clientFaultClass ?? 'unknown',
2956
3112
  mutationOutcomeUnknown:
2957
3113
  this.protocolError?.code === 'CODEX_RPC_OUTCOME_UNKNOWN',
2958
3114
  });
@@ -2976,13 +3132,13 @@ class CodexAppServerClient extends EventEmitter {
2976
3132
  return this.faultWaitPromise;
2977
3133
  }
2978
3134
 
2979
- _rejectAll(cause) {
3135
+ _rejectAll(cause, provenance = faultProvenanceFrom(cause)) {
2980
3136
  let ambiguousMutation = null;
2981
3137
  for (const pending of this.pending.values()) {
2982
3138
  this.clearTimer(pending.timer);
2983
3139
  pending.sinkController?.abort(cause);
2984
3140
  const requestError = pending.stateChanging
2985
- ? mutationDeliveryError(pending, cause)
3141
+ ? mutationDeliveryError(pending, cause, provenance)
2986
3142
  : cause;
2987
3143
  if (
2988
3144
  requestError.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
@@ -20,6 +20,27 @@ const MAX_NODES = 16_384;
20
20
  const MAX_DEPTH = 16;
21
21
  const POST_READ_SETTLE_MS = 25;
22
22
  const SHA256_RE = /^[a-f0-9]{64}$/;
23
+ const CLIENT_ROOT_ERROR_CODES = new Set([
24
+ 'CODEX_PROTOCOL_ERROR',
25
+ 'CODEX_TRANSPORT_ERROR',
26
+ 'CODEX_PROCESS_EXITED',
27
+ 'CODEX_PROCESS_ERROR',
28
+ 'CODEX_RPC_TIMEOUT',
29
+ 'CODEX_SINK_TIMEOUT',
30
+ 'CODEX_PROCESS_CLOSE_TIMEOUT',
31
+ 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
32
+ 'unknown',
33
+ ]);
34
+ const CLIENT_FAULT_CLASSES = new Set([
35
+ 'stderr-limit',
36
+ 'transport',
37
+ 'protocol',
38
+ 'process-exit',
39
+ 'rpc-timeout',
40
+ 'sink',
41
+ 'cleanup',
42
+ 'unknown',
43
+ ]);
23
44
  const EXPECTED_PROFILE_KEYS = new Set([
24
45
  'runtime',
25
46
  'binary',
@@ -467,6 +488,8 @@ function projectClientFault(value) {
467
488
  cleanup: outcome.cleanup,
468
489
  errorCode: outcome.errorCode,
469
490
  cleanupErrorCode: outcome.cleanupErrorCode,
491
+ clientRootErrorCode: outcome.clientRootErrorCode ?? 'unknown',
492
+ clientFaultClass: outcome.clientFaultClass ?? 'unknown',
470
493
  mutationOutcomeUnknown: outcome.mutationOutcomeUnknown,
471
494
  };
472
495
  if (
@@ -484,6 +507,8 @@ function projectClientFault(value) {
484
507
  )
485
508
  )
486
509
  || typeof projected.mutationOutcomeUnknown !== 'boolean'
510
+ || !CLIENT_ROOT_ERROR_CODES.has(projected.clientRootErrorCode)
511
+ || !CLIENT_FAULT_CLASSES.has(projected.clientFaultClass)
487
512
  ) {
488
513
  throw new CodexPreflightError(
489
514
  'Codex preflight client fault handoff was malformed',
@@ -503,6 +528,8 @@ function clientFaultError(outcome) {
503
528
  error.clientFaultContainment = outcome.containment;
504
529
  error.clientFaultCleanup = outcome.cleanup;
505
530
  error.clientFaultCleanupErrorCode = outcome.cleanupErrorCode;
531
+ error.clientRootErrorCode = outcome.clientRootErrorCode;
532
+ error.clientFaultClass = outcome.clientFaultClass;
506
533
  return error;
507
534
  }
508
535
 
@@ -24,6 +24,57 @@ const DEFAULT_MAX_PENDING_STEERS = 16;
24
24
  const MAX_OPAQUE_ID_BYTES = 512;
25
25
  const CONTROL_CHAR_RE = /[\x00-\x08\x0b-\x1f\x7f]/g;
26
26
  const OPAQUE_ID_CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
27
+ const CLIENT_ROOT_ERROR_CODES = new Set([
28
+ 'CODEX_PROTOCOL_ERROR',
29
+ 'CODEX_TRANSPORT_ERROR',
30
+ 'CODEX_PROCESS_EXITED',
31
+ 'CODEX_PROCESS_ERROR',
32
+ 'CODEX_RPC_TIMEOUT',
33
+ 'CODEX_SINK_TIMEOUT',
34
+ 'CODEX_PROCESS_CLOSE_TIMEOUT',
35
+ 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
36
+ 'unknown',
37
+ ]);
38
+ const CLIENT_FAULT_CLASSES = new Set([
39
+ 'stderr-limit',
40
+ 'transport',
41
+ 'protocol',
42
+ 'process-exit',
43
+ 'rpc-timeout',
44
+ 'sink',
45
+ 'cleanup',
46
+ 'unknown',
47
+ ]);
48
+ const NOTIFICATION_METHODS = new Set([
49
+ 'error',
50
+ 'thread/status/changed',
51
+ 'thread/settings/updated',
52
+ 'turn/started',
53
+ 'turn/completed',
54
+ 'item/started',
55
+ 'item/completed',
56
+ 'item/agentMessage/delta',
57
+ ]);
58
+ const PROCESS_STATES = new Set([
59
+ 'Spawning',
60
+ 'Initializing',
61
+ 'AttachingThread',
62
+ 'Idle',
63
+ 'StartingTurn',
64
+ 'Active',
65
+ 'BackgroundWorking',
66
+ 'BackgroundSettling',
67
+ 'Settling',
68
+ 'Quiescing',
69
+ 'Stopped',
70
+ 'Closing',
71
+ 'Closed',
72
+ 'FailedAmbiguous',
73
+ 'RecoveryConflict',
74
+ 'DurabilityBlocked',
75
+ 'ContainmentFailed',
76
+ 'unknown',
77
+ ]);
27
78
 
28
79
  class CodexProcessError extends Error {
29
80
  constructor(message, code, options) {
@@ -72,6 +123,63 @@ function processError(message, code, options) {
72
123
  return new CodexProcessError(message, code, options);
73
124
  }
74
125
 
126
+ function readClientFaultProvenance(error) {
127
+ const seen = new Set();
128
+ let current = error;
129
+ for (let depth = 0; current && depth < 8; depth += 1) {
130
+ if (
131
+ (typeof current !== 'object' && typeof current !== 'function')
132
+ || seen.has(current)
133
+ ) {
134
+ break;
135
+ }
136
+ seen.add(current);
137
+ const root = Object.getOwnPropertyDescriptor(
138
+ current,
139
+ 'clientRootErrorCode',
140
+ )?.value;
141
+ const faultClass = Object.getOwnPropertyDescriptor(
142
+ current,
143
+ 'clientFaultClass',
144
+ )?.value;
145
+ if (
146
+ typeof root === 'string'
147
+ && CLIENT_ROOT_ERROR_CODES.has(root)
148
+ && typeof faultClass === 'string'
149
+ && CLIENT_FAULT_CLASSES.has(faultClass)
150
+ && (root !== 'unknown' || faultClass === 'unknown')
151
+ ) {
152
+ return Object.freeze({
153
+ clientRootErrorCode: root,
154
+ clientFaultClass: faultClass,
155
+ });
156
+ }
157
+ current = Object.getOwnPropertyDescriptor(current, 'cause')?.value;
158
+ }
159
+ return Object.freeze({
160
+ clientRootErrorCode: 'unknown',
161
+ clientFaultClass: 'unknown',
162
+ });
163
+ }
164
+
165
+ function attachClientFaultProvenance(error, provenance) {
166
+ Object.defineProperties(error, {
167
+ clientRootErrorCode: {
168
+ value: provenance.clientRootErrorCode,
169
+ enumerable: true,
170
+ writable: false,
171
+ configurable: false,
172
+ },
173
+ clientFaultClass: {
174
+ value: provenance.clientFaultClass,
175
+ enumerable: true,
176
+ writable: false,
177
+ configurable: false,
178
+ },
179
+ });
180
+ return error;
181
+ }
182
+
75
183
  function modelSettings(model, effort, label = 'settings') {
76
184
  return Object.freeze({
77
185
  model: nonEmptyString(model, `${label}.model`),
@@ -374,6 +482,7 @@ class CodexProcess extends Process {
374
482
  this.containmentError = null;
375
483
  this.containmentErrorCode = null;
376
484
  this.containmentTurnId = null;
485
+ this.containmentProvenance = null;
377
486
  this.containmentCleanupCommitted = null;
378
487
  this.startupReleaseSafe = false;
379
488
  this.stateChangingWriteCommitted = false;
@@ -2072,6 +2181,12 @@ class CodexProcess extends Process {
2072
2181
  'cross-thread-notification',
2073
2182
  'Codex emitted traffic for another provider thread',
2074
2183
  fence,
2184
+ {
2185
+ notificationMethod: NOTIFICATION_METHODS.has(method) ? method : null,
2186
+ observedProcessState: PROCESS_STATES.has(this.state)
2187
+ ? this.state
2188
+ : 'unknown',
2189
+ },
2075
2190
  );
2076
2191
  return;
2077
2192
  }
@@ -2364,10 +2479,10 @@ class CodexProcess extends Process {
2364
2479
  }
2365
2480
  }
2366
2481
 
2367
- async _notificationProtocolFault(reason, message, fence) {
2482
+ async _notificationProtocolFault(reason, message, fence, detail = {}) {
2368
2483
  const error = this._protocolFault(reason, message, false);
2369
2484
  if (this.protocolFaultCount >= this.protocolFaultThreshold) {
2370
- await this._enterContainment(reason, error, null, fence);
2485
+ await this._enterContainment(reason, error, null, fence, detail);
2371
2486
  }
2372
2487
  return error;
2373
2488
  }
@@ -2386,14 +2501,18 @@ class CodexProcess extends Process {
2386
2501
  outcome?.boundary === 'post-spawn'
2387
2502
  || outcome?.containment === 'unverified'
2388
2503
  ) {
2389
- await this._enterContainment(
2390
- outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
2391
- ? 'rpc-outcome-unknown'
2392
- : 'app-server-fault',
2504
+ const error = attachClientFaultProvenance(
2393
2505
  processError(
2394
2506
  'Codex app-server faulted after spawn',
2395
2507
  outcome?.errorCode ?? 'CODEX_PROCESS_EXITED',
2396
2508
  ),
2509
+ readClientFaultProvenance(outcome),
2510
+ );
2511
+ await this._enterContainment(
2512
+ outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
2513
+ ? 'rpc-outcome-unknown'
2514
+ : 'app-server-fault',
2515
+ error,
2397
2516
  );
2398
2517
  }
2399
2518
  }
@@ -2529,7 +2648,13 @@ class CodexProcess extends Process {
2529
2648
  }
2530
2649
 
2531
2650
  _protocolFault(reason, message, enterContainment = true) {
2532
- const error = processError(message, 'CODEX_PROTOCOL_ERROR');
2651
+ const error = attachClientFaultProvenance(
2652
+ processError(message, 'CODEX_PROTOCOL_ERROR'),
2653
+ {
2654
+ clientRootErrorCode: 'CODEX_PROTOCOL_ERROR',
2655
+ clientFaultClass: 'protocol',
2656
+ },
2657
+ );
2533
2658
  this.protocolFaultCount += 1;
2534
2659
  this.emit('protocol-security-fault', this._lifecyclePayload(
2535
2660
  'protocol-security-fault',
@@ -2549,6 +2674,7 @@ class CodexProcess extends Process {
2549
2674
  this._advanceLifecycle();
2550
2675
  this.state = 'FailedAmbiguous';
2551
2676
  this.inFlight = false;
2677
+ const provenance = readClientFaultProvenance(error);
2552
2678
  try {
2553
2679
  await this._checkpoint('failed-ambiguous-entered', {
2554
2680
  reason,
@@ -2556,6 +2682,7 @@ class CodexProcess extends Process {
2556
2682
  turnId: this.activeTurnId
2557
2683
  ?? this.current?.turnId
2558
2684
  ?? this.lastTurnId,
2685
+ ...provenance,
2559
2686
  });
2560
2687
  } catch (checkpointError) {
2561
2688
  this.containmentError = checkpointError;
@@ -2575,6 +2702,7 @@ class CodexProcess extends Process {
2575
2702
  error,
2576
2703
  excludedPending = null,
2577
2704
  fence = null,
2705
+ detail = {},
2578
2706
  ) {
2579
2707
  this._closeSettingsAdmission();
2580
2708
  if (this.state === 'ContainmentFailed') return;
@@ -2583,6 +2711,16 @@ class CodexProcess extends Process {
2583
2711
  ?? this.current?.turnId
2584
2712
  ?? this.lastTurnId;
2585
2713
  this._advanceLifecycle();
2714
+ const notificationMethod = NOTIFICATION_METHODS.has(detail.notificationMethod)
2715
+ ? detail.notificationMethod
2716
+ : null;
2717
+ this.containmentProvenance = Object.freeze({
2718
+ ...readClientFaultProvenance(error),
2719
+ ...(notificationMethod ? { notificationMethod } : {}),
2720
+ observedProcessState: PROCESS_STATES.has(detail.observedProcessState)
2721
+ ? detail.observedProcessState
2722
+ : 'unknown',
2723
+ });
2586
2724
  this.state = 'ContainmentFailed';
2587
2725
  this.containmentReason = reason;
2588
2726
  this.containmentError = error;
@@ -2594,6 +2732,7 @@ class CodexProcess extends Process {
2594
2732
  reason,
2595
2733
  errorCode: error?.code ?? null,
2596
2734
  turnId: ownedTurnId ?? null,
2735
+ ...this.containmentProvenance,
2597
2736
  }, fence);
2598
2737
  } catch (checkpointError) {
2599
2738
  this.containmentError = checkpointError;
@@ -2652,6 +2791,7 @@ class CodexProcess extends Process {
2652
2791
  reason: this.containmentReason,
2653
2792
  errorCode: this.containmentErrorCode,
2654
2793
  turnId: this.containmentTurnId,
2794
+ ...this.containmentProvenance,
2655
2795
  });
2656
2796
  const detail = Object.freeze({
2657
2797
  kind: 'containment-cleanup-committed',
@@ -2660,6 +2800,7 @@ class CodexProcess extends Process {
2660
2800
  hostIdentity: this.hostIdentity,
2661
2801
  bootSessionIdentity: this.bootSessionIdentity,
2662
2802
  containmentReason: this.containmentReason,
2803
+ ...this.containmentProvenance,
2663
2804
  });
2664
2805
  this.containmentCleanupCommitted = detail;
2665
2806
  this.closed = true;
@@ -274,6 +274,8 @@ class ProcessManager {
274
274
  this.procs = new Map(); // sessionKey → Process
275
275
  this._lruWaiters = []; // [{ resolve, reject, timer }]
276
276
  this._shuttingDown = false;
277
+ this._lifecycleAdmissionClosed = false;
278
+ this._cleanRetirementCandidates = new Map();
277
279
  // sessionKey → in-flight start() Promise. Lets a concurrent
278
280
  // getOrSpawn for the same key await the spawn instead of
279
281
  // returning a proc whose start() hasn't resolved (see getOrSpawn).
@@ -497,6 +499,17 @@ class ProcessManager {
497
499
  }
498
500
 
499
501
  _withLifecycleGate(sessionKey, operation) {
502
+ if (this._lifecycleAdmissionClosed) {
503
+ return Promise.reject(new Error('shutdown'));
504
+ }
505
+ return this._enqueueLifecycleGate(sessionKey, operation);
506
+ }
507
+
508
+ _withInternalLifecycleGate(sessionKey, operation) {
509
+ return this._enqueueLifecycleGate(sessionKey, operation);
510
+ }
511
+
512
+ _enqueueLifecycleGate(sessionKey, operation) {
500
513
  const prior = this._lifecycleGates.get(sessionKey);
501
514
  const run = Promise.resolve(prior)
502
515
  .catch(() => {})
@@ -843,6 +856,9 @@ class ProcessManager {
843
856
  if (this.procs.get(sessionKey) === newProc) {
844
857
  this.procs.delete(sessionKey);
845
858
  }
859
+ if (this._lifecycleAdmissionClosed) {
860
+ this._cleanRetirementCandidates.set(sessionKey, newProc);
861
+ }
846
862
  this._maybeSignalLruWaiter();
847
863
  }
848
864
  throw err;
@@ -1231,7 +1247,7 @@ class ProcessManager {
1231
1247
  });
1232
1248
  this._retiring.add(oldest);
1233
1249
  this.procs.delete(oldestKey);
1234
- this._withLifecycleGate(oldestKey, async () => {
1250
+ this._withInternalLifecycleGate(oldestKey, async () => {
1235
1251
  try { await oldest.kill('evict'); } catch {}
1236
1252
  finally { this._retiring.delete(oldest); }
1237
1253
  }).catch(() => {});
@@ -1428,7 +1444,7 @@ class ProcessManager {
1428
1444
  .filter(([, proc]) => !this._retiring.has(proc))
1429
1445
  .map(([sessionKey]) => sessionKey);
1430
1446
  const retirementResults = await Promise.allSettled(targets.map((sessionKey) => (
1431
- this._withLifecycleGate(sessionKey, () => (
1447
+ this._withInternalLifecycleGate(sessionKey, () => (
1432
1448
  this._killLocked(sessionKey, 'shutdown')
1433
1449
  ))
1434
1450
  )));
@@ -1448,130 +1464,168 @@ class ProcessManager {
1448
1464
  );
1449
1465
  }
1450
1466
  this._shuttingDown = true;
1467
+ this._lifecycleAdmissionClosed = true;
1451
1468
  for (const w of this._lruWaiters) {
1452
1469
  clearTimeout(w.timer);
1453
1470
  w.reject(new Error('shutdown'));
1454
1471
  }
1455
1472
  this._lruWaiters.length = 0;
1456
1473
 
1457
- const admittedResults = await Promise.allSettled(
1458
- [...this._lifecycleGates.values()],
1459
- );
1460
- const targets = [...this.procs.entries()]
1461
- .filter(([, proc]) => !this._retiring.has(proc));
1462
- for (const [, proc] of targets) this._retiring.add(proc);
1474
+ const admittedGates = new Map(this._lifecycleGates);
1475
+ const targets = new Set([
1476
+ ...[...this.procs.entries()]
1477
+ .filter(([, proc]) => !this._retiring.has(proc))
1478
+ .map(([sessionKey]) => sessionKey),
1479
+ ...this._cleanRetirementCandidates.keys(),
1480
+ ...admittedGates.keys(),
1481
+ ]);
1482
+ const retiredTargets = new Map();
1463
1483
 
1464
1484
  let settled;
1465
1485
  try {
1466
- settled = await Promise.allSettled(targets.map(async ([sessionKey, proc]) => {
1467
- let snapshot;
1468
- if (this._isCodex(proc)) {
1469
- const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1470
- ? proc.captureCleanRestartCandidate()
1471
- : null;
1472
- let deliveryEvidence = null;
1473
- let deliveryEvidenceError = null;
1486
+ settled = await Promise.allSettled([...targets].map(async (sessionKey) => {
1487
+ let gateError = null;
1488
+ const gate = admittedGates.get(sessionKey);
1489
+ if (gate) {
1474
1490
  try {
1475
- deliveryEvidence = await getDeliveryEvidence(
1476
- sessionKey,
1477
- candidate?.sourceMsgId ?? null,
1478
- );
1491
+ await gate;
1479
1492
  } catch (error) {
1480
- deliveryEvidenceError = error;
1493
+ gateError = error;
1481
1494
  }
1482
- const retirement = await this._strictRetire(proc, 'clean-restart');
1483
- const settledTerminalStatus = this._codexLease?.terminalStatus ?? null;
1484
- const settledTurnId = this._codexLease?.turnId ?? null;
1485
- const deliverySafe = Boolean(
1486
- deliveryEvidence?.fenced === true
1487
- && deliveryEvidence.pending === 0
1488
- && deliveryEvidence.outputAttempted === false
1489
- );
1490
- const exactRetirement = Boolean(
1491
- candidate
1492
- && retirement?.committed === true
1493
- && retirement.disposition === 'stop-cancelled'
1494
- && retirement.sessionKey === candidate.sessionKey
1495
- && retirement.generationId === candidate.generationId
1496
- && retirement.attemptId === candidate.attemptId
1497
- && retirement.providerSessionId === candidate.providerSessionId
1498
- && retirement.providerTurnId === candidate.providerTurnId
1499
- && retirement.sourceMsgId != null
1500
- && String(retirement.sourceMsgId) === String(candidate.sourceMsgId)
1501
- && settledTerminalStatus === 'interrupted'
1502
- && settledTurnId === candidate.providerTurnId
1503
- );
1504
- if (this._codexLeaseMatches(proc)) this._codexLease = null;
1505
- const eligible = deliverySafe && exactRetirement;
1506
- let reason = 'output-evidence';
1507
- if (deliverySafe) reason = 'retirement-binding-mismatch';
1508
- if (deliveryEvidenceError) reason = 'delivery-evidence-failed';
1509
- snapshot = candidate ? {
1510
- runtime: 'codex',
1511
- namespace: 'codex:app-server',
1512
- sourceMsgId: candidate.sourceMsgId,
1513
- providerSessionId: candidate.providerSessionId,
1514
- providerTurnId: candidate.providerTurnId,
1515
- cwd: candidate.cwd,
1516
- model: candidate.model,
1517
- effort: candidate.effort,
1518
- spawnProfileId: candidate.spawnProfileId,
1519
- eligible,
1520
- reason: eligible ? 'eligible' : reason,
1521
- } : {
1522
- sourceMsgId: null,
1523
- eligible: false,
1524
- reason: 'no-active-turn',
1525
- };
1526
- if (deliveryEvidenceError) throw deliveryEvidenceError;
1527
- } else {
1528
- snapshot = await proc.retireForCleanRestart({
1529
- getDeliveryEvidence: (_reportedSessionKey, sourceMsgId) => (
1530
- getDeliveryEvidence(
1495
+ }
1496
+ const proc = this.procs.get(sessionKey)
1497
+ ?? this._cleanRetirementCandidates.get(sessionKey);
1498
+ if (!proc || this._retiring.has(proc)) {
1499
+ if (gateError) throw gateError;
1500
+ return null;
1501
+ }
1502
+ this._retiring.add(proc);
1503
+ retiredTargets.set(sessionKey, proc);
1504
+ let snapshot;
1505
+ try {
1506
+ if (this._isCodex(proc)) {
1507
+ const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1508
+ ? proc.captureCleanRestartCandidate()
1509
+ : null;
1510
+ let deliveryEvidence = null;
1511
+ let deliveryEvidenceError = null;
1512
+ try {
1513
+ deliveryEvidence = await getDeliveryEvidence(
1531
1514
  sessionKey,
1532
- proc.backend === 'cli' ? sourceMsgId : null,
1533
- )
1534
- ),
1515
+ candidate?.sourceMsgId ?? null,
1516
+ );
1517
+ } catch (error) {
1518
+ deliveryEvidenceError = error;
1519
+ }
1520
+ const retirement = await this._strictRetire(proc, 'clean-restart');
1521
+ const settledTerminalStatus = this._codexLease?.terminalStatus ?? null;
1522
+ const settledTurnId = this._codexLease?.turnId ?? null;
1523
+ const deliverySafe = Boolean(
1524
+ deliveryEvidence?.fenced === true
1525
+ && deliveryEvidence.pending === 0
1526
+ && deliveryEvidence.outputAttempted === false
1527
+ );
1528
+ const exactRetirement = Boolean(
1529
+ candidate
1530
+ && retirement?.committed === true
1531
+ && retirement.disposition === 'stop-cancelled'
1532
+ && retirement.sessionKey === candidate.sessionKey
1533
+ && retirement.generationId === candidate.generationId
1534
+ && retirement.attemptId === candidate.attemptId
1535
+ && retirement.providerSessionId === candidate.providerSessionId
1536
+ && retirement.providerTurnId === candidate.providerTurnId
1537
+ && retirement.sourceMsgId != null
1538
+ && String(retirement.sourceMsgId) === String(candidate.sourceMsgId)
1539
+ && settledTerminalStatus === 'interrupted'
1540
+ && settledTurnId === candidate.providerTurnId
1541
+ );
1542
+ if (this._codexLeaseMatches(proc)) this._codexLease = null;
1543
+ const eligible = deliverySafe && exactRetirement;
1544
+ let reason = 'output-evidence';
1545
+ if (deliverySafe) reason = 'retirement-binding-mismatch';
1546
+ if (deliveryEvidenceError) reason = 'delivery-evidence-failed';
1547
+ snapshot = candidate ? {
1548
+ runtime: 'codex',
1549
+ namespace: 'codex:app-server',
1550
+ sourceMsgId: candidate.sourceMsgId,
1551
+ providerSessionId: candidate.providerSessionId,
1552
+ providerTurnId: candidate.providerTurnId,
1553
+ cwd: candidate.cwd,
1554
+ model: candidate.model,
1555
+ effort: candidate.effort,
1556
+ spawnProfileId: candidate.spawnProfileId,
1557
+ eligible,
1558
+ reason: eligible ? 'eligible' : reason,
1559
+ } : {
1560
+ sourceMsgId: null,
1561
+ eligible: false,
1562
+ reason: 'no-active-turn',
1563
+ };
1564
+ if (deliveryEvidenceError) throw deliveryEvidenceError;
1565
+ } else {
1566
+ snapshot = await proc.retireForCleanRestart({
1567
+ getDeliveryEvidence: (_reportedSessionKey, sourceMsgId) => (
1568
+ getDeliveryEvidence(
1569
+ sessionKey,
1570
+ proc.backend === 'cli' ? sourceMsgId : null,
1571
+ )
1572
+ ),
1573
+ });
1574
+ }
1575
+ const supported = proc.backend === 'cli' || this._isCodex(proc);
1576
+ const eligible = supported && snapshot?.eligible === true;
1577
+ if (gateError) throw gateError;
1578
+ return Object.freeze({
1579
+ sessionKey,
1580
+ ...(this._isCodex(proc) && snapshot.runtime ? {
1581
+ runtime: snapshot.runtime,
1582
+ namespace: snapshot.namespace,
1583
+ providerSessionId: snapshot.providerSessionId,
1584
+ providerTurnId: snapshot.providerTurnId,
1585
+ cwd: snapshot.cwd,
1586
+ model: snapshot.model,
1587
+ effort: snapshot.effort,
1588
+ spawnProfileId: snapshot.spawnProfileId,
1589
+ } : {}),
1590
+ sourceMsgId: supported
1591
+ ? (snapshot?.sourceMsgId ?? null)
1592
+ : null,
1593
+ eligible,
1594
+ reason: supported
1595
+ ? (snapshot?.reason || 'retirement-uncertain')
1596
+ : 'unsupported-backend',
1535
1597
  });
1598
+ } catch (error) {
1599
+ if (gateError) throw gateError;
1600
+ throw error;
1536
1601
  }
1537
- const supported = proc.backend === 'cli' || this._isCodex(proc);
1538
- const eligible = supported && snapshot?.eligible === true;
1539
- return Object.freeze({
1540
- sessionKey,
1541
- ...(this._isCodex(proc) && snapshot.runtime ? {
1542
- runtime: snapshot.runtime,
1543
- namespace: snapshot.namespace,
1544
- providerSessionId: snapshot.providerSessionId,
1545
- providerTurnId: snapshot.providerTurnId,
1546
- cwd: snapshot.cwd,
1547
- model: snapshot.model,
1548
- effort: snapshot.effort,
1549
- spawnProfileId: snapshot.spawnProfileId,
1550
- } : {}),
1551
- sourceMsgId: supported
1552
- ? (snapshot?.sourceMsgId ?? null)
1553
- : null,
1554
- eligible,
1555
- reason: supported
1556
- ? (snapshot?.reason || 'retirement-uncertain')
1557
- : 'unsupported-backend',
1558
- });
1559
1602
  }));
1560
1603
  } finally {
1561
- for (const [sessionKey, proc] of targets) {
1604
+ for (const [sessionKey, proc] of retiredTargets) {
1562
1605
  if (proc.closed && this.procs.get(sessionKey) === proc) {
1563
1606
  this.procs.delete(sessionKey);
1564
1607
  }
1608
+ const candidateOwned = (
1609
+ this._cleanRetirementCandidates.get(sessionKey) === proc
1610
+ );
1611
+ if (!proc.closed && candidateOwned && !this.procs.has(sessionKey)) {
1612
+ this.procs.set(sessionKey, proc);
1613
+ }
1614
+ if (
1615
+ candidateOwned
1616
+ && (proc.closed || this.procs.get(sessionKey) === proc)
1617
+ ) {
1618
+ this._cleanRetirementCandidates.delete(sessionKey);
1619
+ }
1565
1620
  this._retiring.delete(proc);
1566
1621
  }
1567
1622
  this._maybeSignalLruWaiter();
1568
1623
  }
1569
- const failure = [
1570
- ...admittedResults,
1571
- ...settled,
1572
- ].find(result => result.status === 'rejected');
1624
+ const failure = settled.find(result => result.status === 'rejected');
1573
1625
  if (failure) throw failure.reason;
1574
- const results = settled.map(result => result.value);
1626
+ const results = settled
1627
+ .filter(result => result.status === 'fulfilled' && result.value != null)
1628
+ .map(result => result.value);
1575
1629
  return Object.freeze(results);
1576
1630
  }
1577
1631
 
@@ -1596,6 +1650,7 @@ class ProcessManager {
1596
1650
  }
1597
1651
 
1598
1652
  async interrupt(sessionKey) {
1653
+ if (this._lifecycleAdmissionClosed) throw new Error('shutdown');
1599
1654
  const proc = this.procs.get(sessionKey);
1600
1655
  if (!proc || proc.closed) return false;
1601
1656
  if (
@@ -1982,7 +2037,7 @@ class ProcessManager {
1982
2037
  }
1983
2038
  const start = this._starting.get(proc.sessionKey) ?? null;
1984
2039
  const lease = this._codexLease;
1985
- this._withLifecycleGate(proc.sessionKey, async () => {
2040
+ this._withInternalLifecycleGate(proc.sessionKey, async () => {
1986
2041
  if (start) await Promise.resolve(start).catch(() => {});
1987
2042
  if (
1988
2043
  this._starting.has(proc.sessionKey)
@@ -2020,7 +2075,7 @@ class ProcessManager {
2020
2075
  // Serialize with start/replacement/kill. Re-check object identity after
2021
2076
  // the gate so a late disconnect from an old generation cannot kill its
2022
2077
  // replacement.
2023
- this._withLifecycleGate(proc.sessionKey, async () => {
2078
+ this._withInternalLifecycleGate(proc.sessionKey, async () => {
2024
2079
  if (this.procs.get(proc.sessionKey) !== proc) return;
2025
2080
  await this._killLocked(proc.sessionKey, 'bridge-disconnected');
2026
2081
  }).catch(err => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.14",
3
+ "version": "0.10.15",
4
4
  "description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",