benignswarm 0.12.134 → 0.12.135

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.
@@ -40,16 +40,21 @@ export async function install(p, out) {
40
40
  lines.push(`(was ${prev.bin}; run b9s doctor to find hooks and watchers still pointing there)`);
41
41
  const restarted = [];
42
42
  const elsewhere = [];
43
+ const failed = [];
43
44
  if (!bool(p.flags, "no-restart")) {
44
- const services = await restartInstallServices(rec.bin);
45
+ const services = await restartInstallServices(rec.bin, undefined, undefined, (message) => process.stderr.write(`b9s: ${message}\n`));
45
46
  restarted.push(...services.restarted);
46
47
  elsewhere.push(...services.not_restarted);
48
+ failed.push(...services.failed);
47
49
  }
48
50
  if (restarted.length)
49
51
  lines.push(`Restarted ${restarted.length} service${restarted.length === 1 ? "" : "s"} on it: ${restarted.map((l) => l.replace("org.benignswarm.watch.", "")).join(", ")}`);
50
52
  if (elsewhere.length)
51
53
  lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
52
- out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
54
+ if (failed.length)
55
+ lines.push(`Failed to restart:\n ${failed.join("\n ")}`);
56
+ out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere, failed });
57
+ return failed.length ? 1 : 0;
53
58
  }
54
59
  export function embeddedHookCommands(value, marker) {
55
60
  const found = [];
@@ -16,7 +16,7 @@ import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
16
  import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
17
17
  import { writeFileAtomic } from "../shared-file.js";
18
18
  import { readState, updateState } from "../state.js";
19
- import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
19
+ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
20
20
  import { CLI_VERSION } from "../version.js";
21
21
  import { probeCapabilities } from "../capabilities.js";
22
22
  import { diskSpaceNotice } from "../notices.js";
@@ -1135,7 +1135,62 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1135
1135
  ? (deps?.probeImdsContainer ? deps.probeImdsContainer({ runner }) : probeContainerImdsIsolation({ runner }))
1136
1136
  : null;
1137
1137
  const containerImdsOk = imdsContainerProbe ? imdsContainerProbe.ok : deps?.containerImdsBlocked;
1138
+ const recoveryFailures = new Map();
1139
+ const recoveryServices = [];
1140
+ const localWatcherServices = watcherServices();
1141
+ for (const session of desired) {
1142
+ if (session.desired !== "running")
1143
+ continue;
1144
+ const local = state.sessions[session.id];
1145
+ if (!local || local.container_name)
1146
+ continue;
1147
+ const project = projects.find((entry) => entry.id === session.project_id || entry.name === session.project);
1148
+ const poolImageOptIn = Boolean(session.pool) && !session.hardware_bound && Boolean(project?.image?.pool_sessions_enabled);
1149
+ const containerMode = isCloudHost || (poolImageOptIn && hostContainerProbe?.runtime !== null);
1150
+ if (containerMode)
1151
+ continue;
1152
+ const service = localWatcherServices.find((entry) => entry.label === watchLabelOf(session.agent));
1153
+ if (!service || serviceActive(service))
1154
+ continue;
1155
+ const sessionWritable = session.sandbox === "workspace-write"
1156
+ ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
1157
+ : writable;
1158
+ const fingerprint = sessionFingerprint({ ...session, thread: reconcileThread(session, local) }, session.sandbox === "workspace-write" ? sessionWritable : []);
1159
+ if (sessionConfigChanged(session, local, fingerprint))
1160
+ continue;
1161
+ recoveryServices.push(service);
1162
+ }
1163
+ if (recoveryServices.length) {
1164
+ const batchTotal = Math.ceil(recoveryServices.length / INSTALL_RESTART_BATCH_SIZE);
1165
+ const recovery = await restartServicesInBatches([], recoveryServices, {
1166
+ progress: (message) => log(`daemon watcher recovery: ${message}`),
1167
+ pause: deps?.wait,
1168
+ });
1169
+ for (const issue of recovery.not_started) {
1170
+ const entry = recoveryServices.find((service) => service.label === issue.label);
1171
+ if (entry)
1172
+ recoveryFailures.set(issue.label, issue.reason);
1173
+ }
1174
+ const count = recoveryServices.length;
1175
+ const returned = recovery.restarted.length;
1176
+ log(`daemon watcher recovery: attempted ${count} inactive session watcher${count === 1 ? "" : "s"} in ${batchTotal} batch${batchTotal === 1 ? "" : "es"}; ${returned} returned`);
1177
+ }
1138
1178
  const out = [];
1179
+ // Watcher recovery and session relaunch are one startup wave. Keep their counts together so
1180
+ // a short recovery tail cannot be followed immediately by a fresh full launch batch.
1181
+ let restartWorkScheduled = recoveryServices.length;
1182
+ const scheduleRestartWork = async (kind, agent) => {
1183
+ if (restartWorkScheduled > 0 && restartWorkScheduled % INSTALL_RESTART_BATCH_SIZE === 0) {
1184
+ log(`daemon restart wave: pausing ${INSTALL_RESTART_BATCH_PAUSE_MS / 1000}s after ${restartWorkScheduled} requests`);
1185
+ await (deps?.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(INSTALL_RESTART_BATCH_PAUSE_MS);
1186
+ }
1187
+ const batch = Math.floor(restartWorkScheduled / INSTALL_RESTART_BATCH_SIZE) + 1;
1188
+ if (restartWorkScheduled % INSTALL_RESTART_BATCH_SIZE === 0) {
1189
+ log(`daemon restart wave batch ${batch}: starting up to ${INSTALL_RESTART_BATCH_SIZE} operations`);
1190
+ }
1191
+ restartWorkScheduled++;
1192
+ log(`daemon restart wave batch ${batch}: ${kind} for ${agent}`);
1193
+ };
1139
1194
  for (const s of desired) {
1140
1195
  const label = watchLabelOf(s.agent);
1141
1196
  const svc = () => watcherServices().find((w) => w.label === label);
@@ -1475,6 +1530,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1475
1530
  throw error;
1476
1531
  }
1477
1532
  try {
1533
+ await scheduleRestartWork("session start/relaunch", s.agent);
1478
1534
  pending.pid = (deps?.startTrackedSession ?? ((childBin, options, result) => startSessionChild(childBin, s.dir, options, result)))(bin, launchOptions, resultFile);
1479
1535
  }
1480
1536
  catch (error) {
@@ -1519,7 +1575,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1519
1575
  };
1520
1576
  }
1521
1577
  else if (!containerMode && hostSvc) {
1578
+ const recoveryFailure = recoveryFailures.get(label);
1579
+ if (recoveryFailure)
1580
+ throw new Error(`its watcher ${label} could not be restarted during daemon recovery: ${recoveryFailure}`);
1522
1581
  if (!serviceActive(hostSvc)) {
1582
+ await scheduleRestartWork("watcher restart", s.agent);
1523
1583
  if (!restartWatcher(hostSvc))
1524
1584
  throw new Error(`its watcher ${label} is not loaded and could not be restarted`);
1525
1585
  log(`${s.agent}: watcher was not running; restarted`);
package/dist/help.js CHANGED
@@ -228,9 +228,9 @@ Machine placement enforces configured session slots and reports machine pressure
228
228
  fault with b9s-admin machine session resume.
229
229
  Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
230
230
  b9s update [--no-restart] the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
231
- restart services on that install without waiting on one stop, and report failures
231
+ restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
232
232
  b9s install [<version> | --latest] [--no-restart] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
233
- restart services resolving to it; other installs are left alone and named
233
+ restart its daemon first, then watchers in batches of 5 with 5 s between batches
234
234
  b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>]
235
235
  what the sandbox this runs in really allows: where commands run, which tools
236
236
  are there, what git can do, which hosts answer, what is writable; facts only
package/dist/install.js CHANGED
@@ -519,10 +519,11 @@ export function rewriteServiceInstall(s, installBin) {
519
519
  return original;
520
520
  }
521
521
  /** Rewrites matching service definitions, then restarts the services on the updated install. */
522
- export async function restartInstallServices(installBin, services = watcherServices(), driver) {
522
+ export async function restartInstallServices(installBin, services = watcherServices(), driver, progress = () => { }, pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
523
523
  const installReal = realpathSync(installBin);
524
524
  const restarted = [];
525
525
  const notRestarted = [];
526
+ const failed = [];
526
527
  const matching = [];
527
528
  for (const service of services) {
528
529
  const program = service.args?.[0];
@@ -548,8 +549,9 @@ export async function restartInstallServices(installBin, services = watcherServi
548
549
  ensureWatcherSliceMemoryLimits();
549
550
  }
550
551
  catch (error) {
551
- notRestarted.push(`Linux watcher memory limits were not applied; services were not restarted: ${error.message}`);
552
- return { restarted, not_restarted: notRestarted };
552
+ const reason = `Linux watcher memory limits were not applied; service was not restarted: ${error.message}`;
553
+ failed.push(...matching.map((service) => `${service.label}: ${reason}`));
554
+ return { restarted, not_restarted: notRestarted, failed };
553
555
  }
554
556
  }
555
557
  const rewritten = [];
@@ -558,7 +560,7 @@ export async function restartInstallServices(installBin, services = watcherServi
558
560
  rewritten.push({ service, original: rewriteServiceInstall(service, installBin) });
559
561
  }
560
562
  catch (error) {
561
- notRestarted.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
563
+ failed.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
562
564
  }
563
565
  }
564
566
  const systemd = rewritten.filter(({ service }) => service.kind === "systemd");
@@ -567,29 +569,23 @@ export async function restartInstallServices(installBin, services = watcherServi
567
569
  if (reload.status !== 0) {
568
570
  for (const { service, original } of systemd) {
569
571
  writeFileAtomic(service.path, original);
570
- notRestarted.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
572
+ failed.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
571
573
  }
572
574
  spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
573
575
  rewritten.splice(0, rewritten.length, ...rewritten.filter(({ service }) => service.kind !== "systemd"));
574
576
  }
575
577
  }
576
- const launchdServices = rewritten.filter(({ service }) => service.kind === "launchd");
577
- const systemdServices = rewritten.filter(({ service }) => service.kind === "systemd").map(({ service }) => service);
578
- for (const { service } of launchdServices) {
579
- try {
580
- reloadLaunchAgent(service.label, service.path);
581
- restarted.push(service.label);
582
- }
583
- catch (error) {
584
- notRestarted.push(`${service.label} resolves to ${installReal}, but could not be restarted: ${error.message}`);
585
- }
586
- }
587
- if (systemdServices.length) {
588
- const report = await restartWatcherServices(systemdServices, driver);
589
- restarted.push(...report.restarted);
590
- notRestarted.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
591
- }
592
- return { restarted, not_restarted: notRestarted };
578
+ const restartable = rewritten.map(({ service }) => service);
579
+ const daemon = restartable.find((service) => service.label === MACHINE_LABEL);
580
+ const watchers = restartable.filter((service) => service.label.startsWith(WATCH_LABEL_PREFIX)).sort((a, b) => a.label.localeCompare(b.label));
581
+ const report = await restartServicesInBatches(daemon ? [daemon] : [], watchers, {
582
+ driver,
583
+ progress,
584
+ pause,
585
+ });
586
+ restarted.push(...report.restarted);
587
+ failed.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
588
+ return { restarted, not_restarted: notRestarted, failed };
593
589
  }
594
590
  /**
595
591
  * A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
@@ -722,6 +718,43 @@ export function requestWatcherRestart(s) {
722
718
  return restartLaunchAgent(s.label);
723
719
  return spawnSync("systemctl", ["--user", "--no-block", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
724
720
  }
721
+ export const INSTALL_RESTART_BATCH_SIZE = 5;
722
+ export const INSTALL_RESTART_BATCH_PAUSE_MS = 5_000;
723
+ /** Start the daemon first, then cap watcher startup bursts and let each wave settle before the next. */
724
+ export async function restartServicesInBatches(daemon, watchers, options = {}) {
725
+ const driver = options.driver ?? watcherRestartDriver;
726
+ const progress = options.progress ?? (() => { });
727
+ const pause = options.pause ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
728
+ const batchSize = options.batchSize ?? INSTALL_RESTART_BATCH_SIZE;
729
+ const pauseMs = options.pauseMs ?? INSTALL_RESTART_BATCH_PAUSE_MS;
730
+ if (!Number.isInteger(batchSize) || batchSize < 1)
731
+ throw new RangeError("restart batch size must be a positive integer");
732
+ if (!Number.isFinite(pauseMs) || pauseMs < 0)
733
+ throw new RangeError("restart batch pause must be non-negative");
734
+ const restarted = [];
735
+ const notStarted = [];
736
+ if (daemon.length) {
737
+ progress("Restarting machine daemon before watcher services");
738
+ const report = await restartWatcherServices(daemon, driver);
739
+ restarted.push(...report.restarted);
740
+ notStarted.push(...report.not_started);
741
+ }
742
+ const batchCount = Math.ceil(watchers.length / batchSize);
743
+ for (let offset = 0; offset < watchers.length; offset += batchSize) {
744
+ const batch = watchers.slice(offset, offset + batchSize);
745
+ const batchNumber = Math.floor(offset / batchSize) + 1;
746
+ progress(`Watcher batch ${batchNumber}/${batchCount}: restarting ${batch.length} services`);
747
+ const report = await restartWatcherServices(batch, driver);
748
+ restarted.push(...report.restarted);
749
+ notStarted.push(...report.not_started);
750
+ progress(`Watcher batch ${batchNumber}/${batchCount}: ${report.restarted.length}/${batch.length} services returned`);
751
+ if (batchNumber < batchCount) {
752
+ progress(`Pausing ${pauseMs / 1000}s before the next watcher batch`);
753
+ await pause(pauseMs);
754
+ }
755
+ }
756
+ return { restarted, not_started: notStarted };
757
+ }
725
758
  function watcherPid(service) {
726
759
  if (service.kind === "systemd") {
727
760
  const r = spawnSync("systemctl", ["--user", "show", "--property=MainPID", "--value", `${service.label}.service`], { encoding: "utf8" });
@@ -746,7 +779,14 @@ export async function restartWatcherServices(services, driver = watcherRestartDr
746
779
  const pending = new Map();
747
780
  const notStarted = [];
748
781
  for (const service of services) {
749
- const previousPid = driver.pid(service);
782
+ let previousPid;
783
+ try {
784
+ previousPid = driver.pid(service);
785
+ }
786
+ catch (error) {
787
+ notStarted.push({ label: service.label, reason: `could not read pre-restart process: ${error.message}` });
788
+ continue;
789
+ }
750
790
  let accepted = false;
751
791
  try {
752
792
  accepted = driver.request(service);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.134";
1
+ export const CLI_VERSION = "0.12.135";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.134",
3
+ "version": "0.12.135",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {