benignswarm 0.12.77 → 0.12.78

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.
@@ -27,8 +27,8 @@ async function main(argv) {
27
27
  await admin({ ...p, positionals: ["admin", ...p.positionals] }, out);
28
28
  return 0;
29
29
  }
30
- main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
30
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (err) => {
31
31
  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) };
32
+ process.exitCode = 1;
32
33
  process.stderr.write(JSON.stringify(e) + "\n");
33
- process.exit(1);
34
34
  });
@@ -92,13 +92,25 @@ export async function watch(p, out) {
92
92
  if (!exec && !once)
93
93
  throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
94
94
  const log = (m) => process.stderr.write(`${new Date().toISOString()} bschat watch[${name}]: ${m}\n`);
95
+ let stopping = false;
96
+ let stoppingCode = 0;
97
+ let signalStop = () => { };
98
+ const stopped = new Promise((resolve) => { signalStop = resolve; });
99
+ let releaseWatchLock;
100
+ const finish = (code) => {
101
+ if (stopping)
102
+ return;
103
+ stopping = true;
104
+ stoppingCode = code;
105
+ releaseWatchLock?.();
106
+ signalStop();
107
+ };
95
108
  if (!once) {
96
109
  // Only one long-running watcher per identity on this machine; a second one exits here.
97
- const release = acquireWatchLock(name);
98
- const bye = (code) => { release(); process.exit(code); };
99
- process.on("exit", release);
100
- process.on("SIGINT", () => bye(130));
101
- process.on("SIGTERM", () => bye(143));
110
+ releaseWatchLock = acquireWatchLock(name);
111
+ process.on("exit", () => releaseWatchLock?.());
112
+ process.once("SIGINT", () => finish(130));
113
+ process.once("SIGTERM", () => finish(143));
102
114
  }
103
115
  log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : turnMode ? `turn mode, at most ${turnTimeout} min a turn` : "single wake-up"} mode)`);
104
116
  // Harness liveness: the files the harness writes while it works, found from the wake command's
@@ -122,9 +134,11 @@ export async function watch(p, out) {
122
134
  let lastKeyCheck = 0;
123
135
  const ctl = { turn: null, failedAt: 0, loggedRunning: null, pausedUntil: 0, pausedAt: 0 };
124
136
  const probe = turn ? probeFor(turn.harness, turn.session, name) : null;
125
- for (;;) {
137
+ while (!stopping) {
126
138
  if (activity && heartbeatClient)
127
139
  lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
140
+ if (stopping)
141
+ return stoppingCode;
128
142
  if (scanCreds.project && Date.now() - lastScan > 3_600_000) {
129
143
  lastScan = Date.now();
130
144
  try {
@@ -183,10 +197,15 @@ export async function watch(p, out) {
183
197
  await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/me");
184
198
  }
185
199
  catch (e) {
186
- if (e.code === "unauthorized")
200
+ if (e.code === "unauthorized") {
187
201
  stopRevokedWatcher(name, log);
202
+ finish(0);
203
+ return stoppingCode;
204
+ }
188
205
  log(`could not check this agent's key: ${e.message}`);
189
206
  }
207
+ if (stopping)
208
+ return stoppingCode;
190
209
  }
191
210
  if (!full) {
192
211
  try {
@@ -196,16 +215,23 @@ export async function watch(p, out) {
196
215
  await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once);
197
216
  }
198
217
  catch (e) {
199
- if (e.code === "unauthorized" && !once)
218
+ if (e.code === "unauthorized" && !once) {
200
219
  stopRevokedWatcher(name, log);
220
+ finish(0);
221
+ return stoppingCode;
222
+ }
201
223
  throw e;
202
224
  }
225
+ if (stopping)
226
+ return stoppingCode;
203
227
  if (once)
204
228
  return;
205
- await new Promise((r) => setTimeout(r, interval * 1000));
229
+ await waitIntervalOrStop(interval * 1000, stopped);
206
230
  continue;
207
231
  }
208
232
  const u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch" });
233
+ if (stopping)
234
+ return stoppingCode;
209
235
  if (u) {
210
236
  const total = u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest;
211
237
  const summary = u.text.split("\n")[0].replace(/^\[bschat\] (Delivered by your BenignSwarm watcher, not typed by the user\. )?/, "");
@@ -222,14 +248,23 @@ export async function watch(p, out) {
222
248
  // Full mode delivers the update payload directly instead of using the wake path, so
223
249
  // record the same actual payload bytes and kinds through the hook's existing metric call.
224
250
  await reportDelivery(name, u.text, u.delivery.by_kind, "watch");
251
+ if (stopping)
252
+ return stoppingCode;
225
253
  }
226
254
  else if (once) {
227
255
  log("nothing new");
228
256
  }
229
257
  if (once)
230
258
  return;
231
- await new Promise((r) => setTimeout(r, interval * 1000));
259
+ await waitIntervalOrStop(interval * 1000, stopped);
232
260
  }
261
+ return stoppingCode;
262
+ }
263
+ async function waitIntervalOrStop(ms, stopped) {
264
+ let timer;
265
+ await Promise.race([new Promise((resolve) => { timer = setTimeout(resolve, ms); }), stopped]);
266
+ if (timer)
267
+ clearTimeout(timer);
233
268
  }
234
269
  /**
235
270
  * One numbered wake-up at a time. Each wake-up carries a sequence number and asks the agent to
@@ -387,8 +422,7 @@ function stopRevokedWatcher(name, log) {
387
422
  ?? watcherServices().find((s) => { const a = s.args ?? []; const i = a.indexOf("--as"); return a[1] === "watch" && i >= 0 && (a[i + 1] === name || a[i + 1] === bare); });
388
423
  log(`this agent's key was revoked (moved to another machine, or retired): stopping and removing ${svc?.label ?? `${label} (no service found; exiting)`}`);
389
424
  if (svc)
390
- removeService(svc); // ends this process when it unloads the service
391
- process.exit(0);
425
+ removeService(svc);
392
426
  }
393
427
  const TURN_RETRY_MS = 5 * 60_000;
394
428
  const KEY_CHECK_MS = 5 * 60_000;
@@ -10,6 +10,18 @@ import { CliError } from "../errors.js";
10
10
  import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fullSha, isAncestor, remoteHead, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, worktreeForBranch } from "../git.js";
11
11
  import { resolve } from "node:path";
12
12
  import { table } from "../output.js";
13
+ export function assignmentDisposition(unit, to) {
14
+ if (unit.status !== "queued")
15
+ return `Assigned to ${unit.owner_name}; they start it with bschat wu start ${unit.number}.`;
16
+ if (unit.preferred_name)
17
+ return `Reserved for ${unit.preferred_name}, who is busy: theirs when free, open to any qualified worker after the takeover window (--hold keeps it assigned to them).`;
18
+ if (to === "queue")
19
+ return `Queued deliberately; dispatch hands it to the first qualified free worker (or bschat wu take ${unit.number} --to <agent>).`;
20
+ const reasons = unit.dispatch_reasons?.length
21
+ ? `\nWhy no worker was selected:\n${unit.dispatch_reasons.map((reason) => `- ${reason}`).join("\n")}`
22
+ : "\nNo eligible worker candidates were found.";
23
+ return `Queued: nobody qualified is free; it goes to the first qualified worker with capacity (or bschat wu take ${unit.number} --to <agent>).${reasons}`;
24
+ }
13
25
  /**
14
26
  * Work units under the project's process. Work is described by tags from the project's
15
27
  * vocabulary; reviewers are whoever is qualified to review those tags.
@@ -134,7 +146,7 @@ export async function wu(p, out) {
134
146
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--tags a,b] [--evidence id] [--replay-of <n>]');
135
147
  const replay = str(p.flags, "replay-of");
136
148
  const r = await client.call("POST", `${base}/assign`, { to, title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), requires: list("requires"), evidence: list("evidence"), replay_of: replay ? Number(replay) : null, branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: !!p.flags.force });
137
- out.print(`${fmt(r.unit)}\n${r.unit.status === "queued" && r.unit.preferred_name ? `Reserved for ${r.unit.preferred_name}, who is busy: theirs when free, open to any qualified worker after the takeover window (--hold keeps it assigned to them).` : r.unit.status === "queued" ? `Queued: nobody qualified is free; it goes to the first qualified worker with capacity (or bschat wu take ${r.unit.number} --to <agent>).` : `Assigned to ${r.unit.owner_name}; they start it with bschat wu start ${r.unit.number}.`}`, r);
149
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}`, r);
138
150
  return;
139
151
  }
140
152
  case "take": {
package/dist/help.js CHANGED
@@ -36,7 +36,8 @@ Agent commands
36
36
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
37
37
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
38
38
  bschat wu assign "<title>" --to <agent|auto|queue> --scope ".." [--tags a,b] [--requires cap,cap] [--force] [--replay-of n] hand out a unit (assigner roles);
39
- auto queues it when nobody qualified is free; queue waits deliberately; naming a
39
+ auto queues it when nobody fits and reports why candidates were passed over;
40
+ queue waits deliberately and says so; naming a
40
41
  busy worker reserves it for them (theirs when free, anyone's after the takeover
41
42
  window); --hold keeps it assigned to them however long it takes
42
43
  bschat wu take <n> [--to <agent>] pull a queued unit for yourself (qualified by works or trial), or hand it to someone
package/dist/index.js CHANGED
@@ -105,11 +105,11 @@ async function main(argv) {
105
105
  if (!fn)
106
106
  throw new CliError("usage", `unknown command ${cmd}`, "Run: bschat --help");
107
107
  warnIfForeignCopy(cmd, CLI_VERSION);
108
- await fn(p, out);
109
- return 0;
108
+ const code = await fn(p, out);
109
+ return code ?? 0;
110
110
  }
111
- main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
111
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (err) => {
112
112
  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) };
113
+ process.exitCode = 1;
113
114
  process.stderr.write(JSON.stringify(e) + "\n");
114
- process.exit(1);
115
115
  });
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.77";
1
+ export const CLI_VERSION = "0.12.78";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.77",
3
+ "version": "0.12.78",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {