@shumkov/orchestra 0.14.0 → 0.15.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.
@@ -85,6 +85,10 @@ const CLIENT_FAULT_CLASS_BY_CODE = Object.freeze({
85
85
  });
86
86
  const MAX_ID_BYTES = 512;
87
87
  const MAX_TEXT_BYTES = 64 * 1024;
88
+ const CODEX_ERROR_KIND_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
89
+ const RESETS_AT_ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
90
+ const RESETS_AT_EPOCH_RE = /^\d{1,16}$/;
91
+ const DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
88
92
  const MAX_COMPLETED_ITEMS = 512;
89
93
  const MAX_RESPONSE_ARRAY_ITEMS = 512;
90
94
  const MAX_RESPONSE_OBJECT_KEYS = 512;
@@ -900,6 +904,109 @@ function projectCollaborationMode(value) {
900
904
  return projected;
901
905
  }
902
906
 
907
+ function projectCodexErrorKind(value, label) {
908
+ const kind = protocolRequiredString(value, label);
909
+ if (!CODEX_ERROR_KIND_RE.test(kind)) {
910
+ throw new CodexAppServerError(
911
+ `app-server ${label} is malformed`,
912
+ 'CODEX_PROTOCOL_ERROR',
913
+ );
914
+ }
915
+ return kind;
916
+ }
917
+
918
+ function projectCodexErrorInfo(value, label) {
919
+ if (value == null) return null;
920
+ if (typeof value === 'string') {
921
+ return {
922
+ kind: projectCodexErrorKind(value, `${label} codexErrorInfo`),
923
+ };
924
+ }
925
+ const info = protocolObject(value, `${label} codexErrorInfo`);
926
+ const keys = Object.keys(info);
927
+ if (keys.length === 0) return null;
928
+ if (Object.hasOwn(info, 'kind') && typeof info.kind === 'string' && info.kind.length > 0) {
929
+ const projected = {
930
+ kind: projectCodexErrorKind(info.kind, `${label} codexErrorInfo kind`),
931
+ };
932
+ if (
933
+ Object.hasOwn(info, 'httpStatusCode')
934
+ && Number.isSafeInteger(info.httpStatusCode)
935
+ && info.httpStatusCode >= 0
936
+ && info.httpStatusCode <= 65_535
937
+ ) {
938
+ projected.httpStatusCode = info.httpStatusCode;
939
+ }
940
+ return projected;
941
+ }
942
+ if (keys.length === 1) {
943
+ const [variant] = keys;
944
+ const projected = {
945
+ kind: projectCodexErrorKind(variant, `${label} codexErrorInfo variant`),
946
+ };
947
+ const inner = info[variant];
948
+ if (inner && typeof inner === 'object' && !Array.isArray(inner)) {
949
+ if (
950
+ Object.hasOwn(inner, 'httpStatusCode')
951
+ && Number.isSafeInteger(inner.httpStatusCode)
952
+ && inner.httpStatusCode >= 0
953
+ && inner.httpStatusCode <= 65_535
954
+ ) {
955
+ projected.httpStatusCode = inner.httpStatusCode;
956
+ }
957
+ }
958
+ return projected;
959
+ }
960
+ throw new CodexAppServerError(
961
+ `app-server ${label} codexErrorInfo is malformed`,
962
+ 'CODEX_PROTOCOL_ERROR',
963
+ );
964
+ }
965
+
966
+ function projectOptionalResetsAt(raw) {
967
+ if (raw == null) return undefined;
968
+ if (Number.isSafeInteger(raw) && raw >= 0) return raw;
969
+ if (typeof raw === 'string') {
970
+ if (RESETS_AT_EPOCH_RE.test(raw)) return raw;
971
+ if (RESETS_AT_ISO_RE.test(raw) && !Number.isNaN(Date.parse(raw))) return raw;
972
+ }
973
+ return undefined;
974
+ }
975
+
976
+ function projectTurnError(value, label) {
977
+ const err = protocolObject(value, label);
978
+ const projected = { present: true };
979
+ const codexErrorInfo = projectCodexErrorInfo(err.codexErrorInfo, label);
980
+ if (codexErrorInfo !== null) {
981
+ projected.codexErrorInfo = codexErrorInfo;
982
+ }
983
+ let rawResetsAt = Object.hasOwn(err, 'resetsAt') ? err.resetsAt : undefined;
984
+ if (
985
+ rawResetsAt == null
986
+ && err.codexErrorInfo
987
+ && typeof err.codexErrorInfo === 'object'
988
+ && !Array.isArray(err.codexErrorInfo)
989
+ ) {
990
+ rawResetsAt = Object.hasOwn(err.codexErrorInfo, 'resetsAt')
991
+ ? err.codexErrorInfo.resetsAt
992
+ : undefined;
993
+ if (rawResetsAt == null) {
994
+ const infoKeys = Object.keys(err.codexErrorInfo);
995
+ if (infoKeys.length === 1) {
996
+ const inner = err.codexErrorInfo[infoKeys[0]];
997
+ if (inner && typeof inner === 'object' && !Array.isArray(inner) && Object.hasOwn(inner, 'resetsAt')) {
998
+ rawResetsAt = inner.resetsAt;
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ const resetsAt = projectOptionalResetsAt(rawResetsAt);
1004
+ if (resetsAt !== undefined) {
1005
+ projected.resetsAt = resetsAt;
1006
+ }
1007
+ return projected;
1008
+ }
1009
+
903
1010
  function projectNotification(message, ownedCwd) {
904
1011
  const source = protocolObject(
905
1012
  message.params ?? {},
@@ -937,9 +1044,8 @@ function projectNotification(message, ownedCwd) {
937
1044
  'CODEX_PROTOCOL_ERROR',
938
1045
  );
939
1046
  }
940
- protocolObject(source.error, 'error notification payload');
941
1047
  params.willRetry = source.willRetry;
942
- params.error = { present: source.error != null };
1048
+ params.error = projectTurnError(source.error, 'error notification payload');
943
1049
  } else if (message.method === 'thread/status/changed') {
944
1050
  params.status = projectThreadStatus(source.status, 'thread status');
945
1051
  } else if (message.method === 'thread/settings/updated') {
@@ -1313,7 +1419,7 @@ function projectTurn(value, label) {
1313
1419
  type: protocolRequiredString(projected.type, `${label} item type`),
1314
1420
  };
1315
1421
  }),
1316
- error: turn.error == null ? null : { present: true },
1422
+ error: turn.error == null ? null : projectTurnError(turn.error, `${label} error`),
1317
1423
  };
1318
1424
  }
1319
1425
 
@@ -2111,6 +2217,22 @@ function projectRequestParams(method, params, spec, ownedCwd) {
2111
2217
  }
2112
2218
  : {}
2113
2219
  );
2220
+ const developerInstructions = () => {
2221
+ if (!Object.hasOwn(params, 'developerInstructions')) return {};
2222
+ const value = params.developerInstructions;
2223
+ if (
2224
+ typeof value !== 'string'
2225
+ || value.length === 0
2226
+ || Buffer.byteLength(value, 'utf8') > MAX_TEXT_BYTES
2227
+ || DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE.test(value)
2228
+ ) {
2229
+ throw new CodexAppServerError(
2230
+ 'app-server developerInstructions is invalid',
2231
+ 'CODEX_RPC_REJECTED',
2232
+ );
2233
+ }
2234
+ return { developerInstructions: value };
2235
+ };
2114
2236
  if (method === 'initialize') {
2115
2237
  plainObject(params.clientInfo, 'initialize clientInfo');
2116
2238
  plainObject(params.capabilities, 'initialize capabilities');
@@ -2183,6 +2305,7 @@ function projectRequestParams(method, params, spec, ownedCwd) {
2183
2305
  return {
2184
2306
  cwd: ownedCwd,
2185
2307
  model: boundedRequiredString(params.model, 'model'),
2308
+ ...developerInstructions(),
2186
2309
  };
2187
2310
  }
2188
2311
  if (method === 'hooks/list') {
@@ -2207,7 +2330,12 @@ function projectRequestParams(method, params, spec, ownedCwd) {
2207
2330
  }
2208
2331
  return { threadId: threadId(), includeTurns: false };
2209
2332
  }
2210
- if (method === 'thread/resume') return { threadId: threadId() };
2333
+ if (method === 'thread/resume') {
2334
+ return {
2335
+ threadId: threadId(),
2336
+ ...developerInstructions(),
2337
+ };
2338
+ }
2211
2339
  if (method === 'turn/start') {
2212
2340
  const projected = {
2213
2341
  threadId: threadId(),
@@ -65,7 +65,9 @@
65
65
  "cwd",
66
66
  "model"
67
67
  ],
68
- "optional": [],
68
+ "optional": [
69
+ "developerInstructions"
70
+ ],
69
71
  "stateChanging": true
70
72
  },
71
73
  "thread/read": {
@@ -77,7 +79,9 @@
77
79
  "required": [
78
80
  "threadId"
79
81
  ],
80
- "optional": [],
82
+ "optional": [
83
+ "developerInstructions"
84
+ ],
81
85
  "stateChanging": true
82
86
  },
83
87
  "turn/start": {
@@ -283,6 +283,25 @@ function authDisabledError() {
283
283
  return err;
284
284
  }
285
285
 
286
+ function attachReplaySafety(err, pending) {
287
+ const replyCount = Array.isArray(pending?.replies) ? pending.replies.length : 0;
288
+ const inFlightReplies = pending?._replyDeliveriesInFlight || 0;
289
+ const consumedByText = Boolean(pending?._consumedByText);
290
+ const hadToolCall = Boolean(pending?._hadToolCall);
291
+ const foldedCount = pending?._foldedCount || 0;
292
+ err.replyCount = replyCount;
293
+ err.hadToolCall = hadToolCall;
294
+ err.foldedCount = foldedCount;
295
+ err.replaySafe = (
296
+ replyCount === 0
297
+ && inFlightReplies === 0
298
+ && !consumedByText
299
+ && !hadToolCall
300
+ && foldedCount === 0
301
+ );
302
+ return err;
303
+ }
304
+
286
305
  class CliProcess extends Process {
287
306
  /**
288
307
  * @param {object} opts
@@ -2102,6 +2121,7 @@ class CliProcess extends Process {
2102
2121
  this._writeToBridge({ kind: 'question_answer', tool_call_id: msg.tool_call_id, result: { cancelled: true, error: 'chat_id mismatch' } });
2103
2122
  return;
2104
2123
  }
2124
+ this._markPendingToolCall([args.turn_id]);
2105
2125
  this._openQuestions.add(msg.tool_call_id);
2106
2126
  this._startQuestionKeepAlive();
2107
2127
  // 0.13 D1: waiting-on-user — claude is legitimately silent, so the
@@ -2293,6 +2313,11 @@ class CliProcess extends Process {
2293
2313
  ...(Array.isArray(args.consumed_turn_ids) ? args.consumed_turn_ids : []),
2294
2314
  ])
2295
2315
  : [];
2316
+ this._markPendingToolCall([
2317
+ replyAttribution.effectiveTurnId,
2318
+ ...(Array.isArray(args.consumed_turn_ids) ? args.consumed_turn_ids : []),
2319
+ args.turn_id,
2320
+ ]);
2296
2321
  const dispatchPromise = Promise.resolve().then(() => this.toolDispatcher({
2297
2322
  sessionKey: this.sessionKey,
2298
2323
  chatId: this.chatId,
@@ -2739,6 +2764,24 @@ class CliProcess extends Process {
2739
2764
  return true;
2740
2765
  }
2741
2766
 
2767
+ _markPendingToolCall(turnIds = []) {
2768
+ let matched = false;
2769
+ for (const tid of turnIds) {
2770
+ if (typeof tid !== 'string' || !tid) continue;
2771
+ const pending = this.pendingTurns.get(tid);
2772
+ if (pending) {
2773
+ pending._hadToolCall = true;
2774
+ matched = true;
2775
+ }
2776
+ }
2777
+ if (!matched && this.pendingTurns.size > 0) {
2778
+ // Unattributed tool dispatch: mark the sole live turn, or fail closed across all live turns.
2779
+ for (const pending of this.pendingTurns.values()) {
2780
+ pending._hadToolCall = true;
2781
+ }
2782
+ }
2783
+ }
2784
+
2742
2785
  /**
2743
2786
  * A follow-up picked up inside a pending turn's query (its UserPromptSubmit
2744
2787
  * carries that turn's prompt_id) was folded into that turn. Remember the
@@ -2746,15 +2789,26 @@ class CliProcess extends Process {
2746
2789
  * claude runs as its own query gets a new prompt_id and no host.
2747
2790
  */
2748
2791
  _noteFoldHost(lEntry, promptId) {
2749
- if (!promptId || lEntry.foldHostTurnId) return;
2750
- if (lEntry.source !== 'autosteer' && lEntry.source !== 'edit-fold') return;
2751
- let hostId = null;
2792
+ if (!promptId) return;
2793
+ const hosts = [];
2752
2794
  for (const [turnId, pending] of this.pendingTurns) {
2753
2795
  if (pending._promptId !== promptId) continue;
2754
- if (hostId) return; // ambiguous: credit nobody
2755
- hostId = turnId;
2796
+ hosts.push([turnId, pending]);
2797
+ }
2798
+ if (hosts.length === 0) return;
2799
+ for (const [turnId, host] of hosts) {
2800
+ if (!lEntry._foldCountedTurnIds?.has(turnId)) {
2801
+ host._foldedCount = (host._foldedCount || 0) + 1;
2802
+ (lEntry._foldCountedTurnIds ||= new Set()).add(turnId);
2803
+ }
2804
+ }
2805
+ if (
2806
+ hosts.length === 1
2807
+ && !lEntry.foldHostTurnId
2808
+ && (lEntry.source === 'autosteer' || lEntry.source === 'edit-fold')
2809
+ ) {
2810
+ lEntry.foldHostTurnId = hosts[0][0];
2756
2811
  }
2757
- if (hostId) lEntry.foldHostTurnId = hostId;
2758
2812
  }
2759
2813
 
2760
2814
  /**
@@ -3694,6 +3748,7 @@ class CliProcess extends Process {
3694
3748
  err.code = 'CLAUDE_API_ERROR';
3695
3749
  err.apiError = apiError;
3696
3750
  }
3751
+ attachReplaySafety(err, pending);
3697
3752
  // Reject BEFORE emitting: the turn's ceilings are already cleared, so a
3698
3753
  // throwing listener must not be able to leave it pending forever.
3699
3754
  try { pending.reject(err); } catch {}
@@ -3922,6 +3977,8 @@ class CliProcess extends Process {
3922
3977
  // 0.13 D1: pickup marker — set when a UserPromptSubmit prompt carries
3923
3978
  // this turn's envelope (the seen-slice). Rung 1's Stop attribution.
3924
3979
  seen: false,
3980
+ _hadToolCall: false,
3981
+ _foldedCount: 0,
3925
3982
  quietTimer: null,
3926
3983
  _activityQuietTimer: null,
3927
3984
  // hardTimer = idle ceiling. Resets on any activity (_noteActivity)
@@ -4750,6 +4807,8 @@ class CliProcess extends Process {
4750
4807
  // a tool-less sub-agent whose only post-boundary signal is its SubagentStop.
4751
4808
  const orphanSubagentStop = ev.type === 'SubagentStop'
4752
4809
  && !(this._pendingSubagentStarts && this._pendingSubagentStarts.length);
4810
+ const isStreamToolHook = (ev.type === 'PreToolUse' || ev.type === 'PostToolUse')
4811
+ && ev.toolName === this._streamToolHookName;
4753
4812
  if (ev.type === 'Stop' || ev.type === 'StopFailure' || orphanSubagentStop) {
4754
4813
  this._lastHookEventAt = Date.now();
4755
4814
  } else if (ev.type && ev.type !== 'parse-error' && ev.type !== 'unknown') {
@@ -4768,8 +4827,6 @@ class CliProcess extends Process {
4768
4827
  // (_lastHookEventAt and _workHookSeq above are deliberately left alone:
4769
4828
  // neither touches stop-grace, and suppressing them would quietly change
4770
4829
  // the other finalizer rungs.)
4771
- const isStreamToolHook = (ev.type === 'PreToolUse' || ev.type === 'PostToolUse')
4772
- && ev.toolName === this._streamToolHookName;
4773
4830
  if (!isStreamToolHook) this._noteActivity(`hook:${ev.type}`);
4774
4831
  }
4775
4832
 
@@ -4868,6 +4925,11 @@ class CliProcess extends Process {
4868
4925
  return;
4869
4926
 
4870
4927
  case 'PreToolUse': {
4928
+ if (!isStreamToolHook) {
4929
+ for (const pending of this.pendingTurns.values()) {
4930
+ if (pending.seen === true) pending._hadToolCall = true;
4931
+ }
4932
+ }
4871
4933
  const activePending = this.pendingTurns.size === 1
4872
4934
  ? this.pendingTurns.values().next().value
4873
4935
  : null;
@@ -4925,6 +4987,9 @@ class CliProcess extends Process {
4925
4987
 
4926
4988
  case 'PostToolUse':
4927
4989
  for (const pending of this.pendingTurns.values()) {
4990
+ if (!isStreamToolHook && pending.seen === true) {
4991
+ pending._hadToolCall = true;
4992
+ }
4928
4993
  pending.activeToolIds?.delete(ev.toolUseId);
4929
4994
  }
4930
4995
  this.emit('tool-result', {
@@ -5450,6 +5515,11 @@ class CliProcess extends Process {
5450
5515
  // 0.13 D2: the injected turn_id is LEDGERED — pre-P3 it never escaped this
5451
5516
  // function, making fold/new-turn/drop indistinguishable (seam S4).
5452
5517
  this._ledgerAdd(turnId, { source, msgId });
5518
+ const lEntry = this.inputLedger.get(turnId);
5519
+ for (const [hostTurnId, pending] of this.pendingTurns) {
5520
+ pending._foldedCount = (pending._foldedCount || 0) + 1;
5521
+ if (lEntry) (lEntry._foldCountedTurnIds ||= new Set()).add(hostTurnId);
5522
+ }
5453
5523
  this._logEvent('inject-user-message', {
5454
5524
  session_key: this.sessionKey,
5455
5525
  chat_id: this.chatId,
@@ -5863,7 +5933,7 @@ class CliProcess extends Process {
5863
5933
  if (pending._stopGraceTimer) clearTimeout(pending._stopGraceTimer);
5864
5934
  if (pending._activityQuietTimer) clearTimeout(pending._activityQuietTimer);
5865
5935
  if (pending._onStop) this.off('stop-hook', pending._onStop);
5866
- try { pending.reject(makeErr()); } catch {}
5936
+ try { pending.reject(attachReplaySafety(makeErr(), pending)); } catch {}
5867
5937
  }
5868
5938
  this.pendingTurns.clear();
5869
5939
 
@@ -5876,7 +5946,7 @@ class CliProcess extends Process {
5876
5946
  for (const item of remaining) {
5877
5947
  drained++;
5878
5948
  try { item.clearTimers?.(); } catch {}
5879
- try { item.reject?.(makeErr()); } catch {}
5949
+ try { item.reject?.(attachReplaySafety(makeErr(), item)); } catch {}
5880
5950
  }
5881
5951
 
5882
5952
  this.inFlight = false;
@@ -22,8 +22,27 @@ const DEFAULT_MAX_TERMINAL_HISTORY = 1_024;
22
22
  const DEFAULT_MAX_STEER_TEXT_BYTES = 256 * 1024;
23
23
  const DEFAULT_MAX_PENDING_STEERS = 16;
24
24
  const MAX_OPAQUE_ID_BYTES = 512;
25
+ const MAX_DEVELOPER_INSTRUCTIONS_BYTES = 64 * 1024;
25
26
  const CONTROL_CHAR_RE = /[\x00-\x08\x0b-\x1f\x7f]/g;
26
27
  const OPAQUE_ID_CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
28
+ const DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
29
+ const PROVIDER_ERROR_CODE_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
30
+ const RESETS_AT_ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
31
+ const RESETS_AT_EPOCH_RE = /^\d{1,16}$/;
32
+
33
+ function validateProviderErrorCode(value) {
34
+ return typeof value === 'string' && PROVIDER_ERROR_CODE_RE.test(value) ? value : null;
35
+ }
36
+
37
+ function validateProviderResetsAt(raw) {
38
+ if (raw == null) return null;
39
+ if (Number.isSafeInteger(raw) && raw >= 0) return raw;
40
+ if (typeof raw === 'string') {
41
+ if (RESETS_AT_EPOCH_RE.test(raw)) return raw;
42
+ if (RESETS_AT_ISO_RE.test(raw) && !Number.isNaN(Date.parse(raw))) return raw;
43
+ }
44
+ return null;
45
+ }
27
46
  const CLIENT_ROOT_ERROR_CODES = new Set([
28
47
  'CODEX_PROTOCOL_ERROR',
29
48
  'CODEX_TRANSPORT_ERROR',
@@ -278,6 +297,7 @@ class CodexProcess extends Process {
278
297
  threadId,
279
298
  label,
280
299
  cwd,
300
+ codexHome = null,
281
301
  clientFactory,
282
302
  staticPolicyAttestor = async () => {},
283
303
  hookVerifier = null,
@@ -308,6 +328,7 @@ class CodexProcess extends Process {
308
328
  super({ sessionKey, chatId, threadId, label });
309
329
  this.backend = 'codex';
310
330
  this.cwd = nonEmptyString(cwd, 'cwd');
331
+ this.codexHome = codexHome ?? null;
311
332
  if (typeof clientFactory !== 'function') {
312
333
  throw new TypeError('CodexProcess: clientFactory required');
313
334
  }
@@ -594,6 +615,24 @@ class CodexProcess extends Process {
594
615
  'CODEX_STRICT_RESUME_INVALID',
595
616
  );
596
617
  }
618
+ let developerInstructions = null;
619
+ if (options.developerInstructions != null) {
620
+ if (
621
+ typeof options.developerInstructions !== 'string'
622
+ || options.developerInstructions.length === 0
623
+ || Buffer.byteLength(options.developerInstructions, 'utf8')
624
+ > MAX_DEVELOPER_INSTRUCTIONS_BYTES
625
+ || DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE.test(
626
+ options.developerInstructions,
627
+ )
628
+ ) {
629
+ throw processError(
630
+ 'Codex developerInstructions must be a bounded string without control characters',
631
+ 'CODEX_DEVELOPER_INSTRUCTIONS_INVALID',
632
+ );
633
+ }
634
+ developerInstructions = options.developerInstructions;
635
+ }
597
636
  this.desiredSettings = this._validatedModelSettings({
598
637
  model: options.model ?? options.chatConfig?.model,
599
638
  effort: options.effort ?? options.chatConfig?.effort,
@@ -649,10 +688,12 @@ class CodexProcess extends Process {
649
688
  existingSessionId
650
689
  ? this._mutation('thread/resume', {
651
690
  threadId: existingSessionId,
691
+ ...(developerInstructions == null ? {} : { developerInstructions }),
652
692
  }, { source: null })
653
693
  : this._mutation('thread/start', {
654
694
  cwd: this.cwd,
655
695
  model: this.desiredSettings.model,
696
+ ...(developerInstructions == null ? {} : { developerInstructions }),
656
697
  }, { source: null })
657
698
  ));
658
699
  this._assertLifecycle(lifecycle);
@@ -1113,6 +1154,11 @@ class CodexProcess extends Process {
1113
1154
  completedItemText: new Map(),
1114
1155
  itemIds: new Set(),
1115
1156
  firstStreamFired: false,
1157
+ hadSideEffects: false,
1158
+ providerError: null,
1159
+ providerErrorCode: null,
1160
+ providerErrorHttpStatus: null,
1161
+ providerErrorResetsAt: null,
1116
1162
  startedAt: null,
1117
1163
  deadlineAt: null,
1118
1164
  settled: false,
@@ -1563,6 +1609,53 @@ class CodexProcess extends Process {
1563
1609
  return error;
1564
1610
  }
1565
1611
 
1612
+ _recordProviderErrorDetails(pending, error) {
1613
+ if (!pending || !error || typeof error !== 'object') return;
1614
+ const info = error.codexErrorInfo;
1615
+ let code = null;
1616
+ let httpStatus = null;
1617
+ if (typeof info === 'string' && info.length > 0) {
1618
+ code = validateProviderErrorCode(info);
1619
+ } else if (info && typeof info === 'object' && !Array.isArray(info)) {
1620
+ if (Object.hasOwn(info, 'kind') && typeof info.kind === 'string' && info.kind.length > 0) {
1621
+ code = validateProviderErrorCode(info.kind);
1622
+ if (
1623
+ Object.hasOwn(info, 'httpStatusCode')
1624
+ && Number.isSafeInteger(info.httpStatusCode)
1625
+ && info.httpStatusCode >= 0
1626
+ && info.httpStatusCode <= 65_535
1627
+ ) {
1628
+ httpStatus = info.httpStatusCode;
1629
+ }
1630
+ } else {
1631
+ const keys = Object.keys(info);
1632
+ if (keys.length === 1) {
1633
+ code = validateProviderErrorCode(keys[0]);
1634
+ const inner = info[keys[0]];
1635
+ if (
1636
+ inner
1637
+ && typeof inner === 'object'
1638
+ && !Array.isArray(inner)
1639
+ && Object.hasOwn(inner, 'httpStatusCode')
1640
+ && Number.isSafeInteger(inner.httpStatusCode)
1641
+ && inner.httpStatusCode >= 0
1642
+ && inner.httpStatusCode <= 65_535
1643
+ ) {
1644
+ httpStatus = inner.httpStatusCode;
1645
+ }
1646
+ }
1647
+ }
1648
+ } else if (Object.hasOwn(error, 'code') && typeof error.code === 'string' && error.code.length > 0) {
1649
+ code = validateProviderErrorCode(error.code);
1650
+ }
1651
+ if (code != null) pending.providerErrorCode = code;
1652
+ if (httpStatus != null) pending.providerErrorHttpStatus = httpStatus;
1653
+ const resetsAt = validateProviderResetsAt(Object.hasOwn(error, 'resetsAt') ? error.resetsAt : null);
1654
+ if (resetsAt != null) {
1655
+ pending.providerErrorResetsAt = resetsAt;
1656
+ }
1657
+ }
1658
+
1566
1659
  _resolveTurn(pending, terminal) {
1567
1660
  const status = terminal.status;
1568
1661
  const text = this._finalTurnText(pending);
@@ -1578,6 +1671,16 @@ class CodexProcess extends Process {
1578
1671
  cost: 0,
1579
1672
  duration,
1580
1673
  error: status === 'completed' ? null : status,
1674
+ ...(status === 'failed' ? {
1675
+ providerErrorCode: pending.providerErrorCode ?? null,
1676
+ ...(pending.providerErrorHttpStatus != null
1677
+ ? { providerErrorHttpStatus: pending.providerErrorHttpStatus }
1678
+ : {}),
1679
+ ...(pending.providerErrorResetsAt != null
1680
+ ? { providerErrorResetsAt: pending.providerErrorResetsAt }
1681
+ : {}),
1682
+ replaySafe: !pending.hadSideEffects,
1683
+ } : {}),
1581
1684
  metrics: {
1582
1685
  inputTokens: null,
1583
1686
  outputTokens: null,
@@ -1745,6 +1848,9 @@ class CodexProcess extends Process {
1745
1848
  'Codex turn/steer acknowledged a different turn',
1746
1849
  );
1747
1850
  }
1851
+ if (this.current?.turnId === turnId) {
1852
+ this.current.hadSideEffects = true;
1853
+ }
1748
1854
  await this._checkpoint('turn-steer-accepted', {
1749
1855
  threadId: this.providerSessionId,
1750
1856
  turnId,
@@ -2745,6 +2851,7 @@ class CodexProcess extends Process {
2745
2851
  }, fence);
2746
2852
  if (!params.willRetry) {
2747
2853
  pending.providerError = 'provider-error';
2854
+ this._recordProviderErrorDetails(pending, params.error);
2748
2855
  }
2749
2856
  fence.assertActive?.();
2750
2857
  return;
@@ -2848,6 +2955,9 @@ class CodexProcess extends Process {
2848
2955
  pending.itemText.set(params.itemId, nextText);
2849
2956
  pending.streamText = streamText;
2850
2957
  pending.streamTextBytes = streamTextBytes;
2958
+ if (typeof params.delta === 'string' && params.delta.length > 0) {
2959
+ pending.hadSideEffects = true;
2960
+ }
2851
2961
  if (isNewItem) pending.lastStreamItemId = params.itemId;
2852
2962
  this._fireFirstStream(pending);
2853
2963
  this.emit('stream-chunk', pending.streamText);
@@ -2896,6 +3006,9 @@ class CodexProcess extends Process {
2896
3006
  fence,
2897
3007
  );
2898
3008
  pending.itemIds.add(item.id);
3009
+ if (item.type !== 'userMessage') {
3010
+ pending.hadSideEffects = true;
3011
+ }
2899
3012
  if (authoritative != null) {
2900
3013
  pending.completedItemText.set(item.id, item.text);
2901
3014
  pending.itemText.set(item.id, item.text);
@@ -2927,8 +3040,18 @@ class CodexProcess extends Process {
2927
3040
  const terminal = {
2928
3041
  turnId,
2929
3042
  status,
3043
+ error: params.turn.error ?? null,
2930
3044
  deadlineAt: pending.deadlineAt,
2931
3045
  };
3046
+ if (
3047
+ Array.isArray(params.turn.items)
3048
+ && params.turn.items.some((item) => item?.type !== 'userMessage')
3049
+ ) {
3050
+ pending.hadSideEffects = true;
3051
+ }
3052
+ if (params.turn.error != null) {
3053
+ this._recordProviderErrorDetails(pending, params.turn.error);
3054
+ }
2932
3055
  await this._checkpoint('turn-terminal', {
2933
3056
  ...this._turnDetail(pending),
2934
3057
  terminalStatus: status,
@@ -3299,6 +3422,13 @@ class CodexProcess extends Process {
3299
3422
  this.logger.error?.(
3300
3423
  `[${this.label}] Codex containment close: ${closeError.message}`,
3301
3424
  );
3425
+ this.emit('codex-lifecycle', Object.freeze({
3426
+ kind: 'containment-cleanup-failed',
3427
+ errorCode: closeError?.code ?? 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
3428
+ sessionKey: this.sessionKey,
3429
+ generationId: this.generationId,
3430
+ codexHome: this.codexHome ?? null,
3431
+ }));
3302
3432
  });
3303
3433
  return this.containmentClosePromise;
3304
3434
  }
@@ -48,7 +48,9 @@ const {
48
48
  } = require('../codex/preflight');
49
49
 
50
50
  const MAX_CODEX_ID_BYTES = 512;
51
+ const MAX_CODEX_DEVELOPER_INSTRUCTIONS_BYTES = 64 * 1024;
51
52
  const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
53
+ const DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
52
54
  const FORBIDDEN_CODEX_CONTEXT_FIELDS = new Set([
53
55
  'cwd',
54
56
  'model',
@@ -68,6 +70,7 @@ const FORBIDDEN_CODEX_CONTEXT_FIELDS = new Set([
68
70
  'permissions',
69
71
  'config',
70
72
  'expectedStaticProfile',
73
+ 'backend',
71
74
  ]);
72
75
 
73
76
  class CodexBackendNotConfiguredError extends Error {
@@ -328,12 +331,27 @@ function createCodexProcess({
328
331
  'strict Codex resume requires an existing thread and interrupted turn',
329
332
  );
330
333
  }
334
+ const developerInstructions = ctx?.developerInstructions;
335
+ if (developerInstructions != null) {
336
+ if (
337
+ typeof developerInstructions !== 'string'
338
+ || developerInstructions.length === 0
339
+ || Buffer.byteLength(developerInstructions, 'utf8')
340
+ > MAX_CODEX_DEVELOPER_INSTRUCTIONS_BYTES
341
+ || DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE.test(developerInstructions)
342
+ ) {
343
+ throw codexConfigurationError(
344
+ 'developerInstructions must be a bounded string without control characters',
345
+ );
346
+ }
347
+ }
331
348
  const spawnOptions = Object.freeze({
332
349
  ...(existingSessionId == null ? {} : { existingSessionId }),
333
350
  ...(strictResume ? {
334
351
  resumePolicy: 'require-interrupted-turn',
335
352
  expectedInterruptedTurnId: ctx.expectedInterruptedTurnId,
336
353
  } : {}),
354
+ ...(developerInstructions == null ? {} : { developerInstructions }),
337
355
  model: selectedSettings.model,
338
356
  effort: selectedSettings.effort,
339
357
  });
@@ -351,6 +369,7 @@ function createCodexProcess({
351
369
  threadId: ctx?.threadId ?? null,
352
370
  label: ctx?.label || sessionKey,
353
371
  cwd: profile.cwd,
372
+ codexHome: profile.codexHome,
354
373
  clientFactory: boundClientFactory,
355
374
  staticPolicyAttestor: (client) => (
356
375
  reattestCodexStaticPolicy(profile, client)
@@ -550,7 +569,14 @@ function createProcessFactory({
550
569
  });
551
570
  }
552
571
 
553
- const choice = pickBackend({ config, chatId, threadId, logger, pmDefault });
572
+ if (ctx?.backend != null && ctx.backend !== 'cli' && ctx.backend !== 'sdk') {
573
+ const err = new Error(`Invalid Claude backend override: ${String(ctx.backend)}`);
574
+ err.code = 'RUNTIME_CONFIG_INVALID';
575
+ throw err;
576
+ }
577
+ const choice = ctx?.backend != null
578
+ ? ctx.backend
579
+ : pickBackend({ config, chatId, threadId, logger, pmDefault });
554
580
 
555
581
  if (choice === 'cli') {
556
582
  const missing = [];