omni-notify-mcp 1.3.367 → 1.3.369

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,6 +1,6 @@
1
1
  import { spawn, spawnSync } from "child_process";
2
2
  import { EventEmitter } from "events";
3
- import { appendFile } from "fs/promises";
3
+ import { appendFile, readdir, rm } from "fs/promises";
4
4
  import { existsSync, mkdtempSync, writeFileSync, createReadStream, rmSync } from "fs";
5
5
  import { tmpdir } from "os";
6
6
  import { join } from "path";
@@ -26,6 +26,20 @@ function running(pid) {
26
26
  throw error;
27
27
  }
28
28
  }
29
+ /** #4135 — a daemon that ends with terminals open (a release takeover, a crash) never reaches finish(), so every spool is named for the daemon that owns it, and the first terminal a later daemon opens removes each spool whose daemon is gone. */
30
+ const spoolOwner = /^bn-native-(\d+)-/;
31
+ let spoolsSwept = false;
32
+ export async function removeEndedDaemonsSpools() {
33
+ for (const name of await readdir(tmpdir())) {
34
+ const owner = spoolOwner.exec(name);
35
+ if (owner === null || Number(owner[1]) === process.pid || running(Number(owner[1])))
36
+ continue;
37
+ await rm(join(tmpdir(), name), { recursive: true, force: true }).catch((error) => {
38
+ // OWNER: ITER/LOOP — a spool of an ended daemon holds no live terminal; one that will not go is said and left to the next daemon's sweep
39
+ process.stderr.write(`[agent-gateway] the spool ${name} of ended daemon ${owner[1]} was not removed: ${error.message}\n`);
40
+ });
41
+ }
42
+ }
29
43
  /** The person BN's door serves, who holds every conversation's CLI whichever provider runs it. Loaded after the module graph is built: the door reads the config this module's importers are still defining, and it needs no gateway section — a daemon without one holds terminals for the same person. */
30
44
  let holder;
31
45
  void import("./passkeyDoor.js").then((door) => { holder = door.personId; });
@@ -51,7 +65,7 @@ export class NativeTerminal {
51
65
  pasting = false;
52
66
  sequence = 0;
53
67
  readers = 0;
54
- spoolDir = mkdtempSync(join(tmpdir(), "bn-native-"));
68
+ spoolDir = mkdtempSync(join(tmpdir(), `bn-native-${process.pid}-`));
55
69
  spool = join(this.spoolDir, "terminal.ansi");
56
70
  writing = Promise.resolve();
57
71
  /** The CLI itself said it exited, so its worker disconnected and its pid is gone — nothing is left to kill. */
@@ -71,6 +85,13 @@ export class NativeTerminal {
71
85
  this.provider = spec.provider.name;
72
86
  this.project = spec.project;
73
87
  this.key = spec.id;
88
+ if (!spoolsSwept) {
89
+ spoolsSwept = true;
90
+ removeEndedDaemonsSpools().catch((error) => {
91
+ // OWNER: the first terminal's open is the sweep's trigger root and awaits nothing — a temp dir that cannot be listed is said and the next daemon sweeps again
92
+ process.stderr.write(`[agent-gateway] the spools of ended daemons were not swept: ${error.message}\n`);
93
+ });
94
+ }
74
95
  this.started = new Promise((resolve) => { this.settleStarted = (refusal) => { clearTimeout(this.startTimer); resolve(refusal); }; });
75
96
  this.startTimer = setTimeout(() => this.fail(`${spec.provider.label} was not running ${MAX_WAIT_SECONDS} s after it was asked to start.`), MAX_WAIT_SECONDS * 1000);
76
97
  this.screen = new Terminal({ cols: spec.cols, rows: spec.rows, allowProposedApi: true });
@@ -1903,13 +1903,27 @@ export function submitStory(board, given, now) {
1903
1903
  writeWhole(board, requestFile(board, given.storyId), request);
1904
1904
  return { request, written: true, ...(standing?.requestId === requestId ? { unackedMs: now - standing.submittedAt } : {}) };
1905
1905
  }
1906
- /** FleetView's pass on this board failed: the reason is put on its mark, so BB's AUTO START switch shows it until a pass succeeds. */
1907
- export function markQueueTrouble(board, why, now) {
1908
- writeWhole(board, servedFile(board), { pid: process.pid, at: now, trouble: why });
1906
+ /** 🔴 #4123 — why this FleetView leaves the board alone: a newer FleetView, alive, drives it; none ⇒ undefined. */
1907
+ function newerDriver(board, version) {
1908
+ const beat = readJson(servedFile(board));
1909
+ // NULL-OK: field version is OPTIONAL and therefore it is ok to check for NULL
1910
+ if (beat === undefined || beat.pid === process.pid || beat.version === undefined || !isProcessAlive(beat.pid) || !newerVersion(beat.version, version))
1911
+ return undefined;
1912
+ return `FleetView ${beat.version} (process ${beat.pid}), newer than this FleetView ${version}, which leaves the board to it`;
1913
+ }
1914
+ /** FleetView's pass on this board failed: the reason is put on its mark, so BB's AUTO START switch shows it until a pass succeeds — never over a newer FleetView's mark. */
1915
+ export function markQueueTrouble(board, why, now, version) {
1916
+ // NULL-OK: field newerDriver is OPTIONAL and therefore it is ok to check for NULL
1917
+ if (newerDriver(board, version) !== undefined)
1918
+ return;
1919
+ writeWhole(board, servedFile(board), { pid: process.pid, at: now, version, trouble: why });
1909
1920
  }
1910
1921
  /** FleetView's queue beat stopped on a defect: the board is marked not driven with that defect, so BB hands its stories to the board's main session again until a FleetView pass drives it. */
1911
- export function markQueueStopped(board, why, now) {
1912
- writeWhole(board, servedFile(board), { pid: process.pid, at: now, stopped: why });
1922
+ export function markQueueStopped(board, why, now, version) {
1923
+ // NULL-OK: field newerDriver is OPTIONAL and therefore it is ok to check for NULL
1924
+ if (newerDriver(board, version) !== undefined)
1925
+ return;
1926
+ writeWhole(board, servedFile(board), { pid: process.pid, at: now, version, stopped: why });
1913
1927
  }
1914
1928
  /** Whether FleetView's story queue drives this board: the process that marked its last pass still runs and its beat has not stopped, with the reason its last pass failed when it did — else why not, in plain words. A live FleetView that stops answering shows as requests its acks never name ({@link ACK_LATE_MS}). */
1915
1929
  export function queueServed(board) {
@@ -1925,6 +1939,17 @@ export function queueServed(board) {
1925
1939
  // NULL-OK: field trouble is OPTIONAL and therefore it is ok to check for NULL
1926
1940
  return beat.trouble === undefined ? { served: true } : { served: true, trouble: beat.trouble };
1927
1941
  }
1942
+ /** 🔴 #4123 — whether dotted version `a` is later than `b`, part by part as numbers. */
1943
+ export function newerVersion(a, b) {
1944
+ const pa = a.split(".").map(Number);
1945
+ const pb = b.split(".").map(Number);
1946
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1947
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1948
+ if (d !== 0)
1949
+ return d > 0;
1950
+ }
1951
+ return false;
1952
+ }
1928
1953
  /** Another process holds the board's queue lock right now: this pass leaves the queue to it. */
1929
1954
  export class QueueBusy extends Error {
1930
1955
  constructor(board, holder) {
@@ -2093,12 +2118,33 @@ export class WorkerRefused extends WorkerNotStarted {
2093
2118
  this.name = "WorkerRefused";
2094
2119
  }
2095
2120
  }
2121
+ // GATE: the first wait before a parked worker is woken in its own session; doubled for each earlier wake up to WAKE_DOUBLINGS, so a worker that keeps stopping is woken less often but is never given up on
2122
+ export const WAKE_BASE_MS = 60_000;
2123
+ // GATE: how many times the wait doubles — past it a parked worker is woken every WAKE_BASE_MS * 2^WAKE_DOUBLINGS (32 min)
2124
+ export const WAKE_DOUBLINGS = 5;
2125
+ /** 🔴 #4123 — how long after its turn ended a worker woken `wakes` times before is woken again. */
2126
+ export const wakeDelayMs = (wakes) => WAKE_BASE_MS * 2 ** Math.min(wakes, WAKE_DOUBLINGS);
2127
+ /** 🔴 #4123 — where every queue worker stands, said at its start and at each wake: what it clears itself, and how a decision of Meni's reaches him and comes back. */
2128
+ const workerStanding = (storyId) => `A stop you named that you or another agent can clear (a board write refused, the board MCP not loaded yet, a release step) is yours to clear now — never a reason to end your turn. A run the box's CPU ceiling refuses is handled as its refusal says; never stop or kill a process to make room.
2129
+ If a decision only Meni can make stands in the way, record it on #${storyId} with bullseye-backlog \`ask\` and ask him with the notify MCP \`ask\` tool, which reaches his email and text; when its wait ends unanswered, keep calling \`wait_for_inbox\` until his reply arrives, then \`rule\` his answer onto #${storyId} verbatim, apply it and go on. End your turn only once the story is shipped.`;
2130
+ /** 🔴 #4123 — what a parked worker is told when the queue wakes it in its own session. */
2131
+ export const wakeMessage = (storyId) => `FleetView's story queue woke you: #${storyId} is still OPEN on the board and you are its one worker. Re-read it with bullseye-backlog \`get\` and carry it to \`ship\` in this turn.
2132
+ ${workerStanding(storyId)}`;
2133
+ /** 🔴 #4123 — the brief a queue worker is started with: the story's own brief first, so its job is still found by its first line, then where a worker with no main session above it stands. */
2134
+ export const workerBrief = (entry) => `${entry.brief}
2135
+
2136
+ FleetView's story queue started you on #${entry.storyId}, and no main session stands above you. Where the brief above speaks of main — a finding sent to main, a turn end that hands you back to main — nobody is there to take it: a finding with no tie to this story is appended to #${entry.storyId}'s Remaining line — read it with bullseye-backlog \`get\`, then \`update\` it with the old text plus the finding, pinned with the \`expectHash\` the read gave — and the review, the land, the release and the ship are yours.
2137
+ ${workerStanding(entry.storyId)}`;
2096
2138
  // GATE: how many times one story's worker is started before the queue gives up on it and its entry stops in `failed` — each start that ends with the story still open is one
2097
2139
  export const WORKER_ATTEMPTS = 3;
2098
2140
  // GATE: the wait before a story whose worker ended is started again: this, doubled for each earlier attempt
2099
2141
  export const RETRY_BASE_MS = 60_000;
2100
2142
  // GATE: the wait before a story the queue gave up on is offered to the line again: this, doubled for each start past WORKER_ATTEMPTS
2101
2143
  export const REARM_BASE_MS = RETRY_BASE_MS * 2 ** WORKER_ATTEMPTS;
2144
+ // GATE: how many times the wait before a given-up story is offered again doubles — past it the story is offered every REARM_BASE_MS * 2^REARM_DOUBLINGS (32 min), so an open story is never left unworked for good
2145
+ export const REARM_DOUBLINGS = 2;
2146
+ /** 🔴 #4123 — how long after the queue gave up on a story it is offered to the line again. */
2147
+ export const rearmDelayMs = (attempts) => REARM_BASE_MS * 2 ** Math.min(Math.max(attempts - WORKER_ATTEMPTS, 0), REARM_DOUBLINGS);
2102
2148
  /** The acks the passes' requests call for: one per request read, carrying its entry's state and place, rewritten only when one of them changed. */
2103
2149
  function writeAcks(board, store, refusals, applied, now) {
2104
2150
  const order = queueOrder(store);
@@ -2143,6 +2189,24 @@ function afterWorker(e, now, why, retried = true) {
2143
2189
  step(e, now, "retry", e.why);
2144
2190
  }
2145
2191
  }
2192
+ /**
2193
+ * 🔴 #14202 — a story the queue no longer works gives back its Claude worker's process the moment that worker's turn is over:
2194
+ * Claude Code's daemon keeps a settled worker at its prompt until the box runs low on memory, so a process the queue leaves
2195
+ * behind holds its memory for good. The entry KEEPS its worker, so a story that comes back to the line wakes that same session;
2196
+ * a worker still mid-turn is read again on the next pass, so its own last acts are never cut off; a stop the provider refused
2197
+ * is tried again after the worker's wait. A Codex worker is a post into a shared Codex main, which has no process to give back.
2198
+ */
2199
+ function idleWorker(worker, reading, now) {
2200
+ // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
2201
+ if (worker === undefined || worker.provider !== "claude")
2202
+ return undefined;
2203
+ const parked = reading().parked;
2204
+ // NULL-OK: field parked is OPTIONAL and therefore it is ok to check for NULL
2205
+ return parked !== undefined && parked.live && stopDue(worker, now) ? worker : undefined;
2206
+ }
2207
+ /** 🔴 #4123 — a parked worker's idle process is stopped at once, and a stop that did not take is tried again only after its wait. */
2208
+ // NULL-OK: field stoppedAt is OPTIONAL and therefore it is ok to check for NULL
2209
+ const stopDue = (worker, now) => worker.stoppedAt === undefined || now >= worker.stoppedAt + wakeDelayMs(worker.wakes ?? 0);
2146
2210
  /**
2147
2211
  * 🔴 ONE PASS OF FLEETVIEW'S STORY QUEUE ON ONE BOARD, under its lock: every request BB wrote is applied and acknowledged,
2148
2212
  * every worker is checked (a story shipped closes its entry; a worker that ended with the story still open is started
@@ -2152,11 +2216,16 @@ function afterWorker(e, now, why, retried = true) {
2152
2216
  */
2153
2217
  export async function driveStoryQueue(board, world, now) {
2154
2218
  return withQueueLock(board, now, async () => {
2155
- writeWhole(board, servedFile(board), { pid: process.pid, at: now });
2219
+ const newer = newerDriver(board, world.driverVersion);
2220
+ // NULL-OK: field newer is OPTIONAL and therefore it is ok to check for NULL
2221
+ if (newer !== undefined)
2222
+ throw new QueueBusy(board, newer);
2223
+ writeWhole(board, servedFile(board), { pid: process.pid, at: now, version: world.driverVersion });
2156
2224
  const store = readQueueStore(board);
2157
2225
  const save = () => writeWhole(board, storeFile(board), store);
2158
2226
  const refusals = new Map();
2159
2227
  const applied = new Map();
2228
+ const wakeable = new Map();
2160
2229
  for (const id of requestedStories(board)) {
2161
2230
  const r = readableRequest(board, id);
2162
2231
  // NULL-OK: field r is OPTIONAL and therefore it is ok to check for NULL
@@ -2171,81 +2240,208 @@ export async function driveStoryQueue(board, world, now) {
2171
2240
  applied.set(id, r.requestId);
2172
2241
  }
2173
2242
  for (const e of store.entries) {
2174
- if (e.state === "withdrawn")
2175
- continue;
2176
- const closed = world.closedWhy(e.storyId);
2177
- if (e.state === "done") {
2178
- // NULL-OK: field closed is OPTIONAL and therefore it is ok to check for NULL
2179
- if (closed !== undefined || !e.eligible)
2243
+ let idle;
2244
+ judge: {
2245
+ if (e.state === "withdrawn") {
2246
+ idle = idleWorker(e.worker, () => world.worker(e, board), now);
2247
+ break judge;
2248
+ }
2249
+ const closed = world.closedWhy(e.storyId);
2250
+ if (e.state === "done") {
2251
+ // NULL-OK: field closed is OPTIONAL and therefore it is ok to check for NULL
2252
+ if (closed !== undefined || !e.eligible) {
2253
+ idle = idleWorker(e.worker, () => world.worker(e, board), now);
2254
+ break judge;
2255
+ }
2256
+ e.state = "queued";
2257
+ e.attempts = 0;
2258
+ delete e.nextTryAt;
2259
+ e.why = "its story is an open row on the board again";
2260
+ step(e, now, "acknowledged", e.why);
2180
2261
  continue;
2181
- e.state = "queued";
2182
- e.attempts = 0;
2183
- delete e.nextTryAt;
2184
- e.why = "its story is an open row on the board again";
2185
- step(e, now, "acknowledged", e.why);
2186
- continue;
2187
- }
2188
- if (closed !== undefined) {
2189
- e.state = "done";
2190
- e.why = closed;
2191
- step(e, now, "closed", closed);
2192
- continue;
2193
- }
2194
- if (e.state === "failed") {
2195
- const gaveUp = e.trace.filter((t) => t.stage === "failed").pop();
2196
- if (!e.eligible || gaveUp === undefined)
2262
+ }
2263
+ if (closed !== undefined) {
2264
+ e.state = "done";
2265
+ e.why = closed;
2266
+ step(e, now, "closed", closed);
2267
+ idle = idleWorker(e.worker, () => world.worker(e, board), now);
2268
+ break judge;
2269
+ }
2270
+ if (e.state === "failed") {
2271
+ const gaveUp = e.trace.filter((t) => t.stage === "failed").pop();
2272
+ if (!e.eligible || gaveUp === undefined)
2273
+ continue;
2274
+ if (now - gaveUp.at < rearmDelayMs(e.attempts))
2275
+ continue;
2276
+ e.state = "queued";
2277
+ delete e.nextTryAt;
2278
+ e.why = `the queue gave up on it ${Math.round((now - gaveUp.at) / 60_000)}m ago and the story is still open, so it is offered to the line again`;
2279
+ step(e, now, "retry", e.why);
2197
2280
  continue;
2198
- if (now - gaveUp.at < REARM_BASE_MS * 2 ** (e.attempts - WORKER_ATTEMPTS))
2281
+ }
2282
+ if (e.state !== "starting" && e.state !== "running")
2199
2283
  continue;
2200
- e.state = "queued";
2201
- delete e.nextTryAt;
2202
- e.why = `the queue gave up on it ${Math.round((now - gaveUp.at) / 60_000)}m ago and the story is still open, so it is offered to the line again`;
2203
- step(e, now, "retry", e.why);
2204
- continue;
2205
- }
2206
- if (e.state !== "starting" && e.state !== "running")
2207
- continue;
2208
- const w = world.worker(e, board);
2209
- // NULL-OK: field found is OPTIONAL and therefore it is ok to check for NULL
2210
- if (e.worker === undefined && w.found !== undefined)
2211
- e.worker = w.found;
2212
- if (!w.alive) {
2213
- step(e, now, "worker-ended", w.why);
2214
- afterWorker(e, now, w.why);
2215
- continue;
2216
- }
2217
- if (e.state === "starting") {
2218
- e.state = "running";
2219
- step(e, now, "started", w.why);
2220
- }
2221
- // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
2222
- if (e.worker !== undefined && ((w.blocked === true) !== (e.worker.blocked === true) || w.needs !== e.worker.needs)) {
2223
- if (w.blocked === true) {
2224
- e.worker.blocked = true;
2225
- // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
2226
- if (w.needs === undefined)
2284
+ const w = world.worker(e, board);
2285
+ // NULL-OK: field found is OPTIONAL and therefore it is ok to check for NULL
2286
+ if (e.worker === undefined && w.found !== undefined)
2287
+ e.worker = w.found;
2288
+ if (!w.alive) {
2289
+ step(e, now, "worker-ended", w.why);
2290
+ afterWorker(e, now, w.why);
2291
+ continue;
2292
+ }
2293
+ if (e.state === "starting") {
2294
+ e.state = "running";
2295
+ step(e, now, "started", w.why);
2296
+ }
2297
+ // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
2298
+ if (e.worker !== undefined && ((w.blocked === true) !== (e.worker.blocked === true) || w.needs !== e.worker.needs)) {
2299
+ if (w.blocked === true) {
2300
+ e.worker.blocked = true;
2301
+ // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
2302
+ if (w.needs === undefined)
2303
+ delete e.worker.needs;
2304
+ else
2305
+ e.worker.needs = w.needs;
2306
+ e.why = `its ${e.provider} worker ${e.worker.jobId} stopped and needs an act before it goes on: ${blockedAct(e.worker)}`;
2307
+ step(e, now, "blocked", e.why);
2308
+ }
2309
+ else {
2310
+ delete e.worker.blocked;
2227
2311
  delete e.worker.needs;
2228
- else
2229
- e.worker.needs = w.needs;
2230
- e.why = `its ${e.provider} worker ${e.worker.jobId} stopped and needs an act before it goes on: ${blockedAct(e.worker)}`;
2231
- step(e, now, "blocked", e.why);
2312
+ e.why = w.why;
2313
+ step(e, now, "progress", `its worker ${e.worker.jobId} works again — ${w.why}`);
2314
+ }
2315
+ }
2316
+ if (w.progressAt !== undefined && e.worker !== undefined && w.progressAt !== e.worker.progressAt) {
2317
+ if (e.worker.progressAt === undefined)
2318
+ step(e, now, "progress", `its work first moved at ${new Date(w.progressAt).toISOString()}`);
2319
+ e.worker.progressAt = w.progressAt;
2320
+ }
2321
+ // NULL-OK: field session is OPTIONAL and therefore it is ok to check for NULL
2322
+ if (w.session !== undefined)
2323
+ e.worker.session = w.session;
2324
+ // NULL-OK: field parked is OPTIONAL and therefore it is ok to check for NULL
2325
+ if (w.parked === undefined) {
2326
+ delete e.worker?.parkedAt;
2327
+ delete e.worker?.stoppedAt;
2328
+ continue;
2232
2329
  }
2233
- else {
2234
- delete e.worker.blocked;
2235
- delete e.worker.needs;
2236
- e.why = w.why;
2237
- step(e, now, "progress", `its worker ${e.worker.jobId} works again — ${w.why}`);
2330
+ const worker = e.worker;
2331
+ if (!e.eligible) {
2332
+ const why = `its ${e.provider} worker ${worker.jobId}'s turn is over and the story is no longer the queue's to work, so it is not woken`;
2333
+ step(e, now, "worker-ended", why);
2334
+ afterWorker(e, now, why);
2335
+ idle = idleWorker(worker, () => w, now);
2336
+ break judge;
2238
2337
  }
2338
+ // NULL-OK: field parkedAt is OPTIONAL and therefore it is ok to check for NULL
2339
+ if (worker.parkedAt === undefined && w.parked.failed === true) {
2340
+ if (e.attempts >= WORKER_ATTEMPTS) {
2341
+ idle = idleWorker(worker, () => w, now);
2342
+ delete e.worker;
2343
+ step(e, now, "worker-ended", w.why);
2344
+ afterWorker(e, now, w.why);
2345
+ break judge;
2346
+ }
2347
+ e.attempts += 1;
2348
+ }
2349
+ // NULL-OK: field parkedAt is OPTIONAL and therefore it is ok to check for NULL
2350
+ if (worker.parkedAt === undefined) {
2351
+ worker.parkedAt = now;
2352
+ step(e, now, "parked", `its ${e.provider} worker ${worker.jobId}'s turn is over with the story open, so it is woken in its own session from ${new Date(now + wakeDelayMs(worker.wakes ?? 0)).toISOString()}`);
2353
+ }
2354
+ if (!w.parked.live) {
2355
+ if (now >= worker.parkedAt + wakeDelayMs(worker.wakes ?? 0))
2356
+ wakeable.set(e, w.parked.sessionId);
2357
+ continue;
2358
+ }
2359
+ if (stopDue(worker, now))
2360
+ idle = worker;
2239
2361
  }
2240
- if (w.progressAt !== undefined && e.worker !== undefined && w.progressAt !== e.worker.progressAt) {
2241
- if (e.worker.progressAt === undefined)
2242
- step(e, now, "progress", `its work first moved at ${new Date(w.progressAt).toISOString()}`);
2243
- e.worker.progressAt = w.progressAt;
2362
+ // NULL-OK: field idle is OPTIONAL and therefore it is ok to check for NULL
2363
+ if (idle === undefined)
2364
+ continue;
2365
+ const open = e.state === "running";
2366
+ const kept = e.worker === idle;
2367
+ // NULL-OK: field stoppedAt is OPTIONAL and therefore it is ok to check for NULL
2368
+ const again = idle.stoppedAt !== undefined;
2369
+ idle.stoppedAt = now;
2370
+ save();
2371
+ try {
2372
+ await world.stop(idle);
2373
+ if (open)
2374
+ step(e, now, "parked", again ? `its worker ${idle.jobId}'s session was still held at the prompt after it was stopped, so it was stopped again` : `its worker ${idle.jobId}'s idle process was stopped, so its session is woken once the process has gone`);
2375
+ else if (kept)
2376
+ step(e, now, "worker-ended", `its worker ${idle.jobId}'s turn is over and the queue no longer works the story, so its idle process was stopped and its session is kept for the story's return`);
2377
+ else
2378
+ step(e, now, "worker-ended", `its worker ${idle.jobId} kept failing and was given up on, so its idle process was stopped`);
2379
+ }
2380
+ catch (err) {
2381
+ if (!(err instanceof WorkerNotStarted))
2382
+ throw err;
2383
+ // OWNER: ITER/LOOP — the provider would not stop this worker's idle process this pass, so it stays at its prompt with the provider's words on its trace and, while its entry still names it, the stop is tried again after its wait; the next entry is read.
2384
+ if (kept)
2385
+ step(e, now, "parked", `its worker ${idle.jobId}'s idle process could not be stopped, so it is stopped again at ${new Date(now + wakeDelayMs(idle.wakes ?? 0)).toISOString()}: ${err.message}`);
2386
+ else
2387
+ step(e, now, "worker-ended", `its worker ${idle.jobId} was given up on and its idle process could not be stopped: ${err.message}`);
2244
2388
  }
2245
2389
  }
2246
2390
  save();
2247
2391
  let lanes = world.lanesRunning();
2248
2392
  for (const e of queueOrder(store)) {
2393
+ const sessionId = wakeable.get(e);
2394
+ // NULL-OK: field sessionId is OPTIONAL and therefore it is ok to check for NULL
2395
+ if (sessionId !== undefined) {
2396
+ const parked = e.worker;
2397
+ const held = world.heldBy(e.storyId);
2398
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
2399
+ if (held !== undefined) {
2400
+ e.why = `${held} works it, so its parked worker ${parked.jobId} is not woken beside it`;
2401
+ continue;
2402
+ }
2403
+ if (lanes >= world.limit) {
2404
+ e.why = `its worker ${parked.jobId} is parked, and ${lanes} lanes run with the lane limit at ${world.limit}, so it is woken when one finishes`;
2405
+ continue;
2406
+ }
2407
+ lanes += 1;
2408
+ const wakes = (parked.wakes ?? 0) + 1;
2409
+ try {
2410
+ const woken = await world.wake(e, board, sessionId, wakeMessage(e.storyId));
2411
+ e.worker = { ...woken, wakes, ...keptSession(parked) };
2412
+ e.why = `its ${woken.provider} worker ${woken.jobId} was woken in its own session (wake ${wakes}), with ${lanes} of ${world.limit} lanes running`;
2413
+ step(e, now, "woken", e.why);
2414
+ }
2415
+ catch (err) {
2416
+ if (!(err instanceof WorkerNotStarted))
2417
+ throw err;
2418
+ const after = world.worker(e, board);
2419
+ // NULL-OK: field parked is OPTIONAL and therefore it is ok to check for NULL
2420
+ if (after.alive && (after.parked === undefined || after.parked.live)) {
2421
+ // OWNER: ITER/LOOP — the wake's answer was lost (a timeout on a busy box) but a process now runs the worker's session, so the wake landed: the entry keeps that worker and no second one is started; the next entry is read.
2422
+ e.worker = { provider: parked.provider, startedAt: now, jobId: parked.jobId, wakes, ...keptSession(parked) };
2423
+ e.why = `its worker ${parked.jobId} was woken in its own session (wake ${wakes}), though its answer was: ${err.message}`;
2424
+ step(e, now, "woken", e.why);
2425
+ }
2426
+ else if (!err.unsent) {
2427
+ // OWNER: ITER/LOOP — the wake's answer was lost and no process has recorded the session yet, so the worker stays parked and is read again next pass; it is never ended on a missing answer, which would start a second worker beside a wake that landed late; the next entry is read.
2428
+ lanes -= 1;
2429
+ e.worker = { ...parked, parkedAt: now, wakes };
2430
+ e.why = `its worker ${parked.jobId}'s wake got no answer, so it stays parked and is read again: ${err.message}`;
2431
+ step(e, now, "parked", e.why);
2432
+ }
2433
+ else {
2434
+ // OWNER: ITER/LOOP — Claude Code refused to wake this story's session and no process runs it, so the worker has ended: its entry carries the provider's words and a fresh worker is started on its backoff; the next entry is read.
2435
+ lanes -= 1;
2436
+ const why = `its ${e.provider} worker ${parked.jobId} could not be woken: ${err.message}`;
2437
+ delete e.worker;
2438
+ step(e, now, "worker-ended", why);
2439
+ afterWorker(e, now, why);
2440
+ }
2441
+ }
2442
+ save();
2443
+ continue;
2444
+ }
2249
2445
  // NULL-OK: field nextTryAt is OPTIONAL and therefore it is ok to check for NULL
2250
2446
  if (!e.eligible || !(e.state === "queued" || ((e.state === "retrying" || e.state === "failed") && e.nextTryAt !== undefined && e.nextTryAt <= now)))
2251
2447
  continue;
@@ -2390,7 +2586,63 @@ const mtimeOf = (file) => {
2390
2586
  return undefined;
2391
2587
  }
2392
2588
  };
2393
- /** A story worker's liveness: a `claude --bg` job whose session a live process runs, with the moment its transcript last moved. */
2589
+ // NULL-OK: field session is OPTIONAL and therefore it is ok to check for NULL
2590
+ const keptSession = (worker) => (worker.session === undefined ? {} : { session: worker.session });
2591
+ /** 🔴 #4123 — a worker whose job record Claude Code no longer keeps: still the story's worker while a process runs its session or that process is inside its start grace, woken in its own session once none does and its transcript is on disk, ended when there is no session to wake. */
2592
+ function goneWorker(worker, now, home) {
2593
+ const gone = `its job ${worker.jobId} is no longer on Claude Code's record`;
2594
+ // NULL-OK: field session is OPTIONAL and therefore it is ok to check for NULL
2595
+ if (worker.session === undefined || mtimeOf(worker.session.transcript) === undefined)
2596
+ return { alive: false, why: gone };
2597
+ if (liveClaudeSessions(home).has(worker.session.id))
2598
+ return { alive: true, why: `${gone}, and a process runs its session ${worker.session.id}, so it is still this story's worker` };
2599
+ if (now - worker.startedAt < WORKER_START_GRACE_MS)
2600
+ return { alive: true, why: `${gone}, and it was started ${Math.round((now - worker.startedAt) / 1000)}s ago, so its process may not have recorded its session ${worker.session.id} yet` };
2601
+ return { alive: true, parked: { sessionId: worker.session.id, live: false }, why: `${gone} — its session ${worker.session.id} is on disk and no process runs it, so it is parked and woken there` };
2602
+ }
2603
+ /** 🔴 #4123 — a job's last whole timeline step, which ends `failed` for a provider's refusal and mid-work for a job killed with the daemon, and whether a step after it is caught mid-append. */
2604
+ function lastTimelineStep(jobId, home) {
2605
+ let text;
2606
+ try {
2607
+ text = fs.readFileSync(path.join(home, "jobs", jobId, "timeline.jsonl"), "utf8");
2608
+ }
2609
+ catch (err) {
2610
+ if (err.code !== "ENOENT")
2611
+ throw err;
2612
+ return { tornTail: false };
2613
+ }
2614
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
2615
+ const tail = lines.pop();
2616
+ // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
2617
+ if (tail === undefined)
2618
+ return { tornTail: false };
2619
+ const whole = timelineStepOf(tail);
2620
+ if (whole !== "torn")
2621
+ return { state: whole, tornTail: false };
2622
+ const before = lines.pop();
2623
+ // NULL-OK: field before is OPTIONAL and therefore it is ok to check for NULL
2624
+ return before === undefined ? { tornTail: true } : { state: JSON.parse(before).state, tornTail: true };
2625
+ }
2626
+ /** 🔴 #4123 — one timeline line's step state, or "torn" while Claude Code is still appending it. */
2627
+ function timelineStepOf(line) {
2628
+ try {
2629
+ return JSON.parse(line).state;
2630
+ }
2631
+ catch (err) {
2632
+ if (!(err instanceof SyntaxError))
2633
+ throw err;
2634
+ return "torn";
2635
+ }
2636
+ }
2637
+ /** 🔴 #4123 — the job states whose turn is over: a process still holding one waits at the prompt, working nothing. */
2638
+ const TURN_OVER = new Set(["done", "blocked", "stopped"]);
2639
+ /**
2640
+ * A story worker's liveness: a `claude --bg` job, with the moment its transcript last moved. 🔴 #4123 — a job whose turn is
2641
+ * over (`done` or `blocked`, with no background task of its own still running) or whose process the daemon retired is
2642
+ * PARKED, alive in its session and woken there, and so is one killed with the daemon or one Claude Code no longer records
2643
+ * whose session is still on disk; a job whose provider call failed, one stopped by anyone but the queue, or one no longer
2644
+ * recorded with no session left to wake has ended.
2645
+ */
2394
2646
  export function storyWorkerLiveness(worker, now, home = claudeHome()) {
2395
2647
  const job = jobRecordOf(worker.jobId, home);
2396
2648
  // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
@@ -2398,27 +2650,63 @@ export function storyWorkerLiveness(worker, now, home = claudeHome()) {
2398
2650
  if (job === "torn")
2399
2651
  return { alive: true, ...asLastRead, why: `its job ${worker.jobId}'s record was caught mid-rewrite, so it is read again on the next pass` };
2400
2652
  if (job === "gone")
2401
- return { alive: false, why: `its job ${worker.jobId} is no longer on Claude Code's record` };
2653
+ return goneWorker(worker, now, home);
2402
2654
  const at = job.linkScanPath === undefined ? undefined : mtimeOf(job.linkScanPath);
2403
- const progress = at === undefined ? {} : { progressAt: at };
2404
- if (job.state === "done" || job.state === "stopped")
2405
- return { alive: false, ...progress, why: `its job ${worker.jobId} ended ${job.state}` };
2406
- if (liveClaudeSessions(home).has(job.sessionId)) {
2407
- // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
2408
- if (job.state === "blocked")
2409
- return { alive: true, ...progress, blocked: true, ...(job.needs === undefined ? {} : { needs: job.needs }), why: `its job ${worker.jobId} is blocked` };
2410
- return { alive: true, ...progress, why: `its job ${worker.jobId} runs as session ${job.sessionId} (${job.state})` };
2411
- }
2655
+ // NULL-OK: field linkScanPath is OPTIONAL and therefore it is ok to check for NULL
2656
+ const progress = { ...(at === undefined ? {} : { progressAt: at }), ...(job.linkScanPath === undefined ? {} : { session: { id: job.sessionId, transcript: job.linkScanPath } }) };
2412
2657
  if (now - worker.startedAt < WORKER_START_GRACE_MS)
2413
2658
  return { alive: true, ...progress, why: `its job ${worker.jobId} was started ${Math.round((now - worker.startedAt) / 1000)}s ago and its process has not recorded itself yet` };
2414
- return { alive: false, ...progress, why: `its job ${worker.jobId} reads ${job.state}, but no process on this machine runs session ${job.sessionId}` };
2659
+ // NULL-OK: field stoppedAt is OPTIONAL and therefore it is ok to check for NULL
2660
+ if (job.state === "stopped" && worker.stoppedAt === undefined)
2661
+ return { alive: false, ...progress, why: `its job ${worker.jobId} ended stopped` };
2662
+ const live = liveClaudeSessions(home).has(job.sessionId);
2663
+ if (job.state === "failed") {
2664
+ // NULL-OK: field detail is OPTIONAL and therefore it is ok to check for NULL
2665
+ const said = `its job ${worker.jobId} failed: ${job.detail ?? "its record names no cause"}`;
2666
+ const step = lastTimelineStep(worker.jobId, home);
2667
+ if (step.tornTail && live)
2668
+ return { alive: true, ...progress, why: `${said} — its timeline's last step is still being written by its running process, so it is read again on the next pass` };
2669
+ if (step.state === "failed" || at === undefined || at <= worker.startedAt)
2670
+ return { alive: false, ...progress, why: said };
2671
+ return { alive: true, ...progress, parked: { sessionId: job.sessionId, live, failed: true }, why: `${said} — it was killed mid-work and its session worked after it was started, so it is parked and woken there` };
2672
+ }
2673
+ // NULL-OK: field inFlight is OPTIONAL and therefore it is ok to check for NULL
2674
+ const waitsOnTasks = job.inFlight !== undefined && job.inFlight.tasks + job.inFlight.queued + job.inFlight.drainableMonitors > 0;
2675
+ // NULL-OK: field needs is OPTIONAL and therefore it is ok to check for NULL
2676
+ const blocked = job.state === "blocked" ? { blocked: true, ...(job.needs === undefined ? {} : { needs: job.needs }) } : {};
2677
+ if (live && (!TURN_OVER.has(job.state) || waitsOnTasks))
2678
+ return { alive: true, ...progress, why: `its job ${worker.jobId} runs as session ${job.sessionId} (${job.state})` };
2679
+ const how = live ? `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}`;
2680
+ return { alive: true, ...progress, ...blocked, parked: { sessionId: job.sessionId, live }, why: `its job ${worker.jobId} is parked — ${how}` };
2681
+ }
2682
+ /** 🔴 #4123 — wakes a parked `claude --bg` session in place with `message`: passed no flags, Claude Code continues the same job with its own saved options. */
2683
+ export function wakeStoryWorker(sessionId, message, board, cli, now) {
2684
+ return new Promise((resolve, reject) => {
2685
+ execFile(cli.cmd, [...cli.args, "--bg", "--resume", sessionId, message], { cwd: board, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
2686
+ const said = `${stdout}${stderr}`;
2687
+ const job = /^backgrounded · (\S+) · /m.exec(said);
2688
+ if (job !== null)
2689
+ return resolve({ provider: "claude", startedAt: now, jobId: job[1] });
2690
+ reject(new WorkerNotStarted(`claude --bg --resume ${err === null ? "printed no job id" : `failed (${err.message.split("\n")[0]})`} — ${said.replace(/\s+/g, " ").trim().slice(-300) || "it printed nothing"}`, err !== null && err.killed !== true));
2691
+ });
2692
+ });
2693
+ }
2694
+ /** 🔴 #4123 — stops a parked `claude --bg` job's idle process, leaving its session to be woken. */
2695
+ export function stopStoryWorker(jobId, cli) {
2696
+ return new Promise((resolve, reject) => {
2697
+ execFile(cli.cmd, [...cli.args, "stop", jobId], { windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
2698
+ if (err === null)
2699
+ return resolve();
2700
+ reject(new WorkerNotStarted(`claude stop ${jobId} failed (${err.message.split("\n")[0]}) — ${`${stdout}${stderr}`.replace(/\s+/g, " ").trim().slice(-300) || "it printed nothing"}`));
2701
+ });
2702
+ });
2415
2703
  }
2416
2704
  // GATE: how long a provider CLI is given to answer a worker start before the start is read as refused
2417
2705
  const LAUNCH_TIMEOUT_MS = 60_000;
2418
2706
  /** A story's worker, started windowless in the board's folder as a `claude --bg` session whose lifetime is the story's; `cli` is Claude Code's program as this machine runs it. */
2419
2707
  export function launchStoryWorker(entry, board, cli, now) {
2420
2708
  return new Promise((resolve, reject) => {
2421
- execFile(cli.cmd, [...cli.args, "--bg", "--name", entry.name, "--model", entry.model, "--permission-mode", "bypassPermissions", entry.brief], { cwd: board, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
2709
+ execFile(cli.cmd, [...cli.args, "--bg", "--name", entry.name, "--model", entry.model, "--permission-mode", "bypassPermissions", workerBrief(entry)], { cwd: board, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
2422
2710
  const said = `${stdout}${stderr}`;
2423
2711
  const job = /^backgrounded · (\S+) · /m.exec(said);
2424
2712
  if (job !== null)
@@ -4,6 +4,7 @@ const fs = require("fs");
4
4
  const http = require("http");
5
5
  const os = require("os");
6
6
  const path = require("path");
7
+ const zlib = require("zlib");
7
8
  const { SHIM_SOURCE } = require("./webviewShim");
8
9
  const { workspacesHere } = require("./workspaceList");
9
10
  const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
@@ -196,6 +197,18 @@ function saveTheme(theme) {
196
197
  function postFrame(message, roots) {
197
198
  return JSON.stringify({ type: "post", message: JSON.parse(repoint(JSON.stringify(message), roots)) });
198
199
  }
200
+ function postTo(sockets, message, roots) {
201
+ const text = postFrame(message, roots);
202
+ const packed = [...sockets].some((socket) => socket.packed === true) ? zlib.gzipSync(text, { level: 1 }) : Buffer.alloc(0);
203
+ for (const socket of sockets) {
204
+ if (socket.packed === true) {
205
+ writeFrameWithOpcode(socket, 0x2, packed);
206
+ }
207
+ else {
208
+ writeFrame(socket, text);
209
+ }
210
+ }
211
+ }
199
212
  function cookieOf(request, name) {
200
213
  // NULL-OK: field cookie is OPTIONAL and therefore it is ok to check for NULL
201
214
  const pair = (request.headers.cookie ?? "").split(";").map((part) => part.trim()).find((part) => part.startsWith(`${name}=`));
@@ -394,7 +407,7 @@ class ServedWebview {
394
407
  * message runs under. `saidOnce` says a failure that persists across the watch's ticks is told to this browser once.
395
408
  */
396
409
  viewerOf(socket) {
397
- const viewer = { search: socket.at, base: socket.base, post: (message) => writeFrame(socket, postFrame(message, this.served)) };
410
+ const viewer = { search: socket.at, base: socket.base, post: (message) => postTo([socket], message, this.served) };
398
411
  viewer.guard = (work, options = {}) => this.guarded(socket, viewer, work, options.saidOnce === true);
399
412
  return viewer;
400
413
  }
@@ -515,10 +528,7 @@ class Page {
515
528
  if (this.mirror !== from || this.sockets.size === 0) {
516
529
  return;
517
530
  }
518
- const frame = postFrame(message, from.roots());
519
- for (const socket of this.sockets) {
520
- writeFrame(socket, frame);
521
- }
531
+ postTo(this.sockets, message, from.roots());
522
532
  }
523
533
  received(socket, text) {
524
534
  let frame;
@@ -533,6 +543,10 @@ class Page {
533
543
  socket.destroy();
534
544
  return;
535
545
  }
546
+ if (frame !== null && frame.type === "packed") {
547
+ socket.packed = true;
548
+ return;
549
+ }
536
550
  // NULL-OK: field mirror is OPTIONAL and therefore it is ok to check for NULL
537
551
  if (frame === null || frame.type !== "message" || this.mirror === undefined) {
538
552
  return;
@@ -543,7 +557,7 @@ class Page {
543
557
  const mirror = this.mirror;
544
558
  mirror.pageLoaded(frame.message);
545
559
  mirror.dispatch(frame.message, "browser", (message) => {
546
- writeFrame(socket, postFrame(message, mirror.roots()));
560
+ postTo([socket], message, mirror.roots());
547
561
  return Promise.resolve(true);
548
562
  }, socket);
549
563
  }
@@ -1091,6 +1105,7 @@ class WebHost {
1091
1105
  socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
1092
1106
  socket.setNoDelay(true);
1093
1107
  socket.peek = url.searchParams.get("peek") === "1";
1108
+ socket.packed = false;
1094
1109
  // NULL-OK: field at is OPTIONAL and therefore it is ok to check for NULL
1095
1110
  socket.at = new URLSearchParams(url.searchParams.get("at") ?? "");
1096
1111
  const leave = () => page.sockets.delete(socket);
@@ -271,12 +271,38 @@ const SHIM_SOURCE = String.raw `(function () {
271
271
  var scheme = window.location.protocol === "https:" ? "wss:" : "ws:";
272
272
  socket = new WebSocket(scheme + "//" + window.location.host + "/__bullseye/ws?page=" + encodeURIComponent(page) + "&at=" + encodeURIComponent(window.location.search) + (new URLSearchParams(window.location.search).get("bullseye-peek") === null ? "" : "&peek=1"));
273
273
  socket.addEventListener("open", function () {
274
+ if (typeof DecompressionStream === "function") {
275
+ socket.send(JSON.stringify({ type: "packed" }));
276
+ }
274
277
  while (queue.length > 0) {
275
278
  socket.send(queue.shift());
276
279
  }
277
280
  });
281
+ socket.binaryType = "blob";
282
+ var unpacking = Promise.resolve();
283
+ var unpackingCount = 0;
278
284
  socket.addEventListener("message", function (event) {
279
- var frame = JSON.parse(String(event.data));
285
+ if (typeof event.data === "string" && unpackingCount === 0) {
286
+ handle(event.data);
287
+ return;
288
+ }
289
+ unpackingCount += 1;
290
+ var text = typeof event.data === "string" ? Promise.resolve(event.data) : new Response(event.data.stream().pipeThrough(new DecompressionStream("gzip"))).text();
291
+ unpacking = unpacking.then(function () {
292
+ return text;
293
+ }).then(function (unpacked) {
294
+ unpackingCount -= 1;
295
+ queueMicrotask(function () {
296
+ handle(unpacked);
297
+ });
298
+ }, function (err) {
299
+ unpackingCount -= 1;
300
+ notice("__bullseye-page-failed", "");
301
+ document.getElementById("__bullseye-page-failed").textContent = "⚠️ A frame from the host could not be unpacked — " + err.message;
302
+ });
303
+ });
304
+ function handle(text) {
305
+ var frame = JSON.parse(text);
280
306
  if (frame.type === "post") {
281
307
  deliver(frame.message);
282
308
  } else if (frame.type === "reload") {
@@ -290,7 +316,7 @@ const SHIM_SOURCE = String.raw `(function () {
290
316
  failedBar.remove();
291
317
  }
292
318
  }
293
- });
319
+ }
294
320
  socket.addEventListener("close", function () {
295
321
  socket = null;
296
322
  window.setTimeout(awaitHost, 1000);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.367",
3
+ "version": "1.3.369",
4
4
  "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.",
5
5
  "main": "dist/daemon.js",
6
6
  "type": "module",