@shumkov/orchestra 0.13.2 → 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.
@@ -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,11 +48,15 @@ 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',
55
57
  'effort',
58
+ 'autoCompactWindow',
59
+ 'promptCacheTtl',
56
60
  'env',
57
61
  'sessionLauncher',
58
62
  'binary',
@@ -66,6 +70,7 @@ const FORBIDDEN_CODEX_CONTEXT_FIELDS = new Set([
66
70
  'permissions',
67
71
  'config',
68
72
  'expectedStaticProfile',
73
+ 'backend',
69
74
  ]);
70
75
 
71
76
  class CodexBackendNotConfiguredError extends Error {
@@ -326,12 +331,27 @@ function createCodexProcess({
326
331
  'strict Codex resume requires an existing thread and interrupted turn',
327
332
  );
328
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
+ }
329
348
  const spawnOptions = Object.freeze({
330
349
  ...(existingSessionId == null ? {} : { existingSessionId }),
331
350
  ...(strictResume ? {
332
351
  resumePolicy: 'require-interrupted-turn',
333
352
  expectedInterruptedTurnId: ctx.expectedInterruptedTurnId,
334
353
  } : {}),
354
+ ...(developerInstructions == null ? {} : { developerInstructions }),
335
355
  model: selectedSettings.model,
336
356
  effort: selectedSettings.effort,
337
357
  });
@@ -349,6 +369,7 @@ function createCodexProcess({
349
369
  threadId: ctx?.threadId ?? null,
350
370
  label: ctx?.label || sessionKey,
351
371
  cwd: profile.cwd,
372
+ codexHome: profile.codexHome,
352
373
  clientFactory: boundClientFactory,
353
374
  staticPolicyAttestor: (client) => (
354
375
  reattestCodexStaticPolicy(profile, client)
@@ -464,6 +485,10 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
464
485
  * here would make them two, and a one-character disagreement would respawn the
465
486
  * session on every message forever. The resolver remains the fallback for consumers
466
487
  * that send no hint on the context.
488
+ * @param {number|null|Function} [opts.autoCompactWindow] — CLI auto-compact window in tokens.
489
+ * @param {'5m'|'1h'|null|Function} [opts.promptCacheTtl] — CLI prompt cache lifetime.
490
+ * Both accept a static value or a (chatId, threadId, config) resolver. A defined
491
+ * spawn-context value overrides either form, including null to clear the variable.
467
492
  * @param {Function} [opts.codexClientFactory] — trusted Codex app-server client
468
493
  * factory. Required only when spawnContext.runtime is exactly 'codex'.
469
494
  * @param {Function} [opts.codexCheckpointSink] — acknowledged durability sink.
@@ -489,6 +514,8 @@ function createProcessFactory({
489
514
  channelsClaudeBin = null,
490
515
  sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER || null,
491
516
  displayHint = '', // orchestra: consumer surface-rendering hint
517
+ autoCompactWindow,
518
+ promptCacheTtl,
492
519
  maxOutboundFileBytes = 100 * 1024 * 1024, // orchestra: consumer outbound file cap
493
520
  // orchestra identity — forwarded to every CliProcess so the engine is neutral.
494
521
  sessionPrefix = 'orchestra',
@@ -542,7 +569,14 @@ function createProcessFactory({
542
569
  });
543
570
  }
544
571
 
545
- 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 });
546
580
 
547
581
  if (choice === 'cli') {
548
582
  const missing = [];
@@ -565,18 +599,17 @@ function createProcessFactory({
565
599
  // hint on the context: a static string (same hint for every session) or
566
600
  // a function called per spawn with the current chat/topic and config, so
567
601
  // the consumer can vary the hint per chat (e.g. a rich-text toggle).
602
+ const resolveOption = option => typeof option === 'function'
603
+ ? option(chatId, threadId, config)
604
+ : option;
568
605
  const resolvedDisplayHint = typeof ctx?.displayHint === 'string'
569
606
  ? ctx.displayHint
570
- : typeof displayHint === 'function'
571
- ? displayHint(chatId, threadId, config)
572
- : displayHint;
607
+ : resolveOption(displayHint);
573
608
  // Same string-or-resolver shape as displayHint: the optional tools a
574
609
  // consumer can honor may vary per chat/topic (a live preview is a
575
610
  // per-chat rollout decision), and the prompt section that teaches them
576
611
  // is resolved at the same moment, so the two can never disagree.
577
- const resolvedCapabilities = typeof toolDispatcherCapabilities === 'function'
578
- ? toolDispatcherCapabilities(chatId, threadId, config)
579
- : toolDispatcherCapabilities;
612
+ const resolvedCapabilities = resolveOption(toolDispatcherCapabilities);
580
613
  return new CliProcess({
581
614
  sessionKey, chatId, threadId, label,
582
615
  tmuxRunner,
@@ -586,6 +619,10 @@ function createProcessFactory({
586
619
  toolDispatcher,
587
620
  toolDispatcherCapabilities: resolvedCapabilities,
588
621
  displayHint: resolvedDisplayHint,
622
+ autoCompactWindow: ctx?.autoCompactWindow !== undefined
623
+ ? ctx.autoCompactWindow : resolveOption(autoCompactWindow),
624
+ promptCacheTtl: ctx?.promptCacheTtl !== undefined
625
+ ? ctx.promptCacheTtl : resolveOption(promptCacheTtl),
589
626
  maxOutboundFileBytes,
590
627
  sessionPrefix, bridgeServerName, appDataDir, attachmentBase, productName, surfaceName,
591
628
  logger,