benignswarm 0.12.86 → 0.12.88

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
@@ -3,7 +3,7 @@ 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
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", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect"];
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
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"];
8
8
  export function parse(argv) {
9
9
  const options = {};
@@ -1,5 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join as joinPath } from "node:path";
5
5
  import { bool, str } from "../args.js";
@@ -13,7 +13,7 @@ import { readState, writeState } from "../state.js";
13
13
  import { join } from "./join.js";
14
14
  import { installWatcherService } from "./watch.js";
15
15
  import { randomUUID } from "node:crypto";
16
- import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript } from "../harnesses.js";
16
+ import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog } from "../harnesses.js";
17
17
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
18
18
  /**
19
19
  * `b9s start` (and `b9s codex start`): one command that brings an agent up on this machine
@@ -23,8 +23,8 @@ const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
23
23
  * resume`; Claude Code: `claude -p --resume`). `--thread` adopts an existing session instead. Learned
24
24
  * from the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
25
25
  *
26
- * b9s start --harness codex|claude-code --as <name> --sandbox <mode> [--token bs_enroll_...]
27
- * [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune]
26
+ * b9s start --harness codex|claude-code|dsh --as <name> --sandbox <mode> [--token bs_enroll_...]
27
+ * [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune] [--dsh <path>]
28
28
  */
29
29
  export async function codexStart(p, out) {
30
30
  return harnessStart(p, out, "codex");
@@ -47,7 +47,16 @@ export async function harnessStart(p, out, harness) {
47
47
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
48
48
  if (process.platform !== "darwin" && process.platform !== "linux")
49
49
  throw new CliError("unsupported", `${cmd} installs its watcher with launchd (macOS) or systemd (Linux)`);
50
- const bin = 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)");
50
+ const dshOverride = str(p.flags, "dsh");
51
+ if (harness !== "dsh" && dshOverride)
52
+ throw new CliError("usage", "--dsh is only valid with --harness dsh");
53
+ const bin = harness === "dsh"
54
+ ? dshPath(dshOverride)
55
+ : 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)");
56
+ if (!bin)
57
+ throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
58
+ if (harness === "dsh" && !existsSync(bin))
59
+ throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
51
60
  const model = str(p.flags, "model");
52
61
  const effort = str(p.flags, "effort");
53
62
  const adopt = str(p.flags, "thread") ?? str(p.flags, "session");
@@ -58,7 +67,9 @@ export async function harnessStart(p, out, harness) {
58
67
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
59
68
  const settings = harness === "codex"
60
69
  ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
61
- : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
70
+ : harness === "dsh"
71
+ ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
72
+ : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
62
73
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
63
74
  const lines = [];
64
75
  const token = str(p.flags, "token");
@@ -74,7 +85,10 @@ export async function harnessStart(p, out, harness) {
74
85
  requireInstall();
75
86
  // 2. Its session: adopt one, or start one headless with an onboarding turn.
76
87
  let session;
88
+ let initialPid;
77
89
  let firstTurnLog = null;
90
+ if (harness === "dsh")
91
+ firstTurnLog = dshTurnLog(ref);
78
92
  if (adopt) {
79
93
  session = adopt.toLowerCase();
80
94
  if (harness === "codex") {
@@ -86,15 +100,22 @@ export async function harnessStart(p, out, harness) {
86
100
  lines.push(`Adopted Codex thread ${session}. Leave it unopened in the Codex app (do not archive it: that moves its session file away): from now on the watcher runs its turns, and two clients on one thread conflict.`);
87
101
  }
88
102
  else {
89
- if (!claudeTranscript(session))
90
- throw new CliError("not_found", `no Claude Code transcript for session ${session} under ~/.claude/projects on this machine`);
91
- lines.push(`Adopted Claude Code session ${session}. Do not resume it in a terminal while the watcher runs it: two clients on one session conflict.`);
103
+ if (harness === "claude-code") {
104
+ if (!claudeTranscript(session))
105
+ throw new CliError("not_found", `no Claude Code transcript for session ${session} under ~/.claude/projects on this machine`);
106
+ lines.push(`Adopted Claude Code session ${session}. Do not resume it in a terminal while the watcher runs it: two clients on one session conflict.`);
107
+ }
108
+ else {
109
+ mkdirSync(joinPath(configRoot(), "logs"), { recursive: true });
110
+ closeSync(openSync(dshTurnLog(ref), "a"));
111
+ lines.push(`Adopted DeepSeek Harness session ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one session conflict.`);
112
+ }
92
113
  }
93
114
  }
94
115
  else {
95
116
  const logDir = joinPath(configRoot(), "logs");
96
117
  mkdirSync(logDir, { recursive: true });
97
- firstTurnLog = joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.${harness === "codex" ? "jsonl" : "json"}`);
118
+ firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.${harness === "codex" ? "jsonl" : "json"}`);
98
119
  const prompt = [
99
120
  `[b9s] You are ${ref}, a BenignSwarm agent, started headless by \`b9s ${cmd}\`; nobody is typing to you.`,
100
121
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
@@ -105,6 +126,12 @@ export async function harnessStart(p, out, harness) {
105
126
  session = await startThread(bin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
106
127
  lines.push(`Started Codex thread ${session}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
107
128
  }
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}`);
134
+ }
108
135
  else {
109
136
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
110
137
  session = randomUUID();
@@ -116,6 +143,8 @@ export async function harnessStart(p, out, harness) {
116
143
  // hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
117
144
  if (harness === "codex")
118
145
  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 } : {}) } });
119
148
  // A session adopted here may end in a usage-limit error from the machine it came from, written in
120
149
  // that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
121
150
  // from turns on this machine pause it; if the account is still limited, the next turn says so here.
@@ -124,8 +153,10 @@ export async function harnessStart(p, out, harness) {
124
153
  // 4. The watcher, in turn mode: it runs each later turn itself.
125
154
  const exec = harness === "codex"
126
155
  ? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
127
- // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
128
- : `${shq(bin)} -p {text} ${[...settings, "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
156
+ : harness === "dsh"
157
+ ? dshResumeCommand(bin, session, settings, dshTurnLog(ref))
158
+ // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
159
+ : `${shq(bin)} -p {text} ${[...settings, "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
129
160
  const watcherOut = [];
130
161
  // Scratch space beside the checkout, not the system's /tmp: on a machine the checkout lives on the
131
162
  // work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
@@ -145,13 +176,57 @@ export async function harnessStart(p, out, harness) {
145
176
  ? `Codex has not trusted b9s's hooks (${missing.join(", ")}) on this machine, so turns run without them: no standing rules at session start, no continuing when work arrives mid-turn. Wake-ups still work. To trust them, run \`codex\` once in a terminal here and approve the hooks when it asks.`
146
177
  : `Codex has trust entries for b9s's hooks here. If they changed since they were trusted, Codex skips them until approved again in an interactive \`codex\`.`);
147
178
  }
179
+ else if (harness === "dsh") {
180
+ lines.push("DeepSeek Harness runs the headless profile without an interactive approval prompt; b9s identifies this agent through BSCHAT_AGENT on each turn.");
181
+ }
148
182
  else {
149
183
  lines.push(`Claude Code runs b9s's hooks from this checkout's .claude/settings.local.json (written by join).`);
150
184
  }
151
- lines.push(`Follow it: tail -f ~/.b9s/logs/watch.${ref.replace("/", ".")}.err.log; ${harness === "codex" ? `read its thread with codex resume ${session}` : `read its transcript under ~/.claude/projects (session ${session})`} only while no turn is running.`);
152
- lines.push(`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}`);
185
+ lines.push(`Follow it: tail -f ~/.b9s/logs/watch.${ref.replace("/", ".")}.err.log; ${harness === "codex" ? `read its thread with codex resume ${session}` : harness === "dsh" ? `read its events in ${dshTurnLog(ref)} or resume with dsh --profile headless --json --session-id ${session}` : `read its transcript under ~/.claude/projects (session ${session})`} only while no turn is running.`);
186
+ lines.push(harness === "dsh"
187
+ ? `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
+ : `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}`);
153
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 });
154
190
  }
191
+ export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
192
+ export const dshResumeArgs = (session, settings) => ["--profile", "headless", "--json", "--session-id", session, ...settings, "-"];
193
+ export function dshResumeCommand(bin, session, settings, logPath) {
194
+ const log = shq(logPath);
195
+ const run = [...[bin, ...dshResumeArgs(session, settings)].map(shq)].join(" ");
196
+ return `printf '\\n{"type":"b9s_invocation_start","at":"%s"}\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> ${log}; ${run} >> ${log} 2>&1; dsh_status=$?; printf '\\n{"type":"b9s_invocation_end","at":"%s","exit":%s}\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$dsh_status" >> ${log}; exit "$dsh_status"`;
197
+ }
198
+ /** Starts a first DeepSeek turn and returns as soon as its first session event is written. */
199
+ export async function startDshSession(bin, args, logPath, agent, prompt) {
200
+ const pidFile = `${logPath}.initial-pid`;
201
+ closeSync(openSync(logPath, "w"));
202
+ if (existsSync(pidFile))
203
+ unlinkSync(pidFile);
204
+ const log = shq(logPath);
205
+ const childArgs = [bin, ...args].map(shq).join(" ");
206
+ const wrapper = `exec 2>> ${log}; exec 3<&0; printf '{"type":"b9s_invocation_start","at":"%s"}\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> ${log}; ${childArgs} <&3 >> ${log} 2>&1 & dsh_pid=$!; printf '%s\\n' "$dsh_pid" > ${shq(pidFile)}; wait "$dsh_pid"; dsh_status=$?; printf '{"type":"b9s_invocation_end","at":"%s","exit":%s}\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$dsh_status" >> ${log}; exit "$dsh_status"`;
207
+ const child = spawn("/bin/sh", ["-c", wrapper], { stdio: ["pipe", "ignore", "ignore"], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent } });
208
+ if (!child.pid)
209
+ throw new CliError("dsh_failed", "could not start the DeepSeek Harness process");
210
+ const groupPid = child.pid;
211
+ let exited = null;
212
+ child.on("exit", (code) => { exited = code ?? 1; });
213
+ child.on("error", () => { exited = 127; });
214
+ child.stdin?.end(prompt);
215
+ child.unref();
216
+ for (let i = 0; i < 180; i++) {
217
+ const text = readFileSync(logPath, "utf8");
218
+ const session = dshSessionFromEvents(text);
219
+ const pid = existsSync(pidFile) ? Number(readFileSync(pidFile, "utf8").trim()) : NaN;
220
+ if (session && Number.isInteger(pid) && pid > 0) {
221
+ unlinkSync(pidFile);
222
+ return { session, pid, groupPid };
223
+ }
224
+ if (exited !== null)
225
+ throw new CliError("dsh_failed", `dsh exited ${exited} before starting a session: ${dshResultError(text) ?? "no session event reported"}; see ${logPath}`);
226
+ await new Promise((r) => setTimeout(r, 500));
227
+ }
228
+ throw new CliError("dsh_failed", `DeepSeek Harness reported no session within 90 s; see ${logPath}`);
229
+ }
155
230
  /**
156
231
  * Starts a headless Claude Code session in its own process group (the first turn may take many
157
232
  * minutes; this command does not wait for it) and returns once its transcript exists, or fails
@@ -65,10 +65,22 @@ export async function evidence(p, out) {
65
65
  if (claim)
66
66
  headers["x-bschat-claim"] = claim;
67
67
  const res = await fetch(`${creds.url}/projects/${project}/evidence`, { method: "POST", headers, body: new Uint8Array(bytes) });
68
- const json = await res.json();
68
+ const responseText = await res.text();
69
+ let json;
70
+ try {
71
+ json = JSON.parse(responseText);
72
+ }
73
+ catch {
74
+ if (!res.ok)
75
+ throw new CliError(`http_${res.status}`, responseText || `evidence upload failed with HTTP ${res.status}`);
76
+ throw new CliError("bad_response", `evidence upload returned non-JSON (${res.status}): ${responseText.slice(0, 200)}`);
77
+ }
69
78
  if (!res.ok)
70
- throw new CliError(json.error, json.message);
71
- out.print(`posted ${filename} (${bytes.length} bytes, sha256 ${sha})${json.deduplicated ? " [content already stored]" : ""}\nref: ${json.ref}\nmention it in chat as ${json.ref}`, json);
79
+ throw new CliError(typeof json?.error === "string" ? json.error : `http_${res.status}`, typeof json?.message === "string" ? json.message : responseText);
80
+ const storedType = json?.evidence?.content_type;
81
+ if (typeof storedType !== "string")
82
+ throw new CliError("bad_response", "evidence upload response omitted evidence.content_type");
83
+ out.print(`posted ${filename} (${bytes.length} bytes, content-type ${storedType}, sha256 ${sha})${json.deduplicated ? " [content already stored]" : ""}\nref: ${json.ref}\nmention it in chat as ${json.ref}`, json);
72
84
  return;
73
85
  }
74
86
  if (sub === "list") {
@@ -3,12 +3,12 @@ import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathS
3
3
  import { delimiter, join } from "node:path";
4
4
  import { bool } from "../args.js";
5
5
  import { CliError } from "../errors.js";
6
- import { binVersion, ensureInstall, formatWatcherRestartReport, latestPublished, lingerEnabled, readInstall, restartWatcherServices, watcherServices } from "../install.js";
6
+ import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, lingerEnabled, readInstall, restartInstallServices, watcherServices } from "../install.js";
7
7
  import { CLI_VERSION } from "../version.js";
8
8
  import { refreshInstalledHooks } from "../harness.js";
9
9
  /**
10
- * b9s install [<version> | --latest] make or upgrade this machine's one b9s install and
11
- * restart the watchers that run it
10
+ * b9s install [<version> | --latest] make or upgrade this machine's one b9s install,
11
+ * repair PATH aliases and restart services that run it
12
12
  */
13
13
  export async function install(p, out) {
14
14
  const prev = readInstall();
@@ -19,6 +19,11 @@ export async function install(p, out) {
19
19
  const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm ?? join(process.execPath, "..", "npm")) : CLI_VERSION);
20
20
  const rec = ensureInstall(version, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
21
21
  const lines = [`b9s ${rec.version} is this machine's install: ${rec.bin}`];
22
+ const aliases = ensureCommandLinks(rec.bin);
23
+ if (aliases.created.length)
24
+ lines.push(`Updated PATH links: ${aliases.created.join(", ")}`);
25
+ if (aliases.conflicts.length)
26
+ lines.push(`Could not add PATH links: ${aliases.conflicts.join(", ")}`);
22
27
  const refreshedHooks = bool(p.flags, "latest") ? refreshInstalledHooks(process.cwd(), rec.bin) : [];
23
28
  if (refreshedHooks.length)
24
29
  lines.push(`Updated harness hooks: ${refreshedHooks.join(", ")}`);
@@ -26,25 +31,16 @@ export async function install(p, out) {
26
31
  lines.push(`(was ${prev.bin}; run b9s doctor to find hooks and watchers still pointing there)`);
27
32
  const restarted = [];
28
33
  const elsewhere = [];
29
- const notStarted = [];
30
34
  if (!bool(p.flags, "no-restart")) {
31
- const matching = [];
32
- for (const w of watcherServices()) {
33
- const program = w.args?.[0];
34
- if (program !== rec.bin) {
35
- elsewhere.push(`${w.label} runs ${program ?? "(unreadable definition)"}`);
36
- continue;
37
- }
38
- matching.push(w);
39
- }
40
- const report = await restartWatcherServices(matching);
41
- restarted.push(...report.restarted);
42
- lines.push(...formatWatcherRestartReport(report));
43
- notStarted.push(...report.not_started.map((failure) => `${failure.label}: ${failure.reason}`));
35
+ const services = await restartInstallServices(rec.bin);
36
+ restarted.push(...services.restarted);
37
+ elsewhere.push(...services.not_restarted);
44
38
  }
39
+ if (restarted.length)
40
+ lines.push(`Restarted ${restarted.length} service${restarted.length === 1 ? "" : "s"} on it: ${restarted.map((l) => l.replace("org.benignswarm.watch.", "")).join(", ")}`);
45
41
  if (elsewhere.length)
46
42
  lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
47
- out.print(lines.join("\n"), { install: rec, restarted, not_restarted: [...elsewhere, ...notStarted] });
43
+ out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
48
44
  }
49
45
  /**
50
46
  * b9s doctor every b9s on this machine and who uses which: the recorded install, copies on
@@ -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");
@@ -9,9 +9,9 @@ import { CliError } from "../errors.js";
9
9
  import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
10
10
  import { applySparse } from "../git.js";
11
11
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
12
- import { TURN_HARNESSES, claudeFacts, claudeSandbox, probeFor, sessionProcesses } from "../harnesses.js";
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";
@@ -116,6 +116,14 @@ export async function reconcile(m, log) {
116
116
  if (!existsSync(s.dir))
117
117
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
118
118
  const local = state.sessions[s.id];
119
+ if (local) {
120
+ const conflict = existingSessionDirectoryConflict(s.id, s.dir, local.thread, s.agent);
121
+ if (conflict) {
122
+ out.push(conflict);
123
+ log(`${s.agent}: ${conflict.error}`);
124
+ continue;
125
+ }
126
+ }
119
127
  await ensureCredentials(client, m, s, local, log);
120
128
  const fp = sessionFingerprint(s, s.sandbox === "workspace-write" ? writable : []);
121
129
  const thread = s.thread ?? local?.thread ?? null;
@@ -350,10 +358,13 @@ async function ensureCredentials(client, m, s, local, log) {
350
358
  local.key_checked_at = Date.now();
351
359
  log(`${s.agent}: key saved for this machine`);
352
360
  }
353
- function errorText(s) {
361
+ export function errorText(s) {
354
362
  const last = s.trim().split("\n").pop() ?? "";
355
363
  try {
356
- return JSON.parse(last).message ?? last;
364
+ const parsed = JSON.parse(last);
365
+ if (parsed.error === "directory_conflict")
366
+ return "directory_conflict: " + (parsed.message ?? last) + (parsed.hint ? "; " + parsed.hint : "");
367
+ return parsed.message ?? last;
357
368
  }
358
369
  catch {
359
370
  return last.slice(0, 500);
@@ -367,10 +378,15 @@ function turnFacts(agent, harness, thread) {
367
378
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
368
379
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
369
380
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
370
- return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness) : null, paused_until: paused };
381
+ return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused };
371
382
  }
372
383
  /** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
373
- export function turnProcess(thread, harness = "codex", psOutput) {
384
+ export function turnProcess(thread, harness = "codex", psOutput, agent) {
385
+ if (harness === "dsh") {
386
+ const initialPid = agent ? readState(agent).harness_session?.initial_pid : undefined;
387
+ const p = dshProcesses(thread, psOutput, initialPid)[0];
388
+ return p ? { pid: p.pid, cpu: p.cpu, rss_bytes: p.rss_bytes } : null;
389
+ }
374
390
  const out = psOutput ?? (spawnSync("ps", ["-axo", "pid=,pcpu=,rss=,args="], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).stdout ?? "");
375
391
  if (harness === "claude-code") {
376
392
  const p = sessionProcesses(thread, out)[0];
@@ -393,19 +409,53 @@ export function turnProcess(thread, harness = "codex", psOutput) {
393
409
  */
394
410
  const CRASH_STARTS = 5;
395
411
  const CRASH_WINDOW_MS = 5 * 60_000;
396
- export function watcherFault(ref, logText, nowMs = Date.now()) {
397
- let text = logText;
398
- if (text === undefined) {
399
- const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
400
- if (!existsSync(f))
401
- return null;
402
- const size = statSync(f).size;
403
- const fd = openSync(f, "r");
404
- const buf = Buffer.alloc(Math.min(size, 65_536));
405
- readSync(fd, buf, 0, buf.length, size - buf.length);
406
- closeSync(fd);
407
- text = buf.toString("utf8");
412
+ function watcherLogText(ref) {
413
+ const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
414
+ if (!existsSync(f))
415
+ return null;
416
+ const size = statSync(f).size;
417
+ const fd = openSync(f, "r");
418
+ const buf = Buffer.alloc(Math.min(size, 65_536));
419
+ readSync(fd, buf, 0, buf.length, size - buf.length);
420
+ closeSync(fd);
421
+ return buf.toString("utf8");
422
+ }
423
+ /** A marked startup failure is unambiguous even when it prevents the first watching banner. */
424
+ export function watcherDirectoryConflict(ref, logText) {
425
+ const text = logText ?? watcherLogText(ref);
426
+ if (text === null)
427
+ return null;
428
+ const lines = text.split("\n").filter((l) => l.trim());
429
+ let latestBanner = -1;
430
+ lines.forEach((line, i) => {
431
+ if (/^\d{4}-\d\d-\d\dT[\d:.]+Z b9s watch\[[^\]]+\]: watching\b/.test(line))
432
+ latestBanner = i;
433
+ });
434
+ for (let i = lines.length - 1; i > latestBanner; i--) {
435
+ if (!lines[i].startsWith('{"error"'))
436
+ continue;
437
+ try {
438
+ const e = JSON.parse(lines[i]);
439
+ if (e.error === "directory_conflict" && e.watcher_exit === true) {
440
+ return `directory_conflict: ${e.message ?? "watcher could not start because the renamed directories differ"}${e.hint ? `; ${e.hint}` : ""}`;
441
+ }
442
+ }
443
+ catch { /* Other JSON output is not a watcher startup fault. */ }
408
444
  }
445
+ return null;
446
+ }
447
+ /** Preserve an existing session as a machine-reported fault instead of trying to restart it. */
448
+ export function existingSessionDirectoryConflict(id, dir, thread, ref) {
449
+ const error = watcherDirectoryConflict(ref);
450
+ return error ? { id, state: "error", dir, thread, watcher: "inactive", error } : null;
451
+ }
452
+ export function watcherFault(ref, logText, nowMs = Date.now()) {
453
+ const text = logText ?? watcherLogText(ref);
454
+ if (text === null)
455
+ return null;
456
+ const directoryConflict = watcherDirectoryConflict(ref, text);
457
+ if (directoryConflict)
458
+ return directoryConflict;
409
459
  const lines = text.split("\n").filter((l) => l.trim());
410
460
  const starts = [];
411
461
  lines.forEach((l, i) => {
@@ -461,12 +511,12 @@ function volumeSpace(path, label) {
461
511
  }
462
512
  /** Whether Codex's own sandbox runs here (`codex sandbox -- true`), with its error; checked at most every 10 min. */
463
513
  let sandboxCache = null;
464
- export function codexSandbox(force = false) {
465
- if (!force && sandboxCache && Date.now() - sandboxCache.at < 10 * 60_000)
514
+ export function codexSandbox(force = false, path = process.env.PATH ?? "") {
515
+ if (!force && sandboxCache && sandboxCache.path === path && Date.now() - sandboxCache.at < 10 * 60_000)
466
516
  return sandboxCache.result;
467
- const r = spawnSync("codex", ["sandbox", "--", "true"], { encoding: "utf8", timeout: 60_000 });
517
+ const r = spawnSync("codex", ["sandbox", "--", "true"], { encoding: "utf8", timeout: 60_000, env: { ...process.env, PATH: path } });
468
518
  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}` };
469
- sandboxCache = { at: Date.now(), result };
519
+ sandboxCache = { at: Date.now(), result, path };
470
520
  return result;
471
521
  }
472
522
  /** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
@@ -480,18 +530,21 @@ function memAvailable() {
480
530
  }
481
531
  /** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
482
532
  let claudeSandboxCache = null;
483
- function claudeReport() {
484
- const f = claudeFacts();
533
+ function claudeReport(path = process.env.PATH ?? "") {
534
+ const f = claudeFacts(undefined, path);
485
535
  if (!f)
486
536
  return null;
487
- if (!claudeSandboxCache || Date.now() - claudeSandboxCache.at > 10 * 60_000)
488
- claudeSandboxCache = { at: Date.now(), result: claudeSandbox() };
537
+ if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
538
+ claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
489
539
  return { ...f, sandbox: claudeSandboxCache.result };
490
540
  }
491
541
  /** What the operator needs to know about this machine, reported with every pass. */
492
542
  export function machineFacts() {
493
- const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
494
- const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8" }) : null;
543
+ const path = process.env.PATH ?? "";
544
+ const env = { ...process.env, PATH: path };
545
+ const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
546
+ const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
547
+ const dsh = dshFacts(platform(), path);
495
548
  let diskFree = null;
496
549
  try {
497
550
  const st = statfsSync(homedir());
@@ -506,9 +559,11 @@ export function machineFacts() {
506
559
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
507
560
  // When this machine last booted: the server ends a maintenance window once the machine is back.
508
561
  booted_at: new Date(Math.floor((Date.now() - uptime() * 1000) / 60_000) * 60_000).toISOString(),
562
+ daemon_path: path,
509
563
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
510
- 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,
511
- "claude-code": claudeReport(),
564
+ 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),
566
+ dsh,
512
567
  managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
513
568
  linger: platform() === "linux" ? lingerEnabled() : null,
514
569
  disk_free_bytes: diskFree,
@@ -522,6 +577,9 @@ export function machineFacts() {
522
577
  */
523
578
  export function prepare(opts = {}) {
524
579
  const steps = [];
580
+ const daemonPath = machineDaemonPath();
581
+ const daemonEnv = { ...process.env, PATH: daemonPath };
582
+ steps.push({ step: "daemon PATH", result: "ok", detail: daemonPath });
525
583
  const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
526
584
  if (platform() === "linux") {
527
585
  const l = lingerEnabled();
@@ -533,16 +591,20 @@ export function prepare(opts = {}) {
533
591
  steps.push(lingerEnabled() ? { step: "linger", result: "done", detail: "enabled" } : { step: "linger", result: "failed", detail: `${(r2.stderr ?? "").trim()} (run: sudo loginctl enable-linger ${userInfo().username})` });
534
592
  }
535
593
  }
536
- const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
594
+ const dsh = dshFacts(platform(), daemonPath);
595
+ steps.push(dsh.available
596
+ ? { step: "dsh", result: "ok", detail: `${dsh.version}, ${dsh.path}` }
597
+ : { step: "dsh", result: platform() === "linux" ? "skipped" : "failed", detail: dsh.error ?? "DeepSeek Harness dsh CLI is unavailable" });
598
+ const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env: daemonEnv });
537
599
  if (codex.status !== 0)
538
600
  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)" });
539
601
  else {
540
- const login = spawnSync("codex", ["login", "status"], { encoding: "utf8" });
602
+ const login = spawnSync("codex", ["login", "status"], { encoding: "utf8", env: daemonEnv });
541
603
  const ok = login.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`);
542
604
  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` });
543
605
  }
544
606
  if (codex.status === 0) {
545
- let sb = codexSandbox(true);
607
+ let sb = codexSandbox(true, daemonPath);
546
608
  if (sb.ok)
547
609
  steps.push({ step: "codex sandbox", result: "ok", detail: "sandboxed (read-only, workspace-write) agents can run here" });
548
610
  else if (platform() !== "linux" || !/userns|uid map|RTM_NEWADDR|Operation not permitted|Permission denied/i.test(sb.error ?? ""))
@@ -554,17 +616,17 @@ export function prepare(opts = {}) {
554
616
  else {
555
617
  const t = spawnSync("sudo", ["-n", "tee", CODEX_APPARMOR_PATH], { input: codexAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
556
618
  const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", CODEX_APPARMOR_PATH], { encoding: "utf8" }) : t;
557
- sb = codexSandbox(true);
619
+ sb = codexSandbox(true, daemonPath);
558
620
  steps.push(l.status === 0 && sb.ok
559
621
  ? { step: "codex sandbox", result: "done", detail: `installed ${CODEX_APPARMOR_PATH} (Codex only); the sandbox works` }
560
622
  : { 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}` });
561
623
  }
562
624
  }
563
625
  // Claude Code is optional on a machine; when it is there, say whether it can run agents.
564
- const claude = claudeFacts();
626
+ const claude = claudeFacts(undefined, daemonPath);
565
627
  if (claude) {
566
628
  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)` });
567
- let sb = claudeSandbox();
629
+ let sb = claudeSandbox(daemonPath);
568
630
  const userns = platform() === "linux" && /RTM_NEWADDR|uid map|Operation not permitted|Permission denied/i.test(sb.error ?? "");
569
631
  if (sb.ok)
570
632
  steps.push({ step: "claude code sandbox", result: "ok", detail: "sandboxed (workspace-write) Claude Code agents can run here" });
@@ -577,7 +639,7 @@ export function prepare(opts = {}) {
577
639
  else {
578
640
  const t = spawnSync("sudo", ["-n", "tee", BWRAP_APPARMOR_PATH], { input: bwrapAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
579
641
  const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", BWRAP_APPARMOR_PATH], { encoding: "utf8" }) : t;
580
- sb = claudeSandbox();
642
+ sb = claudeSandbox(daemonPath);
581
643
  steps.push(l.status === 0 && sb.ok
582
644
  ? { step: "claude code sandbox", result: "done", detail: `installed ${BWRAP_APPARMOR_PATH}; the sandbox works` }
583
645
  : { 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}` });
@@ -631,8 +693,9 @@ export async function machine(p, out) {
631
693
  if (sub === "service") {
632
694
  loadMachine();
633
695
  const bin = requireInstall().bin;
634
- const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir() }, "machine");
635
- 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 });
696
+ const daemonPath = machineDaemonPath();
697
+ const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: daemonPath, HOME: homedir() }, "machine");
698
+ 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 });
636
699
  }
637
700
  const m = loadMachine();
638
701
  const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);