benignswarm 0.12.146 → 0.12.147

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.
@@ -6,7 +6,7 @@ const INHERITED_OPTION_CONTRACTS = new Map([["codex start", ["start"]]]);
6
6
  const PROJECT_COMMANDS = new Set([
7
7
  "notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
8
8
  "wu", "process", "record", "milestones", "milestone", "lock", "unlock", "locks", "ask", "ask-operator",
9
- "explain", "worktrees", "measures", "measure", "environment", "test-results",
9
+ "explain", "worktrees", "measures", "measure", "environment", "test-results", "ux", "gate",
10
10
  ]);
11
11
  function supportsProject(command) {
12
12
  return PROJECT_COMMANDS.has(command[0] ?? "") || (command[0] === "status" && command[1] === "history");
@@ -12,7 +12,7 @@ import { milestoneWith, milestonesWith } from "./wu.js";
12
12
  import { awayUntil } from "./agent.js";
13
13
  import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
14
14
  import { routingAdmin, runRequiredClassUpdate } from "./routing-admin.js";
15
- import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, textCheckAdmin, turnJudgeAdmin, worktreeAdmin } from "./operator.js";
15
+ import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, quotaPoolsAdmin, skillAdmin, tagList, textCheckAdmin, turnJudgeAdmin, worktreeAdmin } from "./operator.js";
16
16
  import { adminNotice } from "./notices.js";
17
17
  import { cloudAdmin } from "./cloud-admin.js";
18
18
  import { projectImageAdmin } from "./image-admin.js";
@@ -129,6 +129,8 @@ export async function admin(p, out) {
129
129
  return notifierAdmin(p, out);
130
130
  case "account":
131
131
  return accountAdmin(p, out, action, rest);
132
+ case "quota-pools":
133
+ return quotaPoolsAdmin(p, out);
132
134
  case "account-stores":
133
135
  return accountStoresAdmin(action, rest, p, out);
134
136
  case "turn-judgment":
@@ -14,7 +14,8 @@ import { readState, updateState } from "../state.js";
14
14
  import { join } from "./join.js";
15
15
  import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService, turnArgs, watch } from "./watch.js";
16
16
  import { randomUUID } from "node:crypto";
17
- import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
17
+ import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, inspectCurrentClaudeEgressCapability, probeFor } from "../harnesses.js";
18
+ import { allocateClaudeEgressPortPair, resolveTrustedControlPlaneOrigin, spawnClaudeEgressSupervised } from "../claude-egress-proxy.js";
18
19
  import { claudeTurnEnv } from "../providers.js";
19
20
  import { DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
20
21
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS } from "../turn.js";
@@ -22,6 +23,7 @@ import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS
22
23
  import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySessionTmpDir, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
23
24
  import { configureGitCredentialForWorktree } from "./git-credential.js";
24
25
  import { checkAndRecordHarnessBinary } from "../machine-binary.js";
26
+ import { clearSessionSecrets, normalizeAndValidateSecretHosts, parseSecretHostsJson, parseSecretKeyNamesJson, SECRET_DECLARED_HOSTS_VAR, SECRET_EGRESS_ENV_KEYS_VAR, wipeSecretMap, writeSessionSecrets, } from "../session-secrets.js";
25
27
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
26
28
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
27
29
  /** The guard states why it refuses. A refusal without a reason is still a refusal (no turn starts) and is reported as the defect it is. */
@@ -89,16 +91,51 @@ export async function harnessStart(p, out, harness) {
89
91
  if (machineSessionId)
90
92
  process.env.BSCHAT_MACHINE_SESSION_ID = machineSessionId;
91
93
  const inContainer = bool(p.flags, "in-container");
94
+ const incomingSecretKeys = parseSecretKeyNamesJson(process.env[SECRET_EGRESS_ENV_KEYS_VAR]);
95
+ const incomingDeclaredHosts = parseSecretHostsJson(process.env[SECRET_DECLARED_HOSTS_VAR]);
96
+ const projectSecretEnv = {};
97
+ for (const key of incomingSecretKeys) {
98
+ const val = process.env[key];
99
+ if (typeof val === "string")
100
+ projectSecretEnv[key] = val;
101
+ delete process.env[key];
102
+ }
103
+ delete process.env[SECRET_EGRESS_ENV_KEYS_VAR];
104
+ delete process.env[SECRET_DECLARED_HOSTS_VAR];
92
105
  let errorSlug = name;
93
106
  let watchArgv = null;
94
107
  let watcherEnv = {};
108
+ let sessionSecretKeyWritten = null;
109
+ let inContainerSecrets;
95
110
  try {
111
+ if ((incomingSecretKeys.length > 0 || incomingDeclaredHosts.length > 0) && (harness === "dsh" || harness === "antigravity")) {
112
+ throw new CliError(`secret_egress_unenforced_${harness}`, `${label} does not enforce per-session secret egress`);
113
+ }
114
+ if (harness === "claude-code" && (incomingSecretKeys.length > 0 || incomingDeclaredHosts.length > 0)) {
115
+ if (!incomingSecretKeys.length || !incomingDeclaredHosts.length) {
116
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code project secret delivery requires both declared hostnames and secret environment keys");
117
+ }
118
+ for (const key of incomingSecretKeys) {
119
+ if (!Object.prototype.hasOwnProperty.call(projectSecretEnv, key)) {
120
+ throw new CliError("session_secrets_unavailable", `missing secret value in launch environment for ${key}`);
121
+ }
122
+ }
123
+ }
96
124
  const sandbox = str(p.flags, "sandbox");
97
125
  // No default: what a headless agent may touch on this machine is the operator's call, every time.
98
126
  if (!sandbox || !SANDBOXES.includes(sandbox))
99
127
  throw new CliError("usage", `${cmd} needs --sandbox <${SANDBOXES.join("|")}>: what the agent may do on this machine, since a headless turn cannot ask for approval`);
100
128
  if (harness === "antigravity" && sandbox === "read-only")
101
129
  throw new CliError("unsupported", "Antigravity has no read-only permission mode; use workspace-write or danger-full-access");
130
+ if (harness === "claude-code" && (incomingSecretKeys.length > 0 || incomingDeclaredHosts.length > 0) && sandbox !== "workspace-write") {
131
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code project secret delivery requires --sandbox workspace-write");
132
+ }
133
+ if (harness === "claude-code" && (incomingSecretKeys.length > 0 || incomingDeclaredHosts.length > 0)) {
134
+ const localEgress = inspectCurrentClaudeEgressCapability();
135
+ if (!localEgress.enforced) {
136
+ throw new CliError("secret_egress_unenforced_claude-code", localEgress.reason ?? "Claude Code project secret egress domain policy is not verified for this runtime");
137
+ }
138
+ }
102
139
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
103
140
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
104
141
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
@@ -166,11 +203,12 @@ export async function harnessStart(p, out, harness) {
166
203
  const explicitWritable = repeated(p, "writable-root").map((w) => w.trim());
167
204
  const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
168
205
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
169
- let settings = harness === "codex"
206
+ const preflightSettings = harness === "codex"
170
207
  ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
171
208
  : harness === "dsh"
172
209
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
173
210
  : harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
211
+ let settings = preflightSettings;
174
212
  const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
175
213
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
176
214
  const lines = [];
@@ -190,6 +228,26 @@ export async function harnessStart(p, out, harness) {
190
228
  await configureGitCredentialForWorktree(process.cwd(), creds);
191
229
  if (creds.vendor && creds.vendor !== harness)
192
230
  throw new CliError("vendor_mismatch", `${ref} is saved as ${creds.vendor}, not ${harness}`);
231
+ let claudeSecretEgress;
232
+ if (harness === "claude-code" && incomingSecretKeys.length > 0) {
233
+ const declaredHosts = normalizeAndValidateSecretHosts(incomingDeclaredHosts, false);
234
+ try {
235
+ resolveTrustedControlPlaneOrigin({ apiUrl: creds.url, trustedControlPlaneUrl: creds.url });
236
+ }
237
+ catch (error) {
238
+ throw new CliError("secret_egress_invalid_hosts", error.message);
239
+ }
240
+ const { httpProxyPort, socksProxyPort } = await allocateClaudeEgressPortPair();
241
+ claudeSecretEgress = {
242
+ declaredHosts,
243
+ apiUrl: creds.url,
244
+ trustedControlPlaneUrl: creds.url,
245
+ provider,
246
+ httpProxyPort,
247
+ socksProxyPort,
248
+ };
249
+ settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, claudeSecretEgress);
250
+ }
193
251
  if (harness === "antigravity") {
194
252
  if (inContainer)
195
253
  provisionContainerInstallRecord();
@@ -218,6 +276,24 @@ export async function harnessStart(p, out, harness) {
218
276
  firstTurnLog = dshTurnLog(ref);
219
277
  if (harness === "antigravity")
220
278
  firstTurnLog = antigravityLog(ref);
279
+ const activateClaudeSecretSession = (claudeSessionId) => {
280
+ const key = machineSessionId ?? `claude-${claudeSessionId}`;
281
+ if (!inContainer && claudeSecretEgress) {
282
+ writeSessionSecrets({
283
+ sessionKey: key,
284
+ agent: ref,
285
+ harness: "claude-code",
286
+ declaredHosts: claudeSecretEgress.declaredHosts,
287
+ secretEnv: projectSecretEnv,
288
+ });
289
+ sessionSecretKeyWritten = key;
290
+ }
291
+ else if (!claudeSecretEgress) {
292
+ clearSessionSecrets(machineSessionId);
293
+ }
294
+ return key;
295
+ };
296
+ let secretSessionKey;
221
297
  if (adopt) {
222
298
  session = adopt.toLowerCase();
223
299
  if (harness === "codex") {
@@ -233,8 +309,9 @@ export async function harnessStart(p, out, harness) {
233
309
  if (!claudeTranscript(session))
234
310
  throw new CliError("not_found", `no Claude Code transcript for session ${session} under ~/.claude/projects on this machine`);
235
311
  if (sandbox === "workspace-write") {
236
- await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), randomUUID(), undefined, unproductivePerHour);
312
+ await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, preflightSettings, maxBudgetUsd, providerEnv, process.cwd(), randomUUID(), undefined, unproductivePerHour);
237
313
  }
314
+ secretSessionKey = activateClaudeSecretSession(session);
238
315
  lines.push(`Adopted Claude Code session ${session}. Do not resume it in a terminal while the watcher runs it: two clients on one session conflict.`);
239
316
  }
240
317
  else if (harness === "dsh") {
@@ -256,7 +333,7 @@ export async function harnessStart(p, out, harness) {
256
333
  // first real turn resumes this same checked session and receives a separate reservation below.
257
334
  if (harness === "claude-code" && sandbox === "workspace-write") {
258
335
  session = randomUUID();
259
- await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), session, undefined, unproductivePerHour);
336
+ await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, preflightSettings, maxBudgetUsd, providerEnv, process.cwd(), session, undefined, unproductivePerHour);
260
337
  }
261
338
  const logDir = joinPath(configRoot(), "logs");
262
339
  mkdirSync(logDir, { recursive: true });
@@ -294,7 +371,8 @@ export async function harnessStart(p, out, harness) {
294
371
  else {
295
372
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
296
373
  session ??= randomUUID();
297
- await startClaudeSession(bin, ["-p", prompt, ...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), ...claudeSessionStartArgs(sandbox, session), "--output-format", "json"], firstTurnLog, ref, session, providerEnv, model, provider);
374
+ secretSessionKey = activateClaudeSecretSession(session);
375
+ await startClaudeSession(bin, ["-p", prompt, ...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), ...claudeSessionStartArgs(sandbox, session), "--output-format", "json"], firstTurnLog, ref, session, providerEnv, model, provider, claudeSecretEgress ? projectSecretEnv : {}, claudeSecretEgress);
298
376
  lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
299
377
  }
300
378
  }
@@ -350,9 +428,13 @@ export async function harnessStart(p, out, harness) {
350
428
  const prune = bool(p.flags, "prune");
351
429
  watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
352
430
  const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
353
- ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd } } : {}),
431
+ ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd, ...(claudeSecretEgress ? { secretEgress: { declaredHosts: claudeSecretEgress.declaredHosts, apiUrl: creds.url, envKeys: incomingSecretKeys, ...(!inContainer && secretSessionKey ? { sessionKey: secretSessionKey } : {}) } } : {}) } } : {}),
354
432
  ...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable, tmpSessionKey: antigravityTmpSessionKey, tmpDir: antigravityTmp } } : {}),
355
433
  ...(machineSessionId ? { machineSessionId } : {}) };
434
+ if (inContainer && claudeSecretEgress) {
435
+ inContainerSecrets = { ...projectSecretEnv };
436
+ }
437
+ wipeSecretMap(projectSecretEnv);
356
438
  if (inContainer) {
357
439
  const sess = sessionOfExec(exec);
358
440
  if (sess)
@@ -422,6 +504,10 @@ export async function harnessStart(p, out, harness) {
422
504
  out.print(lines.join("\n"), startPayload);
423
505
  }
424
506
  catch (err) {
507
+ if (sessionSecretKeyWritten)
508
+ clearSessionSecrets(sessionSecretKeyWritten);
509
+ if (inContainerSecrets)
510
+ wipeSecretMap(inContainerSecrets);
425
511
  if (inContainer) {
426
512
  writeContainerStatusFile(containerStatusFile("error", errorSlug), {
427
513
  agent: errorSlug,
@@ -433,10 +519,13 @@ export async function harnessStart(p, out, harness) {
433
519
  }
434
520
  throw err;
435
521
  }
522
+ finally {
523
+ wipeSecretMap(projectSecretEnv);
524
+ }
436
525
  if (inContainer && watchArgv) {
437
526
  Object.assign(process.env, watcherEnv);
438
527
  try {
439
- await watch(parse(watchArgv), { json: false, print: () => { } });
528
+ await watch(parse(watchArgv), { json: false, print: () => { } }, inContainerSecrets ? { wakeOnceDependencies: { inMemorySecrets: inContainerSecrets } } : {});
440
529
  }
441
530
  catch (err) {
442
531
  writeContainerStatusFile(containerStatusFile("error", errorSlug), {
@@ -448,6 +537,10 @@ export async function harnessStart(p, out, harness) {
448
537
  });
449
538
  throw err;
450
539
  }
540
+ finally {
541
+ if (inContainerSecrets)
542
+ wipeSecretMap(inContainerSecrets);
543
+ }
451
544
  }
452
545
  }
453
546
  export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
@@ -494,19 +587,40 @@ export async function startDshSession(bin, args, logPath, agent, prompt) {
494
587
  * minutes; this command does not wait for it) and returns once its transcript exists, or fails
495
588
  * with Claude Code's own error when it exits first.
496
589
  */
497
- async function startClaudeSession(bin, args, logPath, agent, session, providerEnv, model, provider) {
590
+ async function startClaudeSession(bin, args, logPath, agent, session, providerEnv, model, provider, secretEnv = {}, secretEgress) {
591
+ if (secretEgress && (!secretEgress.httpProxyPort || !secretEgress.socksProxyPort)) {
592
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret delivery requires an active outer egress proxy boundary");
593
+ }
498
594
  const fd = openSync(logPath, "w");
499
- const child = spawn(bin, args, {
500
- stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(),
501
- env: {
502
- ...process.env,
503
- BSCHAT_AGENT: agent,
504
- ...(model ? { BSCHAT_MODEL: model } : {}),
505
- BSCHAT_SESSION_ID: session,
506
- BSCHAT_PROVIDER: provider,
507
- ...providerEnv,
508
- },
509
- });
595
+ const childEnv = {
596
+ ...process.env,
597
+ BSCHAT_AGENT: agent,
598
+ ...(model ? { BSCHAT_MODEL: model } : {}),
599
+ BSCHAT_SESSION_ID: session,
600
+ BSCHAT_PROVIDER: provider,
601
+ ...providerEnv,
602
+ ...secretEnv,
603
+ };
604
+ const child = secretEgress
605
+ ? spawnClaudeEgressSupervised({
606
+ config: {
607
+ provider,
608
+ apiUrl: secretEgress.apiUrl ?? "https://api.benignswarm.org",
609
+ trustedControlPlaneUrl: secretEgress.trustedControlPlaneUrl ?? secretEgress.apiUrl ?? "https://api.benignswarm.org",
610
+ allowLoopbackControlPlaneForTests: secretEgress.allowLoopbackControlPlaneForTests,
611
+ declaredHosts: secretEgress.declaredHosts,
612
+ httpProxyPort: secretEgress.httpProxyPort,
613
+ socksProxyPort: secretEgress.socksProxyPort,
614
+ mode: "exec",
615
+ bin,
616
+ args,
617
+ },
618
+ cwd: process.cwd(),
619
+ env: childEnv,
620
+ stdio: ["ignore", fd, fd],
621
+ detached: true,
622
+ })
623
+ : spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: childEnv });
510
624
  closeSync(fd);
511
625
  let exited = null;
512
626
  child.on("exit", (code) => { exited = code ?? 1; });
@@ -7,6 +7,7 @@ import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
7
7
  import { projectOf } from "./agent.js";
8
8
  import { CliError } from "../errors.js";
9
9
  import { table } from "../output.js";
10
+ import { consoleLink } from "../console-links.js";
10
11
  const TYPES = {
11
12
  ".txt": "text/plain", ".log": "text/plain", ".md": "text/markdown", ".json": "application/json", ".csv": "text/csv",
12
13
  ".html": "text/html", ".xml": "application/xml", ".yaml": "application/yaml", ".yml": "application/yaml",
@@ -83,7 +84,10 @@ export async function evidence(p, out) {
83
84
  const storedType = json?.evidence?.content_type;
84
85
  if (typeof storedType !== "string")
85
86
  throw new CliError("bad_response", "evidence upload response omitted evidence.content_type");
86
- out.print(`posted ${filename} (${bytes.length} bytes, content-type ${storedType}, sha256 ${sha})${json.deduplicated ? " [content already stored]" : ""}\nref: ${json.ref}\nmention it in chat as ${json.ref}`, json);
87
+ const evidenceId = typeof json.evidence?.id === "string" ? json.evidence.id : typeof json.ref === "string" ? json.ref.replace(/^evidence:/, "") : null;
88
+ if (!evidenceId)
89
+ throw new CliError("bad_response", "evidence upload response omitted evidence id");
90
+ out.print(`posted ${filename} (${bytes.length} bytes, content-type ${storedType}, sha256 ${sha})${json.deduplicated ? " [content already stored]" : ""}\nref: evidence:${evidenceId}\nConsole: ${consoleLink("evidence", project, evidenceId)}\nmention it in chat as evidence:${evidenceId}`, json);
87
91
  return;
88
92
  }
89
93
  if (sub === "list") {
@@ -0,0 +1,113 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { createReadStream, writeSync } from "node:fs";
3
+ import { constants } from "node:os";
4
+ const command = JSON.parse(process.argv[2] ?? "[]");
5
+ const send = (record) => {
6
+ try {
7
+ writeSync(4, Buffer.from(`${JSON.stringify(record)}\n`));
8
+ }
9
+ catch { /* The lock owner may have died; the command tree must still be stopped. */ }
10
+ };
11
+ let stopping = false;
12
+ let killTimer;
13
+ let spawnError;
14
+ let taskExitCode;
15
+ let task;
16
+ function groupExists(pid) {
17
+ if (!pid || process.platform === "win32")
18
+ return false;
19
+ try {
20
+ process.kill(-pid, 0);
21
+ return true;
22
+ }
23
+ catch (error) {
24
+ const code = error.code;
25
+ if (code === "ESRCH")
26
+ return false;
27
+ if (code === "EPERM")
28
+ return true;
29
+ throw error;
30
+ }
31
+ }
32
+ async function waitForGroupGone(pid, timeoutMs) {
33
+ const deadline = Date.now() + timeoutMs;
34
+ while (groupExists(pid) && Date.now() < deadline)
35
+ await new Promise((resolve) => setTimeout(resolve, 50));
36
+ return !groupExists(pid);
37
+ }
38
+ function signalTree(signal) {
39
+ if (!task?.pid)
40
+ return;
41
+ if (process.platform === "win32") {
42
+ const result = spawnSync("taskkill", ["/PID", String(task.pid), "/T", "/F"], { stdio: "ignore" });
43
+ if (result.error)
44
+ throw result.error;
45
+ return;
46
+ }
47
+ try {
48
+ process.kill(-task.pid, signal);
49
+ }
50
+ catch (error) {
51
+ if (error.code !== "ESRCH")
52
+ throw error;
53
+ }
54
+ }
55
+ function stopTree(signal = "SIGTERM") {
56
+ if (stopping)
57
+ return;
58
+ stopping = true;
59
+ signalTree(signal);
60
+ killTimer = setTimeout(() => signalTree("SIGKILL"), 5_000);
61
+ killTimer.unref?.();
62
+ }
63
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
64
+ process.on(signal, () => stopTree(signal));
65
+ const control = createReadStream("", { fd: 3 });
66
+ control.on("end", () => stopTree());
67
+ control.resume();
68
+ function finish(exitCode, startFailure) {
69
+ if (killTimer)
70
+ clearTimeout(killTimer);
71
+ control.destroy();
72
+ process.stdout.end(() => {
73
+ send({ type: "done", exit_code: exitCode, ...(startFailure ? { spawn_error: startFailure } : {}) });
74
+ // This process has verified its command group is gone; terminate the small
75
+ // supervisor even if inherited terminal handles remain open.
76
+ process.kill(process.pid, "SIGKILL");
77
+ });
78
+ }
79
+ if (!Array.isArray(command) || typeof command[0] !== "string" || command.length === 0) {
80
+ send({ type: "spawn_error", message: "missing command" });
81
+ finish(127, "missing command");
82
+ }
83
+ else {
84
+ task = spawn(command[0], command.slice(1), {
85
+ stdio: ["inherit", "pipe", "pipe"],
86
+ detached: process.platform !== "win32",
87
+ });
88
+ task.stdout?.pipe(process.stdout);
89
+ task.stderr?.pipe(process.stderr);
90
+ task.once("error", (error) => { spawnError = error; taskExitCode = 127; });
91
+ task.once("exit", (code, signal) => {
92
+ // Stop any detached descendants that remain in the command's process group.
93
+ if (process.platform !== "win32" && groupExists(task?.pid))
94
+ stopTree();
95
+ taskExitCode = spawnError ? 127 : (code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0));
96
+ if (spawnError)
97
+ send({ type: "spawn_error", message: spawnError.message });
98
+ });
99
+ task.once("close", async () => {
100
+ const pid = task?.pid;
101
+ if (pid && process.platform !== "win32" && groupExists(pid)) {
102
+ stopTree();
103
+ if (!await waitForGroupGone(pid, 5_000)) {
104
+ signalTree("SIGKILL");
105
+ if (!await waitForGroupGone(pid, 5_000)) {
106
+ process.stderr.write("b9s: command descendants remain after SIGKILL; retaining the lock supervisor\n");
107
+ return;
108
+ }
109
+ }
110
+ }
111
+ finish(taskExitCode ?? (spawnError ? 127 : 1), spawnError?.message);
112
+ });
113
+ }