@shumkov/orchestra 0.7.0 → 0.7.1

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.
@@ -28,6 +28,7 @@ const execFileAsync = promisify(execFile);
28
28
  const CONTROLLED_PATH = '/usr/bin:/bin';
29
29
  const SUPERVISOR_PATH = path.join(__dirname, 'app-server-supervisor.mjs');
30
30
  const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
31
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
31
32
  const DEFAULT_CLOSE_GRACE_MS = 1_000;
32
33
  const DEFAULT_CLOSE_KILL_MS = 1_000;
33
34
  const DEFAULT_MAX_LINE_BYTES = 1024 * 1024;
@@ -411,6 +412,17 @@ function assertPositiveInteger(value, label) {
411
412
  }
412
413
  }
413
414
 
415
+ // Beyond this a delay silently collapses to ~1ms instead of waiting, which
416
+ // would turn a long close budget into no budget at all.
417
+ function assertTimerDelay(value, label) {
418
+ assertPositiveInteger(value, label);
419
+ if (value > MAX_TIMER_DELAY_MS) {
420
+ throw new TypeError(
421
+ `CodexAppServerClient: ${label} must not exceed ${MAX_TIMER_DELAY_MS}`,
422
+ );
423
+ }
424
+ }
425
+
414
426
  function isWithin(root, candidate) {
415
427
  const relative = path.relative(root, candidate);
416
428
  return (
@@ -1725,6 +1737,17 @@ class CodexAppServerClient extends EventEmitter {
1725
1737
  [sinkTimeoutMs, 'sinkTimeoutMs'],
1726
1738
  [closeGraceMs, 'closeGraceMs'],
1727
1739
  [closeKillMs, 'closeKillMs'],
1740
+ ]) {
1741
+ assertTimerDelay(value, label);
1742
+ }
1743
+ // close waits out the supervisor's whole escalation in one timer.
1744
+ if (closeGraceMs + closeKillMs > MAX_TIMER_DELAY_MS) {
1745
+ throw new TypeError(
1746
+ 'CodexAppServerClient: closeGraceMs + closeKillMs must not exceed '
1747
+ + `${MAX_TIMER_DELAY_MS}`,
1748
+ );
1749
+ }
1750
+ for (const [value, label] of [
1728
1751
  [maxLineBytes, 'maxLineBytes'],
1729
1752
  [maxStderrBytes, 'maxStderrBytes'],
1730
1753
  [maxPendingRequests, 'maxPendingRequests'],
@@ -1805,7 +1828,12 @@ class CodexAppServerClient extends EventEmitter {
1805
1828
  this.state = 'starting';
1806
1829
  const args = ['app-server', '--strict-config', '--stdio'];
1807
1830
  const command = process.execPath;
1808
- const commandArgs = [SUPERVISOR_PATH, this.binary, ...args];
1831
+ const commandArgs = [
1832
+ SUPERVISOR_PATH,
1833
+ `--group-term-grace-ms=${this.closeGraceMs}`,
1834
+ this.binary,
1835
+ ...args,
1836
+ ];
1809
1837
  try {
1810
1838
  const [attestation, homeAttestation] = await Promise.all([
1811
1839
  this.attestBinaryFn(this.binary),
@@ -2733,23 +2761,6 @@ class CodexAppServerClient extends EventEmitter {
2733
2761
  );
2734
2762
  }
2735
2763
 
2736
- _signalOwnedTree(signal) {
2737
- if (!this._childAlive()) return false;
2738
- if (
2739
- Number.isSafeInteger(this.child.pid)
2740
- && this.child.pid >= 2
2741
- ) {
2742
- try {
2743
- this.killFn(-this.child.pid, signal);
2744
- return true;
2745
- } catch (error) {
2746
- if (error?.code === 'ESRCH') return false;
2747
- throw error;
2748
- }
2749
- }
2750
- return this.child.kill(signal);
2751
- }
2752
-
2753
2764
  _waitForExit(timeoutMs) {
2754
2765
  let timer;
2755
2766
  return Promise.race([
@@ -2768,42 +2779,45 @@ class CodexAppServerClient extends EventEmitter {
2768
2779
  });
2769
2780
  }
2770
2781
 
2771
- async _ownedGroupMembers() {
2772
- if (!Number.isSafeInteger(this.child?.pid)) return [];
2773
- let stdout;
2774
- try {
2775
- ({ stdout } = await execFileAsync('/bin/ps', ['-axo', 'pid=,pgid='], {
2776
- encoding: 'utf8',
2777
- timeout: Math.max(100, this.closeGraceMs),
2778
- maxBuffer: 1024 * 1024,
2779
- env: { PATH: CONTROLLED_PATH },
2780
- }));
2781
- } catch (error) {
2782
- throw new CodexAppServerError(
2783
- 'could not inspect the owned app-server process group',
2784
- 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
2785
- { cause: error },
2786
- );
2787
- }
2788
- return stdout
2789
- .split('\n')
2790
- .map((line) => line.trim().split(/\s+/).map(Number))
2791
- .filter(([pid, pgid]) => (
2792
- Number.isSafeInteger(pid)
2793
- && Number.isSafeInteger(pgid)
2794
- && pgid === this.child.pid
2795
- ))
2796
- .map(([pid]) => pid);
2782
+ _ownsProcessGroup() {
2783
+ return Number.isSafeInteger(this.child?.pid) && this.child.pid >= 2;
2797
2784
  }
2798
2785
 
2799
- async _waitForOnlySupervisor(timeoutMs) {
2786
+ _cleanupUnverified(message, cause) {
2787
+ return new CodexAppServerError(
2788
+ message,
2789
+ 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
2790
+ cause ? { cause } : undefined,
2791
+ );
2792
+ }
2793
+
2794
+ // Runs only after the supervisor has exited, and only ever reads: a group id
2795
+ // whose leader is gone may be recycled, so signalling it could reach an
2796
+ // unrelated process group. ESRCH is the sole proof that the group is empty.
2797
+ async _proveOwnedGroupEmpty(timeoutMs) {
2798
+ if (!this._ownsProcessGroup()) {
2799
+ throw this._cleanupUnverified(
2800
+ 'could not prove the owned app-server process group is empty',
2801
+ );
2802
+ }
2800
2803
  const deadline = Date.now() + timeoutMs;
2801
- while (this._childAlive() && Date.now() < deadline) {
2802
- const members = await this._ownedGroupMembers();
2803
- if (members.length === 1 && members[0] === this.child.pid) return true;
2804
+ for (;;) {
2805
+ try {
2806
+ this.killFn(-this.child.pid, 0);
2807
+ } catch (error) {
2808
+ if (error?.code === 'ESRCH') return;
2809
+ throw this._cleanupUnverified(
2810
+ 'could not read the owned app-server process group',
2811
+ error,
2812
+ );
2813
+ }
2814
+ if (Date.now() >= deadline) {
2815
+ throw this._cleanupUnverified(
2816
+ 'the owned app-server process group still holds processes',
2817
+ );
2818
+ }
2804
2819
  await this._delay(Math.min(20, Math.max(1, deadline - Date.now())));
2805
2820
  }
2806
- return false;
2807
2821
  }
2808
2822
 
2809
2823
  close() {
@@ -2822,33 +2836,27 @@ class CodexAppServerClient extends EventEmitter {
2822
2836
  ));
2823
2837
  let cleanupError = null;
2824
2838
  if (this._childAlive()) {
2839
+ // Ending stdin is the whole shutdown request. Terminating the owned group
2840
+ // belongs to the supervisor: only the group's live leader can signal it
2841
+ // without racing its own exit and hitting a recycled group id.
2825
2842
  try { this.child.stdin.end(); } catch {}
2826
- this._signalOwnedTree('SIGTERM');
2827
- let onlySupervisor = false;
2828
- try {
2829
- onlySupervisor = await this._waitForOnlySupervisor(this.closeGraceMs);
2830
- } catch (error) {
2831
- cleanupError = error;
2832
- }
2833
- if (onlySupervisor && this._childAlive()) {
2834
- try {
2835
- this.killFn(this.child.pid, 'SIGUSR1');
2836
- } catch (error) {
2837
- if (error?.code !== 'ESRCH') cleanupError ??= error;
2838
- }
2839
- await this._waitForExit(this.closeKillMs);
2840
- }
2841
- }
2842
- if (this._childAlive()) {
2843
- this._signalOwnedTree('SIGKILL');
2844
- await this._waitForExit(this.closeKillMs);
2843
+ await this._waitForExit(this.closeGraceMs + this.closeKillMs);
2845
2844
  }
2846
2845
  if (this._childAlive()) {
2847
2846
  throw new CodexAppServerError(
2848
- 'app-server child survived kill escalation',
2847
+ 'app-server supervisor did not terminate the owned process group',
2849
2848
  'CODEX_PROCESS_CLOSE_TIMEOUT',
2850
2849
  );
2851
2850
  }
2851
+ // Nothing was ever spawned before a pre-spawn fault, so there is no owned
2852
+ // group to account for.
2853
+ if (this.child) {
2854
+ try {
2855
+ await this._proveOwnedGroupEmpty(this.closeKillMs);
2856
+ } catch (error) {
2857
+ cleanupError ??= error;
2858
+ }
2859
+ }
2852
2860
  this.stdoutBuffer = '';
2853
2861
  this.state = 'closed';
2854
2862
  if (!this.protocolError) this.resolveFaultWait(null);
@@ -1,7 +1,12 @@
1
1
  import { spawn } from 'node:child_process';
2
2
 
3
- const [binary, ...args] = process.argv.slice(2);
4
- if (!binary) process.exit(64);
3
+ const GRACE_FLAG = '--group-term-grace-ms=';
4
+ const argv = process.argv.slice(2);
5
+ const graceMs = argv[0]?.startsWith(GRACE_FLAG)
6
+ ? Number(argv.shift().slice(GRACE_FLAG.length))
7
+ : Number.NaN;
8
+ const [binary, ...args] = argv;
9
+ if (!binary || !Number.isSafeInteger(graceMs) || graceMs < 0) process.exit(64);
5
10
 
6
11
  const child = spawn(binary, args, {
7
12
  cwd: process.cwd(),
@@ -9,33 +14,81 @@ const child = spawn(binary, args, {
9
14
  stdio: ['pipe', 'pipe', 'pipe'],
10
15
  });
11
16
 
12
- process.stdin.pipe(child.stdin);
13
- child.stdout.pipe(process.stdout, { end: false });
14
- child.stderr.pipe(process.stderr, { end: false });
15
- child.stdin.on('error', () => {});
17
+ let childGone = false;
18
+ let terminating = false;
19
+ let graceTimer = null;
16
20
 
17
- let childExited = false;
18
- let outputEnded = false;
21
+ // Signalling our own group is safe precisely because we are its live leader:
22
+ // unlike the parent, we cannot have exited between deciding to signal and
23
+ // signalling, so the group id cannot have been recycled underneath the call.
24
+ function signalOwnGroup(signal) {
25
+ try { process.kill(-process.pid, signal); } catch {}
26
+ }
19
27
 
20
- function finishChild() {
21
- if (childExited) return;
22
- childExited = true;
23
- if (!outputEnded) {
24
- outputEnded = true;
25
- process.stdout.end();
28
+ // SIGKILL reaches this process too, so it is the last thing we do. The exit is
29
+ // only reached if the signal could not be sent, and the parent's read-only
30
+ // proof is what catches that.
31
+ function terminateGroup() {
32
+ if (graceTimer !== null) {
33
+ clearTimeout(graceTimer);
34
+ graceTimer = null;
26
35
  }
36
+ signalOwnGroup('SIGKILL');
37
+ process.exit(0);
27
38
  }
28
39
 
29
- child.once('error', finishChild);
30
- child.once('close', finishChild);
31
- child.stdout.once('error', finishChild);
32
- child.stderr.once('error', finishChild);
40
+ function shutdown() {
41
+ if (terminating) return;
42
+ terminating = true;
43
+ if (childGone) {
44
+ terminateGroup();
45
+ return;
46
+ }
47
+ signalOwnGroup('SIGTERM');
48
+ graceTimer = setTimeout(terminateGroup, graceMs);
49
+ }
33
50
 
34
- // The supervisor remains the owned process-group leader while the parent
35
- // verifies that Codex and every descendant have left the group.
36
- process.on('SIGTERM', () => {});
37
- process.on('SIGUSR1', () => {
38
- if (childExited) process.exit(0);
51
+ // Piped, so the app-server's own read rate applies backpressure to ours. The
52
+ // pipe must not end the child's stdin for us, because we end it deliberately
53
+ // on EOF below.
54
+ process.stdin.pipe(child.stdin, { end: false });
55
+
56
+ // The parent ending stdin — or dying — is the shutdown request. The parent
57
+ // never signals the group, so this is the only path that ends it. Ending the
58
+ // child's stdin hands the app-server its own EOF alongside the group signal.
59
+ function onParentStdinEnd() {
60
+ try { child.stdin.end(); } catch {}
61
+ shutdown();
62
+ }
63
+
64
+ process.stdin.once('end', onParentStdinEnd);
65
+ process.stdin.once('close', onParentStdinEnd);
66
+
67
+ child.stdout.pipe(process.stdout, { end: false });
68
+ child.stderr.pipe(process.stderr, { end: false });
69
+ child.stdin.on('error', () => {});
70
+ child.stdout.once('error', () => {});
71
+ child.stderr.once('error', () => {});
72
+ // 'error' can arrive post-spawn — an abort, a failed kill, a failed message
73
+ // send — while the child is still running, so it proves nothing. 'close' is the
74
+ // only report of a gone child, and a failed spawn closes too.
75
+ child.once('error', () => {});
76
+
77
+ child.once('close', () => {
78
+ childGone = true;
79
+ // The pipe does not detach itself from a dead child's stdin, and while it
80
+ // stays attached our stdin never surfaces EOF — which would lose the only
81
+ // shutdown signal we have whenever the app-server exits before the parent
82
+ // closes, stranding us as a permanent group leader. Detaching by hand and
83
+ // resuming restores that; with the child gone the drained bytes have nowhere
84
+ // to go and are discarded.
85
+ process.stdin.unpipe(child.stdin);
86
+ process.stdin.resume();
87
+ process.stdout.end();
88
+ if (terminating) terminateGroup();
39
89
  });
40
90
 
91
+ // We must outlive the group we lead, so we ignore the TERM we send it.
92
+ process.on('SIGTERM', () => {});
93
+
41
94
  setInterval(() => {}, 60_000);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
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",