@shumkov/orchestra 0.10.10 → 0.10.12

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.
@@ -32,8 +32,18 @@ Telegram or WhatsApp:
32
32
 
33
33
  - `toolDispatcher(call) => {ok, error?, message_id?}` — delivers reply/edit/react on the
34
34
  consumer's transport (already injected in polygram/water today).
35
- - `displayHint: string` — surface-rendering rules appended to the system prompt
36
- (**new option**, replacing cli-process's hard `require('../delivery/display-hint')`).
35
+ - `displayHint: string | (chatId, threadId, config) => string` — surface-rendering rules
36
+ appended to the system prompt (**new option**, replacing cli-process's hard
37
+ `require('../delivery/display-hint')`). A resolver is called once per spawn, so the hint
38
+ can vary per chat/topic.
39
+ **Contract for a hint that can change** (e.g. a per-chat rich-text toggle): the hint is
40
+ spawn-time state, so a change reaches a warm session only by respawning it. The consumer
41
+ must put the identical resolved string on the spawn context as `spawnContext.displayHint`.
42
+ That string is what `getOrSpawn` compares against the warm proc to detect the change, and
43
+ it is what the respawn is constructed with — the resolver is only the fallback for a
44
+ context that carries no hint. Two independent sources is the failure mode to avoid: if a
45
+ consumer's context string and its resolver disagree by one character, every message looks
46
+ like drift and the session respawns forever.
37
47
  - `maxOutboundFileBytes: number` — outbound file cap (**new option**, replacing
38
48
  `require('../attachments').resolveFileCaps`).
39
49
  - `claudeBin`, `botName`, `tmuxRunner`, `logger`, `db` (telemetry) — as today.
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,
@@ -351,7 +351,10 @@ class CliProcess extends Process {
351
351
  // PreToolUse/PostToolUse matcher is `.*`, so the agent's own stream calls
352
352
  // arrive here as work hooks — see _handleHookEvent for why that matters.
353
353
  this._streamToolHookName = `mcp__${bridgeServerName}__stream`;
354
- this.displayHint = displayHint;
354
+ // Normalized to a string: the drift check compares with !== against the
355
+ // spawn context's string hint, so a null (from a resolver that returned
356
+ // one) would be drift no context could ever match — a permanent respawn.
357
+ this.displayHint = typeof displayHint === 'string' ? displayHint : '';
355
358
  this._injectedMaxOutboundFileBytes = maxOutboundFileBytes;
356
359
  this.sessionPrefix = sessionPrefix;
357
360
  this.bridgeServerName = bridgeServerName;
@@ -3845,9 +3848,29 @@ class CliProcess extends Process {
3845
3848
  * @returns {boolean}
3846
3849
  */
3847
3850
  wouldReloadFor(spawnContext) {
3848
- if (this.inFlight || this.closed) return false;
3849
- return this._resolveModel(spawnContext) !== this.model
3850
- || this._resolveEffort(spawnContext) !== this.effort;
3851
+ return this.reloadReasonsFor(spawnContext).length > 0;
3852
+ }
3853
+
3854
+ /**
3855
+ * Which spawn-time dimensions have drifted — the drift check itself, with the
3856
+ * answer named so telemetry can tell a rendering toggle from a /model change.
3857
+ * The display hint is spawn-time too (it is woven into the appended system
3858
+ * prompt), so a consumer that varies it per chat needs the same treatment as
3859
+ * model/effort. A spawn context that carries no hint at all is a consumer on
3860
+ * an older build: `undefined` must not read as "drifted to empty", which would
3861
+ * respawn every session on every message.
3862
+ * @returns {string[]} empty when nothing drifted or a reload is not possible
3863
+ */
3864
+ reloadReasonsFor(spawnContext) {
3865
+ if (this.inFlight || this.closed) return [];
3866
+ const reasons = [];
3867
+ if (this._resolveModel(spawnContext) !== this.model) reasons.push('model');
3868
+ if (this._resolveEffort(spawnContext) !== this.effort) reasons.push('effort');
3869
+ if (
3870
+ typeof spawnContext?.displayHint === 'string'
3871
+ && spawnContext.displayHint !== this.displayHint
3872
+ ) reasons.push('display-hint');
3873
+ return reasons;
3851
3874
  }
3852
3875
 
3853
3876
  /**
@@ -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
  });
@@ -420,9 +447,17 @@ function _maybeWarnR12Migration({ rawPm, canonical, chatId, threadId, chatCfg, t
420
447
  * spawn, just before the CliProcess is constructed. The resolver receives the
421
448
  * spawning chat/topic and the factory's config so the consumer can implement its
422
449
  * own per-chat/topic precedence (e.g. a per-chat rich-text toggle) without the
423
- * engine knowing anything about the consumer's config shape. The resolved string
424
- * is what reaches CliProcess. Only the 'cli' backend uses this; the 'sdk' backend
425
- * gets its per-chat hint via spawnFn instead.
450
+ * engine knowing anything about the consumer's config shape. Only the 'cli'
451
+ * backend uses this; the 'sdk' backend gets its per-chat hint via spawnFn instead.
452
+ *
453
+ * A `spawnContext.displayHint` string OVERRIDES both forms, and a consumer whose
454
+ * hint can change must send one: the hint is spawn-time state, so a change reaches
455
+ * a warm session only through getOrSpawn's reload-on-drift, which compares the
456
+ * context's hint against the warm proc's. Passing the identical resolved string on
457
+ * the context makes the reload and the respawn one source — resolving independently
458
+ * here would make them two, and a one-character disagreement would respawn the
459
+ * session on every message forever. The resolver remains the fallback for consumers
460
+ * that send no hint on the context.
426
461
  * @param {Function} [opts.codexClientFactory] — trusted Codex app-server client
427
462
  * factory. Required only when spawnContext.runtime is exactly 'codex'.
428
463
  * @param {Function} [opts.codexCheckpointSink] — acknowledged durability sink.
@@ -515,13 +550,20 @@ function createProcessFactory({
515
550
  `falling back to SdkProcess. Pass these to createProcessFactory.`,
516
551
  );
517
552
  } else {
518
- // displayHint may be a static string (same hint for every session) or a
519
- // resolver called per spawn with the current chat/topic and config, so the
520
- // consumer can vary the hint per chat (e.g. a per-chat rich-text toggle).
521
- // The string form is passed through unchanged.
522
- const resolvedDisplayHint = typeof displayHint === 'function'
523
- ? displayHint(chatId, threadId, config)
524
- : displayHint;
553
+ // The spawn context's hint wins whenever it carries one. getOrSpawn's
554
+ // reload-on-drift compares THAT string against the warm proc's, so the
555
+ // respawn must carry the same one — resolving independently here would
556
+ // make apply-path and detect-path two sources, and a one-character
557
+ // disagreement between them respawns the session on every message,
558
+ // forever. The resolver stays the fallback for consumers that send no
559
+ // hint on the context: a static string (same hint for every session) or
560
+ // a function called per spawn with the current chat/topic and config, so
561
+ // the consumer can vary the hint per chat (e.g. a rich-text toggle).
562
+ const resolvedDisplayHint = typeof ctx?.displayHint === 'string'
563
+ ? ctx.displayHint
564
+ : typeof displayHint === 'function'
565
+ ? displayHint(chatId, threadId, config)
566
+ : displayHint;
525
567
  // Same string-or-resolver shape as displayHint: the optional tools a
526
568
  // consumer can honor may vary per chat/topic (a live preview is a
527
569
  // per-chat rollout decision), and the prompt section that teaches them
@@ -29,6 +29,8 @@
29
29
 
30
30
  'use strict';
31
31
 
32
+ const { createHash } = require('node:crypto');
33
+
32
34
  const DEFAULT_BUDGET = 10; // total Σ cost (SDK cost=1, tmux cost=3)
33
35
  const DEFAULT_LRU_WAIT_MS = 300_000;
34
36
  const DEFAULT_CODEX_RETIREMENT_TIMEOUT_MS = 30_000;
@@ -47,6 +49,19 @@ function managerError(message, code, options) {
47
49
  return new ProcessManagerError(message, code, options);
48
50
  }
49
51
 
52
+ /**
53
+ * Identify a display hint in telemetry without storing it. The hint is a
54
+ * multi-KB system-prompt block and the events table has no retention, so only
55
+ * a fingerprint may be logged — enough to tell a real toggle (two reloads, two
56
+ * different fingerprints) from a treadmill (the same pair, over and over).
57
+ */
58
+ function hintFingerprint(hint) {
59
+ return createHash('sha256')
60
+ .update(typeof hint === 'string' ? hint : '')
61
+ .digest('hex')
62
+ .slice(0, 8);
63
+ }
64
+
50
65
  function findCodexRetirementVerificationError(error) {
51
66
  let current = error;
52
67
  for (let depth = 0; current && depth < 8; depth += 1) {
@@ -419,6 +434,47 @@ class ProcessManager {
419
434
  return proc?.runtime === 'codex' || proc?.backend === 'codex';
420
435
  }
421
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
+
422
478
  _isStateMutationFenced(sessionKey) {
423
479
  const proc = this.procs.get(sessionKey);
424
480
  return Boolean(
@@ -495,6 +551,9 @@ class ProcessManager {
495
551
  let desired;
496
552
  try {
497
553
  desired = this._desiredIdentity(spawnContext);
554
+ if (desired.runtime === 'codex') {
555
+ this._assertCodexResumeControls(spawnContext);
556
+ }
498
557
  } catch (error) {
499
558
  return Promise.reject(error);
500
559
  }
@@ -544,12 +603,15 @@ class ProcessManager {
544
603
  if (this._identityFor(existing).key !== desired.key) {
545
604
  return this._replaceRuntimeLocked(sessionKey, spawnContext, desired);
546
605
  }
547
- // Reload-on-drift (cli): a warm cli proc can't hot-swap model/effort
548
- // (spawn-time flags). If the resolved config has drifted and the proc is
549
- // idle, kill it (preserves session_id) and fall through to a cold respawn
550
- // → --resume keeps the conversation, the new --model/--effort takes
551
- // effect. In-flight cli procs and SDK procs (no wouldReloadFor — they
552
- // apply model live) are reused unchanged.
606
+ if (this._isCodex(existing)) {
607
+ this._assertStrictResumeReuse(existing, spawnContext);
608
+ }
609
+ // Reload-on-drift (cli): a warm cli proc can't hot-swap model/effort or
610
+ // its display hint (all spawn-time). If the resolved config has drifted
611
+ // and the proc is idle, kill it (preserves session_id) and fall through to
612
+ // a cold respawn → --resume keeps the conversation, the new
613
+ // --model/--effort/hint takes effect. In-flight cli procs and SDK procs
614
+ // (no wouldReloadFor — they apply model live) are reused unchanged.
553
615
  if (this._isCodex(existing) && existing.state === 'Stopped') {
554
616
  await this._killLocked(sessionKey, 'stopped-generation');
555
617
  this._throwIfShuttingDown();
@@ -557,10 +619,22 @@ class ProcessManager {
557
619
  typeof existing.wouldReloadFor === 'function'
558
620
  && existing.wouldReloadFor(spawnContext)
559
621
  ) {
622
+ // Which dimension(s) drifted — soak reads this to tell a per-chat
623
+ // rendering toggle from a /model or /effort change. A hint reload also
624
+ // carries both fingerprints (never the hint itself), so a session that
625
+ // respawns on every message is distinguishable from one that toggled.
626
+ const reasons = typeof existing.reloadReasonsFor === 'function'
627
+ ? existing.reloadReasonsFor(spawnContext)
628
+ : null;
560
629
  this._logEvent('cli-config-reload', {
561
630
  sessionKey,
562
631
  from_model: existing.model,
563
632
  from_effort: existing.effort,
633
+ reason: reasons ? reasons.join(',') : null,
634
+ ...(reasons?.includes('display-hint') && {
635
+ from_hint_hash: hintFingerprint(existing.displayHint),
636
+ to_hint_hash: hintFingerprint(spawnContext?.displayHint),
637
+ }),
564
638
  });
565
639
  await this._killLocked(sessionKey, 'config-reload');
566
640
  this._throwIfShuttingDown();
@@ -704,6 +778,9 @@ class ProcessManager {
704
778
  if (competitor && !competitor.closed) {
705
779
  releaseDefinitelyUnstartedReservation();
706
780
  if (this._identityFor(competitor).key === desired.key) {
781
+ if (this._isCodex(competitor)) {
782
+ this._assertStrictResumeReuse(competitor, spawnContext);
783
+ }
707
784
  return competitor;
708
785
  }
709
786
  return this._replaceRuntimeLocked(
@@ -1050,9 +1127,9 @@ class ProcessManager {
1050
1127
  );
1051
1128
  }
1052
1129
  if (this.codexRetirementVerifier) {
1053
- await this._verifyCodexRetirement(proc, reason);
1130
+ return this._verifyCodexRetirement(proc, reason);
1054
1131
  }
1055
- return;
1132
+ return null;
1056
1133
  }
1057
1134
  await proc.kill(reason);
1058
1135
  if (!proc.closed) {
@@ -1093,6 +1170,7 @@ class ProcessManager {
1093
1170
  'CODEX_RETIREMENT_VERIFICATION_FAILED',
1094
1171
  );
1095
1172
  }
1173
+ return verification;
1096
1174
  } catch (cause) {
1097
1175
  if (this._codexLeaseMatches(proc)) {
1098
1176
  this._codexLease.quarantined = true;
@@ -1388,14 +1466,64 @@ class ProcessManager {
1388
1466
  settled = await Promise.allSettled(targets.map(async ([sessionKey, proc]) => {
1389
1467
  let snapshot;
1390
1468
  if (this._isCodex(proc)) {
1391
- await getDeliveryEvidence(sessionKey, null);
1392
- 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
+ );
1393
1504
  if (this._codexLeaseMatches(proc)) this._codexLease = null;
1394
- 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
+ } : {
1395
1522
  sourceMsgId: null,
1396
1523
  eligible: false,
1397
- reason: 'unsupported-backend',
1524
+ reason: 'no-active-turn',
1398
1525
  };
1526
+ if (deliveryEvidenceError) throw deliveryEvidenceError;
1399
1527
  } else {
1400
1528
  snapshot = await proc.retireForCleanRestart({
1401
1529
  getDeliveryEvidence: (_reportedSessionKey, sourceMsgId) => (
@@ -1406,14 +1534,25 @@ class ProcessManager {
1406
1534
  ),
1407
1535
  });
1408
1536
  }
1409
- const cliEligible = proc.backend === 'cli' && snapshot?.eligible === true;
1537
+ const supported = proc.backend === 'cli' || this._isCodex(proc);
1538
+ const eligible = supported && snapshot?.eligible === true;
1410
1539
  return Object.freeze({
1411
1540
  sessionKey,
1412
- 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
1413
1552
  ? (snapshot?.sourceMsgId ?? null)
1414
1553
  : null,
1415
- eligible: cliEligible,
1416
- reason: proc.backend === 'cli'
1554
+ eligible,
1555
+ reason: supported
1417
1556
  ? (snapshot?.reason || 'retirement-uncertain')
1418
1557
  : 'unsupported-backend',
1419
1558
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.10",
3
+ "version": "0.10.12",
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",