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/index.js CHANGED
@@ -19,7 +19,7 @@ import { doctor, install } from "./commands/install.js";
19
19
  import { warnIfForeignCopy } from "./install.js";
20
20
  import { processCmd, record, wu, milestones, milestone, lock, askOperator, explainAsk } from "./commands/wu.js";
21
21
  import { worktrees } from "./commands/worktrees.js";
22
- import { CliError } from "./errors.js";
22
+ import { CliError, DIRECTORY_CONFLICT_EXIT_CODE } from "./errors.js";
23
23
  import { HELP } from "./help.js";
24
24
  import { CLI_VERSION } from "./version.js";
25
25
  import { makeOut } from "./output.js";
@@ -106,6 +106,7 @@ const COMMANDS = {
106
106
  const NOTICE_PREFLIGHT_EXEMPT_COMMANDS = new Set([
107
107
  "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start",
108
108
  ]);
109
+ let invokedCommand;
109
110
  async function main(argv) {
110
111
  warnLegacyAlias();
111
112
  applyEnvAliases();
@@ -116,6 +117,7 @@ async function main(argv) {
116
117
  return 0;
117
118
  }
118
119
  const cmd = p.positionals[0];
120
+ invokedCommand = cmd;
119
121
  if (!cmd || bool(p.flags, "help")) {
120
122
  process.stdout.write(HELP);
121
123
  return cmd ? 0 : 2;
@@ -145,7 +147,10 @@ async function main(argv) {
145
147
  return code ?? 0;
146
148
  }
147
149
  main(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (err) => {
148
- const e = err instanceof CliError ? { error: err.code, message: err.message, hint: err.hint } : { error: "internal", message: err instanceof Error ? err.stack ?? err.message : String(err) };
149
- process.exitCode = 1;
150
+ const isWatcherDirectoryConflict = err instanceof CliError && err.code === "directory_conflict" && invokedCommand === "watch";
151
+ const e = err instanceof CliError
152
+ ? { error: err.code, message: err.message, hint: err.hint, ...(isWatcherDirectoryConflict ? { watcher_exit: true } : {}) }
153
+ : { error: "internal", message: err instanceof Error ? err.stack ?? err.message : String(err) };
154
+ process.exitCode = isWatcherDirectoryConflict ? DIRECTORY_CONFLICT_EXIT_CODE : 1;
150
155
  process.stderr.write(JSON.stringify(e) + "\n");
151
156
  });
package/dist/install.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
3
  import { homedir, userInfo } from "node:os";
4
- import { basename, dirname, join } from "node:path";
4
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { CliError } from "./errors.js";
7
7
  import { cmp } from "./update.js";
@@ -34,6 +34,57 @@ export function requireInstall() {
34
34
  }
35
35
  return r;
36
36
  }
37
+ /** Build the environment installed for the machine daemon and used by its harness checks. */
38
+ export function composeMachinePath(options) {
39
+ const isDirectory = options.exists ?? ((path) => {
40
+ try {
41
+ return statSync(path).isDirectory();
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ });
47
+ const preferred = [
48
+ join(options.home, ".local", "bin"),
49
+ dirname(options.installBin),
50
+ dirname(options.npmBin),
51
+ ...(options.platform === "darwin" ? ["/opt/homebrew/bin", "/usr/local/bin"] : []),
52
+ ];
53
+ const entries = [];
54
+ const seen = new Set();
55
+ for (const entry of [...preferred.filter(isDirectory), ...options.currentPath.split(delimiter).filter(Boolean)]) {
56
+ if (seen.has(entry))
57
+ continue;
58
+ seen.add(entry);
59
+ entries.push(entry);
60
+ }
61
+ return entries.join(delimiter);
62
+ }
63
+ /** The machine daemon must not inherit PATH from whichever shell happened to install it. */
64
+ export function machineDaemonPath(currentPath = process.env.PATH ?? "", platformName = process.platform, home = homedir()) {
65
+ const install = requireInstall();
66
+ // npm is commonly a #!/usr/bin/env node script. Give it the known runtime locations
67
+ // before asking it for the prefix, since the shell that provisioned this machine may
68
+ // not have ~/.local/bin (or the recorded install's bin) on PATH yet.
69
+ const discoveryPath = composeMachinePath({
70
+ platform: platformName,
71
+ home,
72
+ installBin: install.bin,
73
+ npmBin: install.npm,
74
+ currentPath,
75
+ });
76
+ const prefix = spawnSync(install.npm, ["prefix", "-g"], {
77
+ encoding: "utf8",
78
+ timeout: 30_000,
79
+ env: { ...process.env, PATH: discoveryPath },
80
+ });
81
+ if (prefix.status !== 0)
82
+ throw new CliError("npm_prefix_failed", `${install.npm} prefix -g failed while preparing the machine daemon PATH`, (prefix.stderr ?? "").trim().slice(0, 300));
83
+ const globalPrefix = (prefix.stdout ?? "").trim();
84
+ if (!globalPrefix || !globalPrefix.startsWith("/"))
85
+ throw new CliError("npm_prefix_invalid", `${install.npm} prefix -g did not return an absolute path`, (prefix.stdout ?? "").trim().slice(0, 300));
86
+ return composeMachinePath({ platform: platformName, home, installBin: install.bin, npmBin: join(globalPrefix, "bin", "npm"), currentPath });
87
+ }
37
88
  /** "b9s 0.12.38" -> "0.12.38"; null when the binary cannot run. */
38
89
  export function binVersion(bin) {
39
90
  const r = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 20_000 });
@@ -86,6 +137,58 @@ export function ensureInstall(version, log, npmOverride) {
86
137
  writeFileSync(installFile(), JSON.stringify(rec, null, 2) + "\n");
87
138
  return rec;
88
139
  }
140
+ /** Creates b9s-named shell links beside aliases of the same recorded install, without replacing another copy. */
141
+ export function ensureCommandLinks(installBin) {
142
+ const prefixBin = dirname(installBin);
143
+ const dirs = [...new Set([...(process.env.PATH ?? "").split(delimiter).filter(Boolean).map((dir) => resolve(dir)), resolve(prefixBin)])];
144
+ const commands = [
145
+ { legacy: "bschat", primary: "b9s", target: installBin },
146
+ { legacy: "bschat-admin", primary: "b9s-admin", target: join(prefixBin, "b9s-admin") },
147
+ ];
148
+ const created = [];
149
+ const conflicts = [];
150
+ for (const dir of dirs)
151
+ for (const command of commands) {
152
+ const source = join(dir, command.legacy);
153
+ let sourceReal;
154
+ let targetReal;
155
+ try {
156
+ sourceReal = realpathSync(source);
157
+ targetReal = realpathSync(command.target);
158
+ }
159
+ catch {
160
+ continue;
161
+ }
162
+ if (sourceReal !== targetReal)
163
+ continue;
164
+ const dest = join(dir, command.primary);
165
+ try {
166
+ lstatSync(dest);
167
+ try {
168
+ if (realpathSync(dest) !== targetReal)
169
+ conflicts.push(`${dest} points to another install`);
170
+ }
171
+ catch {
172
+ conflicts.push(`${dest} exists but does not resolve`);
173
+ }
174
+ continue;
175
+ }
176
+ catch (error) {
177
+ if (error.code !== "ENOENT") {
178
+ conflicts.push(`${dest}: ${error.message}`);
179
+ continue;
180
+ }
181
+ }
182
+ try {
183
+ symlinkSync(targetReal, dest);
184
+ created.push(dest);
185
+ }
186
+ catch (error) {
187
+ conflicts.push(`${dest}: ${error.message}`);
188
+ }
189
+ }
190
+ return { created, conflicts };
191
+ }
89
192
  /** Single-quotes a path for a shell command (hooks run through sh). */
90
193
  export const shellPath = (p) => (/^[A-Za-z0-9_./-]+$/.test(p) ? p : `'${p.replace(/'/g, `'\\''`)}'`);
91
194
  export const launchAgentsDir = () => join(homedir(), "Library", "LaunchAgents");
@@ -149,8 +252,120 @@ export function unitArgs(text) {
149
252
  const a = JSON.parse(m[1]);
150
253
  return Array.isArray(a) && a.every((x) => typeof x === "string") ? a : null;
151
254
  }
152
- /** systemd's quoting for one ExecStart word or Environment assignment: double quotes, with %, $, \ and " escaped. */
153
- const sdq = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
255
+ function systemdQuote(s) {
256
+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
257
+ }
258
+ /** Rewrites a service definition after its first argument is proven to be the same install file. */
259
+ export function rewriteServiceInstall(s, installBin) {
260
+ const args = s.args;
261
+ if (!args?.length)
262
+ throw new CliError("service_unreadable", `${s.label} has no readable program arguments`);
263
+ let programReal;
264
+ const installReal = realpathSync(installBin);
265
+ try {
266
+ programReal = realpathSync(args[0]);
267
+ }
268
+ catch {
269
+ throw new CliError("service_unresolved", `${s.label} program ${args[0]} does not resolve`);
270
+ }
271
+ if (programReal !== installReal)
272
+ throw new CliError("service_install_mismatch", `${s.label} resolves to ${programReal}, not ${installReal}`);
273
+ const nextArgs = [installBin, ...args.slice(1)];
274
+ if (s.kind === "systemd") {
275
+ const original = readFileSync(s.path, "utf8");
276
+ if (!/^# bschat-args: .*$/m.test(original) || !/^ExecStart=.*$/m.test(original)) {
277
+ throw new CliError("service_unreadable", `${s.label} has no recognized service command metadata`);
278
+ }
279
+ const updated = original
280
+ .replace(/^# bschat-args: .*$/m, `# bschat-args: ${JSON.stringify(nextArgs)}`)
281
+ .replace(/^ExecStart=.*$/m, `ExecStart=${nextArgs.map(systemdQuote).join(" ")}`);
282
+ writeFileSync(s.path, updated);
283
+ return original;
284
+ }
285
+ const read = spawnSync("plutil", ["-convert", "json", "-o", "-", s.path], { encoding: "utf8" });
286
+ if (read.status !== 0)
287
+ throw new CliError("service_unreadable", `could not read ${s.path} as a launchd plist`, (read.stderr ?? "").trim());
288
+ let plist;
289
+ try {
290
+ plist = JSON.parse(read.stdout);
291
+ }
292
+ catch {
293
+ throw new CliError("service_unreadable", `${s.path} is not valid plist JSON`);
294
+ }
295
+ if (!Array.isArray(plist.ProgramArguments) || !plist.ProgramArguments.every((arg) => typeof arg === "string")) {
296
+ throw new CliError("service_unreadable", `${s.label} has no readable ProgramArguments`);
297
+ }
298
+ const original = readFileSync(s.path, "utf8");
299
+ plist.ProgramArguments = nextArgs;
300
+ const write = spawnSync("plutil", ["-convert", "xml1", "-o", s.path, "-"], { input: JSON.stringify(plist), encoding: "utf8" });
301
+ if (write.status !== 0)
302
+ throw new CliError("service_rewrite_failed", `could not rewrite ${s.path}`, (write.stderr ?? "").trim());
303
+ return original;
304
+ }
305
+ /** Rewrites matching service definitions, then restarts the services on the updated install. */
306
+ export async function restartInstallServices(installBin, services = watcherServices(), driver) {
307
+ const installReal = realpathSync(installBin);
308
+ const restarted = [];
309
+ const notRestarted = [];
310
+ const matching = [];
311
+ for (const service of services) {
312
+ const program = service.args?.[0];
313
+ if (!program) {
314
+ notRestarted.push(`${service.label} has an unreadable service definition`);
315
+ continue;
316
+ }
317
+ let resolved;
318
+ try {
319
+ resolved = realpathSync(program);
320
+ }
321
+ catch {
322
+ notRestarted.push(`${service.label} runs ${program} (unresolved)`);
323
+ continue;
324
+ }
325
+ if (resolved !== installReal)
326
+ notRestarted.push(`${service.label} runs ${resolved}`);
327
+ else
328
+ matching.push(service);
329
+ }
330
+ const rewritten = [];
331
+ for (const service of matching) {
332
+ try {
333
+ rewritten.push({ service, original: rewriteServiceInstall(service, installBin) });
334
+ }
335
+ catch (error) {
336
+ notRestarted.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
337
+ }
338
+ }
339
+ const systemd = rewritten.filter(({ service }) => service.kind === "systemd");
340
+ if (systemd.length) {
341
+ const reload = spawnSync("systemctl", ["--user", "daemon-reload"], { encoding: "utf8" });
342
+ if (reload.status !== 0) {
343
+ for (const { service, original } of systemd) {
344
+ writeFileSync(service.path, original);
345
+ notRestarted.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
346
+ }
347
+ spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
348
+ rewritten.splice(0, rewritten.length, ...rewritten.filter(({ service }) => service.kind !== "systemd"));
349
+ }
350
+ }
351
+ const launchdServices = rewritten.filter(({ service }) => service.kind === "launchd");
352
+ const systemdServices = rewritten.filter(({ service }) => service.kind === "systemd").map(({ service }) => service);
353
+ for (const { service } of launchdServices) {
354
+ try {
355
+ reloadLaunchAgent(service.label, service.path);
356
+ restarted.push(service.label);
357
+ }
358
+ catch (error) {
359
+ notRestarted.push(`${service.label} resolves to ${installReal}, but could not be restarted: ${error.message}`);
360
+ }
361
+ }
362
+ if (systemdServices.length) {
363
+ const report = await restartWatcherServices(systemdServices, driver);
364
+ restarted.push(...report.restarted);
365
+ notRestarted.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
366
+ }
367
+ return { restarted, not_restarted: notRestarted };
368
+ }
154
369
  /**
155
370
  * A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
156
371
  * watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
@@ -164,11 +379,12 @@ export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WA
164
379
  `After=network-online.target`,
165
380
  ``,
166
381
  `[Service]`,
167
- `ExecStart=${args.map(sdq).join(" ")}`,
382
+ `ExecStart=${args.map(systemdQuote).join(" ")}`,
168
383
  // Not quoted: systemd reads a quoted WorkingDirectory as a relative path and refuses the unit.
169
384
  `WorkingDirectory=${cwd.replace(/%/g, "%%")}`,
170
- ...Object.entries(env).map(([k, v]) => `Environment=${sdq(`${k}=${v}`)}`),
385
+ ...Object.entries(env).map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`),
171
386
  `Restart=always`,
387
+ `RestartPreventExitStatus=78`,
172
388
  `RestartSec=5`,
173
389
  `KillMode=process`,
174
390
  `StandardOutput=append:${join(logDir, `watch.${slug}.out.log`)}`,
package/dist/turn.js CHANGED
@@ -55,8 +55,10 @@ export function readTurnPhase(rollout) {
55
55
  * LaunchAgent) does not kill a turn halfway through; the next watcher sees it running in the
56
56
  * session file and waits. Output goes to the watcher's logs.
57
57
  */
58
- export function startTurn(cmd, env, seq) {
59
- const child = spawn("/bin/sh", ["-c", cmd], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, ...env }, detached: true });
58
+ export function startTurn(cmd, env, seq, stdin) {
59
+ const child = spawn("/bin/sh", ["-c", cmd], { stdio: [stdin === undefined ? "ignore" : "pipe", "inherit", "inherit"], env: { ...process.env, ...env }, detached: true });
60
+ if (stdin !== undefined)
61
+ child.stdin?.end(stdin);
60
62
  const turn = { seq, child, startedMs: Date.now(), confirmed: false };
61
63
  child.on("close", (code, signal) => { turn.exit = { code, signal }; });
62
64
  child.on("error", () => { turn.exit = { code: 127, signal: null }; });
package/dist/usage.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
+ import { dshUsage } from "./harnesses.js";
2
3
  const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
3
4
  function lines(path) {
4
5
  return readFileSync(path, "utf8").split("\n").filter(Boolean).flatMap((l) => {
@@ -77,5 +78,13 @@ export function sessionUsage(session, since, until) {
77
78
  return codexUsage(session.transcript, since, until);
78
79
  if (session.harness === "claude-code")
79
80
  return claudeUsage(session.transcript, since, until);
81
+ if (session.harness === "dsh") {
82
+ const text = readFileSync(session.transcript, "utf8");
83
+ if (!/"type"\s*:\s*"b9s_invocation_start"/.test(text))
84
+ return none(session.harness, "DeepSeek Harness events have no local invocation timing, so usage cannot be attributed to this work-unit window");
85
+ const tokens = dshUsage(text, since, until);
86
+ const base = { harness: "dsh", source: "dsh-step-end-events", scope: "session", since, until, tokens: null };
87
+ return tokens.total ? { ...base, tokens } : { ...base, reason: "no step_end usage events in the DeepSeek Harness turn log during this window" };
88
+ }
80
89
  return none(session.harness, `${session.harness} keeps no readable token counts locally`);
81
90
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.86";
1
+ export const CLI_VERSION = "0.12.88";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.86",
3
+ "version": "0.12.88",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {