@shumkov/orchestra 0.10.6 → 0.10.8

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.
@@ -31,6 +31,8 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
31
31
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
32
32
  const DEFAULT_CLOSE_GRACE_MS = 1_000;
33
33
  const DEFAULT_CLOSE_KILL_MS = 1_000;
34
+ const CODEX_SUPERVISOR_GRACE_MS =
35
+ DEFAULT_CLOSE_GRACE_MS + DEFAULT_CLOSE_KILL_MS;
34
36
  const DEFAULT_MAX_LINE_BYTES = 1024 * 1024;
35
37
  const DEFAULT_MAX_STDERR_BYTES = 64 * 1024;
36
38
  const DEFAULT_MAX_PENDING_REQUESTS = 64;
@@ -2977,6 +2979,7 @@ class CodexAppServerClient extends EventEmitter {
2977
2979
  }
2978
2980
 
2979
2981
  module.exports = {
2982
+ CODEX_SUPERVISOR_GRACE_MS,
2980
2983
  CodexAppServerClient,
2981
2984
  CodexAppServerError,
2982
2985
  attestPinnedCodexBinary,
@@ -383,7 +383,9 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => {
383
383
  'renders rich, an edited checklist/table/heading is re-rendered rich rather ' +
384
384
  'than flattened. Canonical use: send a plan as `- [ ] step` items, then edit ' +
385
385
  'that same message_id with the WHOLE list again and `- [x]` on completed ' +
386
- 'steps — check items off as you go and the user watches one bubble update. ' +
386
+ 'steps — check items off as you go and the user watches one bubble update, ' +
387
+ 'and one final time when the work ends, every item resolved and the ' +
388
+ 'hourglass gone. ' +
387
389
  'Also fine for a short one-line status. An edit REPLACES the body, so always ' +
388
390
  're-send the full text. An edit is TEXT-ONLY: image markdown degrades to its ' +
389
391
  'caption and cannot add media to a bubble (send media with `reply(files:)`). ' +
@@ -1040,6 +1040,31 @@ class CliProcess extends Process {
1040
1040
  ' (the checkbox column stays aligned). Exactly one item carries it at a',
1041
1041
  ' time; when the item completes it becomes `- [x]` and the ⏳ moves to',
1042
1042
  ' the next one. The user sees at a glance what is happening right now.',
1043
+ '6. Delivering the final answer COMPLETES the last step, so CLOSE THE',
1044
+ ' CHECKLIST OUT: immediately after that final `reply`, edit that same',
1045
+ ' `message_id` one last time, ticking every remaining item and removing',
1046
+ ' the ⏳. Its final state is all `- [x]`, zero ⏳. A turn that ends with',
1047
+ ' a lingering ⏳ on the checklist is a CONTRACT VIOLATION — the user is',
1048
+ ' left looking at work that reads as abandoned one item from the end,',
1049
+ ' however good the answer was.',
1050
+ ' But NEVER tick an item you did not actually complete — a false `- [x]`',
1051
+ ' is worse than an unfinished list. When work stops early — a step fails,',
1052
+ ' is skipped, turns out to be blocked — the close-out edit still happens:',
1053
+ ' remove the ⏳, leave that item unticked, and name the reason ON its',
1054
+ ' line, e.g. `- [ ] Деплой — заблокировано: нет доступа к VPS`. The',
1055
+ ' lingering ⏳ is the violation; an honestly labelled unfinished item',
1056
+ ' is not.',
1057
+ '',
1058
+ 'HARD RULE — a checkbox is a COMMITMENT, not decoration, and this applies to',
1059
+ 'EVERY message you send, the final answer included, not just the progress',
1060
+ 'checklist. `- [ ]` is EXCLUSIVELY for your own work items: steps YOU will',
1061
+ 'tick during this same task. Write one and you are committing to tick it',
1062
+ 'yourself before the work ends. Anything addressed to the USER —',
1063
+ 'recommendations, follow-ups, decisions for them to make, "you could install',
1064
+ 'X" — MUST be a plain bullet (`-`), never a checkbox. A checkbox only the',
1065
+ 'user could ever close is one you cannot tick, so it also makes the close-out',
1066
+ 'above impossible. Putting a checkbox on something only the user can act on',
1067
+ 'is a CONTRACT VIOLATION.',
1043
1068
  '',
1044
1069
  'An edit re-renders the bubble exactly as the original `reply` did — a chat',
1045
1070
  'that renders rich re-renders an edited checklist, table or heading rich, not',
@@ -143,6 +143,10 @@ class CodexProcess extends Process {
143
143
  if (
144
144
  this._state === 'ContainmentFailed'
145
145
  && next !== 'ContainmentFailed'
146
+ && !(
147
+ next === 'Closed'
148
+ && this.containmentCleanupCommitted
149
+ )
146
150
  ) return;
147
151
  if (
148
152
  this._state === 'DurabilityBlocked'
@@ -362,6 +366,9 @@ class CodexProcess extends Process {
362
366
  this.protocolFaultCount = 0;
363
367
  this.containmentReason = null;
364
368
  this.containmentError = null;
369
+ this.containmentErrorCode = null;
370
+ this.containmentTurnId = null;
371
+ this.containmentCleanupCommitted = null;
365
372
  this.startupReleaseSafe = false;
366
373
  this.stateChangingWriteCommitted = false;
367
374
  this.terminalTurnIds = new Set();
@@ -2492,6 +2499,8 @@ class CodexProcess extends Process {
2492
2499
  this.state = 'ContainmentFailed';
2493
2500
  this.containmentReason = reason;
2494
2501
  this.containmentError = error;
2502
+ this.containmentErrorCode = error?.code ?? null;
2503
+ this.containmentTurnId = ownedTurnId ?? null;
2495
2504
  this.inFlight = false;
2496
2505
  try {
2497
2506
  await this._checkpoint('containment-entered', {
@@ -2530,20 +2539,46 @@ class CodexProcess extends Process {
2530
2539
  }
2531
2540
 
2532
2541
  _scheduleContainedTransportClose() {
2533
- if (this.containmentClosePromise) return;
2534
- setImmediate(() => {
2535
- if (this.containmentClosePromise) return;
2536
- this.containmentClosePromise = timeout(
2537
- Promise.resolve().then(() => this.client?.close()),
2538
- this.cleanupTimeoutMs,
2539
- 'Codex contained transport did not close in time',
2540
- 'CODEX_CONTAINMENT_CLOSE_TIMEOUT',
2541
- ).catch((closeError) => {
2542
- this.logger.error?.(
2543
- `[${this.label}] Codex containment close: ${closeError.message}`,
2544
- );
2542
+ if (this.containmentClosePromise) return this.containmentClosePromise;
2543
+ this.containmentClosePromise = new Promise((resolve, reject) => {
2544
+ setImmediate(() => {
2545
+ this._finalizeContainedTransportClose().then(resolve, reject);
2545
2546
  });
2546
2547
  });
2548
+ this.containmentClosePromise.catch((closeError) => {
2549
+ this.logger.error?.(
2550
+ `[${this.label}] Codex containment close: ${closeError.message}`,
2551
+ );
2552
+ });
2553
+ return this.containmentClosePromise;
2554
+ }
2555
+
2556
+ async _finalizeContainedTransportClose() {
2557
+ await timeout(
2558
+ Promise.resolve().then(() => this.client?.close()),
2559
+ this.cleanupTimeoutMs,
2560
+ 'Codex contained transport did not close in time',
2561
+ 'CODEX_CONTAINMENT_CLOSE_TIMEOUT',
2562
+ );
2563
+ if (this.state !== 'ContainmentFailed') return null;
2564
+ await this._checkpoint('containment-cleanup-completed', {
2565
+ reason: this.containmentReason,
2566
+ errorCode: this.containmentErrorCode,
2567
+ turnId: this.containmentTurnId,
2568
+ });
2569
+ const detail = Object.freeze({
2570
+ kind: 'containment-cleanup-committed',
2571
+ backend: this.backend,
2572
+ generationId: this.generationId,
2573
+ hostIdentity: this.hostIdentity,
2574
+ bootSessionIdentity: this.bootSessionIdentity,
2575
+ containmentReason: this.containmentReason,
2576
+ });
2577
+ this.containmentCleanupCommitted = detail;
2578
+ this.closed = true;
2579
+ this.state = 'Closed';
2580
+ this._emitClose(1, null, detail);
2581
+ return detail;
2547
2582
  }
2548
2583
 
2549
2584
  _durabilityFailure(error) {
@@ -2884,8 +2919,7 @@ class CodexProcess extends Process {
2884
2919
  );
2885
2920
  }
2886
2921
  if (this.state === 'ContainmentFailed') {
2887
- this._scheduleContainedTransportClose();
2888
- return;
2922
+ return this._scheduleContainedTransportClose();
2889
2923
  }
2890
2924
  if (this.state === 'DurabilityBlocked') {
2891
2925
  this._scheduleContainedTransportClose();
@@ -2936,10 +2970,10 @@ class CodexProcess extends Process {
2936
2970
  this._emitClose(0, reason);
2937
2971
  }
2938
2972
 
2939
- _emitClose(code, reason = null) {
2973
+ _emitClose(code, reason = null, exactDetail = null) {
2940
2974
  if (this.closeEmitted) return;
2941
2975
  this.closeEmitted = true;
2942
- this.emit('close', code, {
2976
+ this.emit('close', code, exactDetail ?? {
2943
2977
  backend: this.backend,
2944
2978
  generationId: this.generationId,
2945
2979
  reason,
@@ -321,8 +321,8 @@ class ProcessManager {
321
321
 
322
322
  /**
323
323
  * Restore the persisted native-Codex ownership record before accepting any
324
- * Codex spawn. A quarantined record is released only by an explicit restore
325
- * on the same host with a different boot-session identity.
324
+ * Codex spawn. A quarantined record remains fenced until the caller has
325
+ * durably settled recovery and explicitly restores a clear record.
326
326
  *
327
327
  * @param {{status: 'clear'}|{
328
328
  * status: 'quarantined',
@@ -356,22 +356,12 @@ class ProcessManager {
356
356
  'ProcessManager: invalid quarantined codexRecoveryState',
357
357
  );
358
358
  }
359
- const sameHost = (
360
- isOpaqueId(this.codexHostIdentity)
361
- && state.hostIdentity === this.codexHostIdentity
362
- );
363
- const newBoot = (
364
- isOpaqueId(this.codexBootSessionIdentity)
365
- && state.bootSessionIdentity !== this.codexBootSessionIdentity
366
- );
367
359
  this._codexRecoveryReady = true;
368
- this._codexLease = sameHost && newBoot
369
- ? null
370
- : {
371
- kind: 'recovered-quarantine',
372
- generationId: state.generationId,
373
- quarantined: true,
374
- };
360
+ this._codexLease = {
361
+ kind: 'recovered-quarantine',
362
+ generationId: state.generationId,
363
+ quarantined: true,
364
+ };
375
365
  }
376
366
 
377
367
  _hasLiveCodexProcess() {
@@ -944,12 +934,17 @@ class ProcessManager {
944
934
  try {
945
935
  await this._strictRetire(old, 'runtime-switch');
946
936
  } catch (cause) {
937
+ const verificationFailed = Boolean(
938
+ findCodexRetirementVerificationError(cause),
939
+ );
947
940
  const retainExactFence = Boolean(
948
- findCodexRetirementVerificationError(cause)
941
+ oldIsCodex
949
942
  && this._codexLeaseMatches(old),
950
943
  );
951
- if (!retainExactFence) {
952
- this._retiring.delete(old);
944
+ if (!verificationFailed) this._retiring.delete(old);
945
+ if (retainExactFence) {
946
+ if (!this.procs.has(sessionKey)) this.procs.set(sessionKey, old);
947
+ } else {
953
948
  if (
954
949
  reservation
955
950
  && !transferredLease
@@ -1272,7 +1267,9 @@ class ProcessManager {
1272
1267
  try {
1273
1268
  await this._strictRetire(expectedProcess, reason);
1274
1269
  } catch (error) {
1275
- this._retiring.delete(expectedProcess);
1270
+ if (!findCodexRetirementVerificationError(error)) {
1271
+ this._retiring.delete(expectedProcess);
1272
+ }
1276
1273
  throw error;
1277
1274
  }
1278
1275
  if (this.procs.get(sessionKey) === expectedProcess) {
@@ -1292,13 +1289,14 @@ class ProcessManager {
1292
1289
  try {
1293
1290
  await this._strictRetire(proc, reason);
1294
1291
  } catch (error) {
1295
- if (
1296
- findCodexRetirementVerificationError(error)
1297
- && this._codexLeaseMatches(proc)
1298
- ) {
1292
+ const verificationFailed = Boolean(
1293
+ findCodexRetirementVerificationError(error),
1294
+ );
1295
+ if (!verificationFailed) this._retiring.delete(proc);
1296
+ if (this._codexLeaseMatches(proc)) {
1297
+ if (!this.procs.has(sessionKey)) this.procs.set(sessionKey, proc);
1299
1298
  throw error;
1300
1299
  }
1301
- this._retiring.delete(proc);
1302
1300
  if (proc.closed && this.procs.get(sessionKey) === proc) {
1303
1301
  this.procs.delete(sessionKey);
1304
1302
  } else if (!proc.closed && !this.procs.has(sessionKey)) {
@@ -1776,22 +1774,61 @@ class ProcessManager {
1776
1774
  }
1777
1775
  // 'close': process closed itself (iteration loop exited or
1778
1776
  // _closeQuery returned). Remove from the Map + signal LRU.
1779
- proc.on('close', () => {
1780
- if (
1781
- this._isCodex(proc)
1782
- && this._codexLeaseMatches(proc, capturedGeneration)
1783
- ) {
1777
+ proc.on('close', (...args) => {
1778
+ if (!this._isCodex(proc)) {
1779
+ if (
1780
+ !this._retiring.has(proc)
1781
+ && this.procs.get(proc.sessionKey) === proc
1782
+ ) {
1783
+ this.procs.delete(proc.sessionKey);
1784
+ }
1785
+ this._maybeSignalLruWaiter();
1786
+ return;
1787
+ }
1788
+ if (this._codexLeaseMatches(proc, capturedGeneration)) {
1784
1789
  // A generic close is only a transport fact. It never releases the
1785
1790
  // ownership fence by itself.
1786
1791
  this._codexLease.transportClosed = true;
1787
1792
  }
1788
- if (
1789
- !this._retiring.has(proc)
1790
- && this.procs.get(proc.sessionKey) === proc
1791
- ) {
1792
- this.procs.delete(proc.sessionKey);
1793
+ const detail = args[1];
1794
+ const cleanupCommitted = proc.containmentCleanupCommitted;
1795
+ const exactCleanupClose = Boolean(
1796
+ detail
1797
+ && detail === cleanupCommitted
1798
+ && Object.isFrozen(detail)
1799
+ && detail.kind === 'containment-cleanup-committed'
1800
+ && detail.backend === 'codex'
1801
+ && detail.generationId === capturedGeneration
1802
+ && detail.hostIdentity === this.codexHostIdentity
1803
+ && detail.bootSessionIdentity === this.codexBootSessionIdentity
1804
+ );
1805
+ if (!exactCleanupClose) {
1806
+ this._maybeSignalLruWaiter();
1807
+ return;
1793
1808
  }
1794
- this._maybeSignalLruWaiter();
1809
+ const start = this._starting.get(proc.sessionKey) ?? null;
1810
+ const lease = this._codexLease;
1811
+ this._withLifecycleGate(proc.sessionKey, async () => {
1812
+ if (start) await Promise.resolve(start).catch(() => {});
1813
+ if (
1814
+ this._starting.has(proc.sessionKey)
1815
+ || this._retiring.has(proc)
1816
+ || this.procs.get(proc.sessionKey) !== proc
1817
+ || proc.generationId !== capturedGeneration
1818
+ || proc.containmentCleanupCommitted !== detail
1819
+ || proc.closed !== true
1820
+ || proc.state !== 'Closed'
1821
+ || this._codexLease !== lease
1822
+ || !this._codexLeaseMatches(proc, capturedGeneration)
1823
+ ) return;
1824
+ this.procs.delete(proc.sessionKey);
1825
+ this._codexLease = null;
1826
+ this._maybeSignalLruWaiter();
1827
+ }).catch((error) => {
1828
+ this.logger.error?.(
1829
+ `[pm:${proc.label}] Codex containment cleanup release failed: ${error.message}`,
1830
+ );
1831
+ });
1795
1832
  });
1796
1833
  // P0 #3: channels backend emits 'bridge-disconnected' when its socket to
1797
1834
  // the spawned bridge dies (claude crash, bridge crash, EOF). The disconnect
@@ -24,6 +24,11 @@
24
24
  'use strict';
25
25
 
26
26
  const fs = require('fs');
27
+ const {
28
+ CODEX_SUPERVISOR_GRACE_MS,
29
+ } = require('./codex/app-server-client');
30
+
31
+ const CLAIM_PID_FILE_THROWS_ON_SURVIVING_PREDECESSOR = true;
27
32
 
28
33
  /**
29
34
  * Boot-time orphan detection. Writes our PID to `pidPath`. If the
@@ -35,7 +40,14 @@ const fs = require('fs');
35
40
  *
36
41
  * @returns {{ priorPid: number|null, priorAction: string }}
37
42
  */
38
- function claimPidFile(pidPath, { logger = console, sigtermWaitMs = 2000 } = {}) {
43
+ function claimPidFile(
44
+ pidPath,
45
+ {
46
+ logger = console,
47
+ sigtermWaitMs = 2000,
48
+ sigkillWaitMs = 1000,
49
+ } = {},
50
+ ) {
39
51
  const ownPid = process.pid;
40
52
  let priorPid = null;
41
53
  let priorAction = 'no-prior';
@@ -74,9 +86,16 @@ function claimPidFile(pidPath, { logger = console, sigtermWaitMs = 2000 } = {})
74
86
  // Poll for actual death — SIGKILL is delivered async, the
75
87
  // kernel may take a tick to reap (esp. for detached children).
76
88
  const killStart = Date.now();
77
- while (Date.now() - killStart < 1000 && isAlive(parsed)) {
89
+ while (Date.now() - killStart < sigkillWaitMs && isAlive(parsed)) {
78
90
  sleepSync(20);
79
91
  }
92
+ if (isAlive(parsed)) {
93
+ const error = new Error(
94
+ `prior daemon PID ${parsed} remained alive after SIGKILL`,
95
+ );
96
+ error.code = 'PROCESS_GUARD_PREDECESSOR_ALIVE';
97
+ throw error;
98
+ }
80
99
  priorAction = 'sigkill-killed';
81
100
  } else {
82
101
  priorAction = 'sigterm-killed';
@@ -288,6 +307,8 @@ function sleepSync(ms) {
288
307
  }
289
308
 
290
309
  module.exports = {
310
+ CLAIM_PID_FILE_THROWS_ON_SURVIVING_PREDECESSOR,
311
+ CODEX_SUPERVISOR_GRACE_MS,
291
312
  claimPidFile,
292
313
  releasePidFile,
293
314
  installSafetyHandlers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.6",
3
+ "version": "0.10.8",
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",