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.
@@ -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;
@@ -655,6 +655,7 @@ export async function processCmd(p, out) {
655
655
  `Untagged units are approved by ${d.default_approver_role ?? "nobody (set a default approver)"}.${d.classification === "classifier" ? ` A ${d.classifier_role} confirms tags before review.` : ""}`,
656
656
  `A unit needs a title${d.require_scope ? ", a scope statement" : ""}${d.require_evidence_to_submit ? ", evidence before review" : ""}. Nothing is done until every tag is approved by someone qualified; never your own unit.`,
657
657
  `Review SLA ${d.review_sla_minutes} min; after ${d.escalate_after_minutes} min another qualified reviewer takes over. Max ${d.max_open_per_agent} open units per agent. Announcements in #${d.channel}.`,
658
+ ...(r.wake_path_warnings?.length ? [`No verified wake path:`, ...r.wake_path_warnings.map((warning) => ` ${warning.consequence}`)] : []),
658
659
  `Merging: ${d.merge.merged_by === "owner" ? "the owner" : d.merge.merged_by === "approver" ? "an approver" : `a ${d.merge.integrator_role}`} merges approved work into ${d.merge.target_branch}${d.merge.require_rebased ? "; the branch must contain " + d.merge.target_branch + " before review" : ""}${d.merge.require_merge_commit ? "; done carries the merge commit (b9s wu done <n> --merged <sha>)" : ""}.`,
659
660
  r.process.agreements ? `\nWorking agreements:\n${r.process.agreements}` : null,
660
661
  r.process.charter ? `\nCharter (how this project weighs its trade-offs; judge reviews and questions by it):\n${r.process.charter}` : null,
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, readFileSync, realpathSync, renameSync, symlinkSync, writeFileSync } from "node:fs";
1
+ import { closeSync, existsSync, lstatSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { CliError } from "./errors.js";
@@ -15,6 +15,86 @@ function maybeLstat(path) {
15
15
  }
16
16
  function directory(path) { return maybeLstat(path)?.isDirectory() ?? false; }
17
17
  function present(path) { return maybeLstat(path) !== null; }
18
+ function treeEntries(root) {
19
+ const entries = new Map();
20
+ const visit = (path, relative) => {
21
+ const st = lstatSync(path);
22
+ if (st.isDirectory()) {
23
+ for (const name of readdirSync(path).sort())
24
+ visit(join(path, name), relative ? relative + "/" + name : name);
25
+ }
26
+ else if (st.isFile())
27
+ entries.set(relative, { kind: "file", path, size: st.size });
28
+ else if (st.isSymbolicLink())
29
+ entries.set(relative, { kind: "symlink", target: readlinkSync(path) });
30
+ else
31
+ entries.set(relative, { kind: "other", mode: st.mode });
32
+ };
33
+ visit(root, "");
34
+ return entries;
35
+ }
36
+ function sameFileBytes(left, right, size) {
37
+ const a = openSync(left, "r");
38
+ let b;
39
+ try {
40
+ b = openSync(right, "r");
41
+ const leftChunk = Buffer.allocUnsafe(64 * 1024);
42
+ const rightChunk = Buffer.allocUnsafe(64 * 1024);
43
+ let position = 0;
44
+ while (position < size) {
45
+ const expected = Math.min(leftChunk.length, size - position);
46
+ const nLeft = readSync(a, leftChunk, 0, expected, position);
47
+ const nRight = readSync(b, rightChunk, 0, expected, position);
48
+ if (nLeft !== nRight || nLeft === 0 || !leftChunk.subarray(0, nLeft).equals(rightChunk.subarray(0, nRight)))
49
+ return false;
50
+ position += nLeft;
51
+ }
52
+ return true;
53
+ }
54
+ finally {
55
+ closeSync(a);
56
+ if (b !== undefined)
57
+ closeSync(b);
58
+ }
59
+ }
60
+ function differingFiles(left, right) {
61
+ const a = treeEntries(left);
62
+ const b = treeEntries(right);
63
+ return [...new Set([...a.keys(), ...b.keys()])].sort().filter((name) => {
64
+ const x = a.get(name);
65
+ const y = b.get(name);
66
+ if (!x || !y || x.kind !== y.kind)
67
+ return true;
68
+ if (x.kind === "file" && y.kind === "file")
69
+ return x.size !== y.size || !sameFileBytes(x.path, y.path, x.size);
70
+ if (x.kind === "symlink" && y.kind === "symlink")
71
+ return x.target !== y.target;
72
+ return x.kind === "other" && y.kind === "other" && x.mode !== y.mode;
73
+ });
74
+ }
75
+ function shellQuote(value) { return "'" + value.replace(/'/g, "'\\''") + "'"; }
76
+ function conflictHint(current, old, currentName) {
77
+ let backup = old + ".conflict";
78
+ for (let n = 2; existsSync(backup); n++)
79
+ backup = old + ".conflict-" + n;
80
+ return "After reviewing the differences, keep " + current + " as the active copy and preserve the other at " + backup + ": mv -- " + shellQuote(old) + " " + shellQuote(backup) + " && ln -s -- " + shellQuote(currentName) + " " + shellQuote(old);
81
+ }
82
+ function conflictFiles(current, old, names, currentName) {
83
+ const details = names.map((name) => {
84
+ const a = join(current, name);
85
+ const b = join(old, name);
86
+ return (present(a) ? a : a + " (missing)") + " <> " + (present(b) ? b : b + " (missing)");
87
+ });
88
+ return new CliError("directory_conflict", "both " + current + " and " + old + " are real directories with different files: " + details.join("; "), conflictHint(current, old, currentName));
89
+ }
90
+ let quarantineSequence = 0;
91
+ function quarantinePath(old) {
92
+ let path;
93
+ do {
94
+ path = old + ".b9s-migrating-" + process.pid + "-" + quarantineSequence++;
95
+ } while (existsSync(path));
96
+ return path;
97
+ }
18
98
  /** Resolve a renamed state directory, preserving old paths through a symlink. */
19
99
  export function renamedDirectory(parent, currentName, oldName, report = true) {
20
100
  const current = join(parent, currentName);
@@ -23,9 +103,31 @@ export function renamedDirectory(parent, currentName, oldName, report = true) {
23
103
  const oldDir = directory(old);
24
104
  const currentExists = present(current);
25
105
  const oldExists = present(old);
26
- if (currentDir && oldDir)
27
- throw new CliError("directory_conflict", `both ${current} and ${old} are real directories; merge or remove one explicitly before continuing`);
28
- if (!currentExists && oldDir) {
106
+ if (currentDir && oldDir) {
107
+ const different = differingFiles(current, old);
108
+ if (different.length)
109
+ throw conflictFiles(current, old, different, currentName);
110
+ const quarantine = quarantinePath(old);
111
+ renameSync(old, quarantine);
112
+ const changedDuringMove = differingFiles(current, quarantine);
113
+ if (changedDuringMove.length) {
114
+ if (!present(old))
115
+ renameSync(quarantine, old);
116
+ throw conflictFiles(current, present(old) ? old : quarantine, changedDuringMove, currentName);
117
+ }
118
+ try {
119
+ symlinkSync(currentName, old, "dir");
120
+ }
121
+ catch (error) {
122
+ if (!present(old))
123
+ renameSync(quarantine, old);
124
+ throw error;
125
+ }
126
+ rmSync(quarantine, { recursive: true });
127
+ if (report)
128
+ process.stderr.write("[b9s] kept identical " + current + "; removed duplicate " + old + "; " + oldName + " now links to " + currentName + "\n");
129
+ }
130
+ else if (!currentExists && oldDir) {
29
131
  renameSync(old, current);
30
132
  symlinkSync(currentName, old, "dir");
31
133
  if (report)
@@ -67,9 +169,10 @@ export function repoDirectory(root) {
67
169
  const currentBefore = maybeLstat(currentPath);
68
170
  const oldBefore = maybeLstat(oldPath);
69
171
  const migration = oldBefore?.isDirectory() === true && currentBefore === null;
172
+ const identicalCopies = oldBefore?.isDirectory() === true && currentBefore?.isDirectory() === true;
70
173
  const compatibilityLink = oldBefore?.isSymbolicLink() === true && currentBefore?.isDirectory() === true;
71
174
  const current = renamedDirectory(root, ".b9s", ".bschat");
72
- if ((migration || compatibilityLink) && existsSync(join(root, ".git"))) {
175
+ if ((migration || identicalCopies || compatibilityLink) && existsSync(join(root, ".git"))) {
73
176
  const ignore = join(root, ".gitignore");
74
177
  const contents = existsSync(ignore) ? readFileSync(ignore, "utf8") : "";
75
178
  const lines = contents.split("\n");
package/dist/errors.js CHANGED
@@ -7,3 +7,5 @@ export class CliError extends Error {
7
7
  this.hint = hint;
8
8
  }
9
9
  }
10
+ /** systemd's EX_CONFIG status: stop restarting a watcher until its local configuration is fixed. */
11
+ export const DIRECTORY_CONFLICT_EXIT_CODE = 78;
package/dist/harnesses.js CHANGED
@@ -4,6 +4,7 @@ import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  import { configRoot } from "./config.js";
7
+ import { readState, writeState } from "./state.js";
7
8
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
8
9
  import { codexTurnPhase, usageLimitUntil } from "./turn.js";
9
10
  /**
@@ -13,16 +14,221 @@ import { codexTurnPhase, usageLimitUntil } from "./turn.js";
13
14
  * last turn ended. Antigravity is a desktop application with no headless turn and stays hand-run;
14
15
  * Gemini CLI no longer accepts personal logins (Google moved individuals to Antigravity).
15
16
  */
16
- export const TURN_HARNESSES = ["codex", "claude-code"];
17
+ export const TURN_HARNESSES = ["codex", "claude-code", "dsh"];
17
18
  export function turnHarness(h) {
18
19
  if (TURN_HARNESSES.includes(h))
19
20
  return h;
20
21
  throw new CliError("unsupported", `harness ${h} cannot run headless turns; supported: ${TURN_HARNESSES.join(", ")}`);
21
22
  }
22
- export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code" };
23
- export const HARNESS_BIN = { codex: "codex", "claude-code": "claude" };
23
+ export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness" };
24
+ export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh" };
24
25
  export function probeFor(harness, session, ref) {
25
- return harness === "codex" ? codexProbe(session) : claudeProbe(session, ref);
26
+ return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : dshProbe(session, ref);
27
+ }
28
+ export const dshTurnLog = (ref) => join(configRoot(), "logs", `turn.${ref.replace("/", ".")}.jsonl`);
29
+ /** The first session event identifies a newly-created DeepSeek Harness session. */
30
+ export function dshSessionFromEvents(text) {
31
+ for (const line of text.split("\n")) {
32
+ try {
33
+ const event = JSON.parse(line);
34
+ if (event.type === "session" && typeof event.sessionId === "string" && event.sessionId)
35
+ return event.sessionId;
36
+ }
37
+ catch { /* a line may still be streaming */ }
38
+ }
39
+ return null;
40
+ }
41
+ function dshEvents(text) {
42
+ return text.split("\n").flatMap((line) => {
43
+ try {
44
+ return [JSON.parse(line)];
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ });
50
+ }
51
+ function latestDshInvocation(text) {
52
+ let offset = 0;
53
+ let start = -1;
54
+ for (const line of text.split("\n")) {
55
+ try {
56
+ const event = JSON.parse(line);
57
+ if (event.type === "b9s_invocation_start")
58
+ start = offset;
59
+ }
60
+ catch { /* dsh can stream a partial final line */ }
61
+ offset += line.length + 1;
62
+ }
63
+ return start >= 0 ? text.slice(start) : text;
64
+ }
65
+ /** State of the latest turn in the dsh JSON event log. */
66
+ export function dshTurnPhase(text) {
67
+ let running = false;
68
+ let lastError = null;
69
+ for (const e of dshEvents(text)) {
70
+ if (e.type === "status" && e.phase === "turn_start") {
71
+ running = true;
72
+ lastError = null;
73
+ }
74
+ else if (e.type === "error") {
75
+ lastError = typeof e.message === "string" ? e.message : "DeepSeek Harness reported an error";
76
+ }
77
+ else if (e.type === "status" && e.phase === "turn_end") {
78
+ running = false;
79
+ if (e.reason?.kind !== "completed")
80
+ lastError = typeof e.message === "string" ? e.message : `turn ended: ${e.reason?.kind ?? "unknown reason"}`;
81
+ }
82
+ else if (e.type === "final") {
83
+ running = false;
84
+ if (e.reason?.kind === "completed")
85
+ lastError = null;
86
+ else
87
+ lastError = typeof e.message === "string" ? e.message : `final event reason: ${e.reason?.kind ?? "unknown reason"}`;
88
+ }
89
+ }
90
+ return { running, startedAt: null, lastEventAt: null, lastError };
91
+ }
92
+ /** Error from the current recorded turn; success requires its completed final event. */
93
+ export function dshResultError(text) {
94
+ const events = dshEvents(text);
95
+ const invocationEnd = [...events].reverse().find((e) => e.type === "b9s_invocation_end");
96
+ const exitCode = typeof invocationEnd?.exit === "number" ? invocationEnd.exit : null;
97
+ const diagnostic = text.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("{")).at(-1);
98
+ let start = -1;
99
+ for (let i = 0; i < events.length; i++)
100
+ if (events[i].type === "status" && events[i].phase === "turn_start")
101
+ start = i;
102
+ const turn = events.slice(start >= 0 ? start : 0);
103
+ for (const e of turn)
104
+ if (e.type === "error")
105
+ return (typeof e.message === "string" ? e.message : "DeepSeek Harness reported an error").slice(0, 500);
106
+ for (const e of turn)
107
+ if (e.type === "status" && e.phase === "turn_end" && e.reason?.kind !== "completed")
108
+ return (typeof e.message === "string" ? e.message : `turn ended: ${e.reason?.kind ?? "unknown reason"}`).slice(0, 500);
109
+ let finalIndex = -1;
110
+ for (let i = turn.length - 1; i >= 0; i--)
111
+ if (turn[i].type === "final") {
112
+ finalIndex = i;
113
+ break;
114
+ }
115
+ const final = finalIndex >= 0 ? turn[finalIndex] : undefined;
116
+ if (final?.reason?.kind === "completed") {
117
+ if (exitCode === null || exitCode === 0)
118
+ return null;
119
+ return `DeepSeek Harness exited with code ${exitCode}${diagnostic ? `: ${diagnostic}` : ""}`.slice(0, 500);
120
+ }
121
+ if (final)
122
+ return (typeof final.message === "string" ? final.message : `final event reason: ${final.reason?.kind ?? "unknown reason"}`).slice(0, 500);
123
+ if (exitCode !== null && exitCode !== 0)
124
+ return (diagnostic ?? `DeepSeek Harness exited with code ${exitCode}`).slice(0, 500);
125
+ return (diagnostic ?? "DeepSeek Harness exited without a completed final event").slice(0, 500);
126
+ }
127
+ /** DeepSeek emits per-step usage; sum it over the accumulated per-agent turn log. */
128
+ export function dshUsage(text, since, until) {
129
+ const result = { input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 };
130
+ const window = since !== undefined && until !== undefined ? { since: Date.parse(since), until: Date.parse(until) } : null;
131
+ let invocationAt = null;
132
+ for (const e of dshEvents(text)) {
133
+ if (e.type === "b9s_invocation_start") {
134
+ invocationAt = typeof e.at === "string" ? Date.parse(e.at) : null;
135
+ continue;
136
+ }
137
+ if (e.type === "b9s_invocation_end") {
138
+ invocationAt = null;
139
+ continue;
140
+ }
141
+ if (e.type !== "status" || e.phase !== "step_end" || !e.usage)
142
+ continue;
143
+ if (window && (invocationAt === null || invocationAt < window.since || invocationAt > window.until))
144
+ continue;
145
+ result.input += (e.usage.inputTokens ?? 0) + (e.usage.cacheReadTokens ?? 0) + (e.usage.cacheWriteTokens ?? 0);
146
+ result.cached_input += e.usage.cacheReadTokens ?? 0;
147
+ result.output += e.usage.outputTokens ?? 0;
148
+ }
149
+ result.total = result.input + result.output;
150
+ return result;
151
+ }
152
+ /** Map the user's selected sandbox to dsh's native permission mode and writable roots. */
153
+ export function dshSettings(sandbox, cwd, b9sHome, extraWritable = []) {
154
+ if (sandbox === "read-only")
155
+ throw new CliError("unsupported", "DeepSeek Harness has no read-only permission mode; use workspace-write or danger-full-access");
156
+ if (sandbox !== "workspace-write" && sandbox !== "danger-full-access")
157
+ throw new CliError("usage", `unknown sandbox ${sandbox}`);
158
+ const dirs = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
159
+ return ["--permission-mode", sandbox, "--approval-policy", "never", ...dirs.flatMap((dir) => ["--add-dir", dir])];
160
+ }
161
+ /** Locate dsh explicitly, in the macOS app bundle, or on PATH. */
162
+ export function dshPath(explicit, pathEnv = process.env.PATH ?? "", os = process.platform, home = homedir(), fileExists = existsSync) {
163
+ if (explicit)
164
+ return explicit;
165
+ const candidates = os === "darwin" ? [
166
+ "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh",
167
+ join(home, "Applications", "DeepSeek Harness.app", "Contents", "Resources", "runtime", "cli", "bin", "dsh"),
168
+ ] : [];
169
+ candidates.push(...pathEnv.split(":").filter(Boolean).map((dir) => join(dir, "dsh")));
170
+ return candidates.find(fileExists) ?? null;
171
+ }
172
+ /** The machine daemon reports dsh presence and version; this trial found no Linux distribution. */
173
+ export function dshFacts(os = process.platform, pathEnv = process.env.PATH ?? "", home = homedir()) {
174
+ if (os === "linux")
175
+ return { available: false, path: null, version: null, error: "DeepSeek Harness has no Linux build" };
176
+ const path = dshPath(undefined, pathEnv, os, home);
177
+ if (!path)
178
+ return { available: false, path: null, version: null, error: "DeepSeek Harness dsh CLI was not found in the app bundle or PATH" };
179
+ const version = spawnSync(path, ["--version"], { encoding: "utf8", timeout: 30_000 });
180
+ if (version.status !== 0)
181
+ return { available: false, path, version: null, error: `${path} --version failed: ${(version.stderr || version.stdout || `exit ${version.status}`).trim().slice(0, 250)}` };
182
+ return { available: true, path, version: version.stdout.trim(), error: null };
183
+ }
184
+ export function isDshCommand(args) {
185
+ return /^(?:dsh|\/.*\/dsh)(?:\.exe)?\s/.test(args.trimStart());
186
+ }
187
+ /** Processes whose own command is dsh and whose arguments name this session. */
188
+ export function dshProcesses(session, psOutput, initialPid) {
189
+ const out = psOutput ?? (spawnSync("ps", ["-axo", "pid=,pcpu=,rss=,args="], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).stdout ?? "");
190
+ const found = [];
191
+ for (const line of out.split("\n")) {
192
+ const m = /^\s*(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
193
+ const pid = Number(m?.[1]);
194
+ const isSession = !!m && new RegExp(`(?:^|\\s)--session-id\\s+['\"]?${escapeRegExp(session)}(?:['\"]?(?:\\s|$))`).test(m[4]);
195
+ const isInitial = !!m && pid === initialPid;
196
+ if (m && isDshCommand(m[4]) && (isSession || isInitial))
197
+ found.push({ pid, cpu: Number(m[2]), rss_bytes: Number(m[3]) * 1024, args: m[4] });
198
+ }
199
+ return found;
200
+ }
201
+ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
202
+ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
203
+ const readBytes = () => existsSync(path) ? readFileSync(path) : Buffer.alloc(0);
204
+ const read = () => readBytes().toString("utf8");
205
+ const readInvocation = (offset) => readBytes().subarray(offset).toString("utf8");
206
+ let invocationOffset = 0;
207
+ return {
208
+ label: "DeepSeek Harness", what: `session ${session}`,
209
+ phase() {
210
+ if (!existsSync(path))
211
+ return { missing: `no DeepSeek Harness turn log ${path}; cannot tell whether session ${session} is running` };
212
+ const phase = dshTurnPhase(read());
213
+ const stat = statSync(path);
214
+ const initialPid = readState(ref).harness_session?.initial_pid;
215
+ const live = processes ? processes(initialPid) : dshProcesses(session, undefined, initialPid);
216
+ const lastError = live.length ? phase.lastError : dshResultError(latestDshInvocation(read())) ?? phase.lastError;
217
+ return { ...phase, running: live.length > 0, lastError, lastEventAt: stat.mtime.toISOString(), lastErrorAt: stat.mtime.toISOString() };
218
+ },
219
+ beginTurn() {
220
+ invocationOffset = existsSync(path) ? statSync(path).size : 0;
221
+ const state = readState(ref);
222
+ if (state.harness_session?.initial_pid) {
223
+ const { initial_pid: _initialPid, ...session } = state.harness_session;
224
+ writeState(ref, { ...state, harness_session: session });
225
+ }
226
+ },
227
+ startedSince() { return dshEvents(readInvocation(invocationOffset)).some((e) => e.type === "status" && e.phase === "turn_start"); },
228
+ turnError: () => dshResultError(readInvocation(invocationOffset)),
229
+ limitUntil: () => null,
230
+ isLimit: () => false,
231
+ };
26
232
  }
27
233
  function codexProbe(thread) {
28
234
  const read = () => { const r = codexRollout(thread); return r ? codexTurnPhase(readFileSync(r, "utf8")) : null; };
@@ -212,11 +418,12 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
212
418
  * the credentials file changes and at most every 6 hours otherwise; only an authentication error
213
419
  * counts as logged out, and any other failure is reported as unverified with its error.
214
420
  */
215
- export function claudeFacts(verify = verifyClaudeLoginCached) {
216
- const v = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 30_000 });
421
+ export function claudeFacts(verify, path = process.env.PATH ?? "") {
422
+ const env = { ...process.env, PATH: path };
423
+ const v = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 30_000, env });
217
424
  if (v.status !== 0)
218
425
  return null;
219
- const s = spawnSync("claude", ["auth", "status"], { encoding: "utf8", timeout: 30_000 });
426
+ const s = spawnSync("claude", ["auth", "status"], { encoding: "utf8", timeout: 30_000, env });
220
427
  let stored = false;
221
428
  let method = "unknown method";
222
429
  try {
@@ -229,13 +436,13 @@ export function claudeFacts(verify = verifyClaudeLoginCached) {
229
436
  }
230
437
  if (!stored)
231
438
  return { version: v.stdout.trim(), logged_in: false, login: "not logged in", verified: { ok: false, error: "no stored login" } };
232
- const verified = verify();
439
+ const verified = (verify ?? (() => verifyClaudeLoginCached(env)))();
233
440
  const login = verified.ok === true ? `logged in (${method})` : verified.ok === false ? `stored login rejected: ${verified.error}` : `logged in (${method}), not verified: ${verified.error}`;
234
441
  return { version: v.stdout.trim(), logged_in: verified.ok !== false, login: login.slice(0, 200), verified };
235
442
  }
236
443
  /** One minimal headless call; ok false only when Claude Code reports an authentication failure. */
237
- export function verifyClaudeLogin() {
238
- const r = spawnSync("claude", ["-p", "Reply OK", "--model", "claude-haiku-4-5-20251001", "--output-format", "json"], { encoding: "utf8", timeout: 120_000, cwd: homedir() });
444
+ export function verifyClaudeLogin(env = process.env) {
445
+ const r = spawnSync("claude", ["-p", "Reply OK", "--model", "claude-haiku-4-5-20251001", "--output-format", "json"], { encoding: "utf8", timeout: 120_000, cwd: homedir(), env });
239
446
  const error = claudeResultError(r.stdout ?? "") ?? (r.status !== 0 ? `${r.stderr ?? ""}`.trim().split("\n")[0] || `exit ${r.status}` : null);
240
447
  if (!error)
241
448
  return { ok: true, error: null };
@@ -243,12 +450,13 @@ export function verifyClaudeLogin() {
243
450
  }
244
451
  export const claudeIsAuthError = (e) => /401|403|authenticat|not logged in|\/login|oauth token|invalid api key/i.test(e);
245
452
  let loginCache = null;
246
- function verifyClaudeLoginCached() {
453
+ function verifyClaudeLoginCached(env = process.env) {
247
454
  const cred = join(claudeHome(), ".credentials.json");
248
455
  const key = existsSync(cred) ? String(statSync(cred).mtimeMs) : "keychain";
249
- if (loginCache && loginCache.key === key && Date.now() - loginCache.at < 6 * 60 * 60_000)
456
+ const cacheKey = `${key}\0${env.PATH ?? ""}`;
457
+ if (loginCache && loginCache.key === cacheKey && Date.now() - loginCache.at < 6 * 60 * 60_000)
250
458
  return loginCache.result;
251
- loginCache = { key, at: Date.now(), result: verifyClaudeLogin() };
459
+ loginCache = { key: cacheKey, at: Date.now(), result: verifyClaudeLogin(env) };
252
460
  return loginCache.result;
253
461
  }
254
462
  /**
@@ -256,14 +464,15 @@ function verifyClaudeLoginCached() {
256
464
  * bubblewrap and socat, and bubblewrap needs unprivileged user namespaces (Ubuntu 24.04 restricts
257
465
  * them with AppArmor), so this runs bubblewrap the way a sandboxed command would.
258
466
  */
259
- export function claudeSandbox() {
467
+ export function claudeSandbox(path = process.env.PATH ?? "") {
260
468
  if (process.platform === "darwin")
261
469
  return existsSync("/usr/bin/sandbox-exec") ? { ok: true, error: null } : { ok: false, error: "sandbox-exec is missing" };
262
470
  if (process.platform !== "linux")
263
471
  return { ok: false, error: `no Claude Code sandbox on ${process.platform}` };
264
- const missing = ["bwrap", "socat"].filter((b) => spawnSync("/bin/sh", ["-c", `command -v ${b}`]).status !== 0);
472
+ const env = { ...process.env, PATH: path };
473
+ const missing = ["bwrap", "socat"].filter((b) => spawnSync("/bin/sh", ["-c", `command -v ${b}`], { env }).status !== 0);
265
474
  if (missing.length)
266
475
  return { ok: false, error: `${missing.join(" and ")} not installed (sudo apt-get install bubblewrap socat)` };
267
- const r = spawnSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-all", "--die-with-parent", "true"], { encoding: "utf8", timeout: 30_000 });
476
+ const r = spawnSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-all", "--die-with-parent", "true"], { encoding: "utf8", timeout: 30_000, env });
268
477
  return r.status === 0 ? { ok: true, error: null } : { ok: false, error: `bubblewrap cannot start: ${`${r.stderr ?? ""}`.trim().split("\n")[0].slice(0, 250) || `exit ${r.status}`}` };
269
478
  }
package/dist/help.js CHANGED
@@ -41,7 +41,7 @@ Agent commands
41
41
  b9s inbox [--unread] [--after <iso-time>] [--limit n] mentions of you and replies to your messages
42
42
  b9s follow <channel> | unfollow <channel> | following followed channels' new messages are injected by the hook;
43
43
  other channels appear as a one-line unread digest
44
- b9s process the project's process: tag vocabulary, scope templates, reviewer focus, machine/path requirements, slice defaults, agreements
44
+ b9s process the project's process: tag vocabulary, reviewers, wake-path warnings, scope templates, requirements, agreements
45
45
  b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--tier routine|careful|expert] [--requires cap,cap] [--force] [--evidence id[,id...]] [--target <branch>] [--here] open a work unit in its own
46
46
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
47
47
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
@@ -100,6 +100,8 @@ Agent commands
100
100
  b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console)
101
101
  b9s wu propose <n> "answer" owner, reviewer, assigner or expert: recommend an answer to the unit's open question, approvable as written
102
102
  b9s wu escalate <n> [--note ..] the tag's expert: pass the question to the operator
103
+ b9s wu wait <n> --on <m> --note "why" | --clear
104
+ owner, assigner or operator: wait for any non-closed unit; released when it closes
103
105
  b9s wu wait <n> --on "evidence|unit #m|ask id|machine name|text blocker" --note "why" [--partial "verdict"] | --clear
104
106
  owner or reviewer: pause review on a named blocker; reviewer may record a partial verdict
105
107
  b9s wu scope <n> --scope ".." | --scope-file <path> | --scope-from <n> --note ".." assigner or operator: replace the full scope; recorded and announced
@@ -135,20 +137,20 @@ Agent commands
135
137
  --env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
136
138
  ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
137
139
  --service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
138
- itself (--harness codex|claude-code --session <id>); set up by b9s start.
140
+ itself (--harness codex|claude-code|dsh --session <id>); set up by b9s start.
139
141
  Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
140
- b9s update the same as install --latest: upgrade this machine's b9s, restart watchers
141
- without waiting on one stop, and report any that did not come up
142
- b9s install [<version> | --latest] make or upgrade this machine's one b9s (join does it once), restart watchers
143
- without waiting on one stop, and report any that did not come up
142
+ b9s update the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
143
+ restart services on that install without waiting on one stop, and report failures
144
+ b9s install [<version> | --latest] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
145
+ restart services resolving to it; other installs are left alone and named
144
146
  b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
145
147
  hook and instructions, each watcher's plist versus what launchd runs), with fixes
146
148
  b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
147
- b9s start --harness codex|claude-code --as <a> --sandbox <mode> [--token t] [--thread id] [--model m] [--effort e]
149
+ b9s start --harness codex|claude-code|dsh --as <a> --sandbox <mode> [--token t] [--thread id] [--model m] [--effort e] [--dsh path]
148
150
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
149
151
  (b9s codex start is the same with --harness codex)
150
152
  b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
151
- b9s machine run | once | status | prepare | service the machine daemon (set up by b9s-admin machine add)
153
+ b9s machine run | once | status | prepare | service the machine daemon (prepare checks dsh availability/version; Linux reports no DeepSeek build)
152
154
  b9s checkpoint "<title>" --body "..." a resume note without retiring: what you are doing, open threads, next steps;
153
155
  your next session (after a move to another machine) reads it first
154
156
  b9s antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
@@ -163,7 +165,7 @@ Agent commands
163
165
  b9s channel create <name> [--topic t] needs create_channels permission
164
166
  b9s agents
165
167
  b9s roles
166
- b9s evidence post <file> [--label t] [--kind test|diagnosis|review|screenshot|log|other] [--claim "one line"] [--type ct] [--name fn] checksummed evidence
168
+ b9s evidence post <file> [--label t] [--kind test|diagnosis|review|screenshot|log|other] [--claim "one line"] [--type ct] [--name fn] checksummed raw bytes; prints stored content type
167
169
  b9s evidence list [--limit n] [--unit n] [--kind k]
168
170
  b9s evidence info <id|sha256>
169
171
  b9s evidence get <id|sha256> [--out path] verifies sha256 on download