benignswarm 0.12.88 → 0.12.90

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
@@ -2,9 +2,9 @@ import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
3
  // These options accept comma-separated collections, so repeating them should
4
4
  // append another collection instead of discarding earlier values.
5
- export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires"];
6
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect"];
7
- export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted"];
5
+ export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks"];
6
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks"];
7
+ export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source"];
8
8
  export function parse(argv) {
9
9
  const options = {};
10
10
  for (const f of STRING_FLAGS)
package/dist/brief.js CHANGED
@@ -38,15 +38,20 @@ export async function fetchRecoveryBrief(nameOrRef) {
38
38
  return { ...response.brief, notices: active.notices };
39
39
  }
40
40
  export function formatRecoveryBrief(brief) {
41
+ const scope = (base, amendments, omitted = 0) => [
42
+ ...(base ? [`\n base scope: ${base}`] : []),
43
+ ...(amendments ?? []).map((amendment) => `\n amendment ${amendment.at} ${amendment.author}: ${amendment.text}`),
44
+ ...(omitted ? [`\n ${omitted} older scope amendments omitted`] : []),
45
+ ].join("");
41
46
  const lines = [`[b9s] Resume brief for ${brief.agent}`, `Role: ${brief.role}`];
42
47
  if (brief.projects.length)
43
48
  lines.push(`Process: ${brief.projects.map((p) => `${p.name} ${p.process} (${Array.isArray(p.changed_since_last_read) ? `changed since you last read: ${p.changed_since_last_read.join("; ")}` : p.changed_since_last_read})`).join("; ")}`);
44
49
  lines.push("Questions waiting on you:");
45
50
  lines.push(...(brief.questions.length ? brief.questions.map((q) => ` ${q.project} WU #${q.number} (${q.age_minutes ?? 0} min ago): ${q.question} — ${q.next}`) : [" none"]));
46
51
  lines.push("Units:");
47
- lines.push(...(brief.units.length ? brief.units.map((u) => ` [${u.state}] ${u.project} WU #${u.number} ${u.title} — ${u.next}`) : [" none"]));
52
+ lines.push(...(brief.units.length ? brief.units.map((u) => ` [${u.state}] ${u.project} WU #${u.number} ${u.title}${scope(u.base_scope, u.scope_amendments, u.scope_amendments_omitted)} — ${u.next}`) : [" none"]));
48
53
  lines.push("Reviews waiting on you:");
49
- lines.push(...(brief.reviews.length ? brief.reviews.map((r) => ` ${r.project} ${r.slice ? `slice ${r.slice}` : `WU #${r.number}`} ${r.title} — ${r.next}`) : [" none"]));
54
+ lines.push(...(brief.reviews.length ? brief.reviews.map((r) => ` ${r.project} ${r.slice ? `slice ${r.slice}` : `WU #${r.number}`} ${r.title}${scope(r.base_scope, r.scope_amendments, r.scope_amendments_omitted)} — ${r.next}`) : [" none"]));
50
55
  lines.push("Open asks:");
51
56
  lines.push(...(brief.asks.length ? brief.asks.slice(0, 10).map((a) => ` ${a.project} ask ${a.id}: ${a.question} (${a.blocks}) — ${a.next}`) : [" none"]));
52
57
  lines.push("Slices:");
package/dist/client.js CHANGED
@@ -51,7 +51,7 @@ export class Client {
51
51
  for (let attempt = 0;; attempt++) {
52
52
  let res;
53
53
  try {
54
- res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
54
+ res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: opts.signal });
55
55
  }
56
56
  catch (e) {
57
57
  if (attempt < retries) {
@@ -68,6 +68,8 @@ export async function admin(p, out) {
68
68
  return agent(action, rest, p, out);
69
69
  case "role":
70
70
  return role(action, rest, p, out);
71
+ case "wu":
72
+ return workUnitAdmin(action, rest, p, out);
71
73
  case "channel":
72
74
  return channel(action, rest, p, out);
73
75
  case "enroll":
@@ -278,8 +280,8 @@ async function role(action, rest, p, out) {
278
280
  const base = proj ? `/projects/${proj}/roles` : "/roles";
279
281
  if (action === "list") {
280
282
  const r = await c.call("GET", base);
281
- const rows = r.roles.map((x) => ({ name: x.name, scope: x.project_id ? "project" : "account", reviews: (x.reviews ?? []).join(",") || "-", works: (x.works ?? []).join(",") || "-", trials: (x.trials ?? []).join(",") || "-", cardinality: x.cardinality, projects: x.project_id ? "(own)" : (x.permissions.projects ?? []).join(",") || "(none)", post: x.permissions.post_channels.join(","), broadcast: x.permissions.broadcast, create_channels: x.permissions.create_channels, read_account_status: x.permissions.read_account_status }));
282
- out.print(table(rows, ["name", "scope", "reviews", "works", "trials", "cardinality", "projects", "post", "broadcast", "create_channels", "read_account_status"]), r);
283
+ const rows = r.roles.map((x) => ({ name: x.name, scope: x.project_id ? "project" : "account", reviews: (x.reviews ?? []).join(",") || "-", works: (x.works ?? []).join(",") || "-", trials: (x.trials ?? []).join(",") || "-", assign_outside_qualifications: !!x.assign_outside_qualifications, cardinality: x.cardinality, projects: x.project_id ? "(own)" : (x.permissions.projects ?? []).join(",") || "(none)", post: x.permissions.post_channels.join(","), broadcast: x.permissions.broadcast, create_channels: x.permissions.create_channels, read_account_status: x.permissions.read_account_status }));
284
+ out.print(table(rows, ["name", "scope", "reviews", "works", "trials", "assign_outside_qualifications", "cardinality", "projects", "post", "broadcast", "create_channels", "read_account_status"]), r);
283
285
  }
284
286
  else if (action === "create" && rest[0]) {
285
287
  const permissions = permsFromFlags(p, !!proj) ?? { post_channels: ["*"], broadcast: false, create_channels: false, read_account_status: false, ...(proj ? {} : { projects: [] }) };
@@ -294,6 +296,12 @@ async function role(action, rest, p, out) {
294
296
  const card = str(p.flags, "cardinality");
295
297
  if (card !== undefined)
296
298
  body.cardinality = card;
299
+ const assignOutside = str(p.flags, "assign-outside-qualifications");
300
+ if (assignOutside !== undefined) {
301
+ if (assignOutside !== "yes" && assignOutside !== "no")
302
+ throw new CliError("usage", "--assign-outside-qualifications must be yes or no");
303
+ body.assign_outside_qualifications = assignOutside === "yes";
304
+ }
297
305
  const permissions = permsFromFlags(p, !!proj);
298
306
  if (permissions)
299
307
  body.permissions = permissions;
@@ -303,7 +311,7 @@ async function role(action, rest, p, out) {
303
311
  body[q] = v;
304
312
  }
305
313
  if (!Object.keys(body).length)
306
- throw new CliError("usage", "role edit needs --description, --cardinality, --projects, --post, --broadcast, --create-channels, --read-account-status, --permissions, --reviews, --works or --trials");
314
+ throw new CliError("usage", "role edit needs --description, --cardinality, --assign-outside-qualifications yes|no, --projects, --post, --broadcast, --create-channels, --read-account-status, --permissions, --reviews, --works or --trials");
307
315
  const r = await c.call("PATCH", `${base}/${rest[0]}`, body);
308
316
  out.print(`updated role ${r.role.name}: reviews=${(r.role.reviews ?? []).join(",") || "-"} works=${(r.role.works ?? []).join(",") || "-"} trials=${(r.role.trials ?? []).join(",") || "-"} projects=${r.role.permissions.projects.join(",") || "(none)"} post=${r.role.permissions.post_channels.join(",")} broadcast=${r.role.permissions.broadcast}`, r);
309
317
  }
@@ -312,7 +320,17 @@ async function role(action, rest, p, out) {
312
320
  out.print(`deleted role ${rest[0]}`, r);
313
321
  }
314
322
  else
315
- throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--description d] [--cardinality one|many]");
323
+ throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]");
324
+ }
325
+ async function workUnitAdmin(action, rest, p, out) {
326
+ if (action !== "assign" || !rest[0] || !/^\d+$/.test(rest[1] ?? ""))
327
+ throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
328
+ const to = str(p.flags, "to");
329
+ if (!to)
330
+ throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
331
+ const reason = str(p.flags, "reason");
332
+ const r = await adminClient(p).call("POST", `/projects/${rest[0]}/work-units/${Number(rest[1])}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
333
+ out.print(`WU #${r.unit.number} reassigned to ${r.unit.owner_name || r.unit.preferred_name}${r.unit.status === "queued" ? "; queued until they are free" : ""}.`, r);
316
334
  }
317
335
  async function channel(action, rest, p, out) {
318
336
  const c = adminClient(p);
@@ -11,9 +11,11 @@ import { codexHooksPath } from "./codex.js";
11
11
  import { isCodexManagedRequirements } from "../harness.js";
12
12
  import { readState, writeState } from "../state.js";
13
13
  import { join } from "./join.js";
14
- import { installWatcherService } from "./watch.js";
14
+ import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService } from "./watch.js";
15
15
  import { randomUUID } from "node:crypto";
16
- import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog } from "../harnesses.js";
16
+ import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
17
+ import { claudeTurnEnv } from "../providers.js";
18
+ import { DEFAULT_TURNS_PER_HOUR } from "../turn-guard.js";
17
19
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
18
20
  /**
19
21
  * `b9s start` (and `b9s codex start`): one command that brings an agent up on this machine
@@ -42,6 +44,9 @@ export async function harnessStart(p, out, harness) {
42
44
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
43
45
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
44
46
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
47
+ const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
48
+ if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
49
+ throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
45
50
  const interval = Number(str(p.flags, "interval") ?? "30");
46
51
  if (!Number.isInteger(interval) || interval < 5)
47
52
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
@@ -50,6 +55,13 @@ export async function harnessStart(p, out, harness) {
50
55
  const dshOverride = str(p.flags, "dsh");
51
56
  if (harness !== "dsh" && dshOverride)
52
57
  throw new CliError("usage", "--dsh is only valid with --harness dsh");
58
+ const providerName = str(p.flags, "provider") ?? "anthropic";
59
+ if (providerName !== "anthropic" && providerName !== "deepseek")
60
+ throw new CliError("usage", "--provider must be anthropic or deepseek");
61
+ const provider = providerName;
62
+ if (provider === "deepseek" && harness !== "claude-code")
63
+ throw new CliError("usage", "--provider deepseek requires --harness claude-code");
64
+ const model = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
53
65
  const bin = harness === "dsh"
54
66
  ? dshPath(dshOverride)
55
67
  : which(HARNESS_BIN[harness], harness === "codex" ? "install the Codex CLI (npm i -g @openai/codex)" : "install Claude Code (npm i -g @anthropic-ai/claude-code)");
@@ -57,9 +69,7 @@ export async function harnessStart(p, out, harness) {
57
69
  throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
58
70
  if (harness === "dsh" && !existsSync(bin))
59
71
  throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
60
- const model = str(p.flags, "model");
61
72
  const effort = str(p.flags, "effort");
62
- const adopt = str(p.flags, "thread") ?? str(p.flags, "session");
63
73
  // The machine's toolchain and job folders a sandboxed agent may also write (b9s-admin machine writable).
64
74
  const writable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean).map((w) => (w.startsWith("~/") ? joinPath(homedir(), w.slice(2)) : w));
65
75
  if (writable.some((w) => !w.startsWith("/")))
@@ -70,6 +80,7 @@ export async function harnessStart(p, out, harness) {
70
80
  : harness === "dsh"
71
81
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
72
82
  : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
83
+ const providerEnv = claudeTurnEnv(harness === "claude-code" ? provider : undefined, model);
73
84
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
74
85
  const lines = [];
75
86
  const token = str(p.flags, "token");
@@ -82,6 +93,14 @@ export async function harnessStart(p, out, harness) {
82
93
  if (creds.vendor && creds.vendor !== harness)
83
94
  throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not ${harness}`);
84
95
  const ref = agentRef(creds);
96
+ const priorState = readState(ref);
97
+ if (priorState.turn_guard?.fault) {
98
+ const fault = priorState.turn_guard.fault;
99
+ throw new CliError("turn_mode_fault", `turn mode is stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.turns_last_hour} turns in the rolling hour`}; resume it with b9s-admin machine session resume; last output: ${fault.output_tail || "(empty)"}`);
100
+ }
101
+ const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
102
+ const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
103
+ const adopt = str(p.flags, "thread") ?? str(p.flags, "session") ?? rememberedSession ?? undefined;
85
104
  requireInstall();
86
105
  // 2. Its session: adopt one, or start one headless with an onboarding turn.
87
106
  let session;
@@ -115,36 +134,52 @@ export async function harnessStart(p, out, harness) {
115
134
  else {
116
135
  const logDir = joinPath(configRoot(), "logs");
117
136
  mkdirSync(logDir, { recursive: true });
118
- firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.${harness === "codex" ? "jsonl" : "json"}`);
137
+ firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
119
138
  const prompt = [
120
139
  `[b9s] You are ${ref}, a BenignSwarm agent, started headless by \`b9s ${cmd}\`; nobody is typing to you.`,
121
140
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
122
141
  `Now: run \`b9s me\`, \`b9s process\` and \`b9s inbox --unread\`, then do what your role and inbox ask.`,
123
142
  `If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
124
143
  ].join("\n");
125
- if (harness === "codex") {
126
- session = await startThread(bin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
127
- lines.push(`Started Codex thread ${session}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
144
+ const diagnostic = [];
145
+ if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m)))) {
146
+ throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the onboarding turn");
128
147
  }
129
- else if (harness === "dsh") {
130
- const started = await startDshSession(bin, dshStartArgs(settings), firstTurnLog, ref, prompt);
131
- session = started.session;
132
- initialPid = started.pid;
133
- lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
148
+ try {
149
+ if (harness === "codex") {
150
+ session = await startThread(bin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
151
+ lines.push(`Started Codex thread ${session}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
152
+ }
153
+ else if (harness === "dsh") {
154
+ const started = await startDshSession(bin, dshStartArgs(settings), firstTurnLog, ref, prompt);
155
+ session = started.session;
156
+ initialPid = started.pid;
157
+ lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
158
+ }
159
+ else {
160
+ // Claude Code takes the session id from us, so nothing has to be read back from its output.
161
+ session = randomUUID();
162
+ await startClaudeSession(bin, ["-p", prompt, ...settings, "--session-id", session, "--output-format", "json"], firstTurnLog, ref, session, providerEnv);
163
+ lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
164
+ }
134
165
  }
135
- else {
136
- // Claude Code takes the session id from us, so nothing has to be read back from its output.
137
- session = randomUUID();
138
- await startClaudeSession(bin, ["-p", prompt, ...settings, "--session-id", session, "--output-format", "json"], firstTurnLog, ref, session);
139
- lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
166
+ catch (error) {
167
+ const raw = existsSync(firstTurnLog) ? readFileSync(firstTurnLog, "utf8").slice(-800) : "";
168
+ await completePendingTurnGuard(ref, probeFor(harness, session ?? "", ref), (m) => diagnostic.push(m), `${error.message}\n${raw}`.slice(-800));
169
+ const fault = readState(ref).turn_guard?.fault;
170
+ if (fault)
171
+ throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
172
+ throw error;
140
173
  }
141
174
  }
175
+ if (!session)
176
+ throw new CliError("harness_failed", "the harness did not provide a session id");
142
177
  // 3. Bind it, so the hooks in that session deliver to this agent and nobody else. Claude Code's
143
178
  // hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
144
179
  if (harness === "codex")
145
180
  bindSession("codex", session, ref);
146
- if (harness === "dsh")
147
- writeState(ref, { ...readState(ref), harness_session: { harness, transcript: dshTurnLog(ref), session_id: session, at: Date.now(), ...(initialPid ? { initial_pid: initialPid } : {}) } });
181
+ const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
182
+ writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(initialPid ? { initial_pid: initialPid } : {}) } });
148
183
  // A session adopted here may end in a usage-limit error from the machine it came from, written in
149
184
  // that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
150
185
  // from turns on this machine pause it; if the account is still limited, the next turn says so here.
@@ -164,7 +199,7 @@ export async function harnessStart(p, out, harness) {
164
199
  // volume had 750 GB free, and which empties /tmp at every boot.
165
200
  const tmp = sessionTmpDir(process.cwd(), creds.agent);
166
201
  mkdirSync(tmp, { recursive: true });
167
- installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout });
202
+ installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, turnsPerHour, provider, model });
168
203
  const wl = watcherOut.join("\n").split("\n");
169
204
  lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
170
205
  // 5. Hooks.
@@ -186,7 +221,7 @@ export async function harnessStart(p, out, harness) {
186
221
  lines.push(harness === "dsh"
187
222
  ? `DeepSeek Harness failures, including balance or rate limits, are recorded and retried after the ordinary 5-minute backoff; no reset time is inferred from their text.`
188
223
  : `If the ${label} account hits its usage limit, the watcher pauses turns until the time ${label} gives; after switching to an account with quota, resume at once: b9s unpause --as ${ref}`);
189
- out.print(lines.join("\n"), { agent: ref, harness, thread: session, session, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
224
+ out.print(lines.join("\n"), { agent: ref, harness, provider, thread: session, session, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
190
225
  }
191
226
  export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
192
227
  export const dshResumeArgs = (session, settings) => ["--profile", "headless", "--json", "--session-id", session, ...settings, "-"];
@@ -232,9 +267,9 @@ export async function startDshSession(bin, args, logPath, agent, prompt) {
232
267
  * minutes; this command does not wait for it) and returns once its transcript exists, or fails
233
268
  * with Claude Code's own error when it exits first.
234
269
  */
235
- async function startClaudeSession(bin, args, logPath, agent, session) {
270
+ async function startClaudeSession(bin, args, logPath, agent, session, providerEnv) {
236
271
  const fd = openSync(logPath, "w");
237
- const child = spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent } });
272
+ const child = spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent, ...providerEnv } });
238
273
  closeSync(fd);
239
274
  let exited = null;
240
275
  child.on("exit", (code) => { exited = code ?? 1; });
@@ -132,8 +132,10 @@ export async function machineAdmin(action, rest, p, out) {
132
132
  `${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
133
  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
134
  ];
135
- const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", 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
- return out.print([...head, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
135
+ 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
+ const providers = rep.claude_code?.providers ?? {};
137
+ 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);
137
139
  }
138
140
  if (action === "maintenance") {
139
141
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -193,22 +195,37 @@ export async function machineAdmin(action, rest, p, out) {
193
195
  const [sub, machineName, ref] = rest;
194
196
  const [project, agent] = (ref ?? "").split("/");
195
197
  if (!sub || !machineName || !project || !agent)
196
- throw new CliError("usage", "machine session add|stop|start|remove <machine> <project>/<agent> [...]");
198
+ throw new CliError("usage", "machine session add|stop|start|resume|limit|remove <machine> <project>/<agent> [...]");
197
199
  if (sub === "add") {
198
200
  const turnTimeout = str(p.flags, "turn-timeout");
201
+ const turnsPerHour = str(p.flags, "turns-per-hour");
202
+ if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 20))
203
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
199
204
  const body = {
200
- project, agent, harness: str(p.flags, "harness") ?? "codex", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
205
+ project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
201
206
  model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
202
207
  ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
208
+ ...(turnsPerHour ? { turns_per_hour: Number(turnsPerHour) } : {}),
203
209
  create: bool(p.flags, "create"), role: str(p.flags, "role"),
204
210
  };
205
211
  const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
206
- return out.print(`Declared ${r.session.agent} on ${machineName} (${r.session.harness}, ${r.session.sandbox}, ${r.session.dir}). Its daemon starts it within 30 s: b9s-admin machine show ${machineName}`, r);
212
+ return out.print(`Declared ${r.session.agent} on ${machineName} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir}). Its daemon starts it within 30 s: b9s-admin machine show ${machineName}`, r);
207
213
  }
208
214
  if (sub === "stop" || sub === "start") {
209
215
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { desired: sub === "stop" ? "stopped" : "running" });
210
216
  return out.print(`${ref} on ${machineName}: desired ${r.session.desired}; its daemon acts within 30 s.`, r);
211
217
  }
218
+ if (sub === "resume") {
219
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { resume_turns: true });
220
+ return out.print(`${ref} on ${machineName}: turn mode resumed explicitly; its daemon applies the request within 30 s.`, r);
221
+ }
222
+ if (sub === "limit") {
223
+ const value = str(p.flags, "turns-per-hour");
224
+ if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 20)
225
+ throw new CliError("usage", "machine session limit <machine> <project>/<agent> --turns-per-hour <1..20>");
226
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { turns_per_hour: Number(value) });
227
+ return out.print(`${ref} on ${machineName}: turn limit set to ${value} per hour; the daemon applies it within 30 s.`, r);
228
+ }
212
229
  if (sub === "remove") {
213
230
  await c.call("DELETE", `/machines/${machineName}/sessions/${project}/${agent}`);
214
231
  return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
@@ -216,12 +233,14 @@ export async function machineAdmin(action, rest, p, out) {
216
233
  }
217
234
  throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
218
235
  }
219
- /** `[tag=]harness:model[:effort][*weight]`, e.g. `luna=codex:gpt-6-luna:medium*2`. */
236
+ /** `[tag=]harness:model[:effort][*weight][@provider]`, e.g. `luna=claude-code:deepseek-flash@deepseek`. */
220
237
  export function parseVariant(spec) {
221
- const m = /^(?:([a-z0-9][a-z0-9-]*)=)?([a-z0-9-]+)(?::([^:*]+))?(?::([^:*]+))?(?:\*(\d+))?$/.exec(spec.trim());
238
+ const m = /^(?:([a-z0-9][a-z0-9-]*)=)?([a-z0-9-]+)(?::([^:*@]+))?(?::([^:*@]+))?(?:\*(\d+))?(?:@(anthropic|deepseek))?$/.exec(spec.trim());
222
239
  if (!m)
223
- throw new CliError("usage", `--variant ${spec}: expected [tag=]harness:model[:effort][*weight], e.g. luna=codex:gpt-6-luna:medium*2`);
224
- return { ...(m[1] ? { tag: m[1] } : {}), harness: m[2], ...(m[3] ? { model: m[3] } : {}), ...(m[4] ? { effort: m[4] } : {}), ...(m[5] ? { weight: Number(m[5]) } : {}) };
240
+ throw new CliError("usage", `--variant ${spec}: expected [tag=]harness:model[:effort][*weight][@provider], e.g. luna=claude-code:deepseek-flash@deepseek`);
241
+ if (m[6] === "deepseek" && m[2] !== "claude-code")
242
+ throw new CliError("usage", "@deepseek requires the claude-code harness");
243
+ return { ...(m[1] ? { tag: m[1] } : {}), harness: m[2], ...(m[3] ? { model: m[3] } : {}), ...(m[4] ? { effort: m[4] } : {}), ...(m[5] ? { weight: Number(m[5]) } : {}), ...(m[6] ? { provider: m[6] } : {}) };
225
244
  }
226
245
  /** Every value of a repeatable flag (the parser keeps the last; read them from argv). */
227
246
  export function repeated(argv, flag) {
@@ -235,13 +254,13 @@ export function repeated(argv, flag) {
235
254
  return out;
236
255
  }
237
256
  /**
238
- * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min]
257
+ * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]
239
258
  * pool list [project] | show <project>/<name> | remove <project>/<name>
240
259
  */
241
260
  export async function poolAdmin(action, rest, p, out, argv) {
242
261
  const c = adminClient(p);
243
262
  const statusLines = (pool) => [
244
- `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
263
+ `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; max ${pool.turns_per_hour ?? 20} turns/hour; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
245
264
  ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
246
265
  ...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
247
266
  ];
@@ -250,10 +269,13 @@ export async function poolAdmin(action, rest, p, out, argv) {
250
269
  const variants = repeated(argv, "variant").map(parseVariant);
251
270
  const count = Number(str(p.flags, "count"));
252
271
  if (!project || !name || !variants.length || !Number.isInteger(count))
253
- throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min]");
272
+ throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]");
254
273
  const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
255
274
  const tt = str(p.flags, "turn-timeout");
256
- const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}) });
275
+ const tph = str(p.flags, "turns-per-hour");
276
+ if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 20))
277
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
278
+ const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}) });
257
279
  return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
258
280
  }
259
281
  if (action === "list" || action === undefined) {
@@ -340,7 +362,7 @@ function on(host, command, input) {
340
362
  return ssh(host, command, input);
341
363
  }
342
364
  /**
343
- * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--model m] [--effort e]
365
+ * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
344
366
  * [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min] [--force]
345
367
  *
346
368
  * The agent (name, role, record, units, chat) is on the server and does not move; its harness
@@ -354,10 +376,16 @@ export async function agentMove(rest, p, out) {
354
376
  const [project, agent] = ref.split("/");
355
377
  const to = str(p.flags, "to");
356
378
  const sandbox = str(p.flags, "sandbox");
379
+ const harness = str(p.flags, "harness") ?? "codex";
380
+ const provider = str(p.flags, "provider") ?? "anthropic";
357
381
  const carry = str(p.flags, "carry") ?? "note";
358
382
  const from = str(p.flags, "from");
359
383
  if (!project || !agent || !to || !sandbox)
360
- throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]");
384
+ throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]");
385
+ if (provider !== "anthropic" && provider !== "deepseek")
386
+ throw new CliError("usage", "--provider must be anthropic or deepseek");
387
+ if (provider === "deepseek" && harness !== "claude-code")
388
+ throw new CliError("usage", "--provider deepseek requires --harness claude-code");
361
389
  if (carry !== "note" && carry !== "thread")
362
390
  throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
363
391
  if (carry === "thread" && (str(p.flags, "harness") ?? "codex") !== "codex")
@@ -465,11 +493,11 @@ export async function agentMove(rest, p, out) {
465
493
  // 3. The new machine runs it; every other key stops working.
466
494
  const turnTimeout = str(p.flags, "turn-timeout");
467
495
  const r = await c.call("POST", `/machines/${to}/sessions`, {
468
- project, agent, move: true, harness: str(p.flags, "harness") ?? "codex", dir: str(p.flags, "dir") ?? "auto", sandbox,
496
+ project, agent, move: true, harness, provider, dir: str(p.flags, "dir") ?? "auto", sandbox,
469
497
  model, effort, ...(thread ? { thread } : {}), ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
470
498
  });
471
499
  return out.print([
472
- `${ref} now runs on ${to} (${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh thread"}); its daemon starts it within 30 s.`,
500
+ `${ref} now runs on ${to} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh session"}); its daemon starts it within 30 s.`,
473
501
  r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
474
502
  `${r.revoked_keys} key(s) elsewhere revoked: a watcher left running there stops and removes itself. Archive its old thread in the Codex app so nobody types into that copy.`,
475
503
  problems.length ? `Left behind (--force): ${problems.join("; ")}` : null,
@@ -15,6 +15,8 @@ import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, remove
15
15
  import { CLI_VERSION } from "../version.js";
16
16
  import { probeCapabilities } from "../capabilities.js";
17
17
  import { diskSpaceNotice } from "../notices.js";
18
+ import { verifyClaudeProvider } from "../providers.js";
19
+ import { resumeTurnGuard } from "../turn-guard.js";
18
20
  export const machineFile = () => join(configRoot(), "machine.json");
19
21
  export function loadMachine() {
20
22
  const f = machineFile();
@@ -34,8 +36,8 @@ function writeMachineState(s) {
34
36
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
35
37
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
36
38
  */
37
- const START_REV = 3;
38
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
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}`] : [])]);
39
41
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
40
42
  /**
41
43
  * During a maintenance drain or window, a session that would be started fresh (no known thread, so
@@ -54,7 +56,8 @@ export function maintenanceReport(drain, sessions) {
54
56
  /** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
55
57
  export function startArgs(s, thread, writable = []) {
56
58
  return [
57
- "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--json",
59
+ "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? 20), "--json",
60
+ ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
58
61
  ...(s.model ? ["--model", s.model] : []),
59
62
  ...(s.effort ? ["--effort", s.effort] : []),
60
63
  ...(thread ? ["--thread", thread] : []),
@@ -69,6 +72,14 @@ export async function reconcile(m, log) {
69
72
  const client = Client.raw(m.url, m.key);
70
73
  const me = await client.call("GET", "/machines/me");
71
74
  const desired = me.sessions;
75
+ const providerChecks = new Set(["anthropic"]);
76
+ for (const provider of me.provider_checks ?? []) {
77
+ if (provider === "anthropic" || provider === "deepseek")
78
+ providerChecks.add(provider);
79
+ }
80
+ for (const s of desired)
81
+ if (s.harness === "claude-code" && (s.provider === "anthropic" || s.provider === "deepseek"))
82
+ providerChecks.add(s.provider);
72
83
  const projects = me.projects ?? [];
73
84
  const workdir = me.machine?.workdir ?? null;
74
85
  const writable = me.machine?.writable ?? [];
@@ -104,6 +115,10 @@ export async function reconcile(m, log) {
104
115
  }
105
116
  if (!TURN_HARNESSES.includes(s.harness))
106
117
  throw new Error(`harness ${s.harness} is not supported by this b9s ${CLI_VERSION}`);
118
+ if (s.provider && s.provider !== "anthropic" && s.provider !== "deepseek")
119
+ throw new Error(`provider ${s.provider} is not supported by this b9s ${CLI_VERSION}`);
120
+ if ((s.provider ?? "anthropic") === "deepseek" && s.harness !== "claude-code")
121
+ throw new Error("provider deepseek requires harness claude-code");
107
122
  if (!s.dir) {
108
123
  // A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
109
124
  const c = ensureCheckout(s, log, workdir);
@@ -116,6 +131,26 @@ export async function reconcile(m, log) {
116
131
  if (!existsSync(s.dir))
117
132
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
118
133
  const local = state.sessions[s.id];
134
+ let agentState = readState(s.agent);
135
+ if (s.turn_resume_at && agentState.turn_resume_applied_at !== s.turn_resume_at) {
136
+ agentState = { ...agentState, turn_guard: resumeTurnGuard(agentState.turn_guard), turn_resume_applied_at: s.turn_resume_at };
137
+ writeState(s.agent, agentState);
138
+ log(`${s.agent}: operator/assigner resumed turn mode`);
139
+ }
140
+ if (agentState.turn_guard?.fault) {
141
+ const fault = agentState.turn_guard.fault;
142
+ const detail = fault.reason === "unproductive"
143
+ ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call; likely cause: ${fault.likely_cause}`
144
+ : `the ${fault.turns_last_hour}-turn hourly ceiling was reached; likely cause: ${fault.likely_cause}`;
145
+ const error = `turn mode stopped after ${detail}; estimated tokens spent: ${fault.estimated_tokens}; last turn output: ${fault.output_tail || "(empty)"}`.slice(0, 1000);
146
+ const w = svc();
147
+ if (w) {
148
+ removeService(w);
149
+ log(`${s.agent}: turn mode fault; watcher service stopped`);
150
+ }
151
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error });
152
+ continue;
153
+ }
119
154
  if (local) {
120
155
  const conflict = existingSessionDirectoryConflict(s.id, s.dir, local.thread, s.agent);
121
156
  if (conflict) {
@@ -190,7 +225,7 @@ export async function reconcile(m, log) {
190
225
  writeMachineState(state);
191
226
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
192
227
  const report = {
193
- ...machineFacts(), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones,
228
+ ...machineFacts([...providerChecks]), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones,
194
229
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
195
230
  maintenance: maintenanceReport(drainingUntil(), out),
196
231
  };
@@ -530,16 +565,23 @@ function memAvailable() {
530
565
  }
531
566
  /** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
532
567
  let claudeSandboxCache = null;
533
- function claudeReport(path = process.env.PATH ?? "") {
568
+ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"]) {
534
569
  const f = claudeFacts(undefined, path);
535
570
  if (!f)
536
571
  return null;
537
572
  if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
538
573
  claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
539
- return { ...f, sandbox: claudeSandboxCache.result };
574
+ const providers = {};
575
+ for (const provider of providersInUse) {
576
+ const check = provider === "anthropic"
577
+ ? { logged_in: f.logged_in, reason: f.verified.error }
578
+ : verifyClaudeProvider(provider);
579
+ providers[provider] = { ...check, sandbox: claudeSandboxCache.result };
580
+ }
581
+ return { ...f, sandbox: claudeSandboxCache.result, providers };
540
582
  }
541
583
  /** What the operator needs to know about this machine, reported with every pass. */
542
- export function machineFacts() {
584
+ export function machineFacts(providersInUse = ["anthropic"]) {
543
585
  const path = process.env.PATH ?? "";
544
586
  const env = { ...process.env, PATH: path };
545
587
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
@@ -554,6 +596,7 @@ export function machineFacts() {
554
596
  diskFree = null;
555
597
  }
556
598
  const req = "/etc/codex/requirements.toml";
599
+ const claude = claudeReport(path, providersInUse);
557
600
  return {
558
601
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
559
602
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
@@ -562,7 +605,8 @@ export function machineFacts() {
562
605
  daemon_path: path,
563
606
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
564
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,
565
- "claude-code": claudeReport(path),
608
+ "claude-code": claude,
609
+ claude_code: claude,
566
610
  dsh,
567
611
  managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
568
612
  linger: platform() === "linux" ? lingerEnabled() : null,
@@ -704,7 +748,7 @@ export async function machine(p, out) {
704
748
  const state = readMachineState();
705
749
  const rows = desired.map((s) => {
706
750
  const w = watcherServices().find((x) => x.label === watchLabelOf(s.agent));
707
- return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"} ${s.dir}`;
751
+ return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"} ${s.dir}`;
708
752
  });
709
753
  return out.print([`machine ${m.name} (${m.url})`, ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state });
710
754
  }