benignswarm 0.12.145 → 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":
@@ -97,15 +97,28 @@ export async function me(p, out) {
97
97
  }
98
98
  export async function who(p, out) {
99
99
  const { client, creds } = agentClient(p);
100
+ const projectStalls = async (project) => {
101
+ const response = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?all=1`);
102
+ return (response.units ?? []).filter((unit) => unit.stalled).map((unit) => ({ number: unit.number, owner_name: unit.owner_name, age_minutes: unit.stalled.age_minutes, reason: unit.stalled.reason }));
103
+ };
104
+ const statusLines = (statuses, stalled) => statuses.map((status) => {
105
+ const owned = stalled.filter((unit) => unit.owner_name === status.agent_name);
106
+ return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.age_minutes} min · ${unit.reason}`).join("; ")}` : ""}`;
107
+ });
100
108
  if (bool(p.flags, "account") || (!creds.project && !str(p.flags, "project") && !process.env.BSCHAT_PROJECT)) {
101
109
  const r = await client.call("GET", "/account/agents/status");
102
110
  const acct = r.account.statuses.length ? `## account-wide agents\n${r.account.statuses.map(fmtStatus).join("\n")}\n\n` : "";
103
- const text = acct + r.projects.map((pr) => `## ${pr.project}\n${pr.statuses.length ? pr.statuses.map(fmtStatus).join("\n") : "(no agents have reported)"}`).join("\n\n");
104
- out.print(text, r);
111
+ const projects = await Promise.all(r.projects.map(async (pr) => {
112
+ const stalled = await projectStalls(pr.project);
113
+ return { ...pr, stalled_units: stalled, text: `## ${pr.project}\n${pr.statuses.length ? statusLines(pr.statuses, stalled).join("\n") : "(no agents have reported)"}` };
114
+ }));
115
+ const text = acct + projects.map((pr) => pr.text).join("\n\n");
116
+ out.print(text, { ...r, projects });
105
117
  return;
106
118
  }
107
119
  const r = await client.call("GET", `/projects/${projectOf(p, creds)}/agents/status`);
108
- out.print(r.statuses.length ? r.statuses.map(fmtStatus).join("\n") : "(no agents have reported status yet)", r);
120
+ const stalled = await projectStalls(projectOf(p, creds));
121
+ out.print(r.statuses.length ? statusLines(r.statuses, stalled).join("\n") : "(no agents have reported status yet)", { ...r, stalled_units: stalled });
109
122
  }
110
123
  export async function status(p, out) {
111
124
  const sub = p.positionals[1];
@@ -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") {
@@ -225,9 +225,38 @@ export async function gatherUpdates(name, opts) {
225
225
  const followed = [];
226
226
  const readCommands = [];
227
227
  const pendingReads = new Map();
228
+ const stalledLines = [];
229
+ const stalledNext = { ...(state.stalled_work_delivered ?? {}) };
230
+ const stalledRemoved = new Set();
228
231
  try {
229
232
  const projects = creds.project ? [creds.project] : ((await client.call("GET", "/me")).projects ?? []).map((x) => x.name);
230
233
  for (const project of projects) {
234
+ try {
235
+ const work = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?agent=${encodeURIComponent(creds.agent)}`);
236
+ const activeStalls = new Set();
237
+ for (const unit of (work.units ?? []).filter((item) => item.owner_name === creds.agent && item.stalled)) {
238
+ const key = `${project}/${unit.number}`;
239
+ activeStalls.add(key);
240
+ const episode = unit.stalled.since;
241
+ if (typeof episode !== "string" || !episode) {
242
+ process.stderr.write(`b9s: stalled work status for ${project} WU #${unit.number} has no episode timestamp\n`);
243
+ continue;
244
+ }
245
+ if (stalledNext[key] !== episode) {
246
+ stalledLines.push(` ${creds.project ? "" : `[${project}] `}WU #${unit.number}: stalled ${unit.stalled.age_minutes} min · ${unit.stalled.reason} — b9s wu show ${creds.project ? "" : `--project ${project} `}${unit.number}`);
247
+ stalledNext[key] = episode;
248
+ }
249
+ }
250
+ for (const key of Object.keys(stalledNext)) {
251
+ if (key.startsWith(`${project}/`) && !activeStalls.has(key)) {
252
+ delete stalledNext[key];
253
+ stalledRemoved.add(key);
254
+ }
255
+ }
256
+ }
257
+ catch (error) {
258
+ process.stderr.write(`b9s: stalled work status for ${project}: ${error.message}\n`);
259
+ }
231
260
  const since = Object.fromEntries(Object.entries(channelRead).filter(([k]) => k.startsWith(`${project}/`)).map(([k, v]) => [k.slice(project.length + 1), v]));
232
261
  const sinceQuery = Object.keys(since).length ? `?since=${encodeURIComponent(JSON.stringify(since))}` : "";
233
262
  const { cursors } = await client.call("GET", `/projects/${project}/channels/cursors${sinceQuery}`);
@@ -311,13 +340,21 @@ export async function gatherUpdates(name, opts) {
311
340
  // Never backwards: another reader may have surfaced later messages meanwhile.
312
341
  ...(newest && (!onDisk[cursorField] || onDisk[cursorField] < newest) ? { [cursorField]: newest } : {}),
313
342
  ...(nextMeasureState !== null ? { measure_state: nextMeasureState } : {}),
343
+ ...(!opts.dryRun ? { stalled_work_delivered: stalledNext } : {}),
314
344
  channel_read: { ...(onDisk.channel_read ?? {}), ...Object.fromEntries(moved) },
315
345
  ...(pending ? { pending_reads: pending } : {}),
316
346
  ...(noticeChanges ? { notice_state: noticeChanges.next } : {}),
317
347
  };
318
348
  });
319
349
  }
320
- if (!messages.length && !questions.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length)
350
+ if (opts.dryRun && stalledRemoved.size)
351
+ updateState(name, (onDisk) => {
352
+ const delivered = { ...(onDisk.stalled_work_delivered ?? {}) };
353
+ for (const key of stalledRemoved)
354
+ delete delivered[key];
355
+ return { ...onDisk, stalled_work_delivered: delivered };
356
+ });
357
+ if (!messages.length && !questions.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length && !stalledLines.length)
321
358
  return null;
322
359
  const lines = messages.map((m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`);
323
360
  const questionLines = questions.slice(0, 4).map((q) => ` ${q.project} #${q.channel} seq ${q.seq} from ${q.from} (${q.age_minutes} min ago): ${q.question} — ${q.next}`);
@@ -335,6 +372,7 @@ export async function gatherUpdates(name, opts) {
335
372
  followed.length ? `new messages in followed channels` : null,
336
373
  digest.length ? `unread channels` : null,
337
374
  noticeLines.length ? `${noticeLines.length} notice change${noticeLines.length === 1 ? "" : "s"}` : null,
375
+ stalledLines.length ? `${stalledLines.length} stalled work unit${stalledLines.length === 1 ? "" : "s"}` : null,
338
376
  measureLines.length ? `${measureLines.length} outcome measure change${measureLines.length === 1 ? "" : "s"}` : null,
339
377
  ].filter(Boolean).join(", ");
340
378
  const proj = creds.project ? "" : "--project <project> ";
@@ -359,7 +397,8 @@ export async function gatherUpdates(name, opts) {
359
397
  const directPointer = firstDeferred ? inboxPointer : "b9s inbox --unread";
360
398
  const itemPointer = firstItemDeferred ? inboxPointer : "b9s inbox --unread";
361
399
  const followedPointer = pendingReads.size ? "b9s read --pending" : readCommands.join("; ") || "b9s read --pending";
362
- const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, direct_ids: messages.flatMap((message) => message.role_name === "human" ? [] : [String(message.id)]), directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
400
+ const stalledBlock = stalledLines.length ? [`Your stalled work units; see their wait and next actor:`, ...stalledLines] : [];
401
+ const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...stalledBlock, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, direct_ids: messages.flatMap((message) => message.role_name === "human" ? [] : [String(message.id)]), directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
363
402
  const delivery = budgetDelivery(parts);
364
403
  const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
365
404
  const visibleReadCommands = readCommands.slice(0, 8);
@@ -368,7 +407,7 @@ export async function gatherUpdates(name, opts) {
368
407
  const cmds = [...(messages.length || questions.length || items.length ? ["b9s inbox --unread"] : []), ...visibleReadCommands];
369
408
  const escapedAgent = creds.agent.replace(/[-_]/g, "\\$&");
370
409
  const isDirectMessage = (message) => message.role_name === "human" || !!message.reply_to_seq || message.mentions?.includes(creds.agent) || new RegExp(`(^|[^\\w@])@${escapedAgent}(?![\\w-])`).test(message.body);
371
- const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some(isDirectMessage);
410
+ const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || stalledLines.length > 0 || messages.some(isDirectMessage);
372
411
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
373
412
  const turnBindingCandidates = tier === "direct" ? messages.map((message, index) => ({
374
413
  id: String(message.id),
@@ -386,7 +425,7 @@ export async function gatherUpdates(name, opts) {
386
425
  const firstDirectAt = directTimes.sort()[0] ?? null;
387
426
  const urgent = messages.some((message) => message.urgent === true || message.priority === "urgent")
388
427
  || items.some((item) => item.urgent === true || item.priority === "urgent");
389
- return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, turn_binding_candidates: turnBindingCandidates, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
428
+ return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, stalledNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, turn_binding_candidates: turnBindingCandidates, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
390
429
  }
391
430
  /** Command patterns warn without blocking; errors remain visible to the caller. */
392
431
  export async function commandWarnings(name, command) {
@@ -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
+ }