benignswarm 0.12.87 → 0.12.89

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", "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:");
@@ -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);
@@ -14,6 +14,7 @@ import { join } from "./join.js";
14
14
  import { installWatcherService } from "./watch.js";
15
15
  import { randomUUID } from "node:crypto";
16
16
  import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog } from "../harnesses.js";
17
+ import { claudeTurnEnv } from "../providers.js";
17
18
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
18
19
  /**
19
20
  * `b9s start` (and `b9s codex start`): one command that brings an agent up on this machine
@@ -50,6 +51,13 @@ export async function harnessStart(p, out, harness) {
50
51
  const dshOverride = str(p.flags, "dsh");
51
52
  if (harness !== "dsh" && dshOverride)
52
53
  throw new CliError("usage", "--dsh is only valid with --harness dsh");
54
+ const providerName = str(p.flags, "provider") ?? "anthropic";
55
+ if (providerName !== "anthropic" && providerName !== "deepseek")
56
+ throw new CliError("usage", "--provider must be anthropic or deepseek");
57
+ const provider = providerName;
58
+ if (provider === "deepseek" && harness !== "claude-code")
59
+ throw new CliError("usage", "--provider deepseek requires --harness claude-code");
60
+ const model = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
53
61
  const bin = harness === "dsh"
54
62
  ? dshPath(dshOverride)
55
63
  : 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,7 +65,6 @@ export async function harnessStart(p, out, harness) {
57
65
  throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
58
66
  if (harness === "dsh" && !existsSync(bin))
59
67
  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
68
  const effort = str(p.flags, "effort");
62
69
  const adopt = str(p.flags, "thread") ?? str(p.flags, "session");
63
70
  // The machine's toolchain and job folders a sandboxed agent may also write (b9s-admin machine writable).
@@ -70,6 +77,7 @@ export async function harnessStart(p, out, harness) {
70
77
  : harness === "dsh"
71
78
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
72
79
  : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
80
+ const providerEnv = claudeTurnEnv(harness === "claude-code" ? provider : undefined, model);
73
81
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
74
82
  const lines = [];
75
83
  const token = str(p.flags, "token");
@@ -135,7 +143,7 @@ export async function harnessStart(p, out, harness) {
135
143
  else {
136
144
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
137
145
  session = randomUUID();
138
- await startClaudeSession(bin, ["-p", prompt, ...settings, "--session-id", session, "--output-format", "json"], firstTurnLog, ref, session);
146
+ await startClaudeSession(bin, ["-p", prompt, ...settings, "--session-id", session, "--output-format", "json"], firstTurnLog, ref, session, providerEnv);
139
147
  lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
140
148
  }
141
149
  }
@@ -164,7 +172,7 @@ export async function harnessStart(p, out, harness) {
164
172
  // volume had 750 GB free, and which empties /tmp at every boot.
165
173
  const tmp = sessionTmpDir(process.cwd(), creds.agent);
166
174
  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 });
175
+ 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, provider, model });
168
176
  const wl = watcherOut.join("\n").split("\n");
169
177
  lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
170
178
  // 5. Hooks.
@@ -186,7 +194,7 @@ export async function harnessStart(p, out, harness) {
186
194
  lines.push(harness === "dsh"
187
195
  ? `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
196
  : `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 });
197
+ 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
198
  }
191
199
  export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
192
200
  export const dshResumeArgs = (session, settings) => ["--profile", "headless", "--json", "--session-id", session, ...settings, "-"];
@@ -232,9 +240,9 @@ export async function startDshSession(bin, args, logPath, agent, prompt) {
232
240
  * minutes; this command does not wait for it) and returns once its transcript exists, or fails
233
241
  * with Claude Code's own error when it exits first.
234
242
  */
235
- async function startClaudeSession(bin, args, logPath, agent, session) {
243
+ async function startClaudeSession(bin, args, logPath, agent, session, providerEnv) {
236
244
  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 } });
245
+ const child = spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent, ...providerEnv } });
238
246
  closeSync(fd);
239
247
  let exited = null;
240
248
  child.on("exit", (code) => { exited = code ?? 1; });
@@ -118,6 +118,9 @@ export async function join(p, out) {
118
118
  written = [...new Set(written)];
119
119
  }
120
120
  const selfTest = !noBind && !bool(p.flags, "no-skill") && harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
121
+ const codexHookPath = vendor === "codex" ? installCodexHooks(inst.bin) : null;
122
+ const hasLocalHook = !!selfTest || !!codexHookPath || written.some((file) => file.endsWith(".agents/hooks.json"));
123
+ const wakePathWarnings = hasLocalHook ? [] : (json.wake_path_warnings ?? []);
121
124
  const human = [
122
125
  json.project
123
126
  ? `Joined project "${json.project.name}" as agent "${name}" (${vendor})${json.agent.role_name ? ` with role ${json.agent.role_name}` : ""}.`
@@ -129,6 +132,7 @@ export async function join(p, out) {
129
132
  : `This repo now maps ${vendor} -> ${ref} in ${idPath}, so b9s commands here know who you are, even after a reboot.`,
130
133
  written.length ? `Harness files written: ${written.join(", ")}` : null,
131
134
  selfTest,
135
+ ...wakePathWarnings.map((warning) => `No verified wake path${warning.project ? ` for ${warning.project}` : ""}: ${warning.consequence} Set a check schedule with b9s status set --checks-every 30 or run b9s watch --launchd so reminders have somewhere to go.`),
132
136
  ``,
133
137
  `Your model is detected automatically (hook, transcript or harness config); override with --model or BSCHAT_MODEL only if it reports "unknown".`,
134
138
  json.revived && json.resume ? `` : null,
@@ -136,10 +140,10 @@ export async function join(p, out) {
136
140
  json.revived && json.resume ? `--- ${json.resume.title} ---\n${json.resume.body}\n---${json.resume.evidence.length ? `\nevidence: ${json.resume.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}` : null,
137
141
  json.revived && json.resume ? `Read it before doing anything else.` : null,
138
142
  ``,
139
- vendor === "codex" ? `Codex: b9s's hooks are in ${installCodexHooks(inst.bin)} (approve them when Codex asks); they deliver your mentions and assignments inside your thread once b9s knows which thread is you: b9s codex bind <thread-id>, or a watcher (b9s watch --launchd), which is still what wakes you when you are idle.` : vendor === "antigravity" ? `Antigravity: .agents/hooks.json now delivers your mentions and assignments inside your conversation, once b9s knows which conversation is you: b9s antigravity bind <conversation-id> (the folder name under ~/.gemini/antigravity/brain/ holding your artifacts). A watcher (b9s watch --launchd) also binds it, and is still what wakes you when you are idle.` : vendor !== "claude-code" ? `No hook exists for ${vendor}: you will not be told about replies unless you run a watcher. See the skill's "Knowing when someone talks to you" section (b9s watch --launchd).` : null,
143
+ vendor === "codex" ? `Codex: b9s's hooks are in ${codexHookPath} (approve them when Codex asks); they deliver your mentions and assignments inside your thread once b9s knows which thread is you: b9s codex bind <thread-id>, or a watcher (b9s watch --launchd), which is still what wakes you when you are idle.` : vendor === "antigravity" ? `Antigravity: .agents/hooks.json now delivers your mentions and assignments inside your conversation, once b9s knows which conversation is you: b9s antigravity bind <conversation-id> (the folder name under ~/.gemini/antigravity/brain/ holding your artifacts). A watcher (b9s watch --launchd) also binds it, and is still what wakes you when you are idle.` : vendor !== "claude-code" ? `No hook exists for ${vendor}: you will not be told about replies unless you run a watcher. See the skill's "Knowing when someone talks to you" section (b9s watch --launchd).` : null,
140
144
  `Next: b9s me && b9s who && b9s inbox && b9s handoffs --open`,
141
145
  ].filter((l) => l !== null).join("\n");
142
- out.print(human, { install: inst, agent: json.agent, project: json.project, saved: path, identity: idPath, bound: !noBind, written, revived: !!json.revived, resume: json.resume ?? null, export: { BSCHAT_AGENT: ref } });
146
+ out.print(human, { install: inst, agent: json.agent, project: json.project, saved: path, identity: idPath, bound: !noBind, written, wake_path_warnings: wakePathWarnings, revived: !!json.revived, resume: json.resume ?? null, export: { BSCHAT_AGENT: ref } });
143
147
  }
144
148
  /**
145
149
  * Runs the hook command exactly as Claude Code will, with the settings file's own env, and
@@ -104,17 +104,18 @@ export async function machineAdmin(action, rest, p, out) {
104
104
  if (wrote.status !== 0)
105
105
  throw new CliError("provision_failed", `writing ~/.b9s/machine.json on ${host} failed: ${wrote.stderr.trim()}`);
106
106
  // 4. The daemon.
107
- const svc = remoteBschat(host, "machine service");
107
+ const svc = remoteBschat(host, "machine service --json");
108
108
  if (svc.status !== 0)
109
109
  throw new CliError("provision_failed", `installing the machine daemon on ${host} failed: ${svc.stderr.trim().slice(-300)}`);
110
- say(` daemon: ${svc.stdout.trim().split("\n")[0]}`);
110
+ const daemon = JSON.parse(svc.stdout);
111
+ say(` daemon: ${daemon.path} with PATH ${daemon.daemon_path}`);
111
112
  const failed = prepared.filter((s) => s.result === "failed");
112
113
  return out.print([
113
114
  `Machine ${name} (${host}) is provisioned and its daemon is running.`,
114
115
  ...lines,
115
116
  failed.length ? `Still to do on the machine: ${failed.map((s) => `${s.step} (${s.detail})`).join("; ")}` : null,
116
117
  `Declare what it runs: b9s-admin machine session add ${name} <project>/<agent> --dir <checkout on ${host}> --sandbox <mode> [--create --role <role>]`,
117
- ].filter(Boolean).join("\n"), { machine: name, host, bootstrap: steps, prepare: prepared });
118
+ ].filter(Boolean).join("\n"), { machine: name, host, bootstrap: steps, prepare: prepared, daemon_path: daemon.daemon_path });
118
119
  }
119
120
  if (action === "list" || action === undefined) {
120
121
  const r = await c.call("GET", "/machines");
@@ -131,8 +132,10 @@ export async function machineAdmin(action, rest, p, out) {
131
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)` : ""}`,
132
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?)",
133
134
  ];
134
- 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\[[^\]]+\]: /, "") }));
135
- 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);
136
139
  }
137
140
  if (action === "maintenance") {
138
141
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -196,13 +199,13 @@ export async function machineAdmin(action, rest, p, out) {
196
199
  if (sub === "add") {
197
200
  const turnTimeout = str(p.flags, "turn-timeout");
198
201
  const body = {
199
- project, agent, harness: str(p.flags, "harness") ?? "codex", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
202
+ project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
200
203
  model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
201
204
  ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
202
205
  create: bool(p.flags, "create"), role: str(p.flags, "role"),
203
206
  };
204
207
  const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
205
- 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);
208
+ 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);
206
209
  }
207
210
  if (sub === "stop" || sub === "start") {
208
211
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { desired: sub === "stop" ? "stopped" : "running" });
@@ -215,12 +218,14 @@ export async function machineAdmin(action, rest, p, out) {
215
218
  }
216
219
  throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
217
220
  }
218
- /** `[tag=]harness:model[:effort][*weight]`, e.g. `luna=codex:gpt-6-luna:medium*2`. */
221
+ /** `[tag=]harness:model[:effort][*weight][@provider]`, e.g. `luna=claude-code:deepseek-flash@deepseek`. */
219
222
  export function parseVariant(spec) {
220
- const m = /^(?:([a-z0-9][a-z0-9-]*)=)?([a-z0-9-]+)(?::([^:*]+))?(?::([^:*]+))?(?:\*(\d+))?$/.exec(spec.trim());
223
+ const m = /^(?:([a-z0-9][a-z0-9-]*)=)?([a-z0-9-]+)(?::([^:*@]+))?(?::([^:*@]+))?(?:\*(\d+))?(?:@(anthropic|deepseek))?$/.exec(spec.trim());
221
224
  if (!m)
222
- throw new CliError("usage", `--variant ${spec}: expected [tag=]harness:model[:effort][*weight], e.g. luna=codex:gpt-6-luna:medium*2`);
223
- 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]) } : {}) };
225
+ throw new CliError("usage", `--variant ${spec}: expected [tag=]harness:model[:effort][*weight][@provider], e.g. luna=claude-code:deepseek-flash@deepseek`);
226
+ if (m[6] === "deepseek" && m[2] !== "claude-code")
227
+ throw new CliError("usage", "@deepseek requires the claude-code harness");
228
+ 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] } : {}) };
224
229
  }
225
230
  /** Every value of a repeatable flag (the parser keeps the last; read them from argv). */
226
231
  export function repeated(argv, flag) {
@@ -240,7 +245,7 @@ export function repeated(argv, flag) {
240
245
  export async function poolAdmin(action, rest, p, out, argv) {
241
246
  const c = adminClient(p);
242
247
  const statusLines = (pool) => [
243
- `${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` : ""}`,
248
+ `${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}` : ""}${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` : ""}`,
244
249
  ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
245
250
  ...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
246
251
  ];
@@ -249,7 +254,7 @@ export async function poolAdmin(action, rest, p, out, argv) {
249
254
  const variants = repeated(argv, "variant").map(parseVariant);
250
255
  const count = Number(str(p.flags, "count"));
251
256
  if (!project || !name || !variants.length || !Number.isInteger(count))
252
- 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]");
257
+ 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]");
253
258
  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")) } : {}) };
254
259
  const tt = str(p.flags, "turn-timeout");
255
260
  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) } : {}) });
@@ -339,7 +344,7 @@ function on(host, command, input) {
339
344
  return ssh(host, command, input);
340
345
  }
341
346
  /**
342
- * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--model m] [--effort e]
347
+ * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
343
348
  * [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min] [--force]
344
349
  *
345
350
  * The agent (name, role, record, units, chat) is on the server and does not move; its harness
@@ -353,10 +358,16 @@ export async function agentMove(rest, p, out) {
353
358
  const [project, agent] = ref.split("/");
354
359
  const to = str(p.flags, "to");
355
360
  const sandbox = str(p.flags, "sandbox");
361
+ const harness = str(p.flags, "harness") ?? "codex";
362
+ const provider = str(p.flags, "provider") ?? "anthropic";
356
363
  const carry = str(p.flags, "carry") ?? "note";
357
364
  const from = str(p.flags, "from");
358
365
  if (!project || !agent || !to || !sandbox)
359
- 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]");
366
+ 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]");
367
+ if (provider !== "anthropic" && provider !== "deepseek")
368
+ throw new CliError("usage", "--provider must be anthropic or deepseek");
369
+ if (provider === "deepseek" && harness !== "claude-code")
370
+ throw new CliError("usage", "--provider deepseek requires --harness claude-code");
360
371
  if (carry !== "note" && carry !== "thread")
361
372
  throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
362
373
  if (carry === "thread" && (str(p.flags, "harness") ?? "codex") !== "codex")
@@ -464,11 +475,11 @@ export async function agentMove(rest, p, out) {
464
475
  // 3. The new machine runs it; every other key stops working.
465
476
  const turnTimeout = str(p.flags, "turn-timeout");
466
477
  const r = await c.call("POST", `/machines/${to}/sessions`, {
467
- project, agent, move: true, harness: str(p.flags, "harness") ?? "codex", dir: str(p.flags, "dir") ?? "auto", sandbox,
478
+ project, agent, move: true, harness, provider, dir: str(p.flags, "dir") ?? "auto", sandbox,
468
479
  model, effort, ...(thread ? { thread } : {}), ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
469
480
  });
470
481
  return out.print([
471
- `${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.`,
482
+ `${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.`,
472
483
  r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
473
484
  `${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.`,
474
485
  problems.length ? `Left behind (--force): ${problems.join("; ")}` : null,
@@ -11,10 +11,11 @@ import { applySparse } from "../git.js";
11
11
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
12
12
  import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
13
13
  import { readState, writeState } from "../state.js";
14
- import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
14
+ import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
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";
18
19
  export const machineFile = () => join(configRoot(), "machine.json");
19
20
  export function loadMachine() {
20
21
  const f = machineFile();
@@ -35,7 +36,7 @@ function writeMachineState(s) {
35
36
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
36
37
  */
37
38
  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
+ 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, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
39
40
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
40
41
  /**
41
42
  * During a maintenance drain or window, a session that would be started fresh (no known thread, so
@@ -55,6 +56,7 @@ export function maintenanceReport(drain, sessions) {
55
56
  export function startArgs(s, thread, writable = []) {
56
57
  return [
57
58
  "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--json",
59
+ ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
58
60
  ...(s.model ? ["--model", s.model] : []),
59
61
  ...(s.effort ? ["--effort", s.effort] : []),
60
62
  ...(thread ? ["--thread", thread] : []),
@@ -69,6 +71,14 @@ export async function reconcile(m, log) {
69
71
  const client = Client.raw(m.url, m.key);
70
72
  const me = await client.call("GET", "/machines/me");
71
73
  const desired = me.sessions;
74
+ const providerChecks = new Set(["anthropic"]);
75
+ for (const provider of me.provider_checks ?? []) {
76
+ if (provider === "anthropic" || provider === "deepseek")
77
+ providerChecks.add(provider);
78
+ }
79
+ for (const s of desired)
80
+ if (s.harness === "claude-code" && (s.provider === "anthropic" || s.provider === "deepseek"))
81
+ providerChecks.add(s.provider);
72
82
  const projects = me.projects ?? [];
73
83
  const workdir = me.machine?.workdir ?? null;
74
84
  const writable = me.machine?.writable ?? [];
@@ -104,6 +114,10 @@ export async function reconcile(m, log) {
104
114
  }
105
115
  if (!TURN_HARNESSES.includes(s.harness))
106
116
  throw new Error(`harness ${s.harness} is not supported by this b9s ${CLI_VERSION}`);
117
+ if (s.provider && s.provider !== "anthropic" && s.provider !== "deepseek")
118
+ throw new Error(`provider ${s.provider} is not supported by this b9s ${CLI_VERSION}`);
119
+ if ((s.provider ?? "anthropic") === "deepseek" && s.harness !== "claude-code")
120
+ throw new Error("provider deepseek requires harness claude-code");
107
121
  if (!s.dir) {
108
122
  // A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
109
123
  const c = ensureCheckout(s, log, workdir);
@@ -190,7 +204,7 @@ export async function reconcile(m, log) {
190
204
  writeMachineState(state);
191
205
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
192
206
  const report = {
193
- ...machineFacts(), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones,
207
+ ...machineFacts([...providerChecks]), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones,
194
208
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
195
209
  maintenance: maintenanceReport(drainingUntil(), out),
196
210
  };
@@ -511,12 +525,12 @@ function volumeSpace(path, label) {
511
525
  }
512
526
  /** Whether Codex's own sandbox runs here (`codex sandbox -- true`), with its error; checked at most every 10 min. */
513
527
  let sandboxCache = null;
514
- export function codexSandbox(force = false) {
515
- if (!force && sandboxCache && Date.now() - sandboxCache.at < 10 * 60_000)
528
+ export function codexSandbox(force = false, path = process.env.PATH ?? "") {
529
+ if (!force && sandboxCache && sandboxCache.path === path && Date.now() - sandboxCache.at < 10 * 60_000)
516
530
  return sandboxCache.result;
517
- const r = spawnSync("codex", ["sandbox", "--", "true"], { encoding: "utf8", timeout: 60_000 });
531
+ const r = spawnSync("codex", ["sandbox", "--", "true"], { encoding: "utf8", timeout: 60_000, env: { ...process.env, PATH: path } });
518
532
  const result = r.status === 0 ? { ok: true, error: null } : { ok: false, error: `${r.stderr ?? ""}${r.stdout ?? ""}`.trim().split("\n")[0].slice(0, 300) || `exit ${r.status}` };
519
- sandboxCache = { at: Date.now(), result };
533
+ sandboxCache = { at: Date.now(), result, path };
520
534
  return result;
521
535
  }
522
536
  /** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
@@ -530,19 +544,28 @@ function memAvailable() {
530
544
  }
531
545
  /** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
532
546
  let claudeSandboxCache = null;
533
- function claudeReport() {
534
- const f = claudeFacts();
547
+ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"]) {
548
+ const f = claudeFacts(undefined, path);
535
549
  if (!f)
536
550
  return null;
537
- if (!claudeSandboxCache || Date.now() - claudeSandboxCache.at > 10 * 60_000)
538
- claudeSandboxCache = { at: Date.now(), result: claudeSandbox() };
539
- return { ...f, sandbox: claudeSandboxCache.result };
551
+ if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
552
+ claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
553
+ const providers = {};
554
+ for (const provider of providersInUse) {
555
+ const check = provider === "anthropic"
556
+ ? { logged_in: f.logged_in, reason: f.verified.error }
557
+ : verifyClaudeProvider(provider);
558
+ providers[provider] = { ...check, sandbox: claudeSandboxCache.result };
559
+ }
560
+ return { ...f, sandbox: claudeSandboxCache.result, providers };
540
561
  }
541
562
  /** What the operator needs to know about this machine, reported with every pass. */
542
- export function machineFacts() {
543
- const dsh = dshFacts();
544
- const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
545
- const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8" }) : null;
563
+ export function machineFacts(providersInUse = ["anthropic"]) {
564
+ const path = process.env.PATH ?? "";
565
+ const env = { ...process.env, PATH: path };
566
+ const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
567
+ const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
568
+ const dsh = dshFacts(platform(), path);
546
569
  let diskFree = null;
547
570
  try {
548
571
  const st = statfsSync(homedir());
@@ -552,14 +575,17 @@ export function machineFacts() {
552
575
  diskFree = null;
553
576
  }
554
577
  const req = "/etc/codex/requirements.toml";
578
+ const claude = claudeReport(path, providersInUse);
555
579
  return {
556
580
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
557
581
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
558
582
  // When this machine last booted: the server ends a maintenance window once the machine is back.
559
583
  booted_at: new Date(Math.floor((Date.now() - uptime() * 1000) / 60_000) * 60_000).toISOString(),
584
+ daemon_path: path,
560
585
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
561
- 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() } : null,
562
- "claude-code": claudeReport(),
586
+ 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,
587
+ "claude-code": claude,
588
+ claude_code: claude,
563
589
  dsh,
564
590
  managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
565
591
  linger: platform() === "linux" ? lingerEnabled() : null,
@@ -574,6 +600,9 @@ export function machineFacts() {
574
600
  */
575
601
  export function prepare(opts = {}) {
576
602
  const steps = [];
603
+ const daemonPath = machineDaemonPath();
604
+ const daemonEnv = { ...process.env, PATH: daemonPath };
605
+ steps.push({ step: "daemon PATH", result: "ok", detail: daemonPath });
577
606
  const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
578
607
  if (platform() === "linux") {
579
608
  const l = lingerEnabled();
@@ -585,20 +614,20 @@ export function prepare(opts = {}) {
585
614
  steps.push(lingerEnabled() ? { step: "linger", result: "done", detail: "enabled" } : { step: "linger", result: "failed", detail: `${(r2.stderr ?? "").trim()} (run: sudo loginctl enable-linger ${userInfo().username})` });
586
615
  }
587
616
  }
588
- const dsh = dshFacts();
617
+ const dsh = dshFacts(platform(), daemonPath);
589
618
  steps.push(dsh.available
590
619
  ? { step: "dsh", result: "ok", detail: `${dsh.version}, ${dsh.path}` }
591
620
  : { step: "dsh", result: platform() === "linux" ? "skipped" : "failed", detail: dsh.error ?? "DeepSeek Harness dsh CLI is unavailable" });
592
- const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
621
+ const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env: daemonEnv });
593
622
  if (codex.status !== 0)
594
623
  steps.push({ step: "codex", result: "failed", detail: "codex is not on PATH; install the Codex CLI (npm i -g @openai/codex) and log in (codex login --device-auth)" });
595
624
  else {
596
- const login = spawnSync("codex", ["login", "status"], { encoding: "utf8" });
625
+ const login = spawnSync("codex", ["login", "status"], { encoding: "utf8", env: daemonEnv });
597
626
  const ok = login.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`);
598
627
  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` });
599
628
  }
600
629
  if (codex.status === 0) {
601
- let sb = codexSandbox(true);
630
+ let sb = codexSandbox(true, daemonPath);
602
631
  if (sb.ok)
603
632
  steps.push({ step: "codex sandbox", result: "ok", detail: "sandboxed (read-only, workspace-write) agents can run here" });
604
633
  else if (platform() !== "linux" || !/userns|uid map|RTM_NEWADDR|Operation not permitted|Permission denied/i.test(sb.error ?? ""))
@@ -610,17 +639,17 @@ export function prepare(opts = {}) {
610
639
  else {
611
640
  const t = spawnSync("sudo", ["-n", "tee", CODEX_APPARMOR_PATH], { input: codexAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
612
641
  const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", CODEX_APPARMOR_PATH], { encoding: "utf8" }) : t;
613
- sb = codexSandbox(true);
642
+ sb = codexSandbox(true, daemonPath);
614
643
  steps.push(l.status === 0 && sb.ok
615
644
  ? { step: "codex sandbox", result: "done", detail: `installed ${CODEX_APPARMOR_PATH} (Codex only); the sandbox works` }
616
645
  : { step: "codex sandbox", result: "failed", detail: l.status !== 0 ? `installing ${CODEX_APPARMOR_PATH}: ${(l.stderr ?? "").trim()}` : `profile installed but the sandbox still fails: ${sb.error}` });
617
646
  }
618
647
  }
619
648
  // Claude Code is optional on a machine; when it is there, say whether it can run agents.
620
- const claude = claudeFacts();
649
+ const claude = claudeFacts(undefined, daemonPath);
621
650
  if (claude) {
622
651
  steps.push({ step: "claude code", result: claude.logged_in ? "ok" : "failed", detail: claude.logged_in ? `${claude.version}, ${claude.login}` : `${claude.version}, ${claude.login}: run claude auth login on this machine (over ssh it prints a link to open in your browser and asks for the code)` });
623
- let sb = claudeSandbox();
652
+ let sb = claudeSandbox(daemonPath);
624
653
  const userns = platform() === "linux" && /RTM_NEWADDR|uid map|Operation not permitted|Permission denied/i.test(sb.error ?? "");
625
654
  if (sb.ok)
626
655
  steps.push({ step: "claude code sandbox", result: "ok", detail: "sandboxed (workspace-write) Claude Code agents can run here" });
@@ -633,7 +662,7 @@ export function prepare(opts = {}) {
633
662
  else {
634
663
  const t = spawnSync("sudo", ["-n", "tee", BWRAP_APPARMOR_PATH], { input: bwrapAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
635
664
  const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", BWRAP_APPARMOR_PATH], { encoding: "utf8" }) : t;
636
- sb = claudeSandbox();
665
+ sb = claudeSandbox(daemonPath);
637
666
  steps.push(l.status === 0 && sb.ok
638
667
  ? { step: "claude code sandbox", result: "done", detail: `installed ${BWRAP_APPARMOR_PATH}; the sandbox works` }
639
668
  : { step: "claude code sandbox", result: "failed", detail: l.status !== 0 ? `installing ${BWRAP_APPARMOR_PATH}: ${(l.stderr ?? "").trim()}` : `profile installed but the sandbox still fails: ${sb.error}` });
@@ -687,8 +716,9 @@ export async function machine(p, out) {
687
716
  if (sub === "service") {
688
717
  loadMachine();
689
718
  const bin = requireInstall().bin;
690
- const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir() }, "machine");
691
- return out.print(`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run. Logs: ~/.b9s/logs/machine.*.log`, { path, label: MACHINE_LABEL });
719
+ const daemonPath = machineDaemonPath();
720
+ const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: daemonPath, HOME: homedir() }, "machine");
721
+ return out.print(`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run with PATH ${daemonPath}. Logs: ~/.b9s/logs/machine.*.log`, { path, label: MACHINE_LABEL, daemon_path: daemonPath });
692
722
  }
693
723
  const m = loadMachine();
694
724
  const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
@@ -697,7 +727,7 @@ export async function machine(p, out) {
697
727
  const state = readMachineState();
698
728
  const rows = desired.map((s) => {
699
729
  const w = watcherServices().find((x) => x.label === watchLabelOf(s.agent));
700
- 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}`;
730
+ 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}`;
701
731
  });
702
732
  return out.print([`machine ${m.name} (${m.url})`, ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state });
703
733
  }