@shumkov/orchestra 0.10.14 → 0.10.16

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { randomUUID } = require('node:crypto');
3
+ const { hash, randomUUID } = require('node:crypto');
4
4
  const { isDeepStrictEqual } = require('node:util');
5
5
 
6
6
  const { Process, UnsupportedOperationError } = require('./process');
@@ -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`),
@@ -331,6 +439,7 @@ class CodexProcess extends Process {
331
439
 
332
440
  this.state = 'Spawning';
333
441
  this.lifecycleEpoch = 0;
442
+ this.activityEpoch = 0;
334
443
  this.providerSessionId = null;
335
444
  this._resumeAttestation = null;
336
445
  Object.defineProperty(this, 'resumeAttestation', {
@@ -374,6 +483,7 @@ class CodexProcess extends Process {
374
483
  this.containmentError = null;
375
484
  this.containmentErrorCode = null;
376
485
  this.containmentTurnId = null;
486
+ this.containmentProvenance = null;
377
487
  this.containmentCleanupCommitted = null;
378
488
  this.startupReleaseSafe = false;
379
489
  this.stateChangingWriteCommitted = false;
@@ -394,6 +504,16 @@ class CodexProcess extends Process {
394
504
  this.lifecycleEpoch += 1;
395
505
  }
396
506
 
507
+ _advanceActivityEpoch() {
508
+ if (this.activityEpoch === Number.MAX_SAFE_INTEGER) {
509
+ throw processError(
510
+ 'Codex activity epoch is exhausted',
511
+ 'CODEX_ACTIVITY_EPOCH_EXHAUSTED',
512
+ );
513
+ }
514
+ this.activityEpoch += 1;
515
+ }
516
+
397
517
  _assertLifecycle(fence) {
398
518
  if (
399
519
  fence?.epoch !== this.lifecycleEpoch
@@ -983,6 +1103,7 @@ class CodexProcess extends Process {
983
1103
  this.emit('queue-drop', pending);
984
1104
  return pending.promise;
985
1105
  }
1106
+ this._advanceActivityEpoch();
986
1107
  this._pump();
987
1108
  return pending.promise;
988
1109
  }
@@ -1388,6 +1509,7 @@ class CodexProcess extends Process {
1388
1509
  'CODEX_STEER_QUEUE_OVERFLOW',
1389
1510
  ));
1390
1511
  }
1512
+ this._advanceActivityEpoch();
1391
1513
  this.pendingSteerCount += 1;
1392
1514
  const operation = this.steerChain.then(
1393
1515
  () => this._steerTurn(text, context),
@@ -1845,7 +1967,7 @@ class CodexProcess extends Process {
1845
1967
  );
1846
1968
  this._assertLifecycle(lifecycle);
1847
1969
  if (page.count > 0 || page.nextCursor != null) {
1848
- this.state = 'BackgroundWorking';
1970
+ this._activateBackgroundOwnership();
1849
1971
  this._armBackgroundWatchdog(pending.deadlineAt);
1850
1972
  if (this.threadStatusType === 'idle') {
1851
1973
  this._scheduleBackgroundSettlement();
@@ -1853,6 +1975,179 @@ class CodexProcess extends Process {
1853
1975
  }
1854
1976
  }
1855
1977
 
1978
+ _activateBackgroundOwnership() {
1979
+ if (!this.hasActiveBackgroundWork()) {
1980
+ this._advanceActivityEpoch();
1981
+ this.state = 'BackgroundWorking';
1982
+ }
1983
+ }
1984
+
1985
+ _qualificationFenceError() {
1986
+ return processError(
1987
+ 'Codex clean-restart qualification fence changed',
1988
+ 'CODEX_QUALIFICATION_FENCE',
1989
+ );
1990
+ }
1991
+
1992
+ _assertQualificationFence(fence, assertLease) {
1993
+ if (
1994
+ fence.lifecycleEpoch !== this.lifecycleEpoch
1995
+ || fence.generationId !== this.generationId
1996
+ || fence.activityEpoch !== this.activityEpoch
1997
+ ) {
1998
+ throw this._qualificationFenceError();
1999
+ }
2000
+ if (typeof assertLease !== 'function') return;
2001
+ try {
2002
+ if (assertLease() === false) throw this._qualificationFenceError();
2003
+ } catch (error) {
2004
+ if (
2005
+ error?.code === 'CODEX_QUALIFICATION_FENCE'
2006
+ || error?.code === 'CODEX_QUALIFICATION_LEASE_DRIFT'
2007
+ ) throw error;
2008
+ throw this._qualificationFenceError();
2009
+ }
2010
+ }
2011
+
2012
+ _qualificationResult({
2013
+ outcome,
2014
+ reason,
2015
+ backgroundTerminalCount = 0,
2016
+ backgroundTerminalRegistryComplete = true,
2017
+ observedAtMs = Date.now(),
2018
+ }) {
2019
+ return Object.freeze({
2020
+ outcome,
2021
+ reason,
2022
+ generationDigest: hash('sha256', this.generationId, 'hex'),
2023
+ activityEpoch: this.activityEpoch,
2024
+ processState: PROCESS_STATES.has(this.state) ? this.state : 'unknown',
2025
+ activeTurnCount: this.current ? 1 : 0,
2026
+ pendingDeliveryCount: this.hasPendingDeliveryWork() ? 1 : 0,
2027
+ backgroundOwnerCount: this.hasActiveBackgroundWork() ? 1 : 0,
2028
+ backgroundTerminalCount,
2029
+ backgroundTerminalRegistryComplete,
2030
+ observedAtMs,
2031
+ });
2032
+ }
2033
+
2034
+ async inspectCleanRestartQualification({
2035
+ expectedGenerationDigest = hash('sha256', this.generationId, 'hex'),
2036
+ expectedActivityEpoch = this.activityEpoch,
2037
+ assertLease,
2038
+ } = {}) {
2039
+ const fence = Object.freeze({
2040
+ lifecycleEpoch: this.lifecycleEpoch,
2041
+ generationId: this.generationId,
2042
+ activityEpoch: this.activityEpoch,
2043
+ });
2044
+ const generationDigest = hash('sha256', fence.generationId, 'hex');
2045
+ if (
2046
+ expectedGenerationDigest !== generationDigest
2047
+ || expectedActivityEpoch !== fence.activityEpoch
2048
+ ) {
2049
+ throw this._qualificationFenceError();
2050
+ }
2051
+ this._assertQualificationFence(fence, assertLease);
2052
+
2053
+ if (this.state !== 'Idle') {
2054
+ return this._qualificationResult({
2055
+ outcome: 'mismatch',
2056
+ reason: this.current ? 'active-turn' : 'process-not-idle',
2057
+ });
2058
+ }
2059
+ if (!this.client || !this.providerSessionId) {
2060
+ return this._qualificationResult({
2061
+ outcome: 'mismatch',
2062
+ reason: 'process-not-ready',
2063
+ });
2064
+ }
2065
+
2066
+ let backgroundTerminalCount = 0;
2067
+ try {
2068
+ const page = await this.client.request(
2069
+ 'thread/backgroundTerminals/list',
2070
+ { threadId: this.providerSessionId, limit: 100 },
2071
+ { timeoutMs: this.cleanupTimeoutMs },
2072
+ );
2073
+ this._assertQualificationFence(fence, assertLease);
2074
+ if (
2075
+ !page
2076
+ || !Number.isSafeInteger(page.count)
2077
+ || page.count < 0
2078
+ || page.count > 100
2079
+ || (page.nextCursor != null && typeof page.nextCursor !== 'string')
2080
+ ) {
2081
+ throw processError(
2082
+ 'Codex qualification returned an invalid terminal page',
2083
+ 'CODEX_QUALIFICATION_FAILED',
2084
+ );
2085
+ }
2086
+ backgroundTerminalCount = page.count;
2087
+ this._assertQualificationFence(fence, assertLease);
2088
+ const observedAtMs = Date.now();
2089
+ if (page.nextCursor != null) {
2090
+ return this._qualificationResult({
2091
+ outcome: 'mismatch',
2092
+ reason: page.count > 0 ? 'background-terminals' : 'pagination-incomplete',
2093
+ backgroundTerminalCount,
2094
+ backgroundTerminalRegistryComplete: false,
2095
+ observedAtMs,
2096
+ });
2097
+ }
2098
+ if (backgroundTerminalCount > 0) {
2099
+ return this._qualificationResult({
2100
+ outcome: 'mismatch',
2101
+ reason: 'background-terminals',
2102
+ backgroundTerminalCount,
2103
+ observedAtMs,
2104
+ });
2105
+ }
2106
+ if (this.current) {
2107
+ return this._qualificationResult({
2108
+ outcome: 'mismatch',
2109
+ reason: 'active-turn',
2110
+ observedAtMs,
2111
+ });
2112
+ }
2113
+ if (this.hasPendingDeliveryWork()) {
2114
+ return this._qualificationResult({
2115
+ outcome: 'mismatch',
2116
+ reason: 'pending-delivery',
2117
+ observedAtMs,
2118
+ });
2119
+ }
2120
+ if (this.hasActiveBackgroundWork()) {
2121
+ return this._qualificationResult({
2122
+ outcome: 'mismatch',
2123
+ reason: 'background-owner',
2124
+ observedAtMs,
2125
+ });
2126
+ }
2127
+ if (this.state !== 'Idle') {
2128
+ return this._qualificationResult({
2129
+ outcome: 'mismatch',
2130
+ reason: 'process-not-idle',
2131
+ observedAtMs,
2132
+ });
2133
+ }
2134
+ return this._qualificationResult({
2135
+ outcome: 'qualified',
2136
+ reason: 'eligible',
2137
+ observedAtMs,
2138
+ });
2139
+ } catch (error) {
2140
+ if (
2141
+ error?.code === 'CODEX_QUALIFICATION_FENCE'
2142
+ || error?.code === 'CODEX_QUALIFICATION_LEASE_DRIFT'
2143
+ ) throw error;
2144
+ throw processError(
2145
+ 'Codex clean-restart qualification inspection failed',
2146
+ 'CODEX_QUALIFICATION_FAILED',
2147
+ );
2148
+ }
2149
+ }
2150
+
1856
2151
  async _mutation(method, params, detail) {
1857
2152
  const attemptId = boundedOpaqueId(
1858
2153
  detail.attemptId ?? this.mutationAttemptIdFactory(),
@@ -2072,6 +2367,12 @@ class CodexProcess extends Process {
2072
2367
  'cross-thread-notification',
2073
2368
  'Codex emitted traffic for another provider thread',
2074
2369
  fence,
2370
+ {
2371
+ notificationMethod: NOTIFICATION_METHODS.has(method) ? method : null,
2372
+ observedProcessState: PROCESS_STATES.has(this.state)
2373
+ ? this.state
2374
+ : 'unknown',
2375
+ },
2075
2376
  );
2076
2377
  return;
2077
2378
  }
@@ -2091,17 +2392,19 @@ class CodexProcess extends Process {
2091
2392
  }
2092
2393
  if (method === 'thread/status/changed') {
2093
2394
  const statusType = params.status?.type ?? null;
2395
+ const activateBackground = (
2396
+ statusType === 'active'
2397
+ && !this.current
2398
+ && this.state === 'Idle'
2399
+ );
2400
+ if (activateBackground) this._advanceActivityEpoch();
2094
2401
  await this._checkpoint('thread-status-changed', {
2095
2402
  threadId: ownedThreadId,
2096
2403
  statusType,
2097
2404
  }, fence);
2098
2405
  fence.assertActive?.();
2099
2406
  this.threadStatusType = statusType;
2100
- if (
2101
- statusType === 'active'
2102
- && !this.current
2103
- && this.state === 'Idle'
2104
- ) {
2407
+ if (activateBackground && !this.current && this.state === 'Idle') {
2105
2408
  this.state = 'BackgroundWorking';
2106
2409
  } else if (
2107
2410
  statusType === 'idle'
@@ -2364,10 +2667,10 @@ class CodexProcess extends Process {
2364
2667
  }
2365
2668
  }
2366
2669
 
2367
- async _notificationProtocolFault(reason, message, fence) {
2670
+ async _notificationProtocolFault(reason, message, fence, detail = {}) {
2368
2671
  const error = this._protocolFault(reason, message, false);
2369
2672
  if (this.protocolFaultCount >= this.protocolFaultThreshold) {
2370
- await this._enterContainment(reason, error, null, fence);
2673
+ await this._enterContainment(reason, error, null, fence, detail);
2371
2674
  }
2372
2675
  return error;
2373
2676
  }
@@ -2386,14 +2689,18 @@ class CodexProcess extends Process {
2386
2689
  outcome?.boundary === 'post-spawn'
2387
2690
  || outcome?.containment === 'unverified'
2388
2691
  ) {
2389
- await this._enterContainment(
2390
- outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
2391
- ? 'rpc-outcome-unknown'
2392
- : 'app-server-fault',
2692
+ const error = attachClientFaultProvenance(
2393
2693
  processError(
2394
2694
  'Codex app-server faulted after spawn',
2395
2695
  outcome?.errorCode ?? 'CODEX_PROCESS_EXITED',
2396
2696
  ),
2697
+ readClientFaultProvenance(outcome),
2698
+ );
2699
+ await this._enterContainment(
2700
+ outcome?.errorCode === 'CODEX_RPC_OUTCOME_UNKNOWN'
2701
+ ? 'rpc-outcome-unknown'
2702
+ : 'app-server-fault',
2703
+ error,
2397
2704
  );
2398
2705
  }
2399
2706
  }
@@ -2529,7 +2836,13 @@ class CodexProcess extends Process {
2529
2836
  }
2530
2837
 
2531
2838
  _protocolFault(reason, message, enterContainment = true) {
2532
- const error = processError(message, 'CODEX_PROTOCOL_ERROR');
2839
+ const error = attachClientFaultProvenance(
2840
+ processError(message, 'CODEX_PROTOCOL_ERROR'),
2841
+ {
2842
+ clientRootErrorCode: 'CODEX_PROTOCOL_ERROR',
2843
+ clientFaultClass: 'protocol',
2844
+ },
2845
+ );
2533
2846
  this.protocolFaultCount += 1;
2534
2847
  this.emit('protocol-security-fault', this._lifecyclePayload(
2535
2848
  'protocol-security-fault',
@@ -2549,6 +2862,7 @@ class CodexProcess extends Process {
2549
2862
  this._advanceLifecycle();
2550
2863
  this.state = 'FailedAmbiguous';
2551
2864
  this.inFlight = false;
2865
+ const provenance = readClientFaultProvenance(error);
2552
2866
  try {
2553
2867
  await this._checkpoint('failed-ambiguous-entered', {
2554
2868
  reason,
@@ -2556,6 +2870,7 @@ class CodexProcess extends Process {
2556
2870
  turnId: this.activeTurnId
2557
2871
  ?? this.current?.turnId
2558
2872
  ?? this.lastTurnId,
2873
+ ...provenance,
2559
2874
  });
2560
2875
  } catch (checkpointError) {
2561
2876
  this.containmentError = checkpointError;
@@ -2575,6 +2890,7 @@ class CodexProcess extends Process {
2575
2890
  error,
2576
2891
  excludedPending = null,
2577
2892
  fence = null,
2893
+ detail = {},
2578
2894
  ) {
2579
2895
  this._closeSettingsAdmission();
2580
2896
  if (this.state === 'ContainmentFailed') return;
@@ -2583,6 +2899,16 @@ class CodexProcess extends Process {
2583
2899
  ?? this.current?.turnId
2584
2900
  ?? this.lastTurnId;
2585
2901
  this._advanceLifecycle();
2902
+ const notificationMethod = NOTIFICATION_METHODS.has(detail.notificationMethod)
2903
+ ? detail.notificationMethod
2904
+ : null;
2905
+ this.containmentProvenance = Object.freeze({
2906
+ ...readClientFaultProvenance(error),
2907
+ ...(notificationMethod ? { notificationMethod } : {}),
2908
+ observedProcessState: PROCESS_STATES.has(detail.observedProcessState)
2909
+ ? detail.observedProcessState
2910
+ : 'unknown',
2911
+ });
2586
2912
  this.state = 'ContainmentFailed';
2587
2913
  this.containmentReason = reason;
2588
2914
  this.containmentError = error;
@@ -2594,6 +2920,7 @@ class CodexProcess extends Process {
2594
2920
  reason,
2595
2921
  errorCode: error?.code ?? null,
2596
2922
  turnId: ownedTurnId ?? null,
2923
+ ...this.containmentProvenance,
2597
2924
  }, fence);
2598
2925
  } catch (checkpointError) {
2599
2926
  this.containmentError = checkpointError;
@@ -2652,6 +2979,7 @@ class CodexProcess extends Process {
2652
2979
  reason: this.containmentReason,
2653
2980
  errorCode: this.containmentErrorCode,
2654
2981
  turnId: this.containmentTurnId,
2982
+ ...this.containmentProvenance,
2655
2983
  });
2656
2984
  const detail = Object.freeze({
2657
2985
  kind: 'containment-cleanup-committed',
@@ -2660,6 +2988,7 @@ class CodexProcess extends Process {
2660
2988
  hostIdentity: this.hostIdentity,
2661
2989
  bootSessionIdentity: this.bootSessionIdentity,
2662
2990
  containmentReason: this.containmentReason,
2991
+ ...this.containmentProvenance,
2663
2992
  });
2664
2993
  this.containmentCleanupCommitted = detail;
2665
2994
  this.closed = true;