benignswarm 0.12.138 → 0.12.140

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.
package/dist/args.js CHANGED
@@ -34,7 +34,7 @@ export const STRING_FLAGS = [
34
34
  "drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
35
35
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
36
  "machine-session-id", "harness-binary", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
37
- "purpose", "storage-mode", "hosts", "arn", "version-id",
37
+ "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
38
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
40
  "metadata-file", "confirm-agent", "confirm-parked", "step",
@@ -44,10 +44,10 @@ export const BOOL_FLAGS = [
44
44
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
45
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
- "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
47
+ "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
49
49
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
50
- "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "no-commits-beyond-target",
50
+ "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target",
51
51
  ];
52
52
  export function parse(argv) {
53
53
  const options = {};
@@ -127,7 +127,7 @@ export async function admin(p, out) {
127
127
  case "notifier":
128
128
  return notifierAdmin(p, out);
129
129
  case "account":
130
- return accountAdmin(p, out);
130
+ return accountAdmin(p, out, action, rest);
131
131
  case "account-stores":
132
132
  return accountStoresAdmin(action, rest, p, out);
133
133
  case "turn-judgment":
@@ -1,11 +1,11 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { boundSessions } from "../sessions.js";
3
3
  import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statfsSync } from "node:fs";
4
- import { basename, delimiter, join } from "node:path";
4
+ import { basename, delimiter, dirname, join } from "node:path";
5
5
  import { homedir, platform } from "node:os";
6
6
  import { bool } from "../args.js";
7
7
  import { CliError } from "../errors.js";
8
- import { removeCopyCommand, binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, MACHINE_LABEL, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, watcherServices } from "../install.js";
8
+ import { removeCopyCommand, binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, MACHINE_LABEL, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, serviceUsesInstall, serviceUsesNode, watcherServices } from "../install.js";
9
9
  import { CLI_VERSION } from "../version.js";
10
10
  import { CODEX_REQUIREMENTS_PATH, codexHooksDuplicateWithManagedPolicy, reconcileCodexHooks, refreshInstalledHooks } from "../harness.js";
11
11
  import { configRoot } from "../config.js";
@@ -20,11 +20,18 @@ export async function install(p, out) {
20
20
  const want = p.positionals[1];
21
21
  if (want && !/^\d+\.\d+\.\d+$/.test(want))
22
22
  throw new CliError("usage", "install [<version> | --latest] e.g. b9s install --latest, b9s install 0.12.38");
23
- // Explicit install is the only command that may move the machine record to this Node's npm.
24
- const npm = ownNpm();
23
+ const move = bool(p.flags, "move-provisioned");
24
+ const reason = typeof p.flags.reason === "string" ? p.flags.reason.trim() : "";
25
+ if (prev?.provisioned && move && !reason)
26
+ throw new CliError("provisioned_move_reason_required", "moving a provisioned install requires --reason", "Use --move-provisioned --reason '<why>' only when deliberately changing this machine's Node");
27
+ const npm = prev?.provisioned && !move ? prev.npm : ownNpm();
25
28
  const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm) : CLI_VERSION);
26
- const rec = ensureInstall(version, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
29
+ const provisioned = !!(prev?.provisioned || bool(p.flags, "provisioned"));
30
+ const log = (m) => process.stderr.write(`b9s: ${m}\n`);
31
+ const rec = provisioned ? ensureInstall(version, log, npm, true, !!(prev?.provisioned && move)) : ensureInstall(version, log, npm);
27
32
  const lines = [`b9s ${rec.version} is this machine's install: ${rec.bin}`];
33
+ if (prev?.provisioned && move)
34
+ lines.push(`Provisioned Node moved by request: ${reason}`);
28
35
  const aliases = ensureCommandLinks(rec.bin);
29
36
  if (aliases.created.length)
30
37
  lines.push(`Updated PATH links: ${aliases.created.join(", ")}`);
@@ -173,6 +180,12 @@ export async function doctor(_p, out) {
173
180
  checks.push({ ok: false, what: `recorded install ${rec.bin} does not run`, fix: "npx -y benignswarm install" });
174
181
  else
175
182
  checks.push({ ok: true, what: `recorded install: ${rec.bin} (${recVersion})` });
183
+ if (rec?.provisioned) {
184
+ const expectedNode = join(homedir(), ".local", "node", "bin");
185
+ checks.push(dirname(rec.bin) === expectedNode && dirname(rec.npm) === expectedNode
186
+ ? { ok: true, what: `provisioned Node is pinned at ${expectedNode}` }
187
+ : { ok: false, what: `provisioned install is not using ${expectedNode}: b9s ${rec.bin}, npm ${rec.npm}`, fix: "re-run b9s-admin machine add or deliberately move with b9s install --move-provisioned --reason '<why>'" });
188
+ }
176
189
  // Every b9s on PATH, the one the shell finds first marked.
177
190
  const seen = new Set();
178
191
  const onPath = [];
@@ -279,15 +292,18 @@ export async function doctor(_p, out) {
279
292
  checks.push({ ok: false, what: "linger is off: systemd stops the watchers when your last login session on this machine ends", fix: "loginctl enable-linger $USER" });
280
293
  for (const w of services) {
281
294
  const args = w.args ?? [];
295
+ const serviceKind = w.label === MACHINE_LABEL ? "machine daemon" : "watcher";
282
296
  if (w.kind === "systemd") {
283
- const short = w.label.replace("org.benignswarm.watch.", "");
297
+ const short = w.label === MACHINE_LABEL ? "machine daemon" : w.label.replace("org.benignswarm.watch.", "");
284
298
  if (!args.length) {
285
299
  checks.push({ ok: false, what: `watcher ${short}: unreadable unit ${w.path}` });
286
300
  continue;
287
301
  }
288
302
  const ver = binVersion(args[0]);
289
- if (rec && args[0] !== rec.bin)
290
- checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --service (it uses the recorded install and reloads)" });
303
+ if (rec && !serviceUsesInstall(args[0], rec.bin))
304
+ checks.push({ ok: false, what: `${serviceKind} ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --service (it uses the recorded install and reloads)" });
305
+ if (rec?.provisioned && !serviceUsesNode(w.pathEnv, rec.bin))
306
+ checks.push({ ok: false, what: `${serviceKind} ${short} PATH does not select the recorded Node runtime`, fix: "re-run its b9s watch ... --service to capture the pinned Node PATH" });
291
307
  const active = (spawnSync("systemctl", ["--user", "is-active", `${w.label}.service`], { encoding: "utf8" }).stdout ?? "").trim();
292
308
  checks.push(active === "active" ? { ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` } : { ok: false, what: `watcher ${short} is ${active || "unknown"}; see ~/.b9s/logs/watch.${short}.err.log`, fix: `systemctl --user daemon-reload && systemctl --user restart ${w.label}.service` });
293
309
  continue;
@@ -305,8 +321,10 @@ export async function doctor(_p, out) {
305
321
  const pidNum = launchdPid(w.label);
306
322
  const pid = pidNum === null ? undefined : String(pidNum);
307
323
  const ver = binVersion(args[0]);
308
- if (rec && args[0] !== rec.bin)
309
- checks.push({ ok: false, what: `${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: isDaemon ? "run b9s machine service to rewrite and restart the daemon" : "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
324
+ if (rec && !serviceUsesInstall(args[0], rec.bin))
325
+ checks.push({ ok: false, what: `${serviceKind} ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: isDaemon ? "run b9s machine service to rewrite and restart the daemon" : "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
326
+ if (rec?.provisioned && !serviceUsesNode(w.pathEnv, rec.bin))
327
+ checks.push({ ok: false, what: `${serviceKind} ${short} PATH does not select the recorded Node runtime`, fix: "re-run its b9s watch ... --launchd to capture the pinned Node PATH" });
310
328
  if (listed.status !== 0) {
311
329
  checks.push({ ok: false, what: isDaemon ? "machine daemon is not loaded; see b9s machine status" : `${short} is not loaded`, fix: isDaemon ? "run b9s machine service to write and load the daemon service" : `launchctl bootstrap ${domain} ${w.path} (or delete the plist if the agent is gone)` });
312
330
  continue;
@@ -45,10 +45,7 @@ step() { echo "BSCHAT-STEP $1 $2 \${3:-}"; }
45
45
  fail() { step "$1" failed "$2"; exit 1; }
46
46
  mkdir -p "$HOME/.local/bin"
47
47
  case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH"; printf '\\nexport PATH="$HOME/.local/bin:$PATH" # b9s\\n' >> "$HOME/.profile"; step path done "added ~/.local/bin to ~/.profile" ;; esac
48
- major=0
49
- if command -v node >/dev/null 2>&1; then major=$(node -p 'process.versions.node.split(".")[0]'); fi
50
- if [ "$major" -ge 22 ]; then step node ok "$(node --version) $(command -v node)"
51
- else
48
+ {
52
49
  os=$(uname -s | tr A-Z a-z); case "$(uname -m)" in x86_64|amd64) a=x64 ;; aarch64|arm64) a=arm64 ;; *) fail node "unsupported CPU $(uname -m)" ;; esac
53
50
  base=https://nodejs.org/dist/latest-v24.x
54
51
  f=$(curl -fsSL $base/SHASUMS256.txt | awk -v want="node-v[0-9.]*-$os-$a.tar.xz" '$2 ~ "^"want"$" {print $2}') || fail node "cannot reach nodejs.org"
@@ -58,12 +55,13 @@ else
58
55
  rm -rf "$HOME/.local/node" && mkdir -p "$HOME/.local/node" && tar -xJf "$tmp/$f" -C "$HOME/.local/node" --strip-components=1 || fail node "unpack failed"
59
56
  rm -rf "$tmp"
60
57
  for b in node npm npx; do ln -sf "$HOME/.local/node/bin/$b" "$HOME/.local/bin/$b"; done
61
- hash -r; step node done "$(node --version) in ~/.local/node"
62
- fi
58
+ step node done "$("$HOME/.local/node/bin/node" --version) in ~/.local/node"
59
+ }
60
+ export PATH="$HOME/.local/node/bin:/usr/bin:/bin:/usr/sbin:/sbin"
63
61
  # --prefer-online: a cached package listing from before the publish says the version does not exist.
64
- npx -y --prefer-online -p benignswarm@${version} b9s install ${version} >/tmp/bschat-install.$$ 2>&1 || fail b9s "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
62
+ "$HOME/.local/node/bin/npm" exec --yes --prefer-online --package=benignswarm@${version} -- b9s install ${version} --provisioned >/tmp/bschat-install.$$ 2>&1 || fail b9s "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
65
63
  rm -f /tmp/bschat-install.$$
66
- bin=$(node -p 'require(require("os").homedir()+"/.b9s/install.json").bin')
64
+ bin=$("$HOME/.local/node/bin/node" -p 'require(require("os").homedir()+"/.b9s/install.json").bin')
67
65
  for b in b9s b9s-admin bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || ln -sf "$(dirname "$bin")/$b" "$HOME/.local/bin/$b"; done
68
66
  step b9s ok "$("$bin" --version) $bin"
69
67
  `;
@@ -16,7 +16,7 @@ import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
16
  import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
17
17
  import { writeFileAtomic } from "../shared-file.js";
18
18
  import { readState, updateState } from "../state.js";
19
- import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
19
+ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, serviceUsesInstall, serviceUsesNode, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
20
20
  import { CLI_VERSION } from "../version.js";
21
21
  import { probeCapabilities } from "../capabilities.js";
22
22
  import { diskSpaceNotice } from "../notices.js";
@@ -72,7 +72,7 @@ function writeMachineState(s) {
72
72
  * 12: Claude Code workspace-write roots name only the checkout, active unit worktree, narrowed Git metadata, config and caches.
73
73
  */
74
74
  const START_REV = 12;
75
- export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
75
+ export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [`image:${imageDigest}`] : []), ...(s.secret_context_hash ? [`secrets:${s.secret_context_hash}`] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
76
76
  /** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
77
77
  export function sessionConfigChanged(s, local, fingerprint) {
78
78
  const serverThreadChanged = s.thread !== null && s.thread !== (local?.thread ?? null);
@@ -968,7 +968,12 @@ export async function launchDesiredSession(opts) {
968
968
  return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
969
969
  cwd: opts.s.dir,
970
970
  timeout: startWaitMs(opts.s),
971
- env: { ...process.env, ...opts.secretEnv, ...(opts.progressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.progressFile } : {}) },
971
+ env: {
972
+ ...process.env,
973
+ ...opts.secretEnv,
974
+ ...(opts.secretDeclaredHosts?.length ? { B9S_SECRET_DECLARED_HOSTS: JSON.stringify(opts.secretDeclaredHosts) } : {}),
975
+ ...(opts.progressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.progressFile } : {}),
976
+ },
972
977
  });
973
978
  }
974
979
  const { runtime, imageDigest } = resolveContainerLaunchPrereqs({
@@ -1034,14 +1039,16 @@ export async function launchDesiredSession(opts) {
1034
1039
  B9S_URL: opts.m.url,
1035
1040
  B9S_AGENT: opts.s.agent,
1036
1041
  B9S_HOME: "/home/agent/.b9s",
1042
+ ...(opts.secretDeclaredHosts?.length ? { B9S_SECRET_DECLARED_HOSTS: JSON.stringify(opts.secretDeclaredHosts) } : {}),
1037
1043
  ...(opts.containerProgressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.containerProgressFile } : {}),
1038
1044
  },
1045
+ secretEnvKeys: opts.projectSecretEnvKeys,
1039
1046
  command: ["b9s", ...startArgs({ ...opts.s, harness_binary: null }, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
1040
1047
  });
1041
1048
  const launchRes = runner(runtime, runArgs, {
1042
1049
  cwd: opts.s.dir,
1043
1050
  timeout: 60_000,
1044
- env: isolatedSubprocessEnv(process.env),
1051
+ env: isolatedSubprocessEnv(process.env, opts.secretEnv, opts.projectSecretEnvKeys),
1045
1052
  });
1046
1053
  if (launchRes.status !== 0)
1047
1054
  return launchRes;
@@ -1481,68 +1488,112 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1481
1488
  }
1482
1489
  delete state.unsettled_turns[s.dir];
1483
1490
  }
1484
- const secretDelivery = resolveSessionSecretDelivery({
1485
- session: s,
1486
- secrets: me.harness_secrets ?? [],
1487
- targetDir: join(configRoot(), "providers", "ephemeral"),
1488
- runner: deps?.runner,
1489
- });
1490
- const startId = createHash("sha256").update(s.id).digest("hex").slice(0, 24);
1491
- const progressDir = containerMode ? join(agentHomeDirOf(s), ".b9s", "logs") : join(configRoot(), "state", "machine-start");
1492
- mkdirSync(progressDir, { recursive: true, mode: 0o700 });
1493
- const progressFile = join(progressDir, `start-${startId}.json`);
1494
- // What the daemon trusts (the child's identity, the outcome) stays in host-private state:
1495
- // a containerised session can write its own home, and only the progress note lives there.
1496
- // The name is per attempt, so nothing an earlier child wrote is read as this one's.
1497
- const privateDir = join(configRoot(), "state", "machine-start");
1498
- mkdirSync(privateDir, { recursive: true, mode: 0o700 });
1499
- const resultFile = join(privateDir, `result-${startId}-${randomBytes(6).toString("hex")}.json`);
1500
- writeJsonAtomically(progressFile, { state: "starting", at: new Date().toISOString() });
1501
- const launchOptions = {
1502
- m, accountId, s, project: projectEntry, thread, sessionWritable, machineWritable: writable,
1503
- bin, secretEnv: secretDelivery.env, containerMode, pullImage: isPoolImageOptIn, workdir,
1504
- sandboxReport: hostContainerProbe ?? undefined, onEc2, containerImdsBlocked: containerImdsOk,
1505
- startupJitterSeconds: deps?.startupJitterSeconds,
1506
- progressFile: containerMode ? undefined : progressFile,
1507
- containerProgressFile: containerMode ? `/home/agent/.b9s/logs/start-${startId}.json` : undefined,
1508
- };
1509
- rmSync(startChildFile(resultFile), { force: true });
1510
- // The intent is on disk before anything is launched, so a daemon that stops at any point
1511
- // from here finds either this record, the child's own file, or the result: never nothing.
1512
- const pending = {
1513
- pid: 0, pid_started: null, started_at: new Date().toISOString(), progress_file: progressFile, result_file: resultFile,
1514
- child_file: startChildFile(resultFile),
1515
- secret_files: secretDelivery.files, fingerprint: fp, thread, desired: s,
1516
- writable: sessionWritable, image_digest: pinnedImageRef,
1517
- ...(containerMode && containerPrereqs && containerName
1518
- ? {
1519
- container_name: containerName,
1520
- container_runtime: containerPrereqs.runtime,
1521
- container_runtime_version: containerPrereqs.version,
1522
- image_digest: extractPinnedImageDigest(pinnedImageRef),
1523
- image_reference: pinnedImageRef,
1524
- }
1525
- : {}),
1526
- };
1527
- state.starting_sessions[s.id] = pending;
1491
+ let secretDelivery = null;
1492
+ let pending = null;
1493
+ let childLaunched = false;
1494
+ const projectSecretEnv = {};
1495
+ const mergedSecretEnv = {};
1496
+ let secretDeclaredHosts = [];
1528
1497
  try {
1498
+ secretDelivery = resolveSessionSecretDelivery({
1499
+ session: s,
1500
+ secrets: me.harness_secrets ?? [],
1501
+ targetDir: join(configRoot(), "providers", "ephemeral"),
1502
+ runner: deps?.runner,
1503
+ });
1504
+ if (s.secret_grant_required) {
1505
+ const grant = await client.call("POST", `/machines/me/sessions/${encodeURIComponent(s.id)}/secret-grant`, {});
1506
+ const redeemed = await Client.raw(m.url, grant.grant_token).call("POST", "/secret-broker/redeem", {});
1507
+ if (!redeemed.secrets || typeof redeemed.secrets !== "object" || Array.isArray(redeemed.secrets)) {
1508
+ throw new Error("secret broker returned no authorized secret values");
1509
+ }
1510
+ if (!Array.isArray(redeemed.declared_hosts) || redeemed.declared_hosts.some((host) => typeof host !== "string")) {
1511
+ throw new Error("secret broker returned an invalid declared host list");
1512
+ }
1513
+ secretDeclaredHosts = redeemed.declared_hosts;
1514
+ for (const [key, value] of Object.entries(redeemed.secrets)) {
1515
+ if (typeof value !== "string")
1516
+ throw new Error("secret broker returned a non-text secret value");
1517
+ if (Object.prototype.hasOwnProperty.call(secretDelivery.env, key)) {
1518
+ throw new Error(`secret name ${key} collides with a machine credential`);
1519
+ }
1520
+ projectSecretEnv[key] = value;
1521
+ }
1522
+ }
1523
+ Object.assign(mergedSecretEnv, secretDelivery.env, projectSecretEnv);
1524
+ const startId = createHash("sha256").update(s.id).digest("hex").slice(0, 24);
1525
+ const progressDir = containerMode ? join(agentHomeDirOf(s), ".b9s", "logs") : join(configRoot(), "state", "machine-start");
1526
+ mkdirSync(progressDir, { recursive: true, mode: 0o700 });
1527
+ const progressFile = join(progressDir, `start-${startId}.json`);
1528
+ // The child identity and result are private machine state; neither contains secret values.
1529
+ const privateDir = join(configRoot(), "state", "machine-start");
1530
+ mkdirSync(privateDir, { recursive: true, mode: 0o700 });
1531
+ const resultFile = join(privateDir, `result-${startId}-${randomBytes(6).toString("hex")}.json`);
1532
+ pending = {
1533
+ pid: 0, pid_started: null, started_at: new Date().toISOString(), progress_file: progressFile, result_file: resultFile,
1534
+ child_file: startChildFile(resultFile),
1535
+ secret_files: secretDelivery.files, fingerprint: fp, thread, desired: s,
1536
+ writable: sessionWritable, image_digest: pinnedImageRef,
1537
+ ...(containerMode && containerPrereqs && containerName
1538
+ ? {
1539
+ container_name: containerName,
1540
+ container_runtime: containerPrereqs.runtime,
1541
+ container_runtime_version: containerPrereqs.version,
1542
+ image_digest: extractPinnedImageDigest(pinnedImageRef),
1543
+ image_reference: pinnedImageRef,
1544
+ }
1545
+ : {}),
1546
+ };
1547
+ writeJsonAtomically(progressFile, { state: "starting", at: new Date().toISOString() });
1548
+ const launchOptions = {
1549
+ m, accountId, s, project: projectEntry, thread, sessionWritable, machineWritable: writable,
1550
+ bin, secretEnv: mergedSecretEnv, projectSecretEnvKeys: Object.keys(projectSecretEnv), secretDeclaredHosts,
1551
+ containerMode, pullImage: isPoolImageOptIn, workdir,
1552
+ sandboxReport: hostContainerProbe ?? undefined, onEc2, containerImdsBlocked: containerImdsOk,
1553
+ startupJitterSeconds: deps?.startupJitterSeconds,
1554
+ progressFile: containerMode ? undefined : progressFile,
1555
+ containerProgressFile: containerMode ? `/home/agent/.b9s/logs/start-${startId}.json` : undefined,
1556
+ };
1557
+ rmSync(startChildFile(resultFile), { force: true });
1558
+ // Persist the start intent before launch so a daemon restart can find the child/result.
1559
+ state.starting_sessions[s.id] = pending;
1529
1560
  writeMachineState(state);
1530
- }
1531
- catch (error) {
1532
- delete state.starting_sessions[s.id];
1533
- secretDelivery.cleanup();
1534
- throw error;
1535
- }
1536
- try {
1537
1561
  await scheduleRestartWork("session start/relaunch", s.agent);
1538
1562
  pending.pid = (deps?.startTrackedSession ?? ((childBin, options, result) => startSessionChild(childBin, s.dir, options, result)))(bin, launchOptions, resultFile);
1563
+ childLaunched = true;
1539
1564
  }
1540
1565
  catch (error) {
1541
- delete state.starting_sessions[s.id];
1542
- writeMachineState(state);
1543
- cleanupMachineStart(pending);
1566
+ if (pending) {
1567
+ delete state.starting_sessions[s.id];
1568
+ try {
1569
+ writeMachineState(state);
1570
+ }
1571
+ finally {
1572
+ cleanupMachineStart(pending);
1573
+ }
1574
+ }
1544
1575
  throw error;
1545
1576
  }
1577
+ finally {
1578
+ for (const k of Object.keys(projectSecretEnv)) {
1579
+ projectSecretEnv[k] = "";
1580
+ delete projectSecretEnv[k];
1581
+ }
1582
+ for (const k of Object.keys(mergedSecretEnv)) {
1583
+ mergedSecretEnv[k] = "";
1584
+ delete mergedSecretEnv[k];
1585
+ }
1586
+ if (secretDelivery) {
1587
+ for (const k of Object.keys(secretDelivery.env)) {
1588
+ secretDelivery.env[k] = "";
1589
+ delete secretDelivery.env[k];
1590
+ }
1591
+ if (!childLaunched)
1592
+ secretDelivery.cleanup();
1593
+ }
1594
+ }
1595
+ if (!pending)
1596
+ throw new Error("tracked machine start did not persist its intent");
1546
1597
  pending.pid_started = readStartStamp(pending.pid);
1547
1598
  try {
1548
1599
  writeMachineState(state);
@@ -2819,6 +2870,13 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2819
2870
  // macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
2820
2871
  ...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
2821
2872
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
2873
+ b9s_services: watcherServices().map((service) => ({
2874
+ label: service.label,
2875
+ program: service.args?.[0] ?? null,
2876
+ install_match: !!service.args?.[0] && serviceUsesInstall(service.args[0], requireInstall().bin),
2877
+ provisioned: readInstall()?.provisioned === true,
2878
+ node_match: readInstall()?.provisioned === true ? serviceUsesNode(service.pathEnv, requireInstall().bin) : null,
2879
+ })),
2822
2880
  // IPv4 only: temporary IPv6 addresses rotate, and this report is compared for change.
2823
2881
  network: { interfaces: interfaceFacts(true) },
2824
2882
  git_identity: gitIdentity,
@@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { DEFAULT_URL, listSaved } from "../config.js";
5
- import { bool, str } from "../args.js";
5
+ import { bool, need, str } from "../args.js";
6
6
  import { Client } from "../client.js";
7
7
  import { loadAdmin, resolveAdminName } from "../config.js";
8
8
  import { CliError } from "../errors.js";
@@ -395,8 +395,29 @@ export async function notifierAdmin(p, out) {
395
395
  l ? `last report ${l.at.slice(0, 16).replace("T", " ")} UTC (${l.project}, ${l.items} item${l.items === 1 ? "" : "s"})${l.agent ? `\n ${l.agent.ok ? "ok " : "FAIL"} ${l.agent.name}: ${l.agent.detail}` : ""}${l.email ? `\n ${l.email.ok ? "ok " : "FAIL"} email ${l.email.to}: ${l.email.detail}` : ""}` : "nothing reported yet",
396
396
  ].join("\n"), r);
397
397
  }
398
- export async function accountAdmin(p, out) {
398
+ export async function accountAdmin(p, out, action, rest = []) {
399
399
  const c = adminClient(p);
400
+ if (action === "secrets-kms") {
401
+ const sub = rest[0] ?? "status";
402
+ if (sub === "status" && rest.length <= 1) {
403
+ const k = await c.call("GET", "/account/secrets-kms");
404
+ out.print(`Project secret envelope mode: ${k.mode} (available: ${k.value_storage_available ? "yes" : "no"}${k.value_storage_unavailable_reason ? `, reason: ${k.value_storage_unavailable_reason}` : ""})${k.kms_key_id ? `\nKMS key: ${k.kms_key_id} (${k.kms_region ?? "?"})` : ""}${k.deletion_scheduled_at ? `\nDeletion scheduled: ${k.deletion_scheduled_at}` : ""}\n${k.value_storage_unavailable_message ? `${k.value_storage_unavailable_message}\n` : ""}${k.disclosure ?? ""}`.trim(), k);
405
+ return;
406
+ }
407
+ if (sub === "enable" && rest.length === 1) {
408
+ const region = need(p.flags, "region");
409
+ const kmsKeyId = str(p.flags, "kms-key");
410
+ const k = await c.call("PUT", "/account/secrets-kms", {
411
+ region,
412
+ ...(kmsKeyId ? { kms_key_id: kmsKeyId } : {}),
413
+ });
414
+ out.print(`Enabled per-account AWS KMS wrapping in ${k.kms_region}: ${k.kms_key_id}.\n${k.disclosure ?? ""}`.trim(), k);
415
+ return;
416
+ }
417
+ throw new CliError("usage", "b9s-admin account secrets-kms [status | enable --region <aws-region> [--kms-key <arn-or-id>]]");
418
+ }
419
+ if (action)
420
+ throw new CliError("usage", "b9s-admin account [--summary-minutes <n>] | secrets-kms [status | enable --region <r> [--kms-key <id>]]");
400
421
  const m = intFlag(str(p.flags, "summary-minutes"), "summary-minutes");
401
422
  if (m !== undefined)
402
423
  await c.call("PATCH", "/account", { summary_minutes: m });
@@ -1,5 +1,15 @@
1
1
  import { bool, need, str } from "../args.js";
2
2
  import { CliError } from "../errors.js";
3
+ import { table } from "../output.js";
4
+ function limitFlag(p) {
5
+ const raw = str(p.flags, "limit");
6
+ if (raw === undefined)
7
+ return undefined;
8
+ const n = Number(raw);
9
+ if (!Number.isInteger(n) || n < 1)
10
+ throw new CliError("usage", "--limit must be a positive integer");
11
+ return n;
12
+ }
3
13
  function csv(value) {
4
14
  return value?.split(",").map((part) => part.trim()).filter(Boolean) ?? [];
5
15
  }
@@ -12,7 +22,7 @@ function purposeFlag(p) {
12
22
  export async function projectSecrets(rest, p, c, out) {
13
23
  const [project, action, secret, ...extra] = rest;
14
24
  if (!project || !action)
15
- throw new CliError("usage", "project secrets <project> list|show|create|rotate|revoke|delete|set ...");
25
+ throw new CliError("usage", "project secrets <project> list|show|create|update|rotate|revoke|delete|set|audit ...");
16
26
  const base = `/projects/${encodeURIComponent(project)}/secrets`;
17
27
  const resolve = async (name) => {
18
28
  const listed = await c.call("GET", base);
@@ -40,7 +50,12 @@ export async function projectSecrets(rest, p, c, out) {
40
50
  if (mode === "aws_secrets_manager")
41
51
  body.reference = { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") };
42
52
  const result = await c.call("POST", base, body);
43
- out.print(`Created ${secret} for ${project}; values are unavailable until encrypted storage lands in WU #231. Console control: WU #230.`, result);
53
+ const nextHint = mode === "aws_secrets_manager"
54
+ ? "External AWS reference recorded."
55
+ : result.value_storage_available
56
+ ? `Set its encrypted value with: b9s-admin project secrets ${project} set ${secret} --stdin`
57
+ : `Encrypted storage is unavailable (${result.value_storage_unavailable_reason ?? "aws_kms_unconfigured"}); configure per-account AWS KMS before calling set.`;
58
+ out.print(`Created ${secret} for ${project}. ${nextHint} (Console control: WU #230.)`, result);
44
59
  return;
45
60
  }
46
61
  if (action === "show" && secret && !extra.length) {
@@ -49,9 +64,33 @@ export async function projectSecrets(rest, p, c, out) {
49
64
  return;
50
65
  }
51
66
  if (action === "rotate" && secret && !extra.length) {
52
- const result = await c.call("POST", `${base}/${encodeURIComponent(await resolve(secret))}/versions`, { reference: { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") } });
53
- out.print(`Recorded a new external reference version for ${secret}.`, result);
54
- return;
67
+ const id = await resolve(secret);
68
+ const drain = bool(p.flags, "drain");
69
+ const arn = str(p.flags, "arn");
70
+ const versionId = str(p.flags, "version-id");
71
+ if (arn !== undefined || versionId !== undefined) {
72
+ const result = await c.call("POST", `${base}/${encodeURIComponent(id)}/versions`, {
73
+ reference: { arn: need(p.flags, "arn"), version_id: need(p.flags, "version-id") },
74
+ ...(drain ? { drain_sessions: true } : {}),
75
+ });
76
+ out.print(`Recorded a new external reference version v${result.secret?.current_version ?? "?"} for ${secret}.${drain ? ` Drained ${result.drained_sessions?.length ?? 0} running session(s).` : ""}`, result);
77
+ return;
78
+ }
79
+ if (bool(p.flags, "stdin") || process.stdin.isTTY) {
80
+ const meta = await c.call("GET", `${base}/${encodeURIComponent(id)}`);
81
+ if (!meta.value_storage_available) {
82
+ throw new CliError("secret_storage_unavailable", "Secret value rotation is unavailable because encrypted storage is not configured on this server; no value was read or sent.");
83
+ }
84
+ let value = await readSecretValue(bool(p.flags, "stdin"));
85
+ const result = await c.call("PUT", `${base}/${encodeURIComponent(id)}/value`, {
86
+ value,
87
+ ...(drain ? { drain_sessions: true } : {}),
88
+ });
89
+ value = "";
90
+ out.print(`Rotated ${secret} to encrypted v${result.version ?? "?"} (${result.storage?.backend ?? "encrypted"}). Notice: BenignSwarm decrypts hosted secrets in memory during broker delivery to authorized sessions.`, result);
91
+ return;
92
+ }
93
+ throw new CliError("usage", "project secrets <p> rotate <name> (--arn <exact ARN> --version-id <id> | --stdin) [--drain]");
55
94
  }
56
95
  if (action === "update" && secret && !extra.length) {
57
96
  const body = {};
@@ -77,27 +116,54 @@ export async function projectSecrets(rest, p, c, out) {
77
116
  }
78
117
  if (action === "revoke" && secret && !extra.length) {
79
118
  const result = await c.call("POST", `${base}/${encodeURIComponent(await resolve(secret))}/revoke`, {});
80
- out.print(`Revoked future access to ${secret}.`, result);
119
+ out.print(`Revoked access to ${secret}; stopped ${result.stopped_sessions?.length ?? 0} active session(s).`, result);
81
120
  return;
82
121
  }
83
122
  if (action === "delete" && secret && !extra.length) {
84
123
  const result = await c.call("DELETE", `${base}/${encodeURIComponent(await resolve(secret))}`);
85
- out.print(`Deleted definition ${secret}; customer-owned AWS resources are unchanged.`, result);
124
+ out.print(`Deleted ${secret} (${result.stopped_sessions?.length ?? 0} session(s) stopped); customer-owned AWS Secrets Manager secrets and IAM roles remain in your AWS account.`, result);
86
125
  return;
87
126
  }
88
127
  if (action === "set" && secret && !extra.length && (bool(p.flags, "stdin") || process.stdin.isTTY)) {
89
128
  const id = await resolve(secret);
90
129
  const result = await c.call("GET", `${base}/${encodeURIComponent(id)}`);
91
130
  if (!result.value_storage_available) {
92
- throw new CliError("secret_storage_unavailable", "Secret value entry is unavailable until encrypted storage lands in WU #231; no value was read or sent.");
131
+ throw new CliError("secret_storage_unavailable", "Secret value entry is unavailable because encrypted storage is not configured on this server; no value was read or sent.");
93
132
  }
94
- // The metadata capability gate above must precede any read/prompt. WU #231 enables this path.
95
- const value = await readSecretValue(bool(p.flags, "stdin"));
96
- await c.call("PUT", `${base}/${encodeURIComponent(id)}/value`, { value });
97
- out.print(`Saved a new value version for ${secret}.`, { ok: true });
133
+ // The metadata capability gate above must precede any read/prompt.
134
+ let value = await readSecretValue(bool(p.flags, "stdin"));
135
+ const drain = bool(p.flags, "drain");
136
+ const saved = await c.call("PUT", `${base}/${encodeURIComponent(id)}/value`, {
137
+ value,
138
+ ...(drain ? { drain_sessions: true } : {}),
139
+ });
140
+ value = "";
141
+ const kmsNote = saved.storage?.kms_key_id
142
+ ? `encrypted with per-account AWS KMS key (${saved.storage.kms_key_id})`
143
+ : "encrypted with per-account AWS KMS key";
144
+ out.print(`Saved encrypted v${saved.version ?? "?"} for ${secret} (${kmsNote}).${drain ? ` Drained ${saved.drained_sessions?.length ?? 0} running session(s).` : ""} Notice: BenignSwarm decrypts hosted secrets in memory during broker delivery to authorized sessions.`, saved);
145
+ return;
146
+ }
147
+ if (action === "audit" && !extra.length) {
148
+ const limit = limitFlag(p);
149
+ const qs = limit !== undefined ? `?limit=${limit}` : "";
150
+ const path = secret
151
+ ? `${base}/${encodeURIComponent(await resolve(secret))}/audit${qs}`
152
+ : `${base}/audit${qs}`;
153
+ const result = await c.call("GET", path);
154
+ const events = result.events ?? [];
155
+ out.print(events.length
156
+ ? table(events.map((e) => ({
157
+ at: e.created_at,
158
+ action: e.action,
159
+ actor: e.actor_id,
160
+ version: e.version ?? "—",
161
+ detail: typeof e.detail === "string" ? e.detail : JSON.stringify(e.detail ?? {}),
162
+ })), ["at", "action", "actor", "version", "detail"])
163
+ : "No secret audit events.", result);
98
164
  return;
99
165
  }
100
- throw new CliError("usage", "project secrets <project> list | show <name> | create <name> --purpose <text> --storage-mode hosted|aws_secrets_manager --units 1,2 --tags api --hosts db.example.com [--arn <exact ARN> --version-id <id>] | update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]] | rotate <name> --arn <exact ARN> --version-id <id> | revoke <name> | delete <name> | set <name> [--stdin]");
166
+ throw new CliError("usage", "project secrets <project> list | show <name> | audit [<name>] [--limit N] | create <name> --purpose <text> --storage-mode hosted|aws_secrets_manager --units 1,2 --tags api --hosts db.example.com [--arn <exact ARN> --version-id <id>] | update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]] | rotate <name> (--arn <exact ARN> --version-id <id> | --stdin) [--drain] | revoke <name> | delete <name> | set <name> [--stdin] [--drain]");
101
167
  }
102
168
  function decodeSecretValue(bytes) {
103
169
  try {
@@ -8,7 +8,8 @@ import { describeFinding, describeProbe, evaluateProbe, expectedFor, runSandboxP
8
8
  *
9
9
  * b9s sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
10
10
  * measure, from inside the sandbox: where commands run, which tools are there, what git can
11
- * do, which hosts answer, and what is writable. Records facts and judges nothing.
11
+ * do, which hosts answer, and what is writable. Records facts and judges nothing. By default
12
+ * it prints to stdout; --out must name a writable file (for example inside the checkout).
12
13
  * b9s sandbox check <file> --harness <h> --sandbox <mode>
13
14
  * compare a probe's result with what is expected of that harness and mode; exits 1 on a
14
15
  * difference, naming each one.