omni-notify-mcp 1.3.440 → 1.3.441

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.
@@ -1,7 +1,9 @@
1
1
  import { execFile, spawn, spawnSync } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
+ import { createRequire } from "node:module";
4
5
  import { Agent } from "node:http";
6
+ import * as net from "node:net";
5
7
  import { homedir, tmpdir } from "node:os";
6
8
  import * as path from "node:path";
7
9
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -181,6 +183,202 @@ export function ownerBoundLaunch(invocation, ownerPid, cwd, guardDir) {
181
183
  args: [path.join(guardDir, "ownerGuard.cjs"), String(ownerPid), encoded(invocation.cmd), encoded(JSON.stringify(invocation.args)), encoded(cwd)],
182
184
  };
183
185
  }
186
+ // GATE: how long a per-owner watcher must have lived for its death to be answered by a fresh one — one dying sooner says why once and its children stay unbound until the next owner-bound launch
187
+ const OWNER_WATCH_RESTART_MS = 5_000;
188
+ /**
189
+ * #4531 — this realm's binding to the ONE watcher of an owner. A process has several realms (the FleetView server's roster reader is a
190
+ * worker thread with its own module registry), so the watcher also serves a pipe. A realm holding no watcher STARTS one at once and feeds
191
+ * it on stdin, so no child it launches is ever unguarded; when that watcher finds the pipe already served (`taken`), the realm binds its
192
+ * children on the pipe, and only once the serving watcher has answered that it holds them (`!`) is the realm's own watcher ended.
193
+ */
194
+ class OwnerWatch {
195
+ watcher;
196
+ socket;
197
+ shared = false;
198
+ began = 0;
199
+ children = new Set();
200
+ ownerPid;
201
+ guardFile;
202
+ pipe;
203
+ constructor(ownerPid, guardFile, pipe) {
204
+ this.ownerPid = ownerPid;
205
+ this.guardFile = guardFile;
206
+ this.pipe = pipe;
207
+ }
208
+ bind(pid) {
209
+ this.children.add(pid);
210
+ this.send(`+${pid}`);
211
+ }
212
+ unbind(pid) {
213
+ this.children.delete(pid);
214
+ this.send(`-${pid}`);
215
+ }
216
+ /** Whether a watcher holds this realm's children — starting this realm's own when none does; false when none could be started, so that launch takes its own guard. */
217
+ running() {
218
+ return this.ownWatcherLives() || this.socket !== undefined || this.start();
219
+ }
220
+ ownWatcherLives() {
221
+ const watcher = this.watcher;
222
+ // NULL-OK: field watcher is OPTIONAL and therefore it is ok to check for NULL
223
+ return watcher !== undefined && watcher.exitCode === null && watcher.signalCode === null;
224
+ }
225
+ /** Every line goes to every feed this realm holds: during a hand-over both watchers hold the children, never neither. */
226
+ send(line) {
227
+ if (this.ownWatcherLives())
228
+ this.watcher.stdin.write(line + "\n");
229
+ const socket = this.socket;
230
+ // NULL-OK: field socket is OPTIONAL and therefore it is ok to check for NULL
231
+ if (socket !== undefined && !socket.connecting && socket.writable)
232
+ socket.write(line + "\n");
233
+ }
234
+ /** A watcher that ended while children are still bound is started again — unless it lived too briefly, which is said once. */
235
+ ended(how) {
236
+ if (this.children.size === 0 || !isProcessAlive(this.ownerPid))
237
+ return;
238
+ const lived = Date.now() - this.began;
239
+ if (lived >= OWNER_WATCH_RESTART_MS && this.start())
240
+ return;
241
+ process.stderr.write(`[ownerGuard] the watcher of owner ${this.ownerPid} ended (${how}) after ${lived} ms — ${this.children.size} children are unbound until the next owner-bound launch\n`);
242
+ }
243
+ /** Hands this realm's children to the watcher that serves the pipe; this realm's own watcher keeps them until that one answers. */
244
+ handOver() {
245
+ // NULL-OK: field socket is OPTIONAL and therefore it is ok to check for NULL
246
+ if (this.socket !== undefined)
247
+ return;
248
+ const socket = net.connect(this.pipe);
249
+ this.socket = socket;
250
+ socket.unref();
251
+ let heard = "";
252
+ socket.setEncoding("utf8");
253
+ socket.once("connect", () => {
254
+ for (const pid of this.children)
255
+ socket.write(`+${pid}\n`);
256
+ socket.write("?\n");
257
+ });
258
+ socket.on("data", (chunk) => {
259
+ heard += chunk;
260
+ if (this.shared || this.socket !== socket || !heard.includes("!\n"))
261
+ return;
262
+ this.shared = true;
263
+ this.began = Date.now();
264
+ // This realm's own watcher — the one that found the pipe taken, or one started after it died mid-hand-over — goes: every line since the connect also reached the pipe.
265
+ const mine = this.watcher;
266
+ // NULL-OK: field watcher is OPTIONAL and therefore it is ok to check for NULL
267
+ if (mine !== undefined) {
268
+ this.watcher = undefined;
269
+ mine.kill();
270
+ }
271
+ });
272
+ // OWNER: a pipe that cannot be reached or that fails — `close` follows: this realm's own watcher, still holding every child, keeps them.
273
+ socket.on("error", () => undefined);
274
+ socket.once("close", () => {
275
+ if (this.socket !== socket)
276
+ return;
277
+ this.socket = undefined;
278
+ this.shared = false;
279
+ if (!this.ownWatcherLives())
280
+ this.ended("its pipe closed");
281
+ });
282
+ }
283
+ start() {
284
+ let watcher;
285
+ try {
286
+ watcher = spawn(process.execPath, [this.guardFile, "--watch", String(this.ownerPid)], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true, env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } });
287
+ }
288
+ catch (cause) {
289
+ // OWNER: a watcher spawn() refuses outright (it may be called from an exit or close handler) — no watcher, so the launch asking takes its own guard.
290
+ process.stderr.write(`[ownerGuard] the watcher of owner ${this.ownerPid} could not be started: ${cause.message}\n`);
291
+ return false;
292
+ }
293
+ // OWNER: a watcher Windows could not start — its missing pid is read below and the launch asking takes its own guard.
294
+ watcher.on("error", () => undefined);
295
+ // NULL-OK: field pid is OPTIONAL and therefore it is ok to check for NULL
296
+ if (watcher.pid === undefined)
297
+ return false;
298
+ this.began = Date.now();
299
+ let said = "";
300
+ let heard = "";
301
+ watcher.stderr.setEncoding("utf8");
302
+ watcher.stderr.on("data", (chunk) => (said = (said + chunk).slice(-500)));
303
+ watcher.stdout.setEncoding("utf8");
304
+ watcher.stdout.on("data", (chunk) => {
305
+ if (heard === "-")
306
+ return;
307
+ heard += chunk;
308
+ // Another realm's watcher of this owner already serves the pipe: bind there.
309
+ if (/^taken\n/.test(heard)) {
310
+ heard = "-";
311
+ if (this.watcher === watcher)
312
+ this.handOver();
313
+ }
314
+ });
315
+ watcher.unref();
316
+ watcher.stdin.unref();
317
+ watcher.stdout.unref();
318
+ watcher.stderr.unref();
319
+ // OWNER: a write to a watcher that just ended (EPIPE) — its exit below starts the next watcher, handed every child still bound.
320
+ watcher.stdin.on("error", () => undefined);
321
+ watcher.once("exit", (code) => {
322
+ if (this.watcher !== watcher)
323
+ return;
324
+ this.watcher = undefined;
325
+ if (code !== 95 && !this.shared)
326
+ this.ended(`exit ${code}: ${said.trim() || "it printed nothing"}`);
327
+ });
328
+ this.watcher = watcher;
329
+ for (const pid of this.children)
330
+ watcher.stdin.write(`+${pid}\n`);
331
+ return true;
332
+ }
333
+ }
334
+ const ownerWatches = new Map();
335
+ /** Whether `guardFile` exists and is the guard that exports its launch plan instead of running a launch when required. */
336
+ function guardIsModule(guardFile) {
337
+ try {
338
+ return fs.readFileSync(guardFile, "utf8").includes("if (require.main === module)");
339
+ }
340
+ catch (cause) {
341
+ // OWNER: a guard file that does not exist — its launch goes through the per-child guard, which reports the missing file the way it always did.
342
+ if (cause.code === "ENOENT")
343
+ return false;
344
+ throw cause;
345
+ }
346
+ }
347
+ export function spawnOwnerBound(invocation, ownerPid, cwd, guardDir, options) {
348
+ const guarded = () => {
349
+ const launch = ownerBoundLaunch(invocation, ownerPid, cwd, guardDir);
350
+ return spawn(launch.cmd, launch.args, { ...options, windowsHide: true });
351
+ };
352
+ if (process.platform !== "win32" || cwd === "" || !isProcessAlive(ownerPid))
353
+ return guarded();
354
+ const guardFile = path.join(guardDir, "ownerGuard.cjs");
355
+ // GATE: only a guard that is the #4531 module form is required into this process — a missing file, or an older guard whose top level would run (and exit) here, keeps the per-child guard
356
+ if (!guardIsModule(guardFile))
357
+ return guarded();
358
+ const guard = createRequire(guardFile)(guardFile);
359
+ // GATE: a guard of an earlier build that serves no pipe keeps the per-child guard, so a realm never binds to a watcher it cannot share
360
+ if (typeof guard.launchPlan !== "function" || typeof guard.pipeOf !== "function")
361
+ return guarded();
362
+ // NULL-OK: field env is OPTIONAL and therefore it is ok to check for NULL
363
+ const plan = guard.launchPlan(invocation.cmd, invocation.args, cwd, options.env ?? process.env);
364
+ if (plan.refused !== undefined || !plan.found)
365
+ return guarded();
366
+ const known = ownerWatches.get(ownerPid);
367
+ // NULL-OK: field known is OPTIONAL and therefore it is ok to check for NULL
368
+ const watch = known ?? new OwnerWatch(ownerPid, guardFile, guard.pipeOf(ownerPid));
369
+ ownerWatches.set(ownerPid, watch);
370
+ if (!watch.running())
371
+ return guarded();
372
+ const child = spawn(plan.file, plan.args, { ...options, ...plan.options, windowsHide: true });
373
+ // The pid is bound the moment spawn() returns it, so no tick passes in which the owner could die with this child unregistered.
374
+ const pid = child.pid;
375
+ // NULL-OK: field pid is OPTIONAL and therefore it is ok to check for NULL
376
+ if (pid !== undefined) {
377
+ watch.bind(pid);
378
+ child.once("exit", () => watch.unbind(pid));
379
+ }
380
+ return child;
381
+ }
184
382
  // GATE: how long one request to the native Codex daemon may take before it is refused with that wait named — the daemon answers these in well under a second
185
383
  const CODEX_REQUEST_MS = 10_000;
186
384
  // GATE: how long one Codex CLI command (`login status`, `app-server daemon start`) may run before its tree is ended and refused with that wait named — each answers in about a second
@@ -933,18 +1131,19 @@ export class CodexControl {
933
1131
  ++this.generation;
934
1132
  this.failPending(new CodexControlFailed("the native Codex control connection was closed by its owner"));
935
1133
  this.socket?.terminate();
936
- this.proxy?.kill();
1134
+ const proxy = this.proxy;
1135
+ // NULL-OK: field proxy is OPTIONAL and therefore it is ok to check for NULL
1136
+ if (proxy !== undefined && proxy.exitCode === null && proxy.signalCode === null)
1137
+ killTree(proxy);
937
1138
  this.socket = undefined;
938
1139
  this.opening = undefined;
939
1140
  }
940
- /** The CLI behind this process's owner guard, which also finds the CLI's .cmd shim on Windows. */
941
- bound(invocation) {
942
- return ownerBoundLaunch(invocation, process.pid, this.project, this.guardDir);
1141
+ bound(args, stdio) {
1142
+ return spawnOwnerBound({ cmd: this.cli.cmd, args: [...this.cli.args, ...args] }, process.pid, this.project, this.guardDir, { cwd: this.project, windowsHide: true, stdio: [stdio, "pipe", "pipe"], env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } });
943
1143
  }
944
1144
  run(args) {
945
- const launch = this.bound({ cmd: this.cli.cmd, args: [...this.cli.args, ...args] });
946
1145
  return new Promise((resolve, reject) => {
947
- const child = spawn(launch.cmd, launch.args, { cwd: this.project, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } });
1146
+ const child = this.bound(args, "ignore");
948
1147
  let said = "";
949
1148
  child.stdout.on("data", (chunk) => (said += chunk.toString("utf8")));
950
1149
  child.stderr.on("data", (chunk) => (said += chunk.toString("utf8")));
@@ -973,14 +1172,14 @@ export class CodexControl {
973
1172
  return Promise.resolve();
974
1173
  const generation = ++this.generation;
975
1174
  this.opening = import("ws").then(({ default: Socket }) => new Promise((resolve, reject) => {
976
- const launch = this.bound({ cmd: this.cli.cmd, args: [...this.cli.args, "app-server", "proxy"] });
977
- const proxy = (this.proxy = spawn(launch.cmd, launch.args, { cwd: this.project, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } }));
1175
+ const proxy = (this.proxy = this.bound(["app-server", "proxy"], "pipe"));
978
1176
  const stream = Duplex.from({ readable: proxy.stdout, writable: proxy.stdin });
979
1177
  const connection = Object.assign(stream, { connecting: false, setTimeout: () => stream, setNoDelay: () => stream, setKeepAlive: () => stream });
980
1178
  const agent = new Agent();
981
1179
  agent.createConnection = () => connection;
982
1180
  const socket = (this.socket = new Socket("ws://localhost/", { agent, handshakeTimeout: CODEX_REQUEST_MS }));
983
1181
  let said = "";
1182
+ let proxyEnded = false;
984
1183
  proxy.stderr.on("data", (chunk) => (said += chunk.toString("utf8")));
985
1184
  const ended = new Promise((done) => {
986
1185
  proxy.once("exit", (code) => done(`the native Codex control proxy ended (exit ${code}): ${said.trim() || "it printed nothing"}`));
@@ -995,7 +1194,10 @@ export class CodexControl {
995
1194
  this.failPending(cause instanceof CodexControlFailed ? cause : new CodexControlFailed(`the native Codex control connection failed: ${cause.message}`));
996
1195
  }
997
1196
  socket.terminate();
998
- proxy.kill();
1197
+ if (!proxyEnded && proxy.exitCode === null && proxy.signalCode === null) {
1198
+ proxyEnded = true;
1199
+ killTree(proxy);
1200
+ }
999
1201
  };
1000
1202
  proxy.on("error", failed);
1001
1203
  stream.on("error", failed);
@@ -2152,7 +2354,6 @@ class JsonlCliTurn {
2152
2354
  this.lineBuffer = "";
2153
2355
  this.stderr = "";
2154
2356
  this.stderrLines = "";
2155
- const launch = ownerBoundLaunch({ cmd: spec.cli.cmd, args: [...spec.cli.args, ...args] }, spec.ownerPid, spec.project, spec.guardDir);
2156
2357
  return new Promise((resolve, reject) => {
2157
2358
  let settled = false;
2158
2359
  const finish = (fn) => {
@@ -2181,7 +2382,7 @@ class JsonlCliTurn {
2181
2382
  stop();
2182
2383
  finish(() => reject(spec.failures.fail("Cancelled")));
2183
2384
  });
2184
- const child = spawn(launch.cmd, launch.args, { cwd: spec.project, env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
2385
+ const child = spawnOwnerBound({ cmd: spec.cli.cmd, args: [...spec.cli.args, ...args] }, spec.ownerPid, spec.project, spec.guardDir, { cwd: spec.project, env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
2185
2386
  this.child = child;
2186
2387
  child.stdout.setEncoding("utf8");
2187
2388
  child.stderr.setEncoding("utf8");
@@ -3290,7 +3491,8 @@ function applyRequest(store, r, now) {
3290
3491
  if (e.state !== "failed") {
3291
3492
  e.state = "failed";
3292
3493
  delete e.nextTryAt;
3293
- e.why = `the board asks for it again, and ${spent}, so an ordinary ask starts nothing — his Start press does`;
3494
+ // NULL-OK: field accountRefused is OPTIONAL and therefore it is ok to check for NULL
3495
+ e.why = `the board asks for it again, and ${spent}, so ${e.accountRefused === undefined ? `it is offered to the line again at ${new Date(now + rearmDelayMs(e.attempts)).toISOString()}` : "it is read again after its wait and goes back in line once a start would land on a subscription with room"}`;
3294
3496
  step(e, now, "failed", e.why);
3295
3497
  }
3296
3498
  else
@@ -3515,8 +3717,20 @@ const pastQuestion = (worker, now) => {
3515
3717
  delete worker.question;
3516
3718
  worker.pastAt = now;
3517
3719
  };
3518
- /** 🔴 #4499 — whether a question is put to Meni: a prompt his session sits on, or an act its turn ended on that it named itself (`needs`); a question only guessed from what its record says it does is not. */
3519
- export const asksMeni = (q) => q.prompt === true || q.act === true;
3720
+ /** 🔴 #4499 — whether a question is put to Meni: a prompt his session sits on, or an act its turn ended on that it named itself (`needs`); a question only guessed from what its record says it does is not, and 🔴 #4545 neither is a usage-limit stop, whichever FleetView recorded it. */
3721
+ export const asksMeni = (q) => (q.prompt === true || q.act === true) && !USAGE_LIMIT.test(q.text);
3722
+ /** 🔴 #4544/#4545 — a usage-limit stop an earlier pass recorded as his question is no question of his: it leaves the worker whatever state its entry is in, so the board never puts it to him again, and an entry withdrawn on the decision the board made of it says what holds it instead. */
3723
+ function dropUsageLimitQuestion(e, now) {
3724
+ const asked = e.worker?.question;
3725
+ // NULL-OK: field question is OPTIONAL and therefore it is ok to check for NULL
3726
+ if (asked === undefined || !USAGE_LIMIT.test(asked.text))
3727
+ return;
3728
+ pastQuestion(e.worker, now);
3729
+ if (e.state !== "withdrawn" || !e.why.includes(asked.text))
3730
+ return;
3731
+ e.why = `its worker's usage-limit stop "${asked.text}" was never Meni's question, so no decision of his holds it — it is out of the line until BullseyeBacklog asks for it again`;
3732
+ step(e, now, "withdrawn", e.why);
3733
+ }
3520
3734
  /** 🔴 #4499 — his ruling on the question the entry's worker waits on becomes that worker's answer, once: the entry goes first in line, so it is woken with his words before anything else starts. */
3521
3735
  function takeRuling(store, e, now) {
3522
3736
  const asked = e.worker?.question;
@@ -3833,6 +4047,7 @@ async function passHeld(board, world, now) {
3833
4047
  for (const e of store.entries) {
3834
4048
  await slice();
3835
4049
  try {
4050
+ dropUsageLimitQuestion(e, now);
3836
4051
  if (IN_LINE.has(e.state) && inArchive(e.worker) && world.closedWhy(e.storyId) === undefined) {
3837
4052
  const worker = e.worker;
3838
4053
  if (!archiveDue(worker, now))
@@ -4176,6 +4391,7 @@ async function passHeld(board, world, now) {
4176
4391
  delete e.forcedBy;
4177
4392
  }
4178
4393
  delete e.worker?.parkedAt;
4394
+ delete e.worker?.limit;
4179
4395
  delete e.worker?.killedAt;
4180
4396
  step(e, now, "worker-ended", w.why);
4181
4397
  // NULL-OK: field neverHeldRefusals is OPTIONAL and therefore it is ok to check for NULL
@@ -4257,6 +4473,7 @@ async function passHeld(board, world, now) {
4257
4473
  pastQuestion(e.worker, now);
4258
4474
  }
4259
4475
  delete e.worker?.parkedAt;
4476
+ delete e.worker?.limit;
4260
4477
  delete e.worker?.killedAt;
4261
4478
  delete e.worker?.stoppedAt;
4262
4479
  if (waiting) {
@@ -4269,6 +4486,9 @@ async function passHeld(board, world, now) {
4269
4486
  continue;
4270
4487
  }
4271
4488
  const worker = e.worker;
4489
+ // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
4490
+ if (w.parked.limit !== undefined && worker.limit?.said !== w.parked.limit.said)
4491
+ worker.limit = w.parked.limit;
4272
4492
  if (!e.eligible) {
4273
4493
  const why = `its ${worker.provider} worker ${worker.jobId}'s turn is over and the story is no longer the queue's to work, so it is not woken`;
4274
4494
  step(e, now, "worker-ended", why);
@@ -4297,11 +4517,15 @@ async function passHeld(board, world, now) {
4297
4517
  else
4298
4518
  delete worker.killedAt;
4299
4519
  // NULL-OK: field question is OPTIONAL and therefore it is ok to check for NULL
4300
- step(e, now, "parked", asked !== undefined && asked.answer === undefined && asked.prompt === true ? `its ${worker.provider} worker ${worker.jobId} waited on Meni's answer since ${clockOf(asked.at)}, so it is parked and its lane is free; it is woken in its own session, first in line, the moment he answers` : asked?.approval === true ? `its ${worker.provider} worker ${worker.jobId} stopped on Claude Code's approval of a tool call and the queue answered it, so its process is stopped and its own session is woken with that answer from ${new Date(now + parkedWaitMs(worker, w.parked)).toISOString()}` : worker.killedAt === undefined ? `its ${worker.provider} worker ${worker.jobId}'s turn is over with the story open, so it is woken in its own session from ${new Date(now + parkedWaitMs(worker, w.parked)).toISOString()}` : `its ${worker.provider} worker ${worker.jobId} was killed mid-work with the story open, so it is woken in its own session at once, ahead of every waiting story he did not place or press Start on`);
4520
+ step(e, now, "parked", worker.limit !== undefined ? `its ${worker.provider} worker ${worker.jobId} stopped on its account's usage limit, which is never Meni's question, so its lane is free and its own session is woken from ${new Date(parkedWakeAt(worker, worker.parkedAt, w.parked)).toISOString()} — ${worker.limit.said}` : asked !== undefined && asked.answer === undefined && asked.prompt === true ? `its ${worker.provider} worker ${worker.jobId} waited on Meni's answer since ${clockOf(asked.at)}, so it is parked and its lane is free; it is woken in its own session, first in line, the moment he answers` : asked?.approval === true ? `its ${worker.provider} worker ${worker.jobId} stopped on Claude Code's approval of a tool call and the queue answered it, so its process is stopped and its own session is woken with that answer from ${new Date(now + parkedWaitMs(worker, w.parked)).toISOString()}` : worker.killedAt === undefined ? `its ${worker.provider} worker ${worker.jobId}'s turn is over with the story open, so it is woken in its own session from ${new Date(now + parkedWaitMs(worker, w.parked)).toISOString()}` : `its ${worker.provider} worker ${worker.jobId} was killed mid-work with the story open, so it is woken in its own session at once, ahead of every waiting story he did not place or press Start on`);
4301
4521
  }
4302
4522
  if (!w.parked.live) {
4303
4523
  e.state = "queued";
4304
- const due = now >= worker.parkedAt + parkedWaitMs(worker, w.parked);
4524
+ const wakeAt = parkedWakeAt(worker, worker.parkedAt, w.parked);
4525
+ const due = now >= wakeAt;
4526
+ // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
4527
+ if (worker.limit !== undefined && (worker.limit.until === undefined || worker.limit.until > now) && !due)
4528
+ e.why = `⏳ usage limit — parked with its lane free until ${new Date(wakeAt).toISOString()}, then woken in its own session: ${worker.limit.said}`;
4305
4529
  // NULL-OK: field question is OPTIONAL and therefore it is ok to check for NULL
4306
4530
  if (e.forced !== true && asked !== undefined && asked.answer === undefined) {
4307
4531
  e.why = asked.prompt === true ? `parked on Meni's question since ${clockOf(asked.at)} with its lane free — woken first in line the moment he answers: ${asked.text}` : `parked on what it needs since ${clockOf(asked.at)} with its lane free — woken first in line at ${clockOf(worker.parkedAt + parkedWaitMs(worker, w.parked))} to look again: ${asked.text}`;
@@ -5439,15 +5663,62 @@ function timelineStepOf(line) {
5439
5663
  const TURN_OVER = new Set(["done", "blocked", "stopped"]);
5440
5664
  /** 🔴 #4123 — whether a job still has background tasks of its own running. 🔴 #4499 — a message queued to a job stopped on Meni waits behind that stop and is no task of its own; its own tasks still are. */
5441
5665
  // NULL-OK: field inFlight is OPTIONAL and therefore it is ok to check for NULL
5442
- const waitsOnTasks = (job) => job.inFlight !== undefined && (job.inFlight.tasks + job.inFlight.drainableMonitors > 0 || (!waitsOnMeni(job) && messageArriving(job)));
5666
+ const waitsOnTasks = (job) => job.inFlight !== undefined && ((job.inFlight.tasks + job.inFlight.drainableMonitors > 0 && !tasksEndedOnPrompt(job)) || (!waitsOnMeni(job) && messageArriving(job)));
5443
5667
  /** 🔴 #4215 — whether a job has a subagent of its own running: a local agent among its in-flight tasks (its `fan` keeps the finished ones, so it says nothing of what runs now); a record that names no kinds cannot say, so any task it counts is taken as one. */
5444
5668
  const runsSubagent = (job) => {
5445
5669
  // NULL-OK: field inFlight is OPTIONAL and therefore it is ok to check for NULL
5446
5670
  if (job.inFlight === undefined)
5447
5671
  return false;
5448
5672
  // NULL-OK: field kinds is OPTIONAL and therefore it is ok to check for NULL
5449
- return job.inFlight.kinds === undefined ? job.inFlight.tasks > 0 : job.inFlight.kinds.includes("local_agent");
5673
+ return (job.inFlight.kinds === undefined ? job.inFlight.tasks > 0 : job.inFlight.kinds.includes("local_agent")) && !tasksEndedOnPrompt(job);
5450
5674
  };
5675
+ /** 🔴 #4517 — one background task's notification inside a queued message (one message may carry several): its id, then the status it ended with. */
5676
+ const TASK_ENDED = /^\s*<task-id>([^<]+)<\/task-id>(?:(?!<task-notification>)[\s\S])*?<status>(completed|failed|killed|stopped)<\/status>/;
5677
+ /**
5678
+ * 🔴 #4517 — whether every background task (subagent or shell command) the record of a job on Meni's prompt still counts in flight has ended since
5679
+ * the record was written. Claude Code stops rewriting a job's record while its turn waits on a prompt, so a task that finishes then is still
5680
+ * counted, and the job read as working for hours (AW #14553, 2026-11-25: asked 05:47, its subagent ended 05:57). The session's own transcript
5681
+ * decides, task by task: every task of the job's `fan` started by the record's `updatedAt` with no end notice queued by then must have its own end
5682
+ * notice queued after it — a task the record let go a moment before its notice was queued is still waited on by name, never stood in for by a
5683
+ * count — and at least as many as the record counts, so a task outside the fan keeps the record's count. A notice ends a task only when it was
5684
+ * queued at or after that task's own latest start, so a continued subagent's earlier runs end nothing. A record with a monitor draining, or with
5685
+ * no transcript, keeps its own count.
5686
+ */
5687
+ function tasksEndedOnPrompt(job) {
5688
+ // NULL-OK: field inFlight is OPTIONAL and therefore it is ok to check for NULL
5689
+ if (!waitsOnMeni(job) || job.inFlight === undefined || job.inFlight.tasks === 0 || job.inFlight.drainableMonitors > 0)
5690
+ return false;
5691
+ const transcript = job.linkScanPath;
5692
+ // NULL-OK: field linkScanPath is OPTIONAL and therefore it is ok to check for NULL
5693
+ if (transcript === undefined || readingTranscript(transcript, () => mtimeOf(transcript)) === undefined)
5694
+ return false;
5695
+ const recordedAt = Date.parse(job.updatedAt);
5696
+ if (Number.isNaN(recordedAt))
5697
+ throw new Error(`the job record of session ${job.sessionId} (transcript ${transcript}) carries no readable updatedAt (${JSON.stringify(job.updatedAt)}), so what ended since it was written cannot be told`);
5698
+ // NULL-OK: field fan is OPTIONAL and therefore it is ok to check for NULL
5699
+ const tasks = (job.fan ?? []).filter((f) => f.kind !== "todo" && (f.startedAt === undefined || f.startedAt <= recordedAt));
5700
+ if (tasks.length === 0)
5701
+ return false;
5702
+ const ids = new Set(tasks.map((t) => t.id));
5703
+ const from = Math.min(...tasks.map((t) => t.startedAt ?? Number.NEGATIVE_INFINITY));
5704
+ const notices = new Map();
5705
+ readingTranscript(transcript, () => fromTranscriptEnd(transcript, ["queue-operation"], (r) => {
5706
+ const at = r.timestamp === undefined ? NaN : Date.parse(r.timestamp);
5707
+ if (at < from)
5708
+ return true;
5709
+ if (r.type !== "queue-operation" || r.operation !== "enqueue" || typeof r.content !== "string")
5710
+ return undefined;
5711
+ for (const notice of r.content.split("<task-notification>")) {
5712
+ const said = TASK_ENDED.exec(notice);
5713
+ if (said !== null && ids.has(said[1]))
5714
+ notices.set(said[1], [...(notices.get(said[1]) ?? []), at]);
5715
+ }
5716
+ return undefined;
5717
+ }));
5718
+ const endedOf = (t) => (notices.get(t.id) ?? []).filter((at) => t.startedAt === undefined || at >= t.startedAt);
5719
+ const open = tasks.filter((t) => !endedOf(t).some((at) => !(at > recordedAt)));
5720
+ return open.length > 0 && open.every((t) => endedOf(t).some((at) => at > recordedAt)) && open.length >= job.inFlight.tasks;
5721
+ }
5451
5722
  /**
5452
5723
  * 🔴 #4215 — A JOB DOES WORK ONLY WHILE A TURN OR A SUBAGENT RUNS: a turn over, or an idle tempo (with or without a leftover background command — #4330:
5453
5724
  * a record frozen at `working` beside tempo `idle` and nothing in flight is a process at its prompt), is a job at its
@@ -5471,6 +5742,71 @@ const questionOf = (job) => {
5471
5742
  return { question: job.detail, guessed: true };
5472
5743
  return job.state === "blocked" ? {} : { question: `its prompt names no question (job ${job.sessionId})`, guessed: true };
5473
5744
  };
5745
+ /** 🔴 #4544 — the act Claude Code's job record names when its account's usage limit stopped the turn: `rate limited — wait and retry · You've hit your weekly limit · resets Nov 26, 10pm (America/Los_Angeles)`. */
5746
+ export const USAGE_LIMIT = /^rate limited — /;
5747
+ /** 🔴 #4544 — the reset a usage-limit stop names: `resets 2am`, `resets 12:30pm`, `resets Nov 26, 10pm`, each with an optional `(<IANA zone>)`. */
5748
+ const LIMIT_RESET = /resets (?:([A-Z][a-z]{2}) (\d{1,2}),? (?:at )?)?(\d{1,2})(?::(\d{2}))? ?(am|pm)(?: \(([^)]+)\))?/i;
5749
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
5750
+ /** 🔴 #4544 — the wall-clock fields of `at` in `zone` (this machine's own zone when none is named). */
5751
+ const zonedFields = (at, zone) => {
5752
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric" }).formatToParts(at);
5753
+ const n = (type) => Number(parts.find((p) => p.type === type).value);
5754
+ return { y: n("year"), mo: n("month") - 1, d: n("day"), h: n("hour"), mi: n("minute") };
5755
+ };
5756
+ /** 🔴 #4544 — the instant a wall-clock time in `zone` names, its zone offset read at that instant (one correction covers a daylight-saving edge). */
5757
+ const zonedInstant = (y, mo, d, h, mi, zone) => {
5758
+ const wall = Date.UTC(y, mo, d, h, mi);
5759
+ const offsetAt = (at) => {
5760
+ const f = zonedFields(at, zone);
5761
+ return Date.UTC(f.y, f.mo, f.d, f.h, f.mi) - at;
5762
+ };
5763
+ const first = wall - offsetAt(wall);
5764
+ return wall - offsetAt(first);
5765
+ };
5766
+ /**
5767
+ * 🔴 #4544 — the instant a usage-limit stop's `resets …` names, read from the moment Claude Code wrote it (`from`): a time
5768
+ * alone is its next occurrence after `from`, a month and day with no year the one nearest `from`; undefined
5769
+ * when the words name no reset this reads or its zone is not one this machine knows.
5770
+ */
5771
+ export const limitResetAt = (said, from) => {
5772
+ const m = LIMIT_RESET.exec(said);
5773
+ if (m === null)
5774
+ return undefined;
5775
+ const [, month, day, hour, minute, half, zone] = m;
5776
+ const h = (Number(hour) % 12) + (half.toLowerCase() === "pm" ? 12 : 0);
5777
+ const mi = minute === undefined ? 0 : Number(minute);
5778
+ let now;
5779
+ try {
5780
+ now = zonedFields(from, zone);
5781
+ }
5782
+ catch (err) {
5783
+ if (!(err instanceof RangeError))
5784
+ throw err;
5785
+ return undefined;
5786
+ }
5787
+ // NULL-OK: field month is OPTIONAL and therefore it is ok to check for NULL
5788
+ if (month === undefined) {
5789
+ const today = zonedInstant(now.y, now.mo, now.d, h, mi, zone);
5790
+ return today > from ? today : zonedInstant(now.y, now.mo, now.d + 1, h, mi, zone);
5791
+ }
5792
+ const mo = MONTHS.indexOf(month.toLowerCase());
5793
+ if (mo < 0)
5794
+ return undefined;
5795
+ return [now.y - 1, now.y, now.y + 1].map((y) => zonedInstant(y, mo, Number(day), h, mi, zone)).sort((a, b) => Math.abs(a - from) - Math.abs(b - from))[0];
5796
+ };
5797
+ /** 🔴 #4544 — a job whose turn its account's usage limit stopped: the words it stopped on and the reset they name, or undefined for any other stop. */
5798
+ const usageLimitOf = (job) => {
5799
+ // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
5800
+ if (!waitsOnMeni(job) || job.needs === undefined || !USAGE_LIMIT.test(job.needs))
5801
+ return undefined;
5802
+ const recordedAt = Date.parse(job.updatedAt);
5803
+ if (Number.isNaN(recordedAt))
5804
+ throw new Error(`the job record of session ${job.sessionId} carries no readable updatedAt (${JSON.stringify(job.updatedAt)}), so the reset its usage-limit stop names (${job.needs}) cannot be placed in time`);
5805
+ const until = limitResetAt(job.needs, recordedAt);
5806
+ return until === undefined ? { said: job.needs } : { said: job.needs, until };
5807
+ };
5808
+ /** 🔴 #4544 — when a parked worker is next woken: its parked wait, and never before the reset a usage-limit stop names. */
5809
+ const parkedWakeAt = (worker, parkedAt, parked) => Math.max(parkedAt + parkedWaitMs(worker, parked), worker.limit?.until ?? 0);
5474
5810
  /**
5475
5811
  * A story worker's liveness: a `claude --bg` job, with the moment its transcript last moved. 🔴 #4123 — a job whose turn is
5476
5812
  * over (`done` or `blocked`, with no background task of its own still running) or whose process the daemon retired is
@@ -5505,13 +5841,23 @@ export function storyWorkerLiveness(worker, now, home = claudeHome()) {
5505
5841
  return { alive: false, ...progress, why: said };
5506
5842
  return { alive: true, ...progress, parked: { sessionId: job.sessionId, live, failed: true, ...(live ? {} : { killed: true }) }, why: `${said} — it was killed mid-work and its session worked after it was started, so it is parked and woken there` };
5507
5843
  }
5844
+ const limit = usageLimitOf(job);
5845
+ // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
5846
+ if (limit !== undefined && live && runsSubagent(job))
5847
+ return { alive: true, ...progress, why: `its job ${worker.jobId} stopped on its account's usage limit while a subagent of its own still runs, so it keeps its lane until that subagent ends; never Meni's question — ${limit.said}` };
5848
+ // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
5849
+ if (limit !== undefined) {
5850
+ // NULL-OK: field until is OPTIONAL and therefore it is ok to check for NULL
5851
+ const when = limit.until === undefined ? "on its parked wait, since its stop names no reset this reads" : `at its reset, ${new Date(limit.until).toISOString()}`;
5852
+ return { alive: true, ...progress, parked: { sessionId: job.sessionId, live, limit, ...(live && waitsOnTasks(job) ? { tasks: true } : {}) }, why: `its job ${worker.jobId} stopped on its account's usage limit, which is never Meni's question, so it is parked and woken in its own session ${when} — ${limit.said}` };
5853
+ }
5508
5854
  const asked = questionOf(job);
5509
5855
  // NULL-OK: field block is OPTIONAL and therefore it is ok to check for NULL
5510
5856
  const approval = job.state !== "blocked" && job.block?.questions?.[0] === undefined && job.needs !== undefined && TOOL_APPROVAL.test(job.needs);
5511
5857
  // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
5512
5858
  const blocked = waitsOnMeni(job) ? { blocked: true, ...(job.needs === undefined ? {} : { needs: job.needs }), ...asked, ...(job.state === "blocked" ? {} : { prompted: true }), ...(approval ? { approval: true } : {}) } : {};
5513
5859
  if (live && worksNow(job))
5514
- return { alive: true, ...progress, why: `its job ${worker.jobId} runs as session ${job.sessionId} (${job.state})` };
5860
+ return { alive: true, ...progress, ...blocked, why: waitsOnMeni(job) ? `its job ${worker.jobId} waits on Meni while a background task of its own still runs, so it keeps its lane` : `its job ${worker.jobId} runs as session ${job.sessionId} (${job.state})` };
5515
5861
  const how = live ? (job.state !== "blocked" && job.tempo === "blocked" ? `its process sits on a prompt waiting on Meni` : `its turn ended ${job.state} and its process waits at the prompt`) : `it reads ${job.state} and no process on this machine runs session ${job.sessionId}`;
5516
5862
  return { alive: true, ...progress, ...blocked, parked: { sessionId: job.sessionId, live, ...(!live && !TURN_OVER.has(job.state) ? { killed: true } : {}), ...(live && waitsOnTasks(job) ? { tasks: true } : {}) }, why: `its job ${worker.jobId} is parked — ${how}` };
5517
5863
  }
@@ -1,10 +1,8 @@
1
- import { spawn } from "child_process";
2
1
  import { agentEnv } from "./provider.js";
3
- import { ownerBoundLaunch, killTree } from "../agentSession.js";
2
+ import { spawnOwnerBound, killTree } from "../agentSession.js";
4
3
  export async function archiveCodexThread(spec, threadId, method = "thread/archive") {
5
- const launch = ownerBoundLaunch({ cmd: spec.cli.cmd, args: [...spec.cli.args, "app-server"] }, spec.ownerPid, spec.project, spec.guardDir);
6
4
  return new Promise((resolve, reject) => {
7
- const child = spawn(launch.cmd, launch.args, { cwd: spec.project, env: agentEnv(spec.project), windowsHide: true, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
5
+ const child = spawnOwnerBound({ cmd: spec.cli.cmd, args: [...spec.cli.args, "app-server"] }, spec.ownerPid, spec.project, spec.guardDir, { cwd: spec.project, env: agentEnv(spec.project), windowsHide: true, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
8
6
  let buffer = "", stderr = "", done = false;
9
7
  const finish = (error) => {
10
8
  if (done)
@@ -0,0 +1,32 @@
1
+ import { appendFileSync } from "node:fs";
2
+
3
+ // The plugin OpenCode loads in BN's CLI: it appends the bus events a turn is read from, one JSON object per line, to the file `BN_OPENCODE_LOG` names.
4
+ const KEPT = [
5
+ "session.created",
6
+ "session.inbox.enqueued",
7
+ "session.inbox.delivered",
8
+ "session.inbox.cancelled",
9
+ "session.inbox.delivery.changed",
10
+ "session.text.ended",
11
+ "session.retry.scheduled",
12
+ "session.execution.succeeded",
13
+ "session.execution.failed",
14
+ "session.execution.interrupted",
15
+ "permission.asked",
16
+ "form.created",
17
+ ];
18
+
19
+ export default {
20
+ id: "bn-events",
21
+ setup: ({ event }) => {
22
+ const events = event.subscribe({ types: KEPT })[Symbol.asyncIterator]();
23
+ appendFileSync(process.env.BN_OPENCODE_LOG, `${JSON.stringify({ type: "bn.plugin.loaded", data: {} })}\n`);
24
+ (async () => {
25
+ for (let next = await events.next(); !next.done; next = await events.next()) appendFileSync(process.env.BN_OPENCODE_LOG, `${JSON.stringify(next.value)}\n`);
26
+ })().catch((cause) => {
27
+ process.stderr.write(`BN's OpenCode event plugin stopped: it could not write the turn's events to ${process.env.BN_OPENCODE_LOG} (${cause.message}), so BN cannot read this CLI's turns\n`);
28
+ process.exit(1);
29
+ });
30
+ return () => events.return();
31
+ },
32
+ };
@@ -2,14 +2,16 @@
2
2
  * OpenCode behind the provider seam (#3847, #3929): every turn of a conversation runs inside that conversation's OWN
3
3
  * interactive OpenCode TUI on a pty — never a headless `opencode run` — so the browser and MCP reach ONE process. A turn
4
4
  * is typed into it; what it took and how the turn ended are read off a log of the CLI's own bus events, which the plugin
5
- * shipped beside this file (`opencodeEvents.mjs`) appends as they happen (measured on opencode 1.19.5: `session.created`
6
- * with the session id, `message.updated` naming each message's role, `message.part.updated` with a user text part for a
7
- * prompt taken and a text part carrying `time.end` for an assistant reply, `session.status` busy / idle / retry,
8
- * `session.error`, then `session.idle` when the turn is over). Each CLI start writes a log of its own, so a log is never
9
- * another CLI's and a resumed session reads only what this CLI wrote.
5
+ * directory shipped beside this file (`opencodeEvents/`) appends as they happen (measured on opencode 2.3.2: each event
6
+ * carries its session in `data.sessionID`; `session.inbox.enqueued` with a `user` item, then `session.inbox.delivered`
7
+ * when the running execution takes it in (or `session.inbox.cancelled`) for a prompt taken,
8
+ * `session.text.ended` with the text of an assistant reply, `session.retry.scheduled` while the CLI retries,
9
+ * then `session.execution.succeeded`, or `failed` with its error, or `interrupted`, when the turn
10
+ * is over). Each CLI start writes a log of its own, so a log is never another CLI's and a resumed session reads only what
11
+ * this CLI wrote.
10
12
  *
11
13
  * The CLI runs on the key and store `opencodeRoute` names, chosen when its CLI opens. A key the vendor refuses — a
12
- * refusing `session.error`, or the `retry` status the CLI reports while it retries a rate limit in silence — is recorded
14
+ * refusing `session.execution.failed`, or the `session.retry.scheduled` the CLI reports while it retries a rate limit in silence — is recorded
13
15
  * where every switcher reads it and the CLI is ended; the SAME turn then carries on in a fresh CLI that resumes the
14
16
  * session with `-s` on a new route, which skips the refused key, told to carry on from the last message (Meni's ruling
15
17
  * on Q808, #4079). With no key left to run on, the turn fails in the route's own words.
@@ -18,6 +20,7 @@ import { randomUUID } from "crypto";
18
20
  import { existsSync, mkdirSync, readdirSync, rmSync } from "fs";
19
21
  import { homedir } from "os";
20
22
  import { join } from "path";
23
+ import { fileURLToPath } from "url";
21
24
  import autoSwitch from "../webhost/autoSwitch.cjs";
22
25
  import { OpenCodeTurnMemory, opencodeConversationArgs } from "../agentSession.js";
23
26
  import { CliEnded, LoggedCliSession } from "./cliSession.js";
@@ -36,8 +39,8 @@ export function createOpenCodeDriver(runtime) {
36
39
  throw failure(err.message);
37
40
  }
38
41
  }
39
- /** The plugin OpenCode loads in BN's CLI, shipped beside this module — in dist/gateway for a build, beside the bundled daemon in the extension. */
40
- const EVENT_PLUGIN = new URL("./opencodeEvents.mjs", import.meta.url);
42
+ /** The plugin directory OpenCode loads in BN's CLI, shipped beside this module — in dist/gateway for a build, beside the bundled daemon in the extension. */
43
+ const EVENT_PLUGIN = new URL("./opencodeEvents/", import.meta.url);
41
44
  /** The folder each CLI start's own log goes in: this daemon's own config dir, so no other daemon on the machine clears a log this one is reading. */
42
45
  const logDir = () => join(runtime.configDir, "opencode-logs");
43
46
  /** The daemon starting: logs a CLI of an earlier daemon left behind belong to no CLI now. */
@@ -47,6 +50,7 @@ export function createOpenCodeDriver(runtime) {
47
50
  for (const name of readdirSync(logDir()))
48
51
  rmSync(join(logDir(), name), { force: true });
49
52
  }
53
+ const LOADED = "bn.plugin.loaded";
50
54
  /** A string field an event must carry, or a SyntaxError naming the event: OpenCode writes every one of these as a string. */
51
55
  function field(event, value, name) {
52
56
  if (typeof value !== "string")
@@ -59,13 +63,12 @@ export function createOpenCodeDriver(runtime) {
59
63
  key;
60
64
  /** The log is this CLI start's own: no other CLI writes into it. */
61
65
  shared = false;
62
- /** The session this log's turns belong to: a resumed session's own id, else the first session created without a parent. A sub-agent's session is never it. */
66
+ /** The session this log's turns belong to: a resumed session's own id, else the first session created without a parent or given a user prompt. A sub-agent's session is never it. */
63
67
  main;
64
- roles = new Map();
65
- taken = new Set();
68
+ waiting = new Map();
69
+ open = 0;
66
70
  /** The last reply text the CLI finished writing this turn. */
67
71
  said;
68
- failure;
69
72
  constructor(file, resumedSession, key) {
70
73
  this.file = file;
71
74
  this.key = key;
@@ -82,80 +85,101 @@ export function createOpenCodeDriver(runtime) {
82
85
  }
83
86
  /** The vendor refused the key this CLI runs on: it is recorded as refused, and the turn ends the CLI naming it so the session can carry the turn on the next key. */
84
87
  refused(said) {
85
- const why = `${this.key.named} was refused by the provider (${said}), so BN moves this turn on to the next key.`;
86
88
  this.key.refuse(said);
87
- return [{ kind: "failed", why, endsCli: true }];
89
+ return this.close({ kind: "failed", why: `${this.key.named} was refused by the provider (${said}), so BN moves this turn on to the next key.`, endsCli: true });
88
90
  }
89
91
  /** The provider failed a free model this CLI runs on: that model is recorded as failed, and the turn ends the CLI naming it so the session can carry the turn on the next free model or key. */
90
92
  modelFailed(error, record) {
91
93
  record(error.message, error.status);
92
- return [{ kind: "failed", why: `${this.key.named} failed on its model (${error.said}), so BN moves this turn on to the next free model or key.`, endsCli: true }];
94
+ return this.close({ kind: "failed", why: `${this.key.named} failed on its model (${error.said}), so BN moves this turn on to the next free model or key.`, endsCli: true });
95
+ }
96
+ own(id) {
97
+ // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
98
+ if (this.main !== undefined)
99
+ return [];
100
+ this.main = id;
101
+ return [{ kind: "session", id }];
102
+ }
103
+ static error(event, error) {
104
+ const message = field(event, error?.message, "error.message");
105
+ return autoSwitch.opencodeEventError({ name: field(event, error?.type, "error.type"), data: { message, statusCode: error?.status } });
106
+ }
107
+ answer() {
108
+ // NULL-OK: field said is OPTIONAL and therefore it is ok to check for NULL
109
+ return this.said === undefined ? { kind: "silent" } : { kind: "over", answer: this.said };
110
+ }
111
+ close(news) {
112
+ const answered = Math.max(this.open, 1);
113
+ [this.open, this.said] = [0, undefined];
114
+ return Array.from({ length: answered }, () => news);
93
115
  }
94
116
  read(row) {
95
117
  const event = row;
96
- const p = event.properties ?? {};
97
- if (event.type === "session.created") {
98
- if (p.info?.parentID !== undefined || this.main !== undefined)
99
- return [{ kind: "busy" }];
100
- this.main = field(event, p.info?.id, "info.id");
101
- return [{ kind: "session", id: this.main }];
102
- }
103
- if (this.main === undefined || p.sessionID !== this.main)
118
+ const d = event.data;
119
+ if (event.type === LOADED)
120
+ return [{ kind: "busy" }];
121
+ if (event.type === "form.created")
122
+ return [{ kind: "waiting" }];
123
+ if (event.type === "permission.asked")
124
+ return [{ kind: "busy" }];
125
+ const session = field(event, d.sessionID, "data.sessionID");
126
+ // NULL-OK: field parentID is OPTIONAL and therefore it is ok to check for NULL
127
+ if (event.type === "session.created")
128
+ return d.parentID === undefined ? [...this.own(session), { kind: "busy" }] : [{ kind: "busy" }];
129
+ // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
130
+ if (event.type === "session.inbox.enqueued" && field(event, d.item?.type, "data.item.type") === "user" && this.main === undefined)
131
+ return [...this.own(session), ...this.read(row)];
132
+ if (session !== this.main)
104
133
  return [{ kind: "busy" }];
105
134
  switch (event.type) {
106
- case "message.updated":
107
- this.roles.set(field(event, p.info?.id, "info.id"), field(event, p.info?.role, "info.role"));
135
+ case "session.inbox.enqueued": {
136
+ if (field(event, d.item?.type, "data.item.type") === "user")
137
+ this.waiting.set(field(event, d.inboxID, "data.inboxID"), { text: field(event, d.item?.payload?.text, "data.item.payload.text"), delivery: field(event, d.item?.delivery, "data.item.delivery") });
108
138
  return [{ kind: "busy" }];
109
- case "message.part.updated": {
110
- if (typeof p.part !== "object" || p.part === null)
111
- throw new SyntaxError(`an OpenCode message.part.updated event carries no part: ${JSON.stringify(event).slice(0, 200)}`);
112
- const part = p.part;
113
- if (part.type !== "text" || part.synthetic === true)
114
- return [{ kind: "busy" }];
115
- const message = field(event, part.messageID, "part.messageID");
116
- const role = this.roles.get(message);
117
- if (role === undefined)
118
- throw new SyntaxError(`an OpenCode text part arrived before its message was named: ${JSON.stringify(event).slice(0, 200)}`);
119
- if (role === "user") {
120
- if (this.taken.has(message))
121
- return [{ kind: "busy" }];
122
- this.taken.add(message);
123
- this.said = undefined;
124
- this.failure = undefined;
125
- return [{ kind: "taken", text: field(event, part.text, "part.text") }];
126
- }
127
- if (part.time?.end !== undefined)
128
- this.said = field(event, part.text, "part.text");
139
+ }
140
+ case "session.inbox.delivery.changed": {
141
+ const prompt = this.waiting.get(field(event, d.inboxID, "data.inboxID"));
142
+ // NULL-OK: field prompt is OPTIONAL and therefore it is ok to check for NULL
143
+ if (prompt !== undefined)
144
+ prompt.delivery = field(event, d.delivery, "data.delivery");
129
145
  return [{ kind: "busy" }];
130
146
  }
131
- case "session.status": {
132
- const retrying = p.status?.type === "retry" ? p.status.message : undefined;
133
- return typeof retrying === "string" && (RATE_LIMITED.test(retrying) || autoSwitch.OPENCODE_KEY_REFUSAL_WORDS.test(retrying)) ? this.refused(`rate-limited, being retried by the CLI: ${retrying}`) : [{ kind: "busy" }];
147
+ case "session.inbox.delivered": {
148
+ const inbox = field(event, d.inboxID, "data.inboxID");
149
+ const prompt = this.waiting.get(inbox);
150
+ // NULL-OK: field prompt is OPTIONAL and therefore it is ok to check for NULL
151
+ if (prompt === undefined)
152
+ return [{ kind: "busy" }];
153
+ this.waiting.delete(inbox);
154
+ const answered = prompt.delivery === "queue" && this.open > 0 ? this.close(this.answer()) : [];
155
+ this.open += 1;
156
+ return [...answered, { kind: "taken", text: prompt.text }];
157
+ }
158
+ case "session.inbox.cancelled":
159
+ this.waiting.delete(field(event, d.inboxID, "data.inboxID"));
160
+ return [{ kind: "busy" }];
161
+ case "session.text.ended":
162
+ this.said = field(event, d.text, "data.text");
163
+ return [{ kind: "busy" }];
164
+ case "session.retry.scheduled": {
165
+ const error = OpenCodeLog.error(event, d.error);
166
+ return error.keyRefusal || RATE_LIMITED.test(error.message) ? this.refused(`rate-limited, being retried by the CLI: ${error.said}`) : [{ kind: "busy" }];
134
167
  }
135
- case "session.error": {
136
- field(event, p.error?.data?.message ?? p.error?.name, "error message");
137
- const error = autoSwitch.opencodeEventError(p.error);
168
+ case "session.execution.failed": {
169
+ const error = OpenCodeLog.error(event, d.error);
138
170
  if (error.keyRefusal)
139
171
  return this.refused(error.said);
140
172
  // NULL-OK: field modelFailed is OPTIONAL and therefore it is ok to check for NULL
141
173
  if (this.key.modelFailed !== undefined)
142
174
  return this.modelFailed(error, this.key.modelFailed);
143
- this.failure = `OpenCode reported: ${error.said}`;
144
- return [{ kind: "busy" }];
175
+ return this.close({ kind: "failed", why: `OpenCode reported: ${error.said}` });
145
176
  }
146
- case "permission.asked":
147
- return [{ kind: "busy" }];
148
- case "question.asked":
149
- return [{ kind: "waiting" }];
150
- case "session.idle": {
151
- const [said, failure] = [this.said, this.failure];
152
- [this.said, this.failure] = [undefined, undefined];
153
- // NULL-OK: field failure is OPTIONAL and therefore it is ok to check for NULL
154
- if (failure !== undefined)
155
- return [{ kind: "failed", why: failure }];
156
- // NULL-OK: field said is OPTIONAL and therefore it is ok to check for NULL
157
- return said === undefined ? [{ kind: "silent" }] : [{ kind: "over", answer: said }];
177
+ case "session.execution.interrupted": {
178
+ const reason = field(event, d.reason, "data.reason");
179
+ return reason === "superseded" ? [{ kind: "busy" }] : this.close({ kind: "failed", why: `OpenCode stopped the turn (${reason})` });
158
180
  }
181
+ case "session.execution.succeeded":
182
+ return this.close(this.answer());
159
183
  default:
160
184
  return [{ kind: "busy" }];
161
185
  }
@@ -166,6 +190,7 @@ export function createOpenCodeDriver(runtime) {
166
190
  const route = routeOf(spec.model, (message) => spec.failures.fail(message));
167
191
  mkdirSync(logDir(), { recursive: true });
168
192
  const file = join(logDir(), `${randomUUID()}.jsonl`);
193
+ const store = join(route.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"), "opencode");
169
194
  const failedModel = route.modelRefusalId;
170
195
  const refused = (id, reason) => { autoSwitch.markKeyRefused(homedir(), id, reason); };
171
196
  const key = {
@@ -178,10 +203,11 @@ export function createOpenCodeDriver(runtime) {
178
203
  get provider() { return opencodeProvider; },
179
204
  args: (_spec, resumes) => opencodeConversationArgs(resumes ? spec.sessionId : undefined),
180
205
  nativeModel: route.model,
181
- storePath: join(route.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"), "opencode", "opencode.db"),
206
+ storePath: join(store, "opencode.db"),
182
207
  env: { ...route.env, BN_OPENCODE_LOG: file, OPENCODE_CONFIG_CONTENT: JSON.stringify({ model: route.model, plugin: [EVENT_PLUGIN.href], autoupdate: false }) },
183
208
  log: new OpenCodeLog(file, spec.started ? spec.sessionId : undefined, key),
184
209
  refusal: () => nativeCliRefusal("opencode", spec.project, spec.cli, route.env),
210
+ startupDiagnostic: () => existsSync(file) ? undefined : `OpenCode has not loaded BN's event plugin ${fileURLToPath(EVENT_PLUGIN)}, so BN cannot see this turn — OpenCode's own log (${join(store, "log", "opencode.log")}) names why`,
185
211
  };
186
212
  }
187
213
  /**
@@ -230,6 +256,7 @@ export function createOpenCodeDriver(runtime) {
230
256
  get pid() { return this.inner.pid; }
231
257
  get working() { return this.inner.working; }
232
258
  get pendingInput() { return this.inner.pendingInput; }
259
+ get startupDiagnostic() { return this.inner.startupDiagnostic; }
233
260
  quiet() { return this.inner.quiet(); }
234
261
  end() { this.stopped = true; return this.inner.end(); }
235
262
  async ask(prompt, sink, timeoutMs, token) {
@@ -1132,6 +1132,8 @@ function opencodeFreeRoute(home, wanted, now, passed) {
1132
1132
  // GATE: the HTTP statuses on which the provider refused THIS key or account (unauthorized, payment, forbidden, rate-limited) — the turn moves to the next route; any other failure is not the key's
1133
1133
  const OPENCODE_KEY_REFUSAL_STATUSES = Object.freeze(new Set([401, 402, 403, 429]));
1134
1134
  const OPENCODE_KEY_REFUSAL_WORDS = /credit balance is too low|insufficient (?:balance|funds|credit|quota)|out of (?:funds|credit)|invalid x-api-key/i;
1135
+ // GATE: the error types OpenCode 2 itself gives a failure on which the provider refused THIS key or account (auth, rate limit, quota, spend limits) — the turn moves to the next route, whatever status or words came with it
1136
+ const OPENCODE_KEY_REFUSAL_TYPES = Object.freeze(new Set(["provider.auth", "provider.rate-limit", "provider.quota", "provider.budget-limit", "provider.model-budget-limit", "provider.free-limit", "provider.go-limit", "provider.chatgpt-limit"]));
1135
1137
  /**
1136
1138
  * An error OpenCode reported in one of its JSON events, read once for every reader — BN, the shared OpenCodeTurn and DeepAgent's Test: the provider's own message,
1137
1139
  * its HTTP status when it sent one, whether it refused the key or account, and the line every surface shows.
@@ -1142,7 +1144,7 @@ function opencodeEventError(error) {
1142
1144
  const data = error?.data ?? {};
1143
1145
  const message = data.message ?? error?.name ?? "the CLI reported an error";
1144
1146
  const status = typeof data.statusCode === "number" ? data.statusCode : undefined;
1145
- return { message, status, keyRefusal: (status !== undefined && OPENCODE_KEY_REFUSAL_STATUSES.has(status)) || OPENCODE_KEY_REFUSAL_WORDS.test(message), said: status === undefined ? message : `${message} (HTTP ${status})` };
1147
+ return { message, status, keyRefusal: (status !== undefined && OPENCODE_KEY_REFUSAL_STATUSES.has(status)) || OPENCODE_KEY_REFUSAL_WORDS.test(message) || OPENCODE_KEY_REFUSAL_TYPES.has(error?.name), said: status === undefined ? message : `${message} (HTTP ${status})` };
1146
1148
  }
1147
1149
  /**
1148
1150
  * What a failure on a free model means for the turn, decided once for every OpenCode runner (BN, the shared OpenCodeTurn and through it ai_failover):
@@ -919,9 +919,10 @@ class WebHost {
919
919
  if (!(err instanceof SyntaxError))
920
920
  throw err;
921
921
  // OWNER: the page's workspace read is this read's trigger root — a workspace list that is not defined or cannot be read is answered with its reason beside this host's own workspace, so the page says why its picker is short, and the process serving it goes on.
922
- return send(response, 200, MIME[".json"], JSON.stringify({ extension: this.extension, current: this.ownLabel(), workspaces: this.ownWorkspaces(base), listUnreadable: err.message, ...this.level() }), { "Cache-Control": "no-store" });
922
+ const own = this.ownWorkspaces(base);
923
+ return send(response, 200, MIME[".json"], JSON.stringify({ extension: this.extension, current: Object.hasOwn(own, this.ownLabel()) ? this.ownLabel() : "", workspaces: own, listUnreadable: err.message, ...this.level() }), { "Cache-Control": "no-store" });
923
924
  }
924
- return send(response, 200, MIME[".json"], JSON.stringify({ extension: this.extension, current, workspaces, ...this.level() }), { "Cache-Control": "no-store" });
925
+ return send(response, 200, MIME[".json"], JSON.stringify({ extension: this.extension, current: Object.hasOwn(workspaces, current) ? current : "", workspaces, ...this.level() }), { "Cache-Control": "no-store" });
925
926
  }
926
927
  if (request.method !== "GET" && request.method !== "HEAD") {
927
928
  return send(response, 405, MIME[".txt"], "method not allowed");
@@ -159,6 +159,9 @@ const PICKER_SOURCE = String.raw `
159
159
  if (!latest()) return false;
160
160
  current = picked;
161
161
  select.value = current;
162
+ Array.prototype.slice.call(select.children).forEach(function (option) {
163
+ if (option.value === "" && current !== "") option.remove();
164
+ });
162
165
  return true;
163
166
  }, latest);
164
167
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.440",
3
+ "version": "1.3.441",
4
4
  "homepage": "https://www.npmjs.com/package/omni-notify-mcp",
5
5
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
6
6
  "main": "dist/daemon.js",
@@ -15,7 +15,7 @@
15
15
  "scripts": {
16
16
  "sync-shared": "node -e \"require((process.env.BULLSEYE_SHARED||require('os').homedir()+'/Desktop/BullseyeShared')+'/git-bash/gitBash.js').run(process.argv.slice(1))\" sync-shared.sh",
17
17
  "prebuild": "npm run sync-shared",
18
- "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc && node -e \"require('fs').copyFileSync('src/shared/webhost/package.json','dist/shared/webhost/package.json');require('fs').copyFileSync('src/shared/conversation/opencodeEvents.mjs','dist/shared/conversation/opencodeEvents.mjs');require('fs').copyFileSync('vscode-extension/mcpHosts.cjs','dist/mcpHosts.cjs');require('fs').copyFileSync('vscode-extension/channelReading.cjs','dist/channelReading.cjs');require('fs').copyFileSync('vscode-extension/gatewayInstall.cjs','dist/gatewayInstall.cjs')\"",
18
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc && node -e \"require('fs').copyFileSync('src/shared/webhost/package.json','dist/shared/webhost/package.json');require('fs').cpSync('src/shared/conversation/opencodeEvents','dist/shared/conversation/opencodeEvents',{recursive:true});require('fs').copyFileSync('vscode-extension/mcpHosts.cjs','dist/mcpHosts.cjs');require('fs').copyFileSync('vscode-extension/channelReading.cjs','dist/channelReading.cjs');require('fs').copyFileSync('vscode-extension/gatewayInstall.cjs','dist/gatewayInstall.cjs')\"",
19
19
  "build:extension": "node vscode-extension/esbuild.js",
20
20
  "start": "node dist/daemon.js",
21
21
  "test": "npm run build && npm run build:extension && node tests/run-tests.js",
@@ -2,14 +2,13 @@
2
2
  // OWNER-BOUND LAUNCH, Windows, in Node (#3786; run by process.execPath, never a PATH lookup): start one target and end it, with everything it started, the moment its owner process is gone.
3
3
  // argv: <ownerPid> <exeB64> <argsB64 (JSON array)> <cwdB64>. Exit: the target's own exit code; 95 when the owner was already gone, 96 when the
4
4
  // target could not start, 93 when its folder does not exist, 97 when a .cmd target is handed a line break (cmd.exe cannot carry one). Node cannot create a Windows job object, so the tree is ended by `taskkill /T` from the target's pid while it lives.
5
+ // #4531 — argv `--watch <ownerPid>`: ONE watcher for every child of that owner, each child's pid sent on stdin — or, from another realm of that owner (a worker thread), on the pipe it serves — as `+<pid>` and taken off as `-<pid>`; the owner gone, every tree still on it is ended and it exits 95.
6
+ // Required as a module it hands the owner the same launch plan, so a process that spawns many children spawns them itself and binds them all to one watcher.
5
7
  const { spawn, spawnSync } = require("node:child_process");
6
8
  const fs = require("node:fs");
9
+ const net = require("node:net");
7
10
  const path = require("node:path");
8
11
 
9
- const [ownerArg, exeB64, argsB64, cwdB64] = process.argv.slice(2);
10
- const decode = (text) => Buffer.from(text, "base64").toString("utf8");
11
- const owner = Number(ownerArg);
12
-
13
12
  const alive = (pid) => {
14
13
  try {
15
14
  process.kill(pid, 0);
@@ -19,56 +18,118 @@ const alive = (pid) => {
19
18
  }
20
19
  };
21
20
 
22
- if (!alive(owner)) {
23
- console.error(`ownerGuard: the owner process ${owner} is gone - nothing was started`);
24
- process.exit(95);
25
- }
26
-
27
21
  // A .cmd/.bat target runs through cmd.exe, which reads the line once: every argument is wholly quoted, a quote doubled and a percent sign stepped out of the quotes behind a caret, so it arrives as plain text.
28
22
  const caret = (text) => `"${text.replace(/(\\*)"/g, '$1$1""').replace(/(\\+)$/, "$1$1").replace(/%/g, '"^%"')}"`;
29
23
 
30
- // The guard itself runs as Node through ELECTRON_RUN_AS_NODE; the target must not inherit it.
31
- const { ELECTRON_RUN_AS_NODE: _runAsNode, ...targetEnv } = process.env;
32
- const named = decode(exeB64);
33
- const dirs = process.env.PATH.split(";").map((dir) => dir.replace(/^"(.*)"$/, "$1")).filter((dir) => dir !== "");
34
- const onPath = /[\\/]/.test(named) || /\.[a-z0-9]+$/i.test(named)
35
- ? undefined
36
- : dirs.flatMap((dir) => [".com", ".exe", ".bat", ".cmd"].map((ext) => `${dir}\\${named}${ext}`)).find((file) => fs.existsSync(file));
37
- // NULL-OK: field onPath is OPTIONAL and therefore it is ok to check for NULL
38
- const exe = onPath ?? named;
39
- const args = JSON.parse(decode(argsB64));
40
- const cwd = decode(cwdB64);
41
- if (cwd !== "" && !fs.existsSync(cwd)) {
42
- console.error(`ownerGuard: the folder ${cwd} does not exist - nothing was started`);
43
- process.exit(93);
44
- }
45
- targetEnv.PWD = cwd === "" ? process.cwd() : path.resolve(cwd);
46
- const viaCmd = /\.(cmd|bat)$/i.test(exe);
47
- if (viaCmd && args.some((arg) => /[\r\n]/.test(arg))) {
48
- console.error("ownerGuard: a .cmd target cannot carry a line break in an argument - nothing was started");
49
- process.exit(97);
50
- }
51
- const target = viaCmd
52
- ? spawn(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `"${caret(exe)} ${args.map((arg) => caret(arg)).join(" ")}"`], { cwd: cwd === "" ? undefined : cwd, stdio: "inherit", env: targetEnv, windowsHide: true, windowsVerbatimArguments: true })
53
- : spawn(exe, args, { cwd: cwd === "" ? undefined : cwd, stdio: "inherit", env: targetEnv, windowsHide: true });
54
- target.on("error", (cause) => {
55
- console.error(`ownerGuard: the target could not start - ${cause.message}`);
56
- process.exit(96);
57
- });
24
+ const endTree = (pid) => spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
58
25
 
59
- const endTree = () => {
60
- if (target.pid !== undefined && target.exitCode === null) spawnSync("taskkill", ["/PID", String(target.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
61
- };
26
+ /** How `named` with `args` starts in `cwd` under `env`: the file, arguments and spawn options, whether the file is proven to exist, or the exit code and reason it is refused with. */
27
+ function launchPlan(named, args, cwd, env) {
28
+ const pathKey = Object.keys(env).find((key) => key.toUpperCase() === "PATH");
29
+ const dirs = env[pathKey].split(";").map((dir) => dir.replace(/^"(.*)"$/, "$1")).filter((dir) => dir !== "");
30
+ const onPath = /[\\/]/.test(named) || /\.[a-z0-9]+$/i.test(named)
31
+ ? undefined
32
+ : dirs.flatMap((dir) => [".com", ".exe", ".bat", ".cmd"].map((ext) => `${dir}\\${named}${ext}`)).find((file) => fs.existsSync(file));
33
+ // NULL-OK: field onPath is OPTIONAL and therefore it is ok to check for NULL
34
+ const exe = onPath ?? named;
35
+ if (cwd !== "" && !fs.existsSync(cwd)) return { refused: 93, why: `the folder ${cwd} does not exist - nothing was started` };
36
+ const viaCmd = /\.(cmd|bat)$/i.test(exe);
37
+ if (viaCmd && args.some((arg) => /[\r\n]/.test(arg))) return { refused: 97, why: "a .cmd target cannot carry a line break in an argument - nothing was started" };
38
+ // The guard itself runs as Node through ELECTRON_RUN_AS_NODE; the target must not inherit it.
39
+ const { ELECTRON_RUN_AS_NODE: _runAsNode, ...targetEnv } = env;
40
+ targetEnv.PWD = cwd === "" ? process.cwd() : path.resolve(cwd);
41
+ const options = { cwd: cwd === "" ? undefined : cwd, env: targetEnv, windowsHide: true };
42
+ const found = onPath !== undefined || (/[\\/]/.test(exe) && fs.existsSync(exe));
43
+ return viaCmd
44
+ ? { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${caret(exe)} ${args.map((arg) => caret(arg)).join(" ")}"`], options: { ...options, windowsVerbatimArguments: true }, found }
45
+ : { file: exe, args, options, found };
46
+ }
62
47
 
63
- // GATE: how often the owner is checked — at the boundary the target outlives a dead owner by up to this long
64
- const watch = setInterval(() => {
48
+ function guard(ownerArg, exeB64, argsB64, cwdB64) {
49
+ const decode = (text) => Buffer.from(text, "base64").toString("utf8");
50
+ const owner = Number(ownerArg);
65
51
  if (!alive(owner)) {
66
- endTree();
52
+ console.error(`ownerGuard: the owner process ${owner} is gone - nothing was started`);
67
53
  process.exit(95);
68
54
  }
69
- }, 500);
55
+ const plan = launchPlan(decode(exeB64), JSON.parse(decode(argsB64)), decode(cwdB64), process.env);
56
+ if (plan.refused !== undefined) {
57
+ console.error(`ownerGuard: ${plan.why}`);
58
+ process.exit(plan.refused);
59
+ }
60
+ const target = spawn(plan.file, plan.args, { ...plan.options, stdio: "inherit", windowsHide: true });
61
+ target.on("error", (cause) => {
62
+ console.error(`ownerGuard: the target could not start - ${cause.message}`);
63
+ process.exit(96);
64
+ });
65
+ // GATE: how often the owner is checked — at the boundary the target outlives a dead owner by up to this long
66
+ const watching = setInterval(() => {
67
+ if (!alive(owner)) {
68
+ if (target.pid !== undefined && target.exitCode === null) endTree(target.pid);
69
+ process.exit(95);
70
+ }
71
+ }, 500);
72
+ target.on("exit", (code, signal) => {
73
+ clearInterval(watching);
74
+ process.exit(code ?? (signal === null ? 1 : 128));
75
+ });
76
+ }
77
+
78
+ /** The pipe the one watcher of `owner` serves, so every realm of that owner — a worker thread included — binds its children to it. */
79
+ const pipeOf = (owner) => `\\\\.\\pipe\\ownerGuard-${owner}`;
80
+
81
+ function watch(owner) {
82
+ const children = new Set();
83
+ let feeds = 0;
84
+ // Each feed — this watcher's own stdin, and every realm connected on its pipe — sends `+<pid>` / `-<pid>` lines.
85
+ const take = (stream) => {
86
+ feeds++;
87
+ let pending = "";
88
+ let gone = false;
89
+ const end = () => {
90
+ if (gone) return;
91
+ gone = true;
92
+ feeds--;
93
+ };
94
+ stream.setEncoding("utf8");
95
+ stream.on("data", (chunk) => {
96
+ pending += chunk;
97
+ for (let at = pending.indexOf("\n"); at >= 0; at = pending.indexOf("\n")) {
98
+ const line = pending.slice(0, at).trim();
99
+ pending = pending.slice(at + 1);
100
+ if (/^\+\d+$/.test(line)) children.add(Number(line.slice(1)));
101
+ else if (/^-\d+$/.test(line)) children.delete(Number(line.slice(1)));
102
+ // `?` asks whether every line before it is held: a realm handing its children over ends its own watcher only on this `!`.
103
+ else if (line === "?" && stream !== process.stdin) stream.write("!\n");
104
+ }
105
+ });
106
+ stream.on("end", end);
107
+ stream.on("close", end);
108
+ stream.on("error", end);
109
+ };
110
+ take(process.stdin);
111
+ // OWNER: a first line the realm that started this watcher is no longer there to read (EPIPE) — the owner check below still ends every child.
112
+ process.stdout.on("error", () => undefined);
113
+ const server = net.createServer(take);
114
+ // The realm that started this watcher reads its first line: `serving`, or `taken` when another watcher of this owner already holds the pipe (that realm then binds there and ends this one).
115
+ server.once("listening", () => process.stdout.write("serving\n"));
116
+ // OWNER: a pipe this watcher cannot serve — said to the realm that started it, which still feeds it on stdin (or, `taken`, binds to the watcher that holds the pipe).
117
+ server.on("error", (cause) => process.stdout.write(cause.code === "EADDRINUSE" ? "taken\n" : `unserved ${cause.message}\n`));
118
+ server.listen(pipeOf(owner));
119
+ // GATE: how often the owner is checked — at the boundary every child outlives a dead owner by up to this long
120
+ setInterval(() => {
121
+ if (!alive(owner)) {
122
+ for (const pid of children) endTree(pid);
123
+ process.exit(95);
124
+ }
125
+ for (const pid of children) if (!alive(pid)) children.delete(pid);
126
+ if (feeds === 0 && children.size === 0) process.exit(0);
127
+ }, 500);
128
+ }
129
+
130
+ if (require.main === module) {
131
+ if (process.argv[2] === "--watch") watch(Number(process.argv[3]));
132
+ else guard(...process.argv.slice(2));
133
+ }
70
134
 
71
- target.on("exit", (code, signal) => {
72
- clearInterval(watch);
73
- process.exit(code ?? (signal === null ? 1 : 128));
74
- });
135
+ module.exports = { launchPlan, pipeOf };
@@ -1,13 +0,0 @@
1
- import { appendFileSync } from "node:fs";
2
-
3
- // The plugin OpenCode loads in BN's CLI: it appends the bus events a turn is read from, one JSON object per line, to the file `BN_OPENCODE_LOG` names. A tool part is kept only as the fact that one ran.
4
- const KEPT = /^(session\.(created|error|idle|status)|message\.(updated|part\.updated)|permission\.asked|question\.asked)$/;
5
-
6
- export const BnEvents = async () => ({
7
- event: async ({ event }) => {
8
- if (!KEPT.test(event.type)) return;
9
- const part = event.properties?.part;
10
- const row = event.type === "message.part.updated" && part?.type === "tool" ? { type: event.type, properties: { sessionID: event.properties.sessionID, part: { type: "tool" } } } : event;
11
- appendFileSync(process.env.BN_OPENCODE_LOG, `${JSON.stringify(row)}\n`);
12
- },
13
- });