@shumkov/orchestra 0.10.11 → 0.10.13

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.
package/index.js CHANGED
@@ -21,6 +21,8 @@ const {
21
21
  } = require('./lib/codex/preflight');
22
22
  const {
23
23
  attestPinnedCodexHome,
24
+ attestPinnedSessionLauncher,
25
+ characterizePinnedSessionLauncher,
24
26
  buildCodexAppServerEnv,
25
27
  CodexAppServerClient,
26
28
  CodexAppServerError,
@@ -53,7 +55,7 @@ const approvalsStore = require('./lib/approvals/store');
53
55
 
54
56
  module.exports = {
55
57
  // pool + driver
56
- Process, UnsupportedOperationError, ProcessManager, CALLBACK_TO_EVENT, CliProcess, CodexProcess, CodexAppServerClient, CodexAppServerError, CodexPreflightError, SdkProcess, extractAssistantText, sumUsage, makeInputController, createProcessFactory, pickBackend, preflightCodexRuntime, reattestCodexStaticPolicy, createCodexSpawnProfile, assertCodexSpawnProfile, attestPinnedCodexHome, buildCodexAppServerEnv, resolveCodexTargetPin, codexProtocolSchema,
58
+ Process, UnsupportedOperationError, ProcessManager, CALLBACK_TO_EVENT, CliProcess, CodexProcess, CodexAppServerClient, CodexAppServerError, CodexPreflightError, SdkProcess, extractAssistantText, sumUsage, makeInputController, createProcessFactory, pickBackend, preflightCodexRuntime, reattestCodexStaticPolicy, createCodexSpawnProfile, assertCodexSpawnProfile, attestPinnedCodexHome, attestPinnedSessionLauncher, characterizePinnedSessionLauncher, buildCodexAppServerEnv, resolveCodexTargetPin, codexProtocolSchema,
57
59
  // channels bridge (MCP injection protocol)
58
60
  ChannelsBridgeServer, bridgeProtocol,
59
61
  // tmux lifecycle
@@ -71,6 +71,9 @@ const CONSTRUCTOR_KEYS = new Set([
71
71
  'onFault',
72
72
  'attestBinaryFn',
73
73
  'attestCodexHomeFn',
74
+ 'attestSessionLauncherFn',
75
+ 'sessionLauncher',
76
+ 'expectedSessionLauncherSha256',
74
77
  'expectedConfigSha256',
75
78
  'requestTimeoutMs',
76
79
  'sinkTimeoutMs',
@@ -312,6 +315,78 @@ async function attestPinnedCodexBinary(
312
315
  };
313
316
  }
314
317
 
318
+ async function characterizePinnedSessionLauncher(launcher) {
319
+ try {
320
+ if (
321
+ typeof launcher !== 'string'
322
+ || !path.isAbsolute(launcher)
323
+ || realpathSync(launcher) !== launcher
324
+ ) {
325
+ throw new CodexAppServerError(
326
+ 'session launcher identity is malformed',
327
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
328
+ );
329
+ }
330
+ const root = path.parse(launcher).root;
331
+ let component = root;
332
+ for (const part of launcher.slice(root.length).split('/').filter(Boolean)) {
333
+ component = path.join(component, part);
334
+ const componentStat = lstatSync(component);
335
+ if (
336
+ componentStat.isSymbolicLink()
337
+ || componentStat.uid !== 0
338
+ || (componentStat.mode & 0o022) !== 0
339
+ ) {
340
+ throw new CodexAppServerError(
341
+ 'session launcher path ownership or mode is unsafe',
342
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
343
+ );
344
+ }
345
+ }
346
+ const stat = lstatSync(launcher);
347
+ if (
348
+ !stat.isFile()
349
+ || stat.nlink !== 1
350
+ || (process.platform !== 'win32' && (stat.mode & 0o111) === 0)
351
+ ) {
352
+ throw new CodexAppServerError(
353
+ 'session launcher is not a safe executable file',
354
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
355
+ );
356
+ }
357
+ const sha256 = await hashFile(launcher);
358
+ return Object.freeze({
359
+ path: launcher,
360
+ sha256,
361
+ fingerprint: pathFingerprint(launcher),
362
+ });
363
+ } catch (cause) {
364
+ if (cause?.code === 'CODEX_SESSION_LAUNCHER_MISMATCH') throw cause;
365
+ throw new CodexAppServerError(
366
+ 'session launcher could not be attested',
367
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
368
+ { cause },
369
+ );
370
+ }
371
+ }
372
+
373
+ async function attestPinnedSessionLauncher(launcher, expectedSha256) {
374
+ if (typeof expectedSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(expectedSha256)) {
375
+ throw new CodexAppServerError(
376
+ 'session launcher identity is malformed',
377
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
378
+ );
379
+ }
380
+ const attestation = await characterizePinnedSessionLauncher(launcher);
381
+ if (attestation.sha256 !== expectedSha256) {
382
+ throw new CodexAppServerError(
383
+ 'session launcher content changed',
384
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
385
+ );
386
+ }
387
+ return attestation;
388
+ }
389
+
315
390
  function pathFingerprint(target) {
316
391
  const stat = lstatSync(target, { bigint: true });
317
392
  return {
@@ -1037,6 +1112,7 @@ function projectThread(value, label, ownedCwd, modelProvider) {
1037
1112
  }
1038
1113
  return {
1039
1114
  id: protocolRequiredString(thread.id, `${label} id`),
1115
+ ephemeral: thread.ephemeral,
1040
1116
  status,
1041
1117
  turns: thread.turns.map((turn) => projectTurn(turn, `${label} turn`)),
1042
1118
  };
@@ -1766,6 +1842,9 @@ class CodexAppServerClient extends EventEmitter {
1766
1842
  onFault,
1767
1843
  attestBinaryFn = attestPinnedCodexBinary,
1768
1844
  attestCodexHomeFn = attestPinnedCodexHome,
1845
+ attestSessionLauncherFn = attestPinnedSessionLauncher,
1846
+ sessionLauncher = null,
1847
+ expectedSessionLauncherSha256 = null,
1769
1848
  expectedConfigSha256,
1770
1849
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
1771
1850
  sinkTimeoutMs = DEFAULT_SINK_TIMEOUT_MS,
@@ -1781,6 +1860,18 @@ class CodexAppServerClient extends EventEmitter {
1781
1860
  assertAbsolute(binary, 'binary');
1782
1861
  assertAbsolute(cwd, 'cwd');
1783
1862
  assertAbsolute(codexHome, 'codexHome');
1863
+ if (sessionLauncher !== null) assertAbsolute(sessionLauncher, 'sessionLauncher');
1864
+ if (
1865
+ (sessionLauncher === null) !== (expectedSessionLauncherSha256 === null)
1866
+ || (
1867
+ expectedSessionLauncherSha256 !== null
1868
+ && !/^[a-f0-9]{64}$/.test(expectedSessionLauncherSha256)
1869
+ )
1870
+ ) {
1871
+ throw new TypeError(
1872
+ 'CodexAppServerClient: session launcher path and SHA-256 must be paired',
1873
+ );
1874
+ }
1784
1875
  if (
1785
1876
  typeof expectedConfigSha256 !== 'string'
1786
1877
  || !/^[a-f0-9]{64}$/.test(expectedConfigSha256)
@@ -1829,6 +1920,7 @@ class CodexAppServerClient extends EventEmitter {
1829
1920
  [onFault, 'onFault'],
1830
1921
  [attestBinaryFn, 'attestBinaryFn'],
1831
1922
  [attestCodexHomeFn, 'attestCodexHomeFn'],
1923
+ [attestSessionLauncherFn, 'attestSessionLauncherFn'],
1832
1924
  ]) {
1833
1925
  if (typeof value !== 'function') {
1834
1926
  throw new TypeError(`CodexAppServerClient: ${label} must be a function`);
@@ -1876,6 +1968,9 @@ class CodexAppServerClient extends EventEmitter {
1876
1968
  onFault,
1877
1969
  attestBinaryFn,
1878
1970
  attestCodexHomeFn,
1971
+ attestSessionLauncherFn,
1972
+ sessionLauncher,
1973
+ expectedSessionLauncherSha256,
1879
1974
  targetReceipt,
1880
1975
  expectedConfigSha256,
1881
1976
  requestTimeoutMs,
@@ -1937,16 +2032,25 @@ class CodexAppServerClient extends EventEmitter {
1937
2032
  const commandArgs = [
1938
2033
  SUPERVISOR_PATH,
1939
2034
  `--group-term-grace-ms=${this.closeGraceMs}`,
2035
+ ...(this.sessionLauncher
2036
+ ? [`--session-launcher=${this.sessionLauncher}`]
2037
+ : []),
1940
2038
  this.binary,
1941
2039
  ...args,
1942
2040
  ];
1943
2041
  try {
1944
- const [attestation, homeAttestation] = await Promise.all([
2042
+ const [attestation, homeAttestation, launcherAttestation] = await Promise.all([
1945
2043
  this.attestBinaryFn(this.binary, this.targetReceipt),
1946
2044
  this.attestCodexHomeFn(
1947
2045
  this.codexHome,
1948
2046
  this.expectedConfigSha256,
1949
2047
  ),
2048
+ this.sessionLauncher
2049
+ ? this.attestSessionLauncherFn(
2050
+ this.sessionLauncher,
2051
+ this.expectedSessionLauncherSha256,
2052
+ )
2053
+ : null,
1950
2054
  ]);
1951
2055
  if (
1952
2056
  !attestation
@@ -1960,6 +2064,19 @@ class CodexAppServerClient extends EventEmitter {
1960
2064
  'CODEX_BINARY_MISMATCH',
1961
2065
  );
1962
2066
  }
2067
+ if (
2068
+ this.sessionLauncher
2069
+ && (
2070
+ launcherAttestation?.path !== this.sessionLauncher
2071
+ || launcherAttestation.sha256
2072
+ !== this.expectedSessionLauncherSha256
2073
+ )
2074
+ ) {
2075
+ throw new CodexAppServerError(
2076
+ 'session launcher attestation was inconsistent',
2077
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
2078
+ );
2079
+ }
1963
2080
  if (
1964
2081
  !homeAttestation
1965
2082
  || homeAttestation.path !== this.codexHome
@@ -1993,6 +2110,27 @@ class CodexAppServerClient extends EventEmitter {
1993
2110
  'CODEX_BINARY_MISMATCH',
1994
2111
  );
1995
2112
  }
2113
+ if (launcherAttestation?.fingerprint) {
2114
+ let currentLauncherFingerprint;
2115
+ try {
2116
+ currentLauncherFingerprint = pathFingerprint(this.sessionLauncher);
2117
+ } catch (cause) {
2118
+ throw new CodexAppServerError(
2119
+ 'session launcher changed during spawn',
2120
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
2121
+ { cause },
2122
+ );
2123
+ }
2124
+ if (!sameFingerprint(
2125
+ launcherAttestation.fingerprint,
2126
+ currentLauncherFingerprint,
2127
+ )) {
2128
+ throw new CodexAppServerError(
2129
+ 'session launcher changed during spawn',
2130
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
2131
+ );
2132
+ }
2133
+ }
1996
2134
  const afterSpawnHome = await this.attestCodexHomeFn(
1997
2135
  this.codexHome,
1998
2136
  this.expectedConfigSha256,
@@ -2984,6 +3122,8 @@ module.exports = {
2984
3122
  CodexAppServerError,
2985
3123
  attestPinnedCodexBinary,
2986
3124
  attestPinnedCodexHome,
3125
+ attestPinnedSessionLauncher,
3126
+ characterizePinnedSessionLauncher,
2987
3127
  buildCodexAppServerEnv,
2988
3128
  protocolSchema,
2989
3129
  resolveCodexTargetPin,
@@ -5,10 +5,16 @@ const argv = process.argv.slice(2);
5
5
  const graceMs = argv[0]?.startsWith(GRACE_FLAG)
6
6
  ? Number(argv.shift().slice(GRACE_FLAG.length))
7
7
  : Number.NaN;
8
+ const launcherFlag = '--session-launcher=';
9
+ const sessionLauncher = argv[0]?.startsWith(launcherFlag)
10
+ ? argv.shift().slice(launcherFlag.length)
11
+ : null;
8
12
  const [binary, ...args] = argv;
9
13
  if (!binary || !Number.isSafeInteger(graceMs) || graceMs < 0) process.exit(64);
10
14
 
11
- const child = spawn(binary, args, {
15
+ const child = spawn(sessionLauncher ?? binary, sessionLauncher
16
+ ? [binary, ...args]
17
+ : args, {
12
18
  cwd: process.cwd(),
13
19
  env: process.env,
14
20
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -41,6 +41,12 @@ const EXPECTED_PROFILE_KEYS = new Set([
41
41
  'permissionProfileId',
42
42
  'model',
43
43
  'effort',
44
+ 'sessionLauncher',
45
+ 'sessionLauncherSha256',
46
+ ]);
47
+ const OPTIONAL_EXPECTED_PROFILE_KEYS = new Set([
48
+ 'sessionLauncher',
49
+ 'sessionLauncherSha256',
44
50
  ]);
45
51
  const PREFLIGHT_RESULT_KEYS = new Set([
46
52
  'runtime',
@@ -228,7 +234,10 @@ function normalizeExpectedProfile(value) {
228
234
  }
229
235
  }
230
236
  for (const key of EXPECTED_PROFILE_KEYS) {
231
- if (!Object.hasOwn(source, key)) {
237
+ if (
238
+ !OPTIONAL_EXPECTED_PROFILE_KEYS.has(key)
239
+ && !Object.hasOwn(source, key)
240
+ ) {
232
241
  throw new TypeError(`Codex preflight missing static profile field: ${key}`);
233
242
  }
234
243
  }
@@ -255,6 +264,22 @@ function normalizeExpectedProfile(value) {
255
264
  source.protocolSchemaSha256,
256
265
  'protocolSchemaSha256',
257
266
  );
267
+ const suppliedLauncher = source.sessionLauncher ?? null;
268
+ const suppliedLauncherSha256 = source.sessionLauncherSha256 ?? null;
269
+ if ((suppliedLauncher === null) !== (suppliedLauncherSha256 === null)) {
270
+ throw new TypeError(
271
+ 'Codex preflight session launcher path and SHA-256 must be paired',
272
+ );
273
+ }
274
+ const sessionLauncher = suppliedLauncher === null
275
+ ? null
276
+ : requiredString(suppliedLauncher, 'sessionLauncher');
277
+ const sessionLauncherSha256 = suppliedLauncherSha256 === null
278
+ ? null
279
+ : requiredSha256(suppliedLauncherSha256, 'sessionLauncherSha256');
280
+ if (sessionLauncher !== null && !path.isAbsolute(sessionLauncher)) {
281
+ throw new TypeError('Codex preflight session launcher must be absolute');
282
+ }
258
283
  if (
259
284
  target !== targetReceipt.target
260
285
  || binarySha256 !== targetReceipt.binarySha256
@@ -361,6 +386,8 @@ function normalizeExpectedProfile(value) {
361
386
  ),
362
387
  model: requiredString(source.model, 'model'),
363
388
  effort: requiredString(source.effort, 'effort'),
389
+ sessionLauncher,
390
+ sessionLauncherSha256,
364
391
  };
365
392
 
366
393
  assertExpectedPolicy(profile);
@@ -642,6 +669,10 @@ function staticAttestation(profile, configRead, requirements, profiles) {
642
669
  return {
643
670
  binarySha256: profile.binarySha256,
644
671
  binaryPathSha256: digest(profile.binary),
672
+ ...(profile.sessionLauncher === null ? {} : {
673
+ sessionLauncherPathSha256: digest(profile.sessionLauncher),
674
+ sessionLauncherSha256: profile.sessionLauncherSha256,
675
+ }),
645
676
  credentialHomeSha256: digest(profile.codexHome),
646
677
  workspaceSha256: digest(profile.cwd),
647
678
  allowlistedEnvironmentFingerprint:
@@ -971,6 +1002,8 @@ async function preflightCodexRuntime(
971
1002
  let latchedFault = null;
972
1003
  const client = clientFactory({
973
1004
  binary: profile.binary,
1005
+ sessionLauncher: profile.sessionLauncher,
1006
+ expectedSessionLauncherSha256: profile.sessionLauncherSha256,
974
1007
  cwd: profile.cwd,
975
1008
  codexHome: profile.codexHome,
976
1009
  env: profile.env,
@@ -332,6 +332,12 @@ class CodexProcess extends Process {
332
332
  this.state = 'Spawning';
333
333
  this.lifecycleEpoch = 0;
334
334
  this.providerSessionId = null;
335
+ this._resumeAttestation = null;
336
+ Object.defineProperty(this, 'resumeAttestation', {
337
+ enumerable: true,
338
+ configurable: false,
339
+ get: () => this._resumeAttestation,
340
+ });
335
341
  this.attachingThreadId = null;
336
342
  this.activeTurnId = null;
337
343
  this.lastTurnId = null;
@@ -427,12 +433,41 @@ class CodexProcess extends Process {
427
433
 
428
434
  async _start(options) {
429
435
  const lifecycle = this._captureLifecycle();
436
+ this._resumeAttestation = null;
430
437
  const existingSessionId = optionalString(
431
438
  options.existingSessionId
432
439
  ?? options.providerSessionId
433
440
  ?? options.codexThreadId,
434
441
  'existingSessionId',
435
442
  );
443
+ if (
444
+ options.resumePolicy != null
445
+ && options.resumePolicy !== 'require-interrupted-turn'
446
+ ) {
447
+ throw processError(
448
+ 'Unsupported Codex resume policy',
449
+ 'CODEX_STRICT_RESUME_INVALID',
450
+ );
451
+ }
452
+ const strictResume = options.resumePolicy === 'require-interrupted-turn';
453
+ if (!strictResume && options.expectedInterruptedTurnId != null) {
454
+ throw processError(
455
+ 'Expected interrupted turn requires strict Codex resume',
456
+ 'CODEX_STRICT_RESUME_INVALID',
457
+ );
458
+ }
459
+ const expectedInterruptedTurnId = strictResume
460
+ ? boundedOpaqueId(
461
+ options.expectedInterruptedTurnId,
462
+ 'expectedInterruptedTurnId',
463
+ )
464
+ : null;
465
+ if (strictResume && !existingSessionId) {
466
+ throw processError(
467
+ 'Strict Codex resume requires an existing thread',
468
+ 'CODEX_STRICT_RESUME_INVALID',
469
+ );
470
+ }
436
471
  this.desiredSettings = this._validatedModelSettings({
437
472
  model: options.model ?? options.chatConfig?.model,
438
473
  effort: options.effort ?? options.chatConfig?.effort,
@@ -482,6 +517,14 @@ class CodexProcess extends Process {
482
517
  this.providerSessionId = result.thread.id;
483
518
  }
484
519
  this._validateThreadResult(result, existingSessionId);
520
+ if (strictResume) {
521
+ await this._attestStrictResume(
522
+ result,
523
+ existingSessionId,
524
+ expectedInterruptedTurnId,
525
+ lifecycle,
526
+ );
527
+ }
485
528
  if (
486
529
  this.attachingThreadId
487
530
  && result.thread.id !== this.attachingThreadId
@@ -500,6 +543,16 @@ class CodexProcess extends Process {
500
543
  resumed: Boolean(existingSessionId),
501
544
  });
502
545
  this._assertLifecycle(lifecycle);
546
+ if (strictResume) {
547
+ this._resumeAttestation = Object.freeze({
548
+ namespace: 'codex:app-server',
549
+ sessionId: existingSessionId,
550
+ interruptedTurnId: expectedInterruptedTurnId,
551
+ resumed: true,
552
+ freshFallback: false,
553
+ idle: true,
554
+ });
555
+ }
503
556
  const init = {
504
557
  type: 'system',
505
558
  subtype: 'init',
@@ -610,6 +663,40 @@ class CodexProcess extends Process {
610
663
  this.attachmentResponseValidated = true;
611
664
  }
612
665
 
666
+ async _attestStrictResume(
667
+ result,
668
+ expectedThreadId,
669
+ expectedInterruptedTurnId,
670
+ lifecycle,
671
+ ) {
672
+ const thread = result?.thread;
673
+ const tail = Array.isArray(thread?.turns) ? thread.turns.at(-1) : null;
674
+ if (
675
+ thread?.id !== expectedThreadId
676
+ || thread.ephemeral !== false
677
+ || thread.status?.type !== 'idle'
678
+ || tail?.id !== expectedInterruptedTurnId
679
+ || tail.status !== 'interrupted'
680
+ ) {
681
+ throw processError(
682
+ 'Codex strict resume did not attest the exact interrupted turn',
683
+ 'CODEX_STRICT_RESUME_MISMATCH',
684
+ );
685
+ }
686
+ const background = await this.client.request(
687
+ 'thread/backgroundTerminals/list',
688
+ { threadId: expectedThreadId, limit: 100 },
689
+ { timeoutMs: this.cleanupTimeoutMs },
690
+ );
691
+ this._assertLifecycle(lifecycle);
692
+ if (background?.count !== 0 || background.nextCursor != null) {
693
+ throw processError(
694
+ 'Codex strict resume found unresolved background work',
695
+ 'CODEX_STRICT_RESUME_MISMATCH',
696
+ );
697
+ }
698
+ }
699
+
613
700
  _validateAndObserveThreadPolicy(
614
701
  source,
615
702
  { attachmentResponse = false } = {},
@@ -2883,6 +2970,52 @@ class CodexProcess extends Process {
2883
2970
  );
2884
2971
  }
2885
2972
 
2973
+ captureCleanRestartCandidate() {
2974
+ const pending = this.current;
2975
+ const sourceMsgId = pending?.context?.sourceMsgId ?? null;
2976
+ const settings = pending?.admittedSettings ?? this.activeTurnSettings;
2977
+ if (
2978
+ this.state !== 'Active'
2979
+ || !pending
2980
+ || pending.settled
2981
+ || pending.terminal
2982
+ || pending.startDeliveryState !== 'accepted'
2983
+ || pending.turnId == null
2984
+ || pending.turnId !== this.activeTurnId
2985
+ || this.pendingQueue.length !== 1
2986
+ || this.pendingQueue[0] !== pending
2987
+ || this.pendingSteerCount !== 0
2988
+ || this.pendingCancellations.length !== 0
2989
+ || this.cancellationFlushPromise
2990
+ || this.backgroundSettlementPromise
2991
+ || this.hasActiveBackgroundWork()
2992
+ || sourceMsgId == null
2993
+ || !settings
2994
+ || typeof this.generationId !== 'string'
2995
+ || this.generationId.length === 0
2996
+ || typeof pending.attemptId !== 'string'
2997
+ || pending.attemptId.length === 0
2998
+ || typeof this.providerSessionId !== 'string'
2999
+ || this.providerSessionId.length === 0
3000
+ || typeof this.spawnProfileId !== 'string'
3001
+ || this.spawnProfileId.length === 0
3002
+ ) return null;
3003
+ return Object.freeze({
3004
+ runtime: 'codex',
3005
+ namespace: 'codex:app-server',
3006
+ sessionKey: this.sessionKey,
3007
+ generationId: this.generationId,
3008
+ attemptId: pending.attemptId,
3009
+ providerSessionId: this.providerSessionId,
3010
+ providerTurnId: pending.turnId,
3011
+ sourceMsgId,
3012
+ cwd: this.cwd,
3013
+ model: settings.model,
3014
+ effort: settings.effort,
3015
+ spawnProfileId: this.spawnProfileId,
3016
+ });
3017
+ }
3018
+
2886
3019
  hasActiveBackgroundWork() {
2887
3020
  return (
2888
3021
  this.state === 'BackgroundWorking'
@@ -302,8 +302,35 @@ function createCodexProcess({
302
302
  'existingSessionId must be a bounded opaque identifier',
303
303
  );
304
304
  }
305
+ const strictResume = ctx?.resumePolicy === 'require-interrupted-turn';
306
+ if (
307
+ ctx?.resumePolicy != null
308
+ && !strictResume
309
+ ) {
310
+ throw codexConfigurationError('unsupported Codex resume policy');
311
+ }
312
+ if (!strictResume && ctx?.expectedInterruptedTurnId != null) {
313
+ throw codexConfigurationError(
314
+ 'interrupted turn requires strict Codex resume policy',
315
+ );
316
+ }
317
+ if (
318
+ strictResume
319
+ && (
320
+ existingSessionId == null
321
+ || !isBoundedOpaqueId(ctx?.expectedInterruptedTurnId)
322
+ )
323
+ ) {
324
+ throw codexConfigurationError(
325
+ 'strict Codex resume requires an existing thread and interrupted turn',
326
+ );
327
+ }
305
328
  const spawnOptions = Object.freeze({
306
329
  ...(existingSessionId == null ? {} : { existingSessionId }),
330
+ ...(strictResume ? {
331
+ resumePolicy: 'require-interrupted-turn',
332
+ expectedInterruptedTurnId: ctx.expectedInterruptedTurnId,
333
+ } : {}),
307
334
  model: selectedSettings.model,
308
335
  effort: selectedSettings.effort,
309
336
  });
@@ -434,6 +434,47 @@ class ProcessManager {
434
434
  return proc?.runtime === 'codex' || proc?.backend === 'codex';
435
435
  }
436
436
 
437
+ _assertCodexResumeControls(spawnContext) {
438
+ const policy = spawnContext?.resumePolicy;
439
+ const expectedTurnId = spawnContext?.expectedInterruptedTurnId;
440
+ if (
441
+ (policy != null && policy !== 'require-interrupted-turn')
442
+ || (policy !== 'require-interrupted-turn' && expectedTurnId != null)
443
+ ) {
444
+ throw managerError(
445
+ 'Invalid Codex strict resume controls',
446
+ 'CODEX_STRICT_RESUME_INVALID',
447
+ );
448
+ }
449
+ if (policy !== 'require-interrupted-turn') return;
450
+ const expectedSessionId = spawnContext.existingSessionId ?? null;
451
+ if (!isOpaqueId(expectedSessionId) || !isOpaqueId(expectedTurnId)) {
452
+ throw managerError(
453
+ 'Invalid Codex strict resume identity',
454
+ 'CODEX_STRICT_RESUME_INVALID',
455
+ );
456
+ }
457
+ }
458
+
459
+ _assertStrictResumeReuse(proc, spawnContext) {
460
+ if (spawnContext?.resumePolicy !== 'require-interrupted-turn') return;
461
+ const expectedSessionId = spawnContext.existingSessionId ?? null;
462
+ const expectedTurnId = spawnContext.expectedInterruptedTurnId ?? null;
463
+ const attestation = proc?.resumeAttestation;
464
+ if (
465
+ attestation?.resumed !== true
466
+ || attestation.freshFallback !== false
467
+ || attestation.idle !== true
468
+ || attestation.sessionId !== expectedSessionId
469
+ || attestation.interruptedTurnId !== expectedTurnId
470
+ ) {
471
+ throw managerError(
472
+ 'Warm Codex generation does not match strict resume identity',
473
+ 'CODEX_STRICT_RESUME_MISMATCH',
474
+ );
475
+ }
476
+ }
477
+
437
478
  _isStateMutationFenced(sessionKey) {
438
479
  const proc = this.procs.get(sessionKey);
439
480
  return Boolean(
@@ -510,6 +551,9 @@ class ProcessManager {
510
551
  let desired;
511
552
  try {
512
553
  desired = this._desiredIdentity(spawnContext);
554
+ if (desired.runtime === 'codex') {
555
+ this._assertCodexResumeControls(spawnContext);
556
+ }
513
557
  } catch (error) {
514
558
  return Promise.reject(error);
515
559
  }
@@ -559,6 +603,9 @@ class ProcessManager {
559
603
  if (this._identityFor(existing).key !== desired.key) {
560
604
  return this._replaceRuntimeLocked(sessionKey, spawnContext, desired);
561
605
  }
606
+ if (this._isCodex(existing)) {
607
+ this._assertStrictResumeReuse(existing, spawnContext);
608
+ }
562
609
  // Reload-on-drift (cli): a warm cli proc can't hot-swap model/effort or
563
610
  // its display hint (all spawn-time). If the resolved config has drifted
564
611
  // and the proc is idle, kill it (preserves session_id) and fall through to
@@ -731,6 +778,9 @@ class ProcessManager {
731
778
  if (competitor && !competitor.closed) {
732
779
  releaseDefinitelyUnstartedReservation();
733
780
  if (this._identityFor(competitor).key === desired.key) {
781
+ if (this._isCodex(competitor)) {
782
+ this._assertStrictResumeReuse(competitor, spawnContext);
783
+ }
734
784
  return competitor;
735
785
  }
736
786
  return this._replaceRuntimeLocked(
@@ -1077,9 +1127,9 @@ class ProcessManager {
1077
1127
  );
1078
1128
  }
1079
1129
  if (this.codexRetirementVerifier) {
1080
- await this._verifyCodexRetirement(proc, reason);
1130
+ return this._verifyCodexRetirement(proc, reason);
1081
1131
  }
1082
- return;
1132
+ return null;
1083
1133
  }
1084
1134
  await proc.kill(reason);
1085
1135
  if (!proc.closed) {
@@ -1120,6 +1170,7 @@ class ProcessManager {
1120
1170
  'CODEX_RETIREMENT_VERIFICATION_FAILED',
1121
1171
  );
1122
1172
  }
1173
+ return verification;
1123
1174
  } catch (cause) {
1124
1175
  if (this._codexLeaseMatches(proc)) {
1125
1176
  this._codexLease.quarantined = true;
@@ -1415,14 +1466,64 @@ class ProcessManager {
1415
1466
  settled = await Promise.allSettled(targets.map(async ([sessionKey, proc]) => {
1416
1467
  let snapshot;
1417
1468
  if (this._isCodex(proc)) {
1418
- await getDeliveryEvidence(sessionKey, null);
1419
- await this._strictRetire(proc, 'clean-restart');
1469
+ const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1470
+ ? proc.captureCleanRestartCandidate()
1471
+ : null;
1472
+ let deliveryEvidence = null;
1473
+ let deliveryEvidenceError = null;
1474
+ try {
1475
+ deliveryEvidence = await getDeliveryEvidence(
1476
+ sessionKey,
1477
+ candidate?.sourceMsgId ?? null,
1478
+ );
1479
+ } catch (error) {
1480
+ deliveryEvidenceError = error;
1481
+ }
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
+ );
1420
1504
  if (this._codexLeaseMatches(proc)) this._codexLease = null;
1421
- snapshot = {
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
+ } : {
1422
1522
  sourceMsgId: null,
1423
1523
  eligible: false,
1424
- reason: 'unsupported-backend',
1524
+ reason: 'no-active-turn',
1425
1525
  };
1526
+ if (deliveryEvidenceError) throw deliveryEvidenceError;
1426
1527
  } else {
1427
1528
  snapshot = await proc.retireForCleanRestart({
1428
1529
  getDeliveryEvidence: (_reportedSessionKey, sourceMsgId) => (
@@ -1433,14 +1534,25 @@ class ProcessManager {
1433
1534
  ),
1434
1535
  });
1435
1536
  }
1436
- const cliEligible = proc.backend === 'cli' && snapshot?.eligible === true;
1537
+ const supported = proc.backend === 'cli' || this._isCodex(proc);
1538
+ const eligible = supported && snapshot?.eligible === true;
1437
1539
  return Object.freeze({
1438
1540
  sessionKey,
1439
- sourceMsgId: proc.backend === 'cli'
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
1440
1552
  ? (snapshot?.sourceMsgId ?? null)
1441
1553
  : null,
1442
- eligible: cliEligible,
1443
- reason: proc.backend === 'cli'
1554
+ eligible,
1555
+ reason: supported
1444
1556
  ? (snapshot?.reason || 'retirement-uncertain')
1445
1557
  : 'unsupported-backend',
1446
1558
  });
@@ -1726,6 +1838,7 @@ class ProcessManager {
1726
1838
  */
1727
1839
  _wireCallbacks(proc) {
1728
1840
  const capturedGeneration = proc.generationId ?? null;
1841
+ let abnormalTerminationReported = false;
1729
1842
  const hasCapturedGeneration = () => (
1730
1843
  capturedGeneration == null
1731
1844
  || proc.generationId === capturedGeneration
@@ -1735,6 +1848,39 @@ class ProcessManager {
1735
1848
  && !this._retiring.has(proc)
1736
1849
  && hasCapturedGeneration()
1737
1850
  );
1851
+ const reportAbnormalTermination = (event, exitCode = null) => {
1852
+ const verifiedSafeCodexStartupRelease = (
1853
+ event === 'close'
1854
+ && this._isCodex(proc)
1855
+ && this._starting.has(proc.sessionKey)
1856
+ && proc.startupReleaseSafe === true
1857
+ && proc.closed === true
1858
+ && proc.state === 'Closed'
1859
+ );
1860
+ if (
1861
+ abnormalTerminationReported
1862
+ || verifiedSafeCodexStartupRelease
1863
+ || this._shuttingDown
1864
+ || this._retiring.has(proc)
1865
+ || (this._retirementIntents.get(proc.sessionKey) ?? 0) > 0
1866
+ || !isCurrentGeneration()
1867
+ ) return;
1868
+ abnormalTerminationReported = true;
1869
+ const callback = this.callbacks.onAbnormalTermination;
1870
+ if (typeof callback !== 'function') return;
1871
+ const evidence = Object.freeze({
1872
+ event,
1873
+ backend: proc.backend,
1874
+ generationId: capturedGeneration,
1875
+ exitCode: Number.isSafeInteger(exitCode) ? exitCode : null,
1876
+ });
1877
+ try { callback(proc.sessionKey, evidence, proc); }
1878
+ catch (error) {
1879
+ this.logger.error?.(
1880
+ `[pm:${proc.label}] onAbnormalTermination threw: ${error.message}`,
1881
+ );
1882
+ }
1883
+ };
1738
1884
  for (const [cbName, eventName] of Object.entries(CALLBACK_TO_EVENT)) {
1739
1885
  const fn = this.callbacks[cbName];
1740
1886
  if (typeof fn !== 'function') continue;
@@ -1802,6 +1948,7 @@ class ProcessManager {
1802
1948
  // 'close': process closed itself (iteration loop exited or
1803
1949
  // _closeQuery returned). Remove from the Map + signal LRU.
1804
1950
  proc.on('close', (...args) => {
1951
+ reportAbnormalTermination('close', args[0]);
1805
1952
  if (!this._isCodex(proc)) {
1806
1953
  if (
1807
1954
  !this._retiring.has(proc)
@@ -1868,6 +2015,7 @@ class ProcessManager {
1868
2015
  // We don't re-spawn proactively: an idle disconnected session shouldn't
1869
2016
  // burn LRU budget. Lazy respawn on next message is the right shape.
1870
2017
  proc.on('bridge-disconnected', () => {
2018
+ reportAbnormalTermination('bridge-disconnected');
1871
2019
  this.logger.warn?.(`[pm:${proc.label}] channels bridge disconnected — killing dead instance for lazy respawn`);
1872
2020
  // Serialize with start/replacement/kill. Re-check object identity after
1873
2021
  // the gate so a late disconnect from an old generation cannot kill its
@@ -248,6 +248,7 @@ class SdkProcess extends Process {
248
248
  }
249
249
 
250
250
  async _runIteration() {
251
+ let closeEmitted = false;
251
252
  try {
252
253
  for await (const msg of this.query) {
253
254
  await this._handleEvent(msg);
@@ -256,9 +257,12 @@ class SdkProcess extends Process {
256
257
  } catch (err) {
257
258
  this._failAllPendings(err);
258
259
  this.emit('close', err.code === 'AbortError' ? 0 : 1);
260
+ closeEmitted = true;
259
261
  } finally {
262
+ const alreadyClosed = this.closed;
260
263
  this.closed = true;
261
264
  this.inFlight = false;
265
+ if (!closeEmitted && !alreadyClosed) this.emit('close', 0);
262
266
  this.emit('idle');
263
267
  }
264
268
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.11",
3
+ "version": "0.10.13",
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",