benignswarm 0.12.85 → 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/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, 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";
@@ -86,6 +86,58 @@ export function ensureInstall(version, log, npmOverride) {
86
86
  writeFileSync(installFile(), JSON.stringify(rec, null, 2) + "\n");
87
87
  return rec;
88
88
  }
89
+ /** Creates b9s-named shell links beside aliases of the same recorded install, without replacing another copy. */
90
+ export function ensureCommandLinks(installBin) {
91
+ const prefixBin = dirname(installBin);
92
+ const dirs = [...new Set([...(process.env.PATH ?? "").split(delimiter).filter(Boolean).map((dir) => resolve(dir)), resolve(prefixBin)])];
93
+ const commands = [
94
+ { legacy: "bschat", primary: "b9s", target: installBin },
95
+ { legacy: "bschat-admin", primary: "b9s-admin", target: join(prefixBin, "b9s-admin") },
96
+ ];
97
+ const created = [];
98
+ const conflicts = [];
99
+ for (const dir of dirs)
100
+ for (const command of commands) {
101
+ const source = join(dir, command.legacy);
102
+ let sourceReal;
103
+ let targetReal;
104
+ try {
105
+ sourceReal = realpathSync(source);
106
+ targetReal = realpathSync(command.target);
107
+ }
108
+ catch {
109
+ continue;
110
+ }
111
+ if (sourceReal !== targetReal)
112
+ continue;
113
+ const dest = join(dir, command.primary);
114
+ try {
115
+ lstatSync(dest);
116
+ try {
117
+ if (realpathSync(dest) !== targetReal)
118
+ conflicts.push(`${dest} points to another install`);
119
+ }
120
+ catch {
121
+ conflicts.push(`${dest} exists but does not resolve`);
122
+ }
123
+ continue;
124
+ }
125
+ catch (error) {
126
+ if (error.code !== "ENOENT") {
127
+ conflicts.push(`${dest}: ${error.message}`);
128
+ continue;
129
+ }
130
+ }
131
+ try {
132
+ symlinkSync(targetReal, dest);
133
+ created.push(dest);
134
+ }
135
+ catch (error) {
136
+ conflicts.push(`${dest}: ${error.message}`);
137
+ }
138
+ }
139
+ return { created, conflicts };
140
+ }
89
141
  /** Single-quotes a path for a shell command (hooks run through sh). */
90
142
  export const shellPath = (p) => (/^[A-Za-z0-9_./-]+$/.test(p) ? p : `'${p.replace(/'/g, `'\\''`)}'`);
91
143
  export const launchAgentsDir = () => join(homedir(), "Library", "LaunchAgents");
@@ -149,8 +201,120 @@ export function unitArgs(text) {
149
201
  const a = JSON.parse(m[1]);
150
202
  return Array.isArray(a) && a.every((x) => typeof x === "string") ? a : null;
151
203
  }
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, "$$$$")}"`;
204
+ function systemdQuote(s) {
205
+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
206
+ }
207
+ /** Rewrites a service definition after its first argument is proven to be the same install file. */
208
+ export function rewriteServiceInstall(s, installBin) {
209
+ const args = s.args;
210
+ if (!args?.length)
211
+ throw new CliError("service_unreadable", `${s.label} has no readable program arguments`);
212
+ let programReal;
213
+ const installReal = realpathSync(installBin);
214
+ try {
215
+ programReal = realpathSync(args[0]);
216
+ }
217
+ catch {
218
+ throw new CliError("service_unresolved", `${s.label} program ${args[0]} does not resolve`);
219
+ }
220
+ if (programReal !== installReal)
221
+ throw new CliError("service_install_mismatch", `${s.label} resolves to ${programReal}, not ${installReal}`);
222
+ const nextArgs = [installBin, ...args.slice(1)];
223
+ if (s.kind === "systemd") {
224
+ const original = readFileSync(s.path, "utf8");
225
+ if (!/^# bschat-args: .*$/m.test(original) || !/^ExecStart=.*$/m.test(original)) {
226
+ throw new CliError("service_unreadable", `${s.label} has no recognized service command metadata`);
227
+ }
228
+ const updated = original
229
+ .replace(/^# bschat-args: .*$/m, `# bschat-args: ${JSON.stringify(nextArgs)}`)
230
+ .replace(/^ExecStart=.*$/m, `ExecStart=${nextArgs.map(systemdQuote).join(" ")}`);
231
+ writeFileSync(s.path, updated);
232
+ return original;
233
+ }
234
+ const read = spawnSync("plutil", ["-convert", "json", "-o", "-", s.path], { encoding: "utf8" });
235
+ if (read.status !== 0)
236
+ throw new CliError("service_unreadable", `could not read ${s.path} as a launchd plist`, (read.stderr ?? "").trim());
237
+ let plist;
238
+ try {
239
+ plist = JSON.parse(read.stdout);
240
+ }
241
+ catch {
242
+ throw new CliError("service_unreadable", `${s.path} is not valid plist JSON`);
243
+ }
244
+ if (!Array.isArray(plist.ProgramArguments) || !plist.ProgramArguments.every((arg) => typeof arg === "string")) {
245
+ throw new CliError("service_unreadable", `${s.label} has no readable ProgramArguments`);
246
+ }
247
+ const original = readFileSync(s.path, "utf8");
248
+ plist.ProgramArguments = nextArgs;
249
+ const write = spawnSync("plutil", ["-convert", "xml1", "-o", s.path, "-"], { input: JSON.stringify(plist), encoding: "utf8" });
250
+ if (write.status !== 0)
251
+ throw new CliError("service_rewrite_failed", `could not rewrite ${s.path}`, (write.stderr ?? "").trim());
252
+ return original;
253
+ }
254
+ /** Rewrites matching service definitions, then restarts the services on the updated install. */
255
+ export async function restartInstallServices(installBin, services = watcherServices(), driver) {
256
+ const installReal = realpathSync(installBin);
257
+ const restarted = [];
258
+ const notRestarted = [];
259
+ const matching = [];
260
+ for (const service of services) {
261
+ const program = service.args?.[0];
262
+ if (!program) {
263
+ notRestarted.push(`${service.label} has an unreadable service definition`);
264
+ continue;
265
+ }
266
+ let resolved;
267
+ try {
268
+ resolved = realpathSync(program);
269
+ }
270
+ catch {
271
+ notRestarted.push(`${service.label} runs ${program} (unresolved)`);
272
+ continue;
273
+ }
274
+ if (resolved !== installReal)
275
+ notRestarted.push(`${service.label} runs ${resolved}`);
276
+ else
277
+ matching.push(service);
278
+ }
279
+ const rewritten = [];
280
+ for (const service of matching) {
281
+ try {
282
+ rewritten.push({ service, original: rewriteServiceInstall(service, installBin) });
283
+ }
284
+ catch (error) {
285
+ notRestarted.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
286
+ }
287
+ }
288
+ const systemd = rewritten.filter(({ service }) => service.kind === "systemd");
289
+ if (systemd.length) {
290
+ const reload = spawnSync("systemctl", ["--user", "daemon-reload"], { encoding: "utf8" });
291
+ if (reload.status !== 0) {
292
+ for (const { service, original } of systemd) {
293
+ writeFileSync(service.path, original);
294
+ notRestarted.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
295
+ }
296
+ spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
297
+ rewritten.splice(0, rewritten.length, ...rewritten.filter(({ service }) => service.kind !== "systemd"));
298
+ }
299
+ }
300
+ const launchdServices = rewritten.filter(({ service }) => service.kind === "launchd");
301
+ const systemdServices = rewritten.filter(({ service }) => service.kind === "systemd").map(({ service }) => service);
302
+ for (const { service } of launchdServices) {
303
+ try {
304
+ reloadLaunchAgent(service.label, service.path);
305
+ restarted.push(service.label);
306
+ }
307
+ catch (error) {
308
+ notRestarted.push(`${service.label} resolves to ${installReal}, but could not be restarted: ${error.message}`);
309
+ }
310
+ }
311
+ if (systemdServices.length) {
312
+ const report = await restartWatcherServices(systemdServices, driver);
313
+ restarted.push(...report.restarted);
314
+ notRestarted.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
315
+ }
316
+ return { restarted, not_restarted: notRestarted };
317
+ }
154
318
  /**
155
319
  * A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
156
320
  * watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
@@ -164,11 +328,12 @@ export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WA
164
328
  `After=network-online.target`,
165
329
  ``,
166
330
  `[Service]`,
167
- `ExecStart=${args.map(sdq).join(" ")}`,
331
+ `ExecStart=${args.map(systemdQuote).join(" ")}`,
168
332
  // Not quoted: systemd reads a quoted WorkingDirectory as a relative path and refuses the unit.
169
333
  `WorkingDirectory=${cwd.replace(/%/g, "%%")}`,
170
- ...Object.entries(env).map(([k, v]) => `Environment=${sdq(`${k}=${v}`)}`),
334
+ ...Object.entries(env).map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`),
171
335
  `Restart=always`,
336
+ `RestartPreventExitStatus=78`,
172
337
  `RestartSec=5`,
173
338
  `KillMode=process`,
174
339
  `StandardOutput=append:${join(logDir, `watch.${slug}.out.log`)}`,
@@ -260,6 +425,84 @@ export function restartWatcher(s) {
260
425
  return restartLaunchAgent(s.label);
261
426
  return spawnSync("systemctl", ["--user", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
262
427
  }
428
+ /** Restart request accepted; on systemd the stop/start job runs without blocking this process. */
429
+ export function requestWatcherRestart(s) {
430
+ if (s.kind === "launchd")
431
+ return restartLaunchAgent(s.label);
432
+ return spawnSync("systemctl", ["--user", "--no-block", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
433
+ }
434
+ function watcherPid(service) {
435
+ if (service.kind === "systemd") {
436
+ const r = spawnSync("systemctl", ["--user", "show", "--property=MainPID", "--value", `${service.label}.service`], { encoding: "utf8" });
437
+ const pid = Number((r.stdout ?? "").trim());
438
+ return r.status === 0 && Number.isInteger(pid) && pid > 0 ? pid : null;
439
+ }
440
+ const output = spawnSync("launchctl", ["list", service.label], { encoding: "utf8" }).stdout ?? "";
441
+ const pid = Number(/"PID" = (\d+);/.exec(output)?.[1]);
442
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
443
+ }
444
+ const watcherRestartDriver = {
445
+ pid: watcherPid,
446
+ active: serviceActive,
447
+ request: requestWatcherRestart,
448
+ now: Date.now,
449
+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
450
+ };
451
+ /**
452
+ * Queue every restart before polling any service. A single slow stop therefore cannot keep later
453
+ * watchers on the old version. A changed MainPID/PID proves that each previously-running watcher
454
+ * came back; previously-stopped services count once they become active.
455
+ */
456
+ export async function restartWatcherServices(services, driver = watcherRestartDriver, timeoutMs = 5_000, pollMs = 100) {
457
+ const pending = new Map();
458
+ const notStarted = [];
459
+ for (const service of services) {
460
+ const previousPid = driver.pid(service);
461
+ let accepted = false;
462
+ try {
463
+ accepted = driver.request(service);
464
+ }
465
+ catch { /* reported below */ }
466
+ if (accepted)
467
+ pending.set(service.label, { service, previousPid });
468
+ else
469
+ notStarted.push({ label: service.label, reason: "restart request failed" });
470
+ }
471
+ const restarted = [];
472
+ const deadline = driver.now() + timeoutMs;
473
+ while (pending.size && driver.now() < deadline) {
474
+ for (const [label, entry] of pending) {
475
+ let running = false;
476
+ try {
477
+ const pid = driver.pid(entry.service);
478
+ running = driver.active(entry.service) && (entry.previousPid === null || (pid !== null && pid !== entry.previousPid));
479
+ }
480
+ catch { /* retry while there is time */ }
481
+ if (running) {
482
+ restarted.push(label);
483
+ pending.delete(label);
484
+ }
485
+ }
486
+ if (pending.size)
487
+ await driver.wait(Math.min(pollMs, Math.max(0, deadline - driver.now())));
488
+ }
489
+ for (const label of pending.keys())
490
+ notStarted.push({ label, reason: `did not come up within ${timeoutMs >= 1000 ? `${timeoutMs / 1000} s` : `${timeoutMs} ms`}` });
491
+ return { restarted, not_started: notStarted };
492
+ }
493
+ /** Lines for the install/update output and its structured JSON equivalent. */
494
+ export function formatWatcherRestartReport(report) {
495
+ const short = (label) => label.replace(WATCH_LABEL_PREFIX, "");
496
+ const total = report.restarted.length + report.not_started.length;
497
+ const completed = report.restarted.length;
498
+ const heading = completed === total
499
+ ? `Restarted ${completed} watcher${completed === 1 ? "" : "s"}`
500
+ : `Restarted ${completed} of ${total} watcher${total === 1 ? "" : "s"}`;
501
+ const lines = [`${heading}${completed ? `: ${report.restarted.map(short).join(", ")}` : "."}`];
502
+ if (report.not_started.length)
503
+ lines.push(`Watchers that did not come up:\n ${report.not_started.map((failure) => `${short(failure.label)}: ${failure.reason}`).join("\n ")}`);
504
+ return lines;
505
+ }
263
506
  /** Whether this user's systemd services run while nobody is logged in (null when it cannot be told). */
264
507
  export function lingerEnabled() {
265
508
  const r = spawnSync("loginctl", ["show-user", userInfo().username, "-p", "Linger", "--value"], { encoding: "utf8" });
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.85";
1
+ export const CLI_VERSION = "0.12.87";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.85",
3
+ "version": "0.12.87",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {