benignswarm 0.12.86 → 0.12.87

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
@@ -9,7 +9,7 @@ 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
14
  import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
15
15
  import { CLI_VERSION } from "../version.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) => {
@@ -490,6 +540,7 @@ function claudeReport() {
490
540
  }
491
541
  /** What the operator needs to know about this machine, reported with every pass. */
492
542
  export function machineFacts() {
543
+ const dsh = dshFacts();
493
544
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
494
545
  const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8" }) : null;
495
546
  let diskFree = null;
@@ -509,6 +560,7 @@ export function machineFacts() {
509
560
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
510
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,
511
562
  "claude-code": claudeReport(),
563
+ dsh,
512
564
  managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
513
565
  linger: platform() === "linux" ? lingerEnabled() : null,
514
566
  disk_free_bytes: diskFree,
@@ -533,6 +585,10 @@ export function prepare(opts = {}) {
533
585
  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
586
  }
535
587
  }
588
+ const dsh = dshFacts();
589
+ steps.push(dsh.available
590
+ ? { step: "dsh", result: "ok", detail: `${dsh.version}, ${dsh.path}` }
591
+ : { step: "dsh", result: platform() === "linux" ? "skipped" : "failed", detail: dsh.error ?? "DeepSeek Harness dsh CLI is unavailable" });
536
592
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
537
593
  if (codex.status !== 0)
538
594
  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)" });
@@ -78,7 +78,7 @@ export async function watch(p, out) {
78
78
  throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
79
79
  const named = str(p.flags, "harness") ?? (thread ? "codex" : undefined);
80
80
  if (!named)
81
- throw new CliError("usage", "--turn needs --harness <codex|claude-code> and --session <id> (a Codex exec resume command names its thread itself)");
81
+ throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh> and --session <id> (a Codex exec resume command names its thread itself)");
82
82
  const harness = turnHarness(named);
83
83
  const session = (str(p.flags, "session") ?? (harness === "codex" ? thread : null))?.toLowerCase();
84
84
  if (!session)
@@ -144,7 +144,7 @@ export async function watch(p, out) {
144
144
  // another machine) went unnoticed: fabricbios codex-coordinator's kept running on the Mac. Check
145
145
  // the key on its own clock.
146
146
  let lastKeyCheck = 0;
147
- const ctl = { turn: null, failedAt: 0, loggedRunning: null, pausedUntil: 0, pausedAt: 0 };
147
+ const ctl = { turn: null, failedAt: 0, loggedRunning: null, loggedFailureAt: null, pausedUntil: 0, pausedAt: 0 };
148
148
  const probe = turn ? probeFor(turn.harness, turn.session, name) : null;
149
149
  let resumeBriefDelivered = false;
150
150
  while (!stopping) {
@@ -229,7 +229,7 @@ export async function watch(p, out) {
229
229
  try {
230
230
  if (probe)
231
231
  await turnStep(ctl, probe, turnTimeout, log, async (sink) => {
232
- const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink, !resumeBriefDelivered);
232
+ const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "dsh", () => probe.beginTurn?.());
233
233
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
234
234
  }, name);
235
235
  else {
@@ -318,7 +318,7 @@ async function waitIntervalOrStop(ms, stopped) {
318
318
  if (timer)
319
319
  clearTimeout(timer);
320
320
  }
321
- async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false) {
321
+ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, turnStdin = false, beforeTurn) {
322
322
  const state = readState(name);
323
323
  const pending = state.watch_pending;
324
324
  if (pending) {
@@ -405,7 +405,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
405
405
  // `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
406
406
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
407
407
  const line = wake;
408
- if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind)))
408
+ if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, turnStdin, beforeTurn)))
409
409
  return { sent: false, recoveryBriefDelivered: false };
410
410
  writeState(name, {
411
411
  ...readState(name),
@@ -430,19 +430,20 @@ async function recoveryBriefText(name, log) {
430
430
  }
431
431
  }
432
432
  /** Runs the wake command (or prints the wake-up without one). False when the command failed: nothing was delivered. */
433
- async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}) {
433
+ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, turnStdin = false, beforeTurn) {
434
434
  if (!exec) {
435
435
  process.stdout.write(wake + "\n");
436
436
  return true;
437
437
  }
438
- const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", shellQuote(wake));
438
+ const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", turnStdin ? "-" : shellQuote(wake));
439
439
  const env = { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) };
440
440
  if (turnSink) {
441
441
  // The turn runs in the background; turnStep follows it, acknowledges it once the session shows
442
442
  // it started, and reports how it ended.
443
443
  log(`${prefix}[${tier}] starting turn #${seq}: ${summary}`);
444
444
  // The agent's own b9s calls in the turn know who they are without any repo file.
445
- turnSink(startTurn(cmd, { ...env, BSCHAT_AGENT: name }, seq));
445
+ beforeTurn?.();
446
+ turnSink(startTurn(cmd, { ...env, BSCHAT_AGENT: name }, seq, turnStdin ? wake : undefined));
446
447
  }
447
448
  else {
448
449
  log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
@@ -500,7 +501,7 @@ const KEY_CHECK_MS = 5 * 60_000;
500
501
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
501
502
  * broken; one that runs past --turn-timeout is stopped and logged.
502
503
  */
503
- async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
504
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
504
505
  const turn = ctl.turn;
505
506
  if (turn) {
506
507
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
@@ -565,6 +566,18 @@ async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
565
566
  log(ph.missing);
566
567
  return;
567
568
  }
569
+ if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
570
+ const failedAt = Date.parse(ph.lastErrorAt ?? "");
571
+ if (Number.isFinite(failedAt)) {
572
+ const retryAt = failedAt + TURN_RETRY_MS;
573
+ if (ctl.loggedFailureAt !== ph.lastErrorAt) {
574
+ ctl.loggedFailureAt = ph.lastErrorAt;
575
+ log(`the last DeepSeek Harness turn failed (${ph.lastError}); next turn is eligible at ${new Date(retryAt).toISOString()}`);
576
+ }
577
+ if (Date.now() < retryAt)
578
+ return;
579
+ }
580
+ }
568
581
  // A watcher that restarted after a usage-limit failure reads the pause from the session itself.
569
582
  const until = !ph.running && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? probe.limitUntil(ph.lastError) : null;
570
583
  if (until && until > Date.now()) {
@@ -408,11 +408,11 @@ export async function wu(p, out) {
408
408
  case "wait": {
409
409
  const on = str(p.flags, "on");
410
410
  if (!on && !bool(p.flags, "clear"))
411
- throw new CliError("usage", 'wu wait <n> --on <m> [--note ".."] (or --clear)');
411
+ throw new CliError("usage", 'wu wait <n> --on <m> --note "why" (or --clear)');
412
412
  if (on && bool(p.flags, "clear"))
413
413
  throw new CliError("usage", "choose either --on or --clear");
414
414
  if (on && !str(p.flags, "note"))
415
- throw new CliError("usage", 'wu wait <n> --on "evidence|unit #m|ask id|machine name|text blocker" --note "why"');
415
+ throw new CliError("usage", 'wu wait <n> --on <m> --note "why" | wu wait <n> --on "evidence|unit #m|ask id|machine name|text blocker" --note "why"');
416
416
  const r = await client.call("POST", `${base}/${num()}/wait`, waitPayload(on, bool(p.flags, "clear"), str(p.flags, "note") ?? "", str(p.flags, "partial") ?? ""));
417
417
  out.print(fmt(r.unit), r);
418
418
  return;