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.
@@ -2,8 +2,10 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
3
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
- import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
5
+ import { claudeSettings, probeFor, terminateClaudeSessionProcesses, turnHarness } from "../harnesses.js";
6
+ import { allocateClaudeEgressPortPair, buildClaudeEgressSupervisedShellCommand, resolveTrustedControlPlaneOrigin } from "../claude-egress-proxy.js";
6
7
  import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySessionTmpDir, antigravitySettings, finishAntigravityScratchCleanup, parseAntigravityTurnRuntime } from "../antigravity.js";
8
+ import { clearSessionSecrets, normalizeAndValidateSecretHosts, readSessionSecrets, wipeSecretMap } from "../session-secrets.js";
7
9
  import { cleanupAntigravitySandboxProbeRefs } from "../sandbox-probe.js";
8
10
  import { applyAck } from "./wake.js";
9
11
  import { launchdSessionTypeXml, lingerEnabled, machineDaemonPath, plistLaunchdDomain, loadSystemdUnit, readInstall, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
@@ -122,7 +124,34 @@ export async function watch(p, out, dependencies = {}) {
122
124
  || (value.maxBudgetUsd !== undefined && (typeof value.maxBudgetUsd !== "number" || !Number.isFinite(value.maxBudgetUsd) || value.maxBudgetUsd <= 0))) {
123
125
  throw new Error("invalid Claude turn runtime fields");
124
126
  }
125
- claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}) };
127
+ let secretEgress;
128
+ if (value.secretEgress !== undefined) {
129
+ if (value.sandbox !== "workspace-write")
130
+ throw new Error("secretEgress requires workspace-write sandbox");
131
+ if (!value.secretEgress || typeof value.secretEgress !== "object" || Array.isArray(value.secretEgress)) {
132
+ throw new Error("invalid secretEgress configuration");
133
+ }
134
+ const declaredHosts = normalizeAndValidateSecretHosts(value.secretEgress.declaredHosts, false);
135
+ if (!Array.isArray(value.secretEgress.envKeys) || value.secretEgress.envKeys.length < 1
136
+ || value.secretEgress.envKeys.some((k) => typeof k !== "string" || !/^[A-Z_][A-Z0-9_]{0,63}$/.test(k))) {
137
+ throw new Error("secretEgress.envKeys must list uppercase environment variable names");
138
+ }
139
+ if (value.secretEgress.apiUrl !== undefined) {
140
+ if (typeof value.secretEgress.apiUrl !== "string")
141
+ throw new Error("secretEgress.apiUrl must be a URL string");
142
+ new URL(value.secretEgress.apiUrl);
143
+ }
144
+ if (value.secretEgress.sessionKey !== undefined && (typeof value.secretEgress.sessionKey !== "string" || !value.secretEgress.sessionKey)) {
145
+ throw new Error("secretEgress.sessionKey must be a non-empty string");
146
+ }
147
+ secretEgress = {
148
+ declaredHosts,
149
+ envKeys: [...new Set(value.secretEgress.envKeys)],
150
+ ...(value.secretEgress.apiUrl ? { apiUrl: value.secretEgress.apiUrl } : {}),
151
+ ...(value.secretEgress.sessionKey ? { sessionKey: value.secretEgress.sessionKey } : {}),
152
+ };
153
+ }
154
+ claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}), ...(secretEgress ? { secretEgress } : {}) };
126
155
  }
127
156
  catch (error) {
128
157
  throw new CliError("usage", `--turn-claude-runtime must be valid Claude runtime JSON: ${error.message}`);
@@ -178,6 +207,9 @@ export async function watch(p, out, dependencies = {}) {
178
207
  return;
179
208
  stopping = true;
180
209
  stoppingCode = code;
210
+ if (dependencies.wakeOnceDependencies?.inMemorySecrets) {
211
+ wipeSecretMap(dependencies.wakeOnceDependencies.inMemorySecrets);
212
+ }
181
213
  releaseWatchLock?.();
182
214
  signalStop();
183
215
  // The harness command may be awaiting I/O that never settles. The lock is released first,
@@ -315,6 +347,12 @@ export async function watch(p, out, dependencies = {}) {
315
347
  log(`capability probe/report failed: ${e.message}`);
316
348
  }
317
349
  }
350
+ const secretCleanup = {
351
+ sessionKey: turn?.claudeRuntime?.secretEgress?.sessionKey ?? envSessionKey(turn?.machineSessionId),
352
+ claudeSession: turn?.harness === "claude-code" ? turn.session : undefined,
353
+ hasSecrets: Boolean(turn?.claudeRuntime?.secretEgress),
354
+ inMemorySecrets: dependencies.wakeOnceDependencies?.inMemorySecrets,
355
+ };
318
356
  if (!once && Date.now() - lastKeyCheck > KEY_CHECK_MS) {
319
357
  lastKeyCheck = Date.now();
320
358
  try {
@@ -322,12 +360,12 @@ export async function watch(p, out, dependencies = {}) {
322
360
  }
323
361
  catch (e) {
324
362
  if (e.code === "agent_benched") {
325
- stopBenchedWatcher(name, e.message, log);
363
+ stopBenchedWatcher(name, e.message, log, secretCleanup);
326
364
  finish(0);
327
365
  return stoppingCode;
328
366
  }
329
367
  if (e.code === "unauthorized") {
330
- stopRevokedWatcher(name, log);
368
+ stopRevokedWatcher(name, log, secretCleanup);
331
369
  finish(0);
332
370
  return stoppingCode;
333
371
  }
@@ -352,15 +390,20 @@ export async function watch(p, out, dependencies = {}) {
352
390
  }
353
391
  catch (e) {
354
392
  if (e.code === "agent_benched") {
355
- stopBenchedWatcher(name, e.message, log);
393
+ stopBenchedWatcher(name, e.message, log, secretCleanup);
356
394
  finish(0);
357
395
  return stoppingCode;
358
396
  }
359
397
  if (e.code === "unauthorized" && !once) {
360
- stopRevokedWatcher(name, log);
398
+ stopRevokedWatcher(name, log, secretCleanup);
361
399
  finish(0);
362
400
  return stoppingCode;
363
401
  }
402
+ if (e.code === "session_secrets_unavailable" && !once) {
403
+ log(`not starting turn: ${e.message}`);
404
+ await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
405
+ continue;
406
+ }
364
407
  if (e.code === "unit_worktree_diverged" && !once)
365
408
  log(e.message);
366
409
  else
@@ -379,12 +422,12 @@ export async function watch(p, out, dependencies = {}) {
379
422
  }
380
423
  catch (e) {
381
424
  if (e.code === "agent_benched") {
382
- stopBenchedWatcher(name, e.message, log);
425
+ stopBenchedWatcher(name, e.message, log, secretCleanup);
383
426
  finish(0);
384
427
  return stoppingCode;
385
428
  }
386
429
  if (e.code === "unauthorized") {
387
- stopRevokedWatcher(name, log);
430
+ stopRevokedWatcher(name, log, secretCleanup);
388
431
  finish(0);
389
432
  return stoppingCode;
390
433
  }
@@ -439,6 +482,19 @@ async function waitIntervalOrStop(ms, stopped) {
439
482
  if (timer)
440
483
  clearTimeout(timer);
441
484
  }
485
+ /**
486
+ * One numbered wake-up at a time. Each wake-up carries a sequence number and asks the agent to
487
+ * acknowledge it first (b9s wake ack <n>); until it does, nothing else is queued for it, for
488
+ * any reason. Learned from Codex: a harness delivers queued prompts only after its current turn,
489
+ * so the old rule (pending clears when the agent's read cursors move, an operator message or a
490
+ * timeout queues another) let six or seven wake-ups pile up behind a busy turn. Delivered back to
491
+ * back, they pulled sol-architect off its task and it stopped with the task unfinished. The
492
+ * cursors moved because the agent was reading while it worked, not because it saw the wake-up.
493
+ */
494
+ function envSessionKey(explicitSessionId) {
495
+ const id = explicitSessionId ?? process.env.BSCHAT_MACHINE_SESSION_ID;
496
+ return id && id.trim() ? id.trim() : undefined;
497
+ }
442
498
  /** Bind only when the server says this identity has exactly one active owner assignment. */
443
499
  export async function resolveWatcherWorkUnitBinding(name) {
444
500
  const creds = loadAgent(name);
@@ -880,9 +936,35 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
880
936
  }
881
937
  turnCwd = preparedWorktree?.path ?? process.cwd();
882
938
  }
939
+ let turnEgressRuntime;
940
+ if (turnSink && dependencies.claudeRuntime?.secretEgress) {
941
+ if (dependencies.claudeRuntime.sandbox !== "workspace-write" || !turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
942
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret-bearing turns require workspace-write settings expansion");
943
+ }
944
+ const enrolledUrl = loadAgent(name).url;
945
+ const requestedApiUrl = dependencies.claudeRuntime.secretEgress.apiUrl ?? enrolledUrl;
946
+ try {
947
+ resolveTrustedControlPlaneOrigin({ apiUrl: requestedApiUrl, trustedControlPlaneUrl: enrolledUrl });
948
+ }
949
+ catch (error) {
950
+ throw new CliError("secret_egress_invalid_hosts", error.message);
951
+ }
952
+ const { httpProxyPort, socksProxyPort } = await allocateClaudeEgressPortPair();
953
+ turnEgressRuntime = { httpProxyPort, socksProxyPort, apiUrl: requestedApiUrl, trustedControlPlaneUrl: enrolledUrl };
954
+ }
883
955
  if (turnSink && dependencies.claudeRuntime && turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
884
956
  const runtime = dependencies.claudeRuntime;
885
- const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined);
957
+ const secretEgress = runtime.secretEgress
958
+ ? {
959
+ declaredHosts: runtime.secretEgress.declaredHosts,
960
+ apiUrl: turnEgressRuntime.apiUrl,
961
+ trustedControlPlaneUrl: turnEgressRuntime.trustedControlPlaneUrl,
962
+ provider,
963
+ httpProxyPort: turnEgressRuntime.httpProxyPort,
964
+ socksProxyPort: turnEgressRuntime.socksProxyPort,
965
+ }
966
+ : undefined;
967
+ const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined, secretEgress);
886
968
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
887
969
  }
888
970
  if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
@@ -891,7 +973,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
891
973
  const args = antigravitySettings(runtime.sandbox, process.cwd(), configRoot(), runtime.apiHost, [...runtime.writableRoots, ...(preparedWorktree ? [preparedWorktree.path] : [])], runtime.b9sBin, runtime.nodeBin, name, preparedWorktree ?? undefined);
892
974
  turnExec = turnExec.replace(ANTIGRAVITY_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
893
975
  }
894
- if (!(await deliver(name, turnExec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId, workUnitBinding, workUnitBindingReason: bindingResolution?.reason ?? null, ...(turnCwd ? { cwd: turnCwd } : {}) }, allowTurn))) {
976
+ if (!(await deliver(name, turnExec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId, workUnitBinding, workUnitBindingReason: bindingResolution?.reason ?? null, ...(turnCwd ? { cwd: turnCwd } : {}), ...(dependencies.claudeRuntime?.secretEgress ? { secretEgress: dependencies.claudeRuntime.secretEgress, egressRuntime: turnEgressRuntime } : {}), ...(dependencies.inMemorySecrets ? { inMemorySecrets: dependencies.inMemorySecrets } : {}) }, allowTurn))) {
895
977
  debug("no wake: delivery failed or turn guard denied the launch");
896
978
  return { sent: false, recoveryBriefDelivered: false };
897
979
  }
@@ -925,6 +1007,9 @@ async function recoveryBriefText(name, log) {
925
1007
  const CLAUDE_SETTINGS_PLACEHOLDER = "__B9S_CLAUDE_TURN_SETTINGS__";
926
1008
  export async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, provider, model, turnStdin = false, beforeTurn, dependencies = {}, allowTurn) {
927
1009
  if (!exec) {
1010
+ if (dependencies.secretEgress) {
1011
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret-bearing delivery cannot run without an outer egress proxy turn command");
1012
+ }
928
1013
  process.stdout.write(wake + "\n");
929
1014
  return true;
930
1015
  }
@@ -941,18 +1026,69 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
941
1026
  const providerEnv = claudeTurnEnv(provider, turnModel, dependencies.providerRoot);
942
1027
  if (allowTurn && !(await allowTurn()))
943
1028
  return false;
1029
+ const turnSecretEnv = {};
1030
+ let launchCmd = cmd;
1031
+ const egressRunnerEnv = {};
1032
+ if (dependencies.secretEgress) {
1033
+ if (!dependencies.egressRuntime) {
1034
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code secret-bearing turns require an active outer egress proxy boundary");
1035
+ }
1036
+ if (dependencies.inMemorySecrets) {
1037
+ for (const key of dependencies.secretEgress.envKeys) {
1038
+ const val = dependencies.inMemorySecrets[key];
1039
+ if (typeof val !== "string") {
1040
+ throw new CliError("session_secrets_unavailable", `required project secret ${key} is no longer in session memory`);
1041
+ }
1042
+ turnSecretEnv[key] = val;
1043
+ }
1044
+ }
1045
+ else {
1046
+ const keyId = dependencies.secretEgress.sessionKey ?? envSessionKey();
1047
+ if (!keyId) {
1048
+ throw new CliError("session_secrets_unavailable", `missing session secret reference for ${name}`);
1049
+ }
1050
+ Object.assign(turnSecretEnv, readSessionSecrets({
1051
+ sessionKey: keyId,
1052
+ expectedAgent: name,
1053
+ expectedHarness: "claude-code",
1054
+ expectedKeys: dependencies.secretEgress.envKeys,
1055
+ expectedDeclaredHosts: dependencies.secretEgress.declaredHosts,
1056
+ }));
1057
+ }
1058
+ const runnerConfig = {
1059
+ provider: provider ?? "anthropic",
1060
+ apiUrl: dependencies.egressRuntime.apiUrl,
1061
+ trustedControlPlaneUrl: dependencies.egressRuntime.trustedControlPlaneUrl,
1062
+ declaredHosts: dependencies.secretEgress.declaredHosts,
1063
+ httpProxyPort: dependencies.egressRuntime.httpProxyPort,
1064
+ socksProxyPort: dependencies.egressRuntime.socksProxyPort,
1065
+ mode: "shell",
1066
+ shellCommand: cmd,
1067
+ };
1068
+ egressRunnerEnv.B9S_CLAUDE_EGRESS_RUNNER_CONFIG = JSON.stringify(runnerConfig);
1069
+ launchCmd = buildClaudeEgressSupervisedShellCommand();
1070
+ }
944
1071
  beforeTurn?.();
945
1072
  const launchedAt = new Date().toISOString();
946
1073
  const binding = dependencies.workUnitBinding ?? null;
947
1074
  updateState(name, (onDisk) => ({ ...onDisk, watch_turn_binding: { launched_at: launchedAt, started_at: null, work_unit_number: binding?.work_unit_number ?? null, assignment_event_id: binding?.assignment_event_id ?? null, reason: binding ? null : dependencies.workUnitBindingReason ?? "agent has no in-progress work unit" } }));
948
- const startedTurn = (dependencies.startTurn ?? startTurn)(cmd, {
949
- ...env,
950
- BSCHAT_AGENT: name,
951
- ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
952
- ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
953
- ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
954
- ...providerEnv,
955
- }, seq, turnStdin ? wake : undefined, binding, dependencies.cwd);
1075
+ let startedTurn;
1076
+ try {
1077
+ startedTurn = (dependencies.startTurn ?? startTurn)(launchCmd, {
1078
+ ...env,
1079
+ BSCHAT_AGENT: name,
1080
+ ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
1081
+ ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
1082
+ ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
1083
+ ...providerEnv,
1084
+ ...egressRunnerEnv,
1085
+ ...turnSecretEnv,
1086
+ }, seq, turnStdin ? wake : undefined, binding, dependencies.cwd);
1087
+ }
1088
+ finally {
1089
+ wipeSecretMap(turnSecretEnv);
1090
+ wipeSecretMap(egressRunnerEnv);
1091
+ }
956
1092
  const startedAt = Number.isFinite(startedTurn.startedMs) ? new Date(startedTurn.startedMs).toISOString() : launchedAt;
957
1093
  updateState(name, (onDisk) => {
958
1094
  const pending = onDisk.watch_turn_binding;
@@ -983,13 +1119,24 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
983
1119
  }
984
1120
  return true;
985
1121
  }
1122
+ function cleanupWatcherSecrets(cleanup) {
1123
+ if (!cleanup)
1124
+ return;
1125
+ if (cleanup.inMemorySecrets)
1126
+ wipeSecretMap(cleanup.inMemorySecrets);
1127
+ if (cleanup.sessionKey)
1128
+ clearSessionSecrets(cleanup.sessionKey);
1129
+ if (cleanup.hasSecrets && cleanup.claudeSession)
1130
+ terminateClaudeSessionProcesses(cleanup.claudeSession);
1131
+ }
986
1132
  /**
987
1133
  * The agent's key no longer works here: it was moved to another machine (b9s-admin agent move
988
1134
  * revokes every key not minted for the new one) or retired. Keys are only ever revoked on purpose,
989
1135
  * so this watcher stops for good and removes its own service; otherwise launchd or systemd would
990
1136
  * restart it into the same 401 forever. A daemon that still runs the agent here reinstalls it.
991
1137
  */
992
- function stopRevokedWatcher(name, log) {
1138
+ function stopRevokedWatcher(name, log, cleanup) {
1139
+ cleanupWatcherSecrets(cleanup);
993
1140
  const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
994
1141
  // By label, else by the --as it runs with: watchers installed before 0.9 carry labels without the
995
1142
  // project (org.benignswarm.watch.visualizer-creator), and missing them left a restart loop.
@@ -1000,7 +1147,8 @@ function stopRevokedWatcher(name, log) {
1000
1147
  if (svc)
1001
1148
  removeService(svc);
1002
1149
  }
1003
- function stopBenchedWatcher(name, reason, log) {
1150
+ function stopBenchedWatcher(name, reason, log, cleanup) {
1151
+ cleanupWatcherSecrets(cleanup);
1004
1152
  const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
1005
1153
  const bare = name.split("/").pop();
1006
1154
  const svc = watcherServices().find((s) => s.label === label)
@@ -122,10 +122,17 @@ export async function pruneProjectWorktrees(creds, project, cwd, protection, log
122
122
  }))];
123
123
  const probe = freeSpaceProbe(report.prunable.map((item) => item.path));
124
124
  let removed = 0;
125
+ let removedPathCount = 0;
126
+ const removedPaths = [];
125
127
  for (const candidate of report.prunable) {
126
128
  const result = removePrunable(candidate, cwd, undefined, protection.inUse, true);
127
- if (result.removed)
129
+ if (result.removed) {
128
130
  removed++;
131
+ removedPathCount++;
132
+ removedPaths.push(candidate.path);
133
+ if (removedPaths.length > 5)
134
+ removedPaths.shift();
135
+ }
129
136
  log(result.removed ? `pruned ${candidate.path}${candidate.branch ? ` (${candidate.branch})` : ""}` : `kept ${candidate.path}: ${result.reason}`);
130
137
  }
131
138
  const freeSpace = probe.after();
@@ -137,7 +144,7 @@ export async function pruneProjectWorktrees(creds, project, cwd, protection, log
137
144
  log(`post-prune worktree scan failed: ${error.message}`);
138
145
  }
139
146
  }
140
- return { project, repo: before.repo, removed, free_space: freeSpace, dirty_closed: dirtyClosed };
147
+ return { project, repo: before.repo, removed, paths: removedPaths, paths_count: removedPathCount, free_space: freeSpace, dirty_closed: dirtyClosed };
141
148
  }
142
149
  /**
143
150
  * The project's worktree registry.
@@ -20,6 +20,7 @@ import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompac
20
20
  import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
21
21
  import { formatStandingRuleSet } from "../standing-rules.js";
22
22
  import { projectOf } from "./agent.js";
23
+ import { consoleLink } from "../console-links.js";
23
24
  import { isAntigravityWorkspaceWrite } from "../antigravity.js";
24
25
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
25
26
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
@@ -997,6 +998,19 @@ export async function wu(p, out) {
997
998
  out.print(`${fmt(r.unit)}\n${actionResult}`, r);
998
999
  return;
999
1000
  }
1001
+ case "reviewer": {
1002
+ const replace = str(p.flags, "replace");
1003
+ const withName = str(p.flags, "with");
1004
+ const note = str(p.flags, "note");
1005
+ if (!replace?.trim() || !note?.trim()) {
1006
+ throw new CliError("usage", 'wu reviewer <n> --replace <agent> [--with <agent>] --note "why this reviewer is being replaced"');
1007
+ }
1008
+ const r = await client.call("POST", `${base}/${num()}/reviewer`, {
1009
+ replace: replace.trim(), ...(withName?.trim() ? { with: withName.trim() } : {}), note: note.trim(),
1010
+ });
1011
+ out.print(withRuleText(fmt(r.unit), r, "submit"), r);
1012
+ return;
1013
+ }
1000
1014
  case "approve":
1001
1015
  case "proceed":
1002
1016
  case "changes": {
@@ -1314,7 +1328,7 @@ export async function wu(p, out) {
1314
1328
  const recoveryText = recovery ? `\nRecovery: ${recovery.available ? `available (${recovery.size ?? "?"} bytes, sha256 ${recovery.sha256 ?? "?"})` : "not verified"}${recovery.expires_at ? `; expires ${recovery.expires_at}` : ""}${recovery.manifest?.skipped?.length ? `; skipped ${recovery.manifest.skipped.length} regenerable path(s)` : ""}${recovery.manifest?.omitted?.length ? `; ${recovery.manifest.omitted.length} uncaptured path(s), source volume remains protected` : ""}${recovery.available ? `; restore: b9s wu recovery restore ${r.unit.number}` : ""}` : "";
1315
1329
  const routingLines = formatUnitRoutingExplanation(r.unit);
1316
1330
  const routingText = routingLines.length ? `\nRouting:\n${routingLines.join("\n")}` : "";
1317
- out.print(`${fmt(r.unit)}${routingText}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
1331
+ out.print(`${fmt(r.unit)}\nConsole: ${consoleLink("work", project, r.unit.number)}${routingText}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
1318
1332
  return;
1319
1333
  }
1320
1334
  case "list":
@@ -1857,6 +1871,22 @@ export function lockWaiterActivity(waiter, nowMs) {
1857
1871
  const seconds = Math.floor(Math.max(0, nowMs - polledAt) / 1000);
1858
1872
  return ` · last poll ${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m`} ago`;
1859
1873
  }
1874
+ function lockHolderLabel(holder, nowMs) {
1875
+ return `slot ${holder.slot}: ${holder.name}${holder.unit ? ` (WU #${holder.unit})` : ""}${holder.legacy === 1 ? " (legacy, no token)" : holder.job_id ? ` job ${holder.job_id}` : ""}${holder.note ? `: ${holder.note}` : ""}${holder.acquired_at ? ` since ${holder.acquired_at.slice(11, 16)} UTC` : ""}${lockActivity({ running: holder.running, acquired_at: holder.acquired_at, holder_legacy: holder.legacy }, nowMs)}`;
1876
+ }
1877
+ export function lockSlotsLabel(lock, nowMs) {
1878
+ if (!Number.isInteger(lock.capacity) || lock.capacity < 2)
1879
+ return lock.holder_name
1880
+ ? `held by ${lock.holder_name}${lock.unit ? ` (WU #${lock.unit})` : ""}${lock.holder_legacy === 1 ? " (legacy, no token)" : lock.holder_job_id ? ` job ${lock.holder_job_id}` : ""}${lock.note ? `: ${lock.note}` : ""} since ${lock.acquired_at.slice(11, 16)} UTC${lockActivity(lock, nowMs)}`
1881
+ : "free";
1882
+ const holders = Array.isArray(lock.holders) ? lock.holders : [];
1883
+ const slots = Array.from({ length: lock.capacity }, (_, index) => {
1884
+ const slot = index + 1;
1885
+ const holder = holders.find((item) => item.slot === slot);
1886
+ return holder ? lockHolderLabel(holder, nowMs) : `slot ${slot}: free`;
1887
+ });
1888
+ return `${lock.capacity} slots [${slots.join("; ")}]`;
1889
+ }
1860
1890
  export async function lock(p, out) {
1861
1891
  const name = resolveAgentName(str(p.flags, "as"));
1862
1892
  const creds = loadAgent(name);
@@ -1866,7 +1896,7 @@ export async function lock(p, out) {
1866
1896
  const lockName = p.positionals[1];
1867
1897
  if (cmd === "locks") {
1868
1898
  const r = await client.call("GET", `/projects/${project}/locks`);
1869
- out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${l.holder_name ? `held by ${l.holder_name}${l.unit ? ` (WU #${l.unit})` : ""}${l.holder_legacy === 1 ? " (legacy, no token)" : l.holder_job_id ? ` job ${l.holder_job_id}` : ""}${l.note ? `: ${l.note}` : ""} since ${l.acquired_at.slice(11, 16)} UTC${lockActivity(l, Date.now())}` : "free"}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1899
+ out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${lockSlotsLabel(l, Date.now())}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1870
1900
  return;
1871
1901
  }
1872
1902
  if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
@@ -1881,7 +1911,7 @@ export async function lock(p, out) {
1881
1911
  const shared = bool(p.flags, "shared");
1882
1912
  const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
1883
1913
  const machine = defaultMachine();
1884
- const deps = processDeps((method, path, body) => client.call(method, path, body, { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
1914
+ const deps = processDeps((method, path, body) => client.call(method, path, body, path.endsWith('/output') ? { signal: AbortSignal.timeout(5000) } : { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
1885
1915
  try {
1886
1916
  process.exitCode = await runUnderLock({
1887
1917
  project, identity: agentRef(creds), projectSelection: creds.project ? undefined : project,
@@ -0,0 +1,17 @@
1
+ const CONSOLE_URL = "https://benignswarm.org";
2
+ /** Build the canonical console destination used when CLI output names a record. */
3
+ export function consoleLink(kind, project, id) {
4
+ const base = CONSOLE_URL;
5
+ if (kind === "work") {
6
+ if (!project)
7
+ throw new Error("A work-unit console link requires its project");
8
+ return `${base}/projects/${encodeURIComponent(project)}/work?unit=${encodeURIComponent(String(id))}`;
9
+ }
10
+ if (kind === "evidence") {
11
+ if (!project)
12
+ throw new Error("An evidence console link requires its project");
13
+ return `${base}/projects/${encodeURIComponent(project)}/evidence/${encodeURIComponent(String(id))}`;
14
+ }
15
+ const query = new URLSearchParams({ need: String(id) });
16
+ return `${base}${project ? `/projects/${encodeURIComponent(project)}` : ""}/needs?${query}`;
17
+ }