benignswarm 0.12.91 → 0.12.93

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.
@@ -11,6 +11,7 @@ import { codexHooksPath } from "./codex.js";
11
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
12
12
  import { detectVendor } from "../vendor.js";
13
13
  import { CLI_VERSION } from "../version.js";
14
+ import { assertEnrolledStartProject } from "../start-options.js";
14
15
  function repoRoot() {
15
16
  const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
16
17
  return r.status === 0 ? r.stdout.trim() : process.cwd();
@@ -64,7 +65,7 @@ export async function setup(p, out) {
64
65
  const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
65
66
  out.print(`b9s ${inst.version} for this machine: ${inst.bin}\nRecorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { install: inst, identity: idPath, written: uniq, hook_verified: !!selfTest });
66
67
  }
67
- export async function join(p, out) {
68
+ export async function join(p, out, expectedProject) {
68
69
  const name = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
69
70
  if (!name)
70
71
  throw new CliError("usage", "join needs --as <agent-name> (the name you were given)");
@@ -107,6 +108,9 @@ export async function join(p, out) {
107
108
  if (!res.ok)
108
109
  throw new CliError(json.error ?? `http_${res.status}`, json.message ?? "join failed");
109
110
  const project = json.project ? json.project.name : null;
111
+ // Used internally by `b9s start --as project/name --token ...`: enrollment always
112
+ // submits the bare name, then verifies the token was actually scoped to that project.
113
+ assertEnrolledStartProject(expectedProject, project);
110
114
  const ref = agentRef({ project, agent: name });
111
115
  const path = saveAgent({ url, key: json.key, account: json.project ? json.project.id : "", project, agent: name, vendor, machine });
112
116
  const idPath = noBind ? null : writeIdentity(root, vendor, name, model, bool(p.flags, "replace"), project);
@@ -51,6 +51,17 @@ for b in b9s b9s-admin bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || l
51
51
  step b9s ok "$("$bin" --version) $bin"
52
52
  `;
53
53
  }
54
+ export function machineCapabilityLines(projects) {
55
+ return projects.flatMap((project) => {
56
+ if (!project.capabilities.length)
57
+ return [];
58
+ const values = project.capabilities.map((capability) => {
59
+ const state = capability.ok ? capability.version ?? "ready" : capability.error ?? "not probed";
60
+ return `${capability.name}: ${state}`;
61
+ });
62
+ return [` ${project.project} capabilities: ${values.join("; ")}`];
63
+ });
64
+ }
54
65
  /**
55
66
  * Runs `command` on `host` with /bin/sh, whatever the account's login shell: zsh aborts a command
56
67
  * whose glob matches nothing (mini1: the archived-sessions pattern of a thread lookup). Output may be
@@ -132,10 +143,11 @@ export async function machineAdmin(action, rest, p, out) {
132
143
  `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}`,
133
144
  rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
134
145
  ];
146
+ const capabilityLines = machineCapabilityLines(m.capabilities ?? []);
135
147
  const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
136
148
  const providers = rep.claude_code?.providers ?? {};
137
149
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
138
- return out.print([...head, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
150
+ return out.print([...head, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
139
151
  }
140
152
  if (action === "maintenance") {
141
153
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -219,6 +231,13 @@ export async function machineAdmin(action, rest, p, out) {
219
231
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { resume_turns: true });
220
232
  return out.print(`${ref} on ${machineName}: turn mode resumed explicitly; its daemon applies the request within 30 s.`, r);
221
233
  }
234
+ if (sub === "thread") {
235
+ const thread = rest[3];
236
+ if (thread === undefined)
237
+ throw new CliError("usage", "machine session thread <machine> <project>/<agent> <thread-id|none>");
238
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { thread: thread === "none" ? null : thread });
239
+ return out.print(`${ref} on ${machineName}: ${thread === "none" ? "thread cleared" : `thread set to ${thread}`}; its daemon applies the change within 30 s.`, r);
240
+ }
222
241
  if (sub === "limit") {
223
242
  const value = str(p.flags, "turns-per-hour");
224
243
  if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 20)
@@ -231,7 +250,7 @@ export async function machineAdmin(action, rest, p, out) {
231
250
  return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
232
251
  }
233
252
  }
234
- throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
253
+ throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|resume|limit|thread|remove <machine> <project>/<agent> [...]");
235
254
  }
236
255
  /** `[tag=]harness:model[:effort][*weight][@provider]`, e.g. `luna=claude-code:deepseek-flash@deepseek`. */
237
256
  export function parseVariant(spec) {
@@ -1,4 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, statfsSync, writeFileSync } from "node:fs";
3
4
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, totalmem, uptime, userInfo } from "node:os";
4
5
  import { dirname, join } from "node:path";
@@ -17,6 +18,7 @@ import { probeCapabilities } from "../capabilities.js";
17
18
  import { diskSpaceNotice } from "../notices.js";
18
19
  import { verifyClaudeProvider } from "../providers.js";
19
20
  import { resumeTurnGuard } from "../turn-guard.js";
21
+ import { defaultWorkspaceWritableRoots } from "../start-options.js";
20
22
  export const machineFile = () => join(configRoot(), "machine.json");
21
23
  export function loadMachine() {
22
24
  const f = machineFile();
@@ -30,14 +32,19 @@ function writeMachineState(s) {
30
32
  mkdirSync(dirname(stateFile()), { recursive: true });
31
33
  writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
32
34
  }
33
- /** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
35
+ /** What a session's watcher is started with; a change means re-running codex start. */
34
36
  /**
35
37
  * Bumped when `b9s start` builds a session's settings differently, so every session is started
36
38
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
37
39
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
38
40
  */
39
- const START_REV = 4;
40
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
41
+ const START_REV = 5;
42
+ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
43
+ /** A clear is distinct from a thread that the server has not received from the machine yet. */
44
+ export function reconcileThread(s, local) {
45
+ const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
46
+ return clearing ? null : s.thread ?? local?.thread ?? null;
47
+ }
41
48
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
42
49
  /**
43
50
  * During a maintenance drain or window, a session that would be started fresh (no known thread, so
@@ -61,12 +68,15 @@ export function startArgs(s, thread, writable = []) {
61
68
  ...(s.model ? ["--model", s.model] : []),
62
69
  ...(s.effort ? ["--effort", s.effort] : []),
63
70
  ...(thread ? ["--thread", thread] : []),
64
- ...(writable.length && s.sandbox === "workspace-write" ? ["--writable", writable.join(",")] : []),
71
+ ...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
65
72
  ];
66
73
  }
67
74
  const KEY_CHECK_MS = 10 * 60_000;
68
75
  const CAPABILITY_PROBE_MS = 60 * 60_000;
69
76
  const lastCapabilityProbe = new Map();
77
+ export function turnFaultSessionFields(fault) {
78
+ return { turn_fault_at: new Date(fault.at).toISOString() };
79
+ }
70
80
  /** One pass: make what runs here match what the operator declared, then report. */
71
81
  export async function reconcile(m, log) {
72
82
  const client = Client.raw(m.url, m.key);
@@ -148,7 +158,7 @@ export async function reconcile(m, log) {
148
158
  removeService(w);
149
159
  log(`${s.agent}: turn mode fault; watcher service stopped`);
150
160
  }
151
- out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error });
161
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error, ...turnFaultSessionFields(fault) });
152
162
  continue;
153
163
  }
154
164
  if (local) {
@@ -160,8 +170,11 @@ export async function reconcile(m, log) {
160
170
  }
161
171
  }
162
172
  await ensureCredentials(client, m, s, local, log);
163
- const fp = sessionFingerprint(s, s.sandbox === "workspace-write" ? writable : []);
164
- const thread = s.thread ?? local?.thread ?? null;
173
+ const sessionWritable = s.sandbox === "workspace-write"
174
+ ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
175
+ : writable;
176
+ const thread = reconcileThread(s, local);
177
+ const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : []);
165
178
  const threadChanged = !!local?.thread && !!s.thread && s.thread !== local.thread;
166
179
  if (!svc() || !local || local.fingerprint !== fp || threadChanged) {
167
180
  // A new session's start runs its first turn at once, past the watchers' check: during a
@@ -173,11 +186,17 @@ export async function reconcile(m, log) {
173
186
  out.push(held);
174
187
  continue;
175
188
  }
176
- const r = spawnSync(bin, startArgs(s, thread, writable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
189
+ const r = spawnSync(bin, startArgs(s, thread, sessionWritable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
177
190
  if (r.status !== 0)
178
191
  throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
179
192
  const started = JSON.parse(r.stdout);
180
- state.sessions[s.id] = { label, fingerprint: fp, thread: started.thread, key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now() };
193
+ state.sessions[s.id] = {
194
+ label,
195
+ fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : []),
196
+ thread: started.thread,
197
+ thread_override_at: s.thread_override_at ?? null,
198
+ key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
199
+ };
181
200
  log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
182
201
  }
183
202
  else {
@@ -239,7 +258,7 @@ export async function reconcile(m, log) {
239
258
  const projectDir = desired.find((s) => s.project_id === project.id && s.dir)?.dir ?? homedir();
240
259
  if (!project.capabilities.length)
241
260
  continue;
242
- capabilities[project.id] = probeCapabilities(project.capabilities, projectDir);
261
+ capabilities[project.id] = await probeCapabilities(project.capabilities, projectDir);
243
262
  probedProjects.push(project.id);
244
263
  log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
245
264
  }
@@ -409,11 +428,11 @@ export function errorText(s) {
409
428
  function turnFacts(agent, harness, thread) {
410
429
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
411
430
  if (!thread || !ph || "missing" in ph)
412
- return { turn: { running: false, since: null }, process: null, paused_until: null };
431
+ return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null };
413
432
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
414
433
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
415
434
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
416
- return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused };
435
+ return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null };
417
436
  }
418
437
  /** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
419
438
  export function turnProcess(thread, harness = "codex", psOutput, agent) {
@@ -604,7 +623,7 @@ export function machineFacts(providersInUse = ["anthropic"]) {
604
623
  booted_at: new Date(Math.floor((Date.now() - uptime() * 1000) / 60_000) * 60_000).toISOString(),
605
624
  daemon_path: path,
606
625
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
607
- codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), sandbox: codexSandbox(false, path) } : null,
626
+ codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null,
608
627
  "claude-code": claude,
609
628
  claude_code: claude,
610
629
  dsh,
@@ -614,6 +633,17 @@ export function machineFacts(providersInUse = ["anthropic"]) {
614
633
  at: new Date().toISOString(),
615
634
  };
616
635
  }
636
+ /** Stable, non-reversible account identity for detecting a login switch without reporting its id. */
637
+ export function codexAccountFingerprint(authFile = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "auth.json")) {
638
+ try {
639
+ const auth = JSON.parse(readFileSync(authFile, "utf8"));
640
+ const accountId = auth.tokens?.account_id ?? auth.account_id;
641
+ return typeof accountId === "string" && accountId ? createHash("sha256").update(accountId).digest("hex") : null;
642
+ }
643
+ catch {
644
+ return null;
645
+ }
646
+ }
617
647
  /**
618
648
  * Provisioning steps that need this machine's own view, run by `machine add` over ssh: linger on
619
649
  * Linux, Codex present and logged in, and b9s's hooks in Codex's administrator layer when sudo
@@ -647,6 +677,12 @@ export function prepare(opts = {}) {
647
677
  const ok = login.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`);
648
678
  steps.push({ step: "codex", result: ok ? "ok" : "failed", detail: ok ? `${codex.stdout.trim()}, ${`${login.stdout}${login.stderr}`.trim()}` : `${codex.stdout.trim()} is not logged in: run codex login --device-auth on this machine` });
649
679
  }
680
+ const gitName = spawnSync("git", ["config", "--global", "--get", "user.name"], { encoding: "utf8", env: daemonEnv });
681
+ const gitEmail = spawnSync("git", ["config", "--global", "--get", "user.email"], { encoding: "utf8", env: daemonEnv });
682
+ const hasGitIdentity = gitName.status === 0 && !!gitName.stdout.trim() && gitEmail.status === 0 && !!gitEmail.stdout.trim();
683
+ steps.push(hasGitIdentity
684
+ ? { step: "git identity", result: "ok", detail: `commits will use ${gitName.stdout.trim()} <${gitEmail.stdout.trim()}>` }
685
+ : { step: "git identity", result: "failed", detail: 'configure both values before agents commit: git config --global user.name "Your Name" && git config --global user.email "you@example.com"' });
650
686
  if (codex.status === 0) {
651
687
  let sb = codexSandbox(true, daemonPath);
652
688
  if (sb.ok)
@@ -24,6 +24,7 @@ import { probeCapabilities } from "../capabilities.js";
24
24
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
25
25
  import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
26
26
  import { sessionUsage } from "../usage.js";
27
+ import { collectPruneProtection } from "../prune-protection.js";
27
28
  function omitMeasuresAlreadyIn(text, updates) {
28
29
  if (!text)
29
30
  return updates;
@@ -34,7 +35,7 @@ function omitMeasuresAlreadyIn(text, updates) {
34
35
  }
35
36
  /** Reports host probes without refreshing the agent's presence; the host identity is still explicit. */
36
37
  export async function reportWatcherCapabilities(creds, project, definitions, cwd = process.cwd()) {
37
- const results = probeCapabilities(definitions, cwd);
38
+ const results = await probeCapabilities(definitions, cwd);
38
39
  await Client.forAgent(creds, undefined, { presence: false, machineIdentity: true }).call("POST", `/projects/${project}/agents/me/capabilities`, { results });
39
40
  }
40
41
  /**
@@ -96,7 +97,8 @@ export async function watch(p, out) {
96
97
  throw new CliError("usage", "--provider must be anthropic or deepseek");
97
98
  if (providerName === "deepseek" && harness !== "claude-code")
98
99
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
99
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model: str(p.flags, "model") };
100
+ const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
101
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model };
100
102
  }
101
103
  else if (p.flags.provider !== undefined) {
102
104
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -186,7 +188,8 @@ export async function watch(p, out) {
186
188
  // Space back on a schedule: only clean worktrees whose work has landed or whose unit is
187
189
  // closed; never one a unit is still being worked in (it may have no commits yet).
188
190
  const units = await unitWorktrees(scanCreds, scanCreds.project);
189
- const prunable = pruneReport(process.cwd(), units.closed, units.active).prunable;
191
+ const protection = await collectPruneProtection(scanCreds, scanCreds.project);
192
+ const prunable = pruneReport(process.cwd(), units.closed, units.active, undefined, protection).prunable;
190
193
  const probe = freeSpaceProbe(prunable.map((c) => c.path));
191
194
  let pruned = 0;
192
195
  for (const c of prunable) {
@@ -245,7 +248,7 @@ export async function watch(p, out) {
245
248
  try {
246
249
  if (probe)
247
250
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
248
- const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" && turn.provider === "deepseek" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn);
251
+ const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined);
249
252
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
250
253
  }, name, turn?.turnsPerHour ?? turnsPerHour);
251
254
  else {
@@ -334,7 +337,7 @@ async function waitIntervalOrStop(ms, stopped) {
334
337
  if (timer)
335
338
  clearTimeout(timer);
336
339
  }
337
- async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn) {
340
+ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId) {
338
341
  const state = readState(name);
339
342
  const pending = state.watch_pending;
340
343
  if (pending) {
@@ -421,7 +424,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
421
424
  // `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
422
425
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
423
426
  const line = wake;
424
- if (!(await deliver(name, exec, 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, undefined, allowTurn)))
427
+ if (!(await deliver(name, exec, 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, { sessionId }, allowTurn)))
425
428
  return { sent: false, recoveryBriefDelivered: false };
426
429
  writeState(name, {
427
430
  ...readState(name),
@@ -452,7 +455,7 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
452
455
  return true;
453
456
  }
454
457
  const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", turnStdin ? "-" : shellQuote(wake));
455
- const env = { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) };
458
+ const env = { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total), ...(model ? { BSCHAT_MODEL: model } : {}) };
456
459
  if (turnSink) {
457
460
  // The turn runs in the background; turnStep follows it, acknowledges it once the session shows
458
461
  // it started, and reports how it ended.
@@ -460,11 +463,19 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
460
463
  // The agent's own b9s calls in the turn know who they are without any repo file.
461
464
  // Provider credentials are read only when spawning the turn and are never persisted in the
462
465
  // launchd/systemd service or its command line.
463
- const providerEnv = claudeTurnEnv(provider, model, dependencies.providerRoot);
466
+ const turnModel = model ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
467
+ const providerEnv = claudeTurnEnv(provider, turnModel, dependencies.providerRoot);
464
468
  if (allowTurn && !(await allowTurn()))
465
469
  return false;
466
470
  beforeTurn?.();
467
- turnSink((dependencies.startTurn ?? startTurn)(cmd, { ...env, BSCHAT_AGENT: name, ...providerEnv }, seq, turnStdin ? wake : undefined));
471
+ turnSink((dependencies.startTurn ?? startTurn)(cmd, {
472
+ ...env,
473
+ BSCHAT_AGENT: name,
474
+ ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
475
+ ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
476
+ ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
477
+ ...providerEnv,
478
+ }, seq, turnStdin ? wake : undefined));
468
479
  }
469
480
  else {
470
481
  log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
@@ -522,17 +533,19 @@ const KEY_CHECK_MS = 5 * 60_000;
522
533
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
523
534
  * broken; one that runs past --turn-timeout is stopped and logged.
524
535
  */
525
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR) {
536
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env) {
526
537
  const turn = ctl.turn;
527
538
  if (turn) {
528
539
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
529
540
  turn.confirmed = true;
530
- await ackTurn(name, turn.seq, log);
541
+ await ackTurn(name, turn.seq, log, env);
531
542
  log(`turn #${turn.seq} started in the session; wake-up acknowledged`);
532
543
  }
533
544
  if (turn.exit) {
534
545
  const mins = Math.round((Date.now() - turn.startedMs) / 60_000);
535
546
  const how = turn.exit.code !== null ? `exit ${turn.exit.code}` : `signal ${turn.exit.signal}`;
547
+ if (turn.stdinError)
548
+ log(`turn #${turn.seq}: ${turn.stdinError}`);
536
549
  // A harness may exit 0 with an error in its result (Claude Code's is_error), so both count.
537
550
  let error = null;
538
551
  if (!turn.killedForTimeout) {
@@ -545,7 +558,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
545
558
  }
546
559
  if (turn.exit.code === 0 && !error) {
547
560
  if (!turn.confirmed)
548
- await ackTurn(name, turn.seq, log);
561
+ await ackTurn(name, turn.seq, log, env);
549
562
  log(`turn #${turn.seq} finished after ${mins} min`);
550
563
  }
551
564
  else if (turn.killedForTimeout) {
@@ -564,11 +577,11 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
564
577
  log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged"}${error ? `; ${probe.label} said: ${error}` : ""}${probe.isLimit(error) ? ` (a usage limit with no reset time named)` : ""}. Next turn in 5 min at the earliest; its output is in this log.`);
565
578
  }
566
579
  if (!turn.confirmed)
567
- writeState(name, { ...readState(name), watch_pending: undefined, watch_dormant_logged_at: undefined });
580
+ writeState(name, { ...readState(name, env), watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
568
581
  ctl.failedAt = Date.now();
569
582
  }
570
583
  ctl.turn = null;
571
- await completePendingTurnGuard(name, probe, log);
584
+ await completePendingTurnGuard(name, probe, log, undefined, env);
572
585
  return;
573
586
  }
574
587
  if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
@@ -578,7 +591,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
578
591
  return;
579
592
  }
580
593
  // b9s unpause: the operator switched the harness to an account with quota.
581
- const unpausedAt = readState(name).turn_unpaused_at ?? 0;
594
+ const unpausedAt = readState(name, env).turn_unpaused_at ?? 0;
582
595
  if (ctl.pausedUntil > Date.now() && unpausedAt > ctl.pausedAt) {
583
596
  log(`usage-limit pause lifted by b9s unpause`);
584
597
  ctl.pausedUntil = 0;
@@ -592,23 +605,23 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
592
605
  // running by a watcher that restarted (turns run in their own process group and outlive it).
593
606
  // Never start a second one.
594
607
  const ph = probe.phase();
595
- const savedGuard = readState(name).turn_guard;
608
+ const savedGuard = readState(name, env).turn_guard;
596
609
  if (savedGuard?.fault) {
597
610
  log(`TURN MODE FAULT: ${turnFaultSummary(savedGuard.fault)}; operator/assigner must resume this session before turns can continue`);
598
611
  return;
599
612
  }
600
613
  if ("missing" in ph) {
601
614
  if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
602
- await completePendingTurnGuard(name, probe, log);
603
- if (readState(name).turn_guard?.fault)
615
+ await completePendingTurnGuard(name, probe, log, undefined, env);
616
+ if (readState(name, env).turn_guard?.fault)
604
617
  return;
605
618
  }
606
619
  log(ph.missing);
607
620
  return;
608
621
  }
609
622
  if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
610
- await completePendingTurnGuard(name, probe, log);
611
- if (readState(name).turn_guard?.fault)
623
+ await completePendingTurnGuard(name, probe, log, undefined, env);
624
+ if (readState(name, env).turn_guard?.fault)
612
625
  return;
613
626
  }
614
627
  if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
@@ -633,7 +646,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
633
646
  }
634
647
  // A turn that started before this machine last booted died with it: no process survives a
635
648
  // reboot, and waiting out the quiet limit would idle the agent for up to --turn-timeout.
636
- const bootedAt = Date.now() - uptime() * 1000;
649
+ const bootedAt = ph.running ? Date.now() - uptime() * 1000 : 0;
637
650
  if (ph.running && ph.startedAt && Date.parse(ph.startedAt) < bootedAt) {
638
651
  if (ctl.loggedRunning !== `boot:${ph.startedAt}`)
639
652
  log(`the turn started at ${ph.startedAt} was cut off when this machine restarted (booted ${new Date(bootedAt).toISOString()}); treating it as ended`);
@@ -660,47 +673,50 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
660
673
  ctl.loggedRunning = ph.startedAt;
661
674
  }
662
675
  // A maintenance window on this machine: no new turn from 15 min before it until it ends.
663
- const maint = drainingUntil();
676
+ const maint = drainingUntil(undefined, undefined, env);
664
677
  if (maint) {
665
678
  if (ctl.loggedRunning !== `maint:${maint.start}`)
666
679
  log(`maintenance on this machine ${maint.start.slice(0, 16)} to ${maint.end.slice(11, 16)} UTC: starting no new turns until it ends`);
667
680
  ctl.loggedRunning = `maint:${maint.start}`;
668
681
  return;
669
682
  }
670
- const st = readState(name);
683
+ const st = readState(name, env);
671
684
  if (st.watch_pending) {
672
685
  // Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
673
686
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
674
- writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined });
687
+ writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
675
688
  }
676
689
  await wake((t) => { ctl.turn = t; }, async () => {
677
- return beginTurnGuardAttempt(name, turnsPerHour, log);
690
+ return beginTurnGuardAttempt(name, turnsPerHour, log, env);
678
691
  });
679
692
  }
680
- async function turnActivity(name) {
681
- const snapshot = await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/agents/me/turn-activity");
693
+ async function turnActivity(name, env) {
694
+ const snapshot = await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("GET", "/agents/me/turn-activity");
682
695
  if (!Number.isInteger(snapshot.activity_seq) || snapshot.activity_seq < 0)
683
696
  throw new Error("server returned an invalid turn activity sequence");
684
697
  return snapshot;
685
698
  }
686
699
  /** Reserve every actual harness launch, including b9s start's onboarding turn. */
687
- export async function beginTurnGuardAttempt(name, turnsPerHour, log) {
688
- const before = await turnActivity(name);
689
- const current = readState(name);
700
+ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env) {
701
+ const before = await turnActivity(name, env);
702
+ const current = readState(name, env);
690
703
  if (current.turn_guard?.fault) {
691
704
  log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
692
705
  return false;
693
706
  }
694
707
  const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq);
695
- writeState(name, { ...current, turn_guard: begun.state });
708
+ writeState(name, { ...current, turn_guard: begun.state }, env);
696
709
  if (!begun.start) {
697
710
  log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
698
711
  return false;
699
712
  }
700
713
  return true;
701
714
  }
702
- export async function completePendingTurnGuard(name, probe, log, outputOverride) {
703
- const current = readState(name);
715
+ export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverrideOrEnv, envOverride = process.env) {
716
+ // The watcher passes its isolated environment; start-turn callers may pass measured tokens.
717
+ const env = tokenOverrideOrEnv !== null && typeof tokenOverrideOrEnv === "object" ? tokenOverrideOrEnv : envOverride;
718
+ const tokenOverride = tokenOverrideOrEnv === null || typeof tokenOverrideOrEnv === "number" ? tokenOverrideOrEnv : undefined;
719
+ const current = readState(name, env);
704
720
  const guard = current.turn_guard;
705
721
  const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
706
722
  if (!guard || !pending || pending.activity_seq_before === undefined)
@@ -708,7 +724,7 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride)
708
724
  let activitySeq = pending.activity_seq_before;
709
725
  let sampleError = null;
710
726
  try {
711
- activitySeq = (await turnActivity(name)).activity_seq;
727
+ activitySeq = (await turnActivity(name, env)).activity_seq;
712
728
  }
713
729
  catch (e) {
714
730
  sampleError = `could not verify the agent's BenignSwarm activity: ${e.message}`;
@@ -733,16 +749,20 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride)
733
749
  }
734
750
  else
735
751
  output = outputOverride;
736
- try {
737
- directTokens = probe.turnTokens?.() ?? null;
738
- }
739
- catch (e) {
740
- sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
741
- }
752
+ if (tokenOverride !== undefined)
753
+ directTokens = tokenOverride;
754
+ else
755
+ try {
756
+ directTokens = probe.turnTokens?.() ?? null;
757
+ }
758
+ catch (e) {
759
+ sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
760
+ }
742
761
  output = (output || error || sampleError || "").slice(-800);
743
762
  const measured = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()).tokens?.total ?? 0 : 0;
744
- const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null);
745
- writeState(name, { ...current, turn_guard: nextGuard });
763
+ const tokenCount = tokenOverride !== undefined ? tokenOverride : directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null;
764
+ const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount);
765
+ writeState(name, { ...current, turn_guard: nextGuard }, env);
746
766
  if (!productive)
747
767
  log(`turn made no agent-key call to BenignSwarm (${nextGuard.consecutive_unproductive}/${MAX_UNPRODUCTIVE_TURNS} consecutive); ${nextGuard.fault ? `FAULT: ${turnFaultSummary(nextGuard.fault)}` : `last output: ${output || "(empty)"}`}`);
748
768
  else if (nextGuard.consecutive_unproductive === 0)
@@ -752,10 +772,10 @@ function turnFaultSummary(fault) {
752
772
  return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `hourly ceiling reached (${fault.turns_last_hour} turns in the last hour)`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
753
773
  }
754
774
  /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
755
- async function ackTurn(name, seq, log) {
756
- writeState(name, applyAck(readState(name), seq).next);
775
+ async function ackTurn(name, seq, log, env = process.env) {
776
+ writeState(name, applyAck(readState(name, env), seq).next, env);
757
777
  try {
758
- await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
778
+ await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
759
779
  }
760
780
  catch (e) {
761
781
  log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
@@ -6,6 +6,7 @@ import { CliError } from "../errors.js";
6
6
  import { spawnSync } from "node:child_process";
7
7
  import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
8
8
  import { table } from "../output.js";
9
+ import { collectPruneProtection } from "../prune-protection.js";
9
10
  const CLOSED = ["done", "abandoned", "superseded"];
10
11
  const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
11
12
  const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
@@ -88,7 +89,8 @@ export async function worktrees(p, out, timeouts = {}) {
88
89
  const requestTimeoutMs = timeouts.requestTimeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
89
90
  const statusTimeoutMs = timeouts.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS;
90
91
  const units = await unitWorktrees(creds, project, { timeoutMs: requestTimeoutMs, onProgress: progress });
91
- const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs });
92
+ const protection = await collectPruneProtection(creds, project);
93
+ const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs, ...protection });
92
94
  // --archive: a closed unit's worktree with uncommitted files is saved to archive/wu<n>-leftovers
93
95
  // and then removed. Never for a unit still open, never for a worktree whose status is unreadable.
94
96
  const archive = bool(p.flags, "archive") ? rep.kept.filter((k) => k.archivable) : [];