omni-notify-mcp 1.3.483 → 1.3.487

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.
@@ -184,9 +184,9 @@ export class AgentGateway {
184
184
  void (c.forkOf === undefined ? answered : answered.finally(() => this.end(c.id))).catch((err) => appendEvent(c.id, { role: "system", kind: "status", text: `❌ The answer could not be sent to this ${c.platform} thread after the BN restart: ${err instanceof Error ? err.message : String(err)}` }));
185
185
  }
186
186
  }
187
- /** No chat message waiting on its conversation's creation: the gateway can pass to another process without losing one. A turn under way never holds it — the next build takes a cut turn up again on its session and sends its answer to its chat (#2116, #4584). */
187
+ /** No chat message waiting on its conversation's creation and no CLI running a background subagent or shell: the gateway can pass to another process without losing either. A turn under way never holds it — the next build takes a cut turn up again on its session and sends its answer to its chat (#2116, #4584); background work cannot be taken up again, so its CLI is kept until that work ends (#4814). */
188
188
  quiet() {
189
- return !creationsPending();
189
+ return !creationsPending() && this.driver.backgroundHolders().length === 0;
190
190
  }
191
191
  /** Gives the store back when this process hands the gateway over. */
192
192
  async shutdown() {
package/dist/daemon.js CHANGED
@@ -12,7 +12,7 @@ import { spawn } from "child_process";
12
12
  import { existsSync, readFileSync, mkdirSync } from "fs";
13
13
  import { join } from "path";
14
14
  import { fileURLToPath } from "url";
15
- import { DAEMON_BEAT_PATH, CONFIG_DIR, DAEMON_TAG, PACKAGE_VERSION, startNotifyServer, takePendingInbox, yieldGateway } from "./notify.js";
15
+ import { DAEMON_BEAT_PATH, CONFIG_DIR, DAEMON_TAG, PACKAGE_VERSION, handoverWait, startNotifyServer, takePendingInbox, yieldGateway } from "./notify.js";
16
16
  import { startNotifyDoor } from "./gateway/notifyDoor.js";
17
17
  import { writeRecordFile } from "./gateway/conversationOwner.js";
18
18
  import { announceTakeover, inThisBoot } from "./shared/webhost/originHandover.js";
@@ -106,8 +106,8 @@ const tunnel = new TunnelRunner();
106
106
  const daemonHost = {
107
107
  clientId: DAEMON_TAG, tag: DAEMON_TAG,
108
108
  onDoorOwned: (port) => {
109
- tunnel.beat(port);
110
- setInterval(() => tunnel.beat(port), HEARTBEAT_MS);
109
+ tunnel.beat(port, handoverWait());
110
+ setInterval(() => tunnel.beat(port, handoverWait()), HEARTBEAT_MS);
111
111
  },
112
112
  onSuperseded: () => (handedOver === undefined ? replaceWithInstalledBuild() : void handedOver.then(() => process.exit(0))),
113
113
  };
@@ -6,7 +6,6 @@ void import("./passkeyDoor.js").then((door) => { personId = door.personId; });
6
6
  import { createConversationOwner } from "../shared/conversation/conversationOwner.js";
7
7
  import { GatewayError } from "../shared/conversation/conversations.js";
8
8
  import { sameRoot } from "../shared/webhost/workspaceList.js";
9
- import { FLEET_OWNER } from "../shared/providerOwnership.js";
10
9
  function driverOptions() {
11
10
  const bundledGuard = new URL("../scripts/shared/", import.meta.url);
12
11
  const guardDir = fileURLToPath(existsSync(bundledGuard) ? bundledGuard : new URL("../../scripts/shared/", import.meta.url));
@@ -35,7 +34,6 @@ function driverOptions() {
35
34
  }
36
35
  export const conversationOwner = createConversationOwner({
37
36
  get configDir() { return CONFIG_DIR; },
38
- startOwner: FLEET_OWNER,
39
37
  personId: () => personId(),
40
38
  driver: driverOptions(),
41
39
  });
@@ -71,7 +71,7 @@ export class TunnelRunner {
71
71
  reading;
72
72
  firstBeat = true;
73
73
  /** One heartbeat of the door holder: follow the saved setup (start, restart on a new save, stop when removed) and publish the state. */
74
- beat(port) {
74
+ beat(port, handover) {
75
75
  if (this.firstBeat) {
76
76
  this.firstBeat = false;
77
77
  this.endLeftover();
@@ -102,7 +102,7 @@ export class TunnelRunner {
102
102
  // NULL-OK: field setup is OPTIONAL and therefore it is ok to check for NULL
103
103
  if (setup && !this.child && this.reading === undefined)
104
104
  this.start(setup.token);
105
- this.publish(port);
105
+ this.publish(port, handover);
106
106
  }
107
107
  stop() {
108
108
  const child = this.child;
@@ -112,11 +112,11 @@ export class TunnelRunner {
112
112
  this.child = undefined;
113
113
  child.kill();
114
114
  }
115
- publish(port) {
115
+ publish(port, handover) {
116
116
  mkdirSync(CONFIG_DIR, { recursive: true });
117
117
  const path = join(CONFIG_DIR, GATEWAY_STATE_FILE);
118
118
  const staged = `${path}.${process.pid}.tmp`;
119
- writeFileSync(staged, JSON.stringify({ pid: process.pid, at: Date.now(), port, tunnel: this.reading ?? null }));
119
+ writeFileSync(staged, JSON.stringify({ pid: process.pid, at: Date.now(), port, tunnel: this.reading ?? null, handover: handover ?? null }));
120
120
  renameSync(staged, path);
121
121
  }
122
122
  /** A connector a hard-killed predecessor left running is ended once, and only when its executable is BN's own copy of cloudflared. */
@@ -382,7 +382,7 @@ const SLACK_HINTS = {
382
382
  not_authed: "no bot token was sent — paste one in BN settings",
383
383
  token_revoked: "the bot token was revoked — reinstall the BN Slack app and paste its new token",
384
384
  account_inactive: "the bot's Slack account is deactivated — reinstall the BN Slack app",
385
- missing_scope: "the BN Slack app lacks a permission this needs (im:history, im:write, chat:write, users:read) — add it and reinstall the app",
385
+ missing_scope: "the BN Slack app lacks a permission this needs (im:history, chat:write, users:read) — add it and reinstall the app",
386
386
  token_expired: "the configuration token expired — paste a new configuration token and its refresh token into BN settings, Slack",
387
387
  invalid_refresh_token: "Slack refused the configuration refresh token — paste a new configuration token and its refresh token into BN settings, Slack",
388
388
  messages_tab_disabled: "the app's App Home Messages tab does not let people message it — BN setup turns it on once it holds a configuration token",
@@ -1,6 +1,6 @@
1
1
  import { SlackRefused, SlackUnreachable, SlackUnknown, slackCall } from "./messenger.js";
2
- /** Every bot scope BN's Slack side uses: the DM chat (im:*, chat:write), the bus channel (channels:*, groups:*) and finding Meni (users:read). */
3
- export const SLACK_BOT_SCOPES = ["chat:write", "channels:history", "channels:read", "channels:join", "groups:history", "groups:read", "im:history", "im:read", "im:write", "users:read"];
2
+ /** Every bot scope BN's Slack side uses: the DM chat (im:history, im:read, chat:write), the bus channel (channels:*, groups:*) and finding Meni (users:read). */
3
+ export const SLACK_BOT_SCOPES = ["chat:write", "channels:history", "channels:read", "channels:join", "groups:history", "groups:read", "im:history", "im:read", "users:read"];
4
4
  /** The events BN's live link takes (#4585): his direct messages to the bot, and each opening of the App Home tab. */
5
5
  export const SLACK_BOT_EVENTS = ["message.im", "app_home_opened"];
6
6
  /** The app BN needs, as Slack's manifest states it: a bot user people can message from the App Home Messages tab, with every scope above, and (#4585) a Home tab, Socket Mode, interactivity for its buttons and the events its live link takes. */
package/dist/notify.js CHANGED
@@ -3834,11 +3834,25 @@ function tryOwnGateway(polling, host) {
3834
3834
  lastBindRefusal = cause;
3835
3835
  }).finally(() => { ownershipAttempting = false; });
3836
3836
  }
3837
+ let stepAsideHeldBy;
3838
+ let stepAsideWaitSince;
3839
+ /** #4814 — the conversations whose background subagents keep this build from handing the gateway to the installed release, and since when; undefined while none does. */
3840
+ export function handoverWait() {
3841
+ return stepAsideWaitSince === undefined ? undefined : { build: PACKAGE_VERSION, conversations: stepAsideHeldBy, since: stepAsideWaitSince };
3842
+ }
3837
3843
  /** Hands the gateway over, a turn under way or not: the pollers finish their reads, the driver gives the store back, then the port is let go for the installed build, which takes a cut turn up again on its session and sends its answer to the chat it came from (#2116). */
3838
3844
  async function stepAside(polling, host) {
3839
3845
  const gateway = AgentGateway.instance();
3840
- if (polling && !gateway.quiet())
3846
+ if (polling && !gateway.quiet()) {
3847
+ const holders = gateway.driver.backgroundHolders().join(", ");
3848
+ if (holders !== stepAsideHeldBy)
3849
+ log("·", "listener", holders === "" ? "the hand-over waits for a chat message mid-creation" : `the hand-over waits for the background subagents of conversation ${holders}; this build keeps their CLI until they end`);
3850
+ stepAsideHeldBy = holders;
3851
+ stepAsideWaitSince = holders === "" ? undefined : stepAsideWaitSince ?? Date.now();
3841
3852
  return;
3853
+ }
3854
+ stepAsideHeldBy = undefined;
3855
+ stepAsideWaitSince = undefined;
3842
3856
  ownershipAttempting = true;
3843
3857
  try {
3844
3858
  if (polling) {
@@ -462,6 +462,7 @@ export function requestCodexStop(stateDir, threadId, turnId, kind, requestedAt)
462
462
  }
463
463
  }
464
464
  export const NATIVE_OWNER_CLIENT_ID = "bullseye";
465
+ export const NATIVE_TURN_ABSENT = "native latest turn is absent";
465
466
  function codexObservationObject(value) {
466
467
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
467
468
  }
@@ -631,7 +632,7 @@ export class CodexControl {
631
632
  const parent = codexObservedParent(thread);
632
633
  const unread = (reason) => ({ ...unknown(threadId, reason), parent });
633
634
  if (before === undefined || after === undefined)
634
- return unread("native latest turn is absent");
635
+ return unread(NATIVE_TURN_ABSENT);
635
636
  if (before.id !== after.id || before.status !== after.status)
636
637
  return unread("native generation or turn status changed during observation");
637
638
  if (expectedTurnId !== undefined && after.id !== expectedTurnId)
@@ -3000,6 +3001,7 @@ function rememberClaudeAssignment(board, entry, worker, at) {
3000
3001
  const FINISHED = new Set(["done", "withdrawn"]);
3001
3002
  /** The store written whole, each finished entry's middle steps first appended to the history file the queue never reads, so the file every pass parses holds only what the queue still acts on. */
3002
3003
  function writeStore(board, store) {
3004
+ refuseAbandonedWrite(board);
3003
3005
  for (const e of store.entries)
3004
3006
  if (e.ordered === true && !WAITING_STATES.has(e.state) && e.state !== "starting") {
3005
3007
  delete e.manual;
@@ -3032,6 +3034,7 @@ const RENAME_TRIES = 5;
3032
3034
  const madeQueueDirs = new Set();
3033
3035
  /** One queue file written whole: a reader sees the old bytes or the new, never half; the queue folder keeps itself out of git. */
3034
3036
  function writeWhole(board, file, value) {
3037
+ refuseAbandonedWrite(board);
3035
3038
  const dir = path.dirname(file);
3036
3039
  // 🔴 #4336 — a pass writes up to one ack per request: the folder and its .gitignore are made once per process, and again when the folder is found gone
3037
3040
  const makeDir = () => {
@@ -3516,6 +3519,55 @@ const PASS_WAIT_MS = 5_000;
3516
3519
  const lineHere = new Map();
3517
3520
  /** 🔴 #4336 — the lock files the running async context already holds, so a call made from inside a pass never waits on that pass. */
3518
3521
  const locksHeld = new AsyncLocalStorage();
3522
+ /** 🔴 #4756 — the pass of this process holding each lock file now. */
3523
+ const passHolds = new Map();
3524
+ /** 🔴 #4756 — the pass the running async context belongs to, so a write of a pass its driver abandoned is refused. */
3525
+ const passHere = new AsyncLocalStorage();
3526
+ /** 🔴 #4756 — a pass that no longer holds its board's lock (its driver abandoned it at its bound, or its lock file was removed or taken) tried to write the board's queue: the write is refused, so it never writes beside the pass that holds the lock now. */
3527
+ export class QueuePassAbandoned extends PassRefused {
3528
+ constructor(board) {
3529
+ super(`this pass over ${board}'s story queue no longer holds the board's lock — it was abandoned at its bound, or its lock file was removed or taken — so none of its writes lands`);
3530
+ this.name = "QueuePassAbandoned";
3531
+ }
3532
+ }
3533
+ /** 🔴 #4756 — each story whose worker start or wake is in flight in this process now, by board lock and story: a pass that runs on after it was abandoned is still inside it. */
3534
+ const startsInFlight = new Set();
3535
+ const startInFlightKey = (board, storyId) => `${lockFile(board)}#${storyId}`;
3536
+ /** 🔴 #4756 — refuses a write made by a pass its driver abandoned ({@link abandonQueuePass}), or whose lock file no longer carries its hold. */
3537
+ function refuseAbandonedWrite(board) {
3538
+ const held = passHere.getStore();
3539
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
3540
+ if (held === undefined || lockFile(held.board) !== lockFile(board))
3541
+ return;
3542
+ if (held.abandoned || readJson(lockFile(board))?.hold !== held.hold)
3543
+ throw new QueuePassAbandoned(board);
3544
+ }
3545
+ /** 🔴 #4756 — runs `work` as no pass's: work a pass sets going that outlives it (another board's pass, an opened slot's pass, a pause on another board) holds none of its locks and is never refused as its writes are. */
3546
+ export function outsideAnyPass(work) {
3547
+ return locksHeld.exit(() => passHere.exit(work));
3548
+ }
3549
+ /** 🔴 #4756 — removes the lock file only while it is still this hold's own, so a pass that ends after it was abandoned never removes the lock a newer pass took. */
3550
+ function letGoOwnLock(file, hold) {
3551
+ if (readJson(file)?.hold === hold)
3552
+ fs.rmSync(file, { force: true });
3553
+ }
3554
+ /**
3555
+ * 🔴 #4756 — THE PASS THE DRIVER ABANDONED LETS THE BOARD GO AT ONCE. MEASURED 2026-12-01: AlphaWave's pass took the lock at 17:26:03Z, the beat
3556
+ * abandoned it at 600 s, and it went on holding the lock while it started workers one at a time — every later pass over AlphaWave read
3557
+ * "being driven by process 58496 since 17:26:03" and started nothing for 38 minutes. The abandoned pass's lock is let go now, its line settles,
3558
+ * and every write it still makes is refused ({@link QueuePassAbandoned}). Answers whether a pass of this process held the board.
3559
+ */
3560
+ export function abandonQueuePass(board) {
3561
+ const file = lockFile(board);
3562
+ const held = passHolds.get(file);
3563
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
3564
+ if (held === undefined)
3565
+ return false;
3566
+ held.abandoned = true;
3567
+ passHolds.delete(file);
3568
+ held.letGo();
3569
+ return true;
3570
+ }
3519
3571
  /**
3520
3572
  * 🔴 #4336 — joins the end of this process's line on the lock file and waits up to {@link PASS_WAIT_MS} for the one ahead to let go;
3521
3573
  * returns the act that lets the next one in line through. A pass lets the thread go between entries, so a press can arrive mid-pass;
@@ -3552,10 +3604,11 @@ export async function withQueueLock(board, now, drive, pass = false) {
3552
3604
  const ahead = pass || locksHeld.getStore()?.has(file) === true ? undefined : lineHere.get(file);
3553
3605
  // NULL-OK: field ahead is OPTIONAL and therefore it is ok to check for NULL
3554
3606
  const leave = ahead === undefined ? () => undefined : await joinLine(file, ahead);
3607
+ const hold = randomBytes(8).toString("hex");
3555
3608
  try {
3556
3609
  for (let attempt = 0;; attempt++) {
3557
3610
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
3558
- fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: now }));
3611
+ fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: now, hold }));
3559
3612
  try {
3560
3613
  fs.linkSync(tmp, file);
3561
3614
  break;
@@ -3577,26 +3630,39 @@ export async function withQueueLock(board, now, drive, pass = false) {
3577
3630
  }
3578
3631
  let passEnded = () => undefined;
3579
3632
  let line;
3633
+ const settleLine = () => {
3634
+ // 🔴 #4336 — the line settles even when the lock file cannot be removed, so no press waits out its whole bound on a pass that ended
3635
+ passEnded();
3636
+ // NULL-OK: field line is OPTIONAL and therefore it is ok to check for NULL
3637
+ if (line !== undefined && lineHere.get(file) === line)
3638
+ lineHere.delete(file);
3639
+ };
3640
+ const held = { board, hold, abandoned: false, letGo: () => { try {
3641
+ letGoOwnLock(file, hold);
3642
+ }
3643
+ finally {
3644
+ settleLine();
3645
+ } } };
3580
3646
  if (pass) {
3581
3647
  const ended = new Promise((resolve) => { passEnded = resolve; });
3582
3648
  const before = lineHere.get(file);
3583
3649
  // NULL-OK: field before is OPTIONAL and therefore it is ok to check for NULL
3584
3650
  line = before === undefined ? ended : before.then(() => ended);
3585
3651
  lineHere.set(file, line);
3652
+ passHolds.set(file, held);
3586
3653
  }
3587
3654
  try {
3588
- return await locksHeld.run(new Set([...(locksHeld.getStore() ?? []), file]), drive);
3655
+ const run = () => locksHeld.run(new Set([...(locksHeld.getStore() ?? []), file]), drive);
3656
+ return await (pass ? passHere.run(held, run) : run());
3589
3657
  }
3590
3658
  finally {
3659
+ if (passHolds.get(file) === held)
3660
+ passHolds.delete(file);
3591
3661
  try {
3592
- fs.rmSync(file, { force: true });
3662
+ letGoOwnLock(file, hold);
3593
3663
  }
3594
3664
  finally {
3595
- // 🔴 #4336 — the line settles even when the lock file cannot be removed, so no press waits out its whole bound on a pass that ended
3596
- passEnded();
3597
- // NULL-OK: field line is OPTIONAL and therefore it is ok to check for NULL
3598
- if (line !== undefined && lineHere.get(file) === line)
3599
- lineHere.delete(file);
3665
+ settleLine();
3600
3666
  }
3601
3667
  }
3602
3668
  }
@@ -4082,8 +4148,7 @@ export function memoryHeldWhy(freeMemory, now) {
4082
4148
  // NULL-OK: field freeMemory is OPTIONAL and therefore it is ok to check for NULL
4083
4149
  if (freeMemory === undefined)
4084
4150
  return undefined;
4085
- recentStarts.splice(0, recentStarts.length, ...recentStarts.filter((at) => at > now - START_MEMORY_GROWTH_MS));
4086
- const growing = recentStarts.length;
4151
+ const growing = growingStarts(now);
4087
4152
  const free = freeMemory();
4088
4153
  if (free - growing * AGENT_TREE_BYTES >= START_MEMORY_FLOOR_BYTES)
4089
4154
  return undefined;
@@ -4091,6 +4156,18 @@ export function memoryHeldWhy(freeMemory, now) {
4091
4156
  const reserved = growing === 0 ? "" : `, less ${gib(growing * AGENT_TREE_BYTES)} GB still to grow in the ${growing} worker${growing === 1 ? "" : "s"} started in the last ${START_MEMORY_GROWTH_MS / 60_000} min`;
4092
4157
  return { trace, why: `${MEMORY_WAIT_WORD} — ${gib(free)} GB free${reserved}, below the ${gib(START_MEMORY_FLOOR_BYTES)} GB floor; it starts on the first pass the box has that much free again` };
4093
4158
  }
4159
+ /** 🔴 #4460 — how many workers this box started in the last {@link START_MEMORY_GROWTH_MS}, whose trees are still growing into its memory. */
4160
+ function growingStarts(now) {
4161
+ recentStarts.splice(0, recentStarts.length, ...recentStarts.filter((at) => at > now - START_MEMORY_GROWTH_MS));
4162
+ return recentStarts.length;
4163
+ }
4164
+ /** 🔴 #4814 — this box's room for a start in MB, measured as {@link memoryHeldWhy} measures it: free memory less what its recent starts still grow into; a world that reads no memory has unbounded room. */
4165
+ export function startRoomMB(freeMemory, now) {
4166
+ // NULL-OK: field freeMemory is OPTIONAL and therefore it is ok to check for NULL
4167
+ if (freeMemory === undefined)
4168
+ return Infinity;
4169
+ return (freeMemory() - growingStarts(now) * AGENT_TREE_BYTES) / 1024 ** 2;
4170
+ }
4094
4171
  /** 🔴 #4460 — the release the step of a start or wake carries when free memory was what last held it; a hold that another reason took over since carries none. */
4095
4172
  function memoryReleased(e, now) {
4096
4173
  const held = e.memoryHeld;
@@ -4157,7 +4234,8 @@ const killedAfterWork = (worker, parked) => parked.killed === true && worker.pro
4157
4234
  /** 🔴 #4162 — how long a parked worker waits before it is woken: none when {@link killedAfterWork}, else {@link wakeDelayMs} — so a session that dies on waking, whose only write is the wake's own message, still backs off and never wakes in a loop. */
4158
4235
  export const parkedWaitMs = (worker, parked) => (killedAfterWork(worker, parked) ? 0 : wakeDelayMs(worker.wakes ?? 0));
4159
4236
  /** 🔴 #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. */
4160
- 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. You run no test, on any box (Meni 2026-11-24: "never run agents that perform tests!!!"): write it, compile, ship — DELL-XPS's scheduled runner runs it and its reds come back as rows. A build the box's CPU ceiling refuses is never a reason to end your turn or to say you will retry later — nothing wakes you for it: hold ONE bounded background wait (at most 10 minutes) inside this turn and then rerun; never stop or kill a process to make room.
4237
+ 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. You run no test, on any box (Meni 2026-11-24: "never run agents that perform tests!!!"): write it, compile, ship — DELL-XPS's scheduled runner runs it and its reds come back as rows.
4238
+ YOU UNBLOCK YOURSELF — nobody else will. Never wait inside a tool call: anything that may run past 2 minutes (a build, a scan, a reviewer, a file you wait for) runs with run_in_background or as a background subagent, its completion notice reaches you by itself, and you do the story's other work meanwhile — never a sleep or poll loop; the harness hands a shell call back after 2 minutes and fails an MCP call after 30 minutes anyway. A call that hangs, times out or fails: kill only the ONE process your own call started (its resolved PID), retry once with a tighter bound, and if it still fails route around it (another door, another box, another way) and decide yourself — never hand the story back or wait to be unstuck. A build the box's CPU ceiling refuses is rerun in the background, never a reason to end your turn; never stop another's process to make room. A review that rejects again is never a stop: fix each real finding, answer each wrong one with its proof on #${storyId}, and send it back to the reviewer in the same turn as a background task. A FleetView message is acted on in your very next step. Every process, browser and background task you start is stopped by you at the end of the step that needed it.
4161
4239
  If a decision only Meni can make stands in the way, ask him with AskUserQuestion: the story queue puts the question on #${storyId}, sends it to him, frees your lane while it waits, and wakes you in this session with his answer, already ruled onto #${storyId} verbatim — apply it and go on. With no AskUserQuestion tool (a Codex worker), 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.`;
4162
4240
  /** 🔴 #4123 — what a parked worker is told when the queue wakes it in its own session; 🔴 #4499 — with Meni's answer, verbatim, when it was parked on his question. */
4163
4241
  export const wakeMessage = (storyId, answered) => `FleetView's story queue woke you: #${storyId} is still OPEN on the board and you are its one worker.${answered === undefined ? "" : answered.approval === true ? ` Your tool call stopped on Claude Code's approval prompt ("${answered.question}"), and the queue answered it itself: ${answered.answer}` : ` Meni answered your question "${answered.question}" — his words, verbatim: "${answered.answer}". His ruling is already on #${storyId}'s row; apply it.`} Re-read it with bullseye-backlog \`get\` and carry it to \`ship\` in this turn.
@@ -4855,6 +4933,16 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
4855
4933
  // hours while its story is not worked. It goes back in line with that start given back, and this pass says so once on the row itself. Nothing of
4856
4934
  // THIS pass can be seen here — the selection and the recorded worker both happen after this loop — so only a pass that ended can have left one.
4857
4935
  if (e.worker === undefined && (e.state === "starting" || e.state === "running")) {
4936
+ // 🔴 #4756 — a pass abandoned at its bound may still be inside this row's start in this process: that row is not wedged, and starting it again would put a second worker on its story
4937
+ if (startsInFlight.has(startInFlightKey(board, e.storyId))) {
4938
+ const said = "its start is still in flight in a pass abandoned at its bound, so it is left starting and never started twice";
4939
+ if (e.why !== said) {
4940
+ e.why = said;
4941
+ step(e, now, "updated", said);
4942
+ save();
4943
+ }
4944
+ continue;
4945
+ }
4858
4946
  const gives = (e.wedgeGives ?? 0) + 1;
4859
4947
  e.wedgeGives = gives;
4860
4948
  // 🔴 #4642 — AND ONCE IS THE GIVING BACK: a row found this way over and over is not a pass that died but something that stops its own start, so it
@@ -4880,6 +4968,8 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
4880
4968
  }
4881
4969
  const waiting = parkedInLine(e);
4882
4970
  const watching = e.state === "starting" || e.state === "running" || waiting;
4971
+ if (watching && fs.existsSync(pressFile(board, `${e.storyId}.stop`)))
4972
+ continue;
4883
4973
  if (watching && e.worker !== undefined && noteCarried(e, workerNow(), now))
4884
4974
  continue;
4885
4975
  const replacement = e.handStop === undefined && (watching || (e.state === "failed" && e.worker !== undefined)) ? await world.replaceUnanswered?.(e, board, save) : undefined;
@@ -5158,7 +5248,10 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
5158
5248
  delete failedWorker.blocked;
5159
5249
  delete failedWorker.needs;
5160
5250
  failedWorker.parkedAt ??= now;
5161
- e.why = `${routeError}; its session and work are kept for the next available route`;
5251
+ const refusedModel = failedWorker.nativeModel ?? (e.selectedRoute?.provider === provider ? e.selectedRoute.model : undefined);
5252
+ e.why = refusedModel !== undefined && MODEL_REFUSAL.test(routeError)
5253
+ ? `${provider} refused model ${refusedModel}: ${routeError}; that model is set aside and the next start picks another from the provider's own list, its session and work kept`
5254
+ : `${routeError}; its session and work are kept for the next available route`;
5162
5255
  if (w.parked.live) {
5163
5256
  if (w.parked.tasks === undefined)
5164
5257
  idle = idleWorker(failedWorker, () => w, now);
@@ -5528,11 +5621,20 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
5528
5621
  return;
5529
5622
  // NULL-OK: field progressOf is OPTIONAL and therefore it is ok to check for NULL
5530
5623
  const progress = (storyId) => world.progressOf?.(storyId) ?? Number.POSITIVE_INFINITY;
5531
- const lane = yieldLaneFor(store.entries, cut.storyId, cut.pri, progress);
5624
+ // 🔴 #4756 — the box's memory is every workspace's: a cut held by memory alone pauses no lane of its own priority on its own board — only a lower one here, else the lowest below it on another workspace of this box
5625
+ const below = PRI_ORDER[rankIn(PRI_ORDER, cut.pri) + 1];
5626
+ // NULL-OK: field below is OPTIONAL and therefore it is ok to check for NULL
5627
+ const lane = overLimit ? yieldLaneFor(store.entries, cut.storyId, cut.pri, progress) : below === undefined ? undefined : yieldLaneFor(store.entries, cut.storyId, below, progress);
5532
5628
  const over = overLimit ? laneWords(true) : short.why;
5533
5629
  // NULL-OK: field lane is OPTIONAL and therefore it is ok to check for NULL
5534
5630
  if (lane === undefined) {
5535
- step(cut, now, "started", `its ⚡ Force start runs past the limit: ${over}, and no running worker of this queue on this box is of its priority or lower with a stop asked at its next step, so none is paused for it`);
5631
+ // NULL-OK: field yieldMemoryElsewhere is OPTIONAL and therefore it is ok to check for NULL
5632
+ if (!overLimit && below !== undefined && world.yieldMemoryElsewhere !== undefined) {
5633
+ world.yieldMemoryElsewhere(cut, by);
5634
+ step(cut, now, "started", `its ⚡ Force start runs past the memory floor (${over}), and no lane of this board is of a lower priority, so a pause is asked of the lowest-priority lane below ${cut.pri} with the least progress on another workspace of this box — its outcome is in that board's log`);
5635
+ return;
5636
+ }
5637
+ step(cut, now, "started", `its ⚡ Force start runs past the limit: ${over}, and no running worker of this queue on this box is of ${overLimit ? "its priority or lower" : "a lower priority"} with a stop asked at its next step, so none is paused for it`);
5536
5638
  return;
5537
5639
  }
5538
5640
  lane.handStop = { at: now, by: `${by} ⚡ Force start of #${cut.storyId}`, yieldFor: cut.storyId };
@@ -5640,7 +5742,15 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
5640
5742
  save();
5641
5743
  try {
5642
5744
  const answered = parked.question?.answer === undefined ? undefined : { question: parked.question.text, answer: parked.question.answer, ...(parked.question.approval === true ? { approval: true } : {}) };
5643
- const woken = await world.wake(e, board, sessionId, wakeMessage(e.storyId, answered), worker => { e.worker = worker; save(); });
5745
+ const waking = startInFlightKey(board, e.storyId);
5746
+ startsInFlight.add(waking);
5747
+ let woken;
5748
+ try {
5749
+ woken = await world.wake(e, board, sessionId, wakeMessage(e.storyId, answered), worker => { e.worker = worker; save(); });
5750
+ }
5751
+ finally {
5752
+ startsInFlight.delete(waking);
5753
+ }
5644
5754
  workerMade(false, e.storyId);
5645
5755
  delete e.nextTryAt;
5646
5756
  e.landedAt = now;
@@ -5864,16 +5974,15 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
5864
5974
  }
5865
5975
  const lowMemory = e.forced === true ? undefined : memoryHeldWhy(world.freeMemory, now);
5866
5976
  let spillTo;
5867
- // NULL-OK: field lowMemory is OPTIONAL and therefore it is ok to check for NULL
5868
- if (lowMemory !== undefined) {
5977
+ if (e.forced !== true) {
5869
5978
  try {
5870
5979
  // NULL-OK: field spillBox is OPTIONAL and therefore it is ok to check for NULL
5871
- spillTo = world.spillBox === undefined ? { refused: "no agent cluster starts workers on other boxes for this queue" } : await world.spillBox(e);
5980
+ spillTo = world.spillBox === undefined ? { refused: "no agent cluster starts workers on other boxes for this queue" } : await world.spillBox(e, { held: lowMemory !== undefined, roomMB: startRoomMB(world.freeMemory, now) });
5872
5981
  }
5873
5982
  catch (err) {
5874
5983
  if (!(err instanceof WorkerNotStarted))
5875
5984
  throw err;
5876
- // OWNER: ITER/LOOP — an agent cluster that could not be asked for this story's box holds the story on memory naming why; the next pass asks again.
5985
+ // OWNER: ITER/LOOP — an agent cluster that could not be asked for this story's box holds a start this box's memory holds, naming why, and starts any other here; the next pass asks again.
5877
5986
  spillTo = { refused: err.message };
5878
5987
  }
5879
5988
  }
@@ -5883,9 +5992,11 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
5883
5992
  continue;
5884
5993
  }
5885
5994
  // NULL-OK: field spillTo is OPTIONAL and therefore it is ok to check for NULL
5886
- const box = spillTo === undefined ? undefined : spillTo.box;
5887
- // NULL-OK: field box is OPTIONAL and therefore it is ok to check for NULL
5888
- const released = box === undefined ? memoryReleased(e, now) : ` — on ${box}, because ${lowMemory.why}`;
5995
+ const placed = spillTo !== undefined && "box" in spillTo ? spillTo : undefined;
5996
+ // NULL-OK: field placed is OPTIONAL and therefore it is ok to check for NULL
5997
+ const box = placed?.box;
5998
+ // NULL-OK: field lowMemory is OPTIONAL and therefore it is ok to check for NULL
5999
+ const released = placed === undefined ? memoryReleased(e, now) : ` — on ${placed.box}, because ${lowMemory?.why ?? placed.why}`;
5889
6000
  if (world.resolveRoute !== undefined) {
5890
6001
  try {
5891
6002
  const route = await world.resolveRoute(e, box);
@@ -5923,8 +6034,15 @@ async function passHeld(board, world, now, yieldsToPresses = true) {
5923
6034
  delete e.wedgeGives;
5924
6035
  save();
5925
6036
  };
5926
- // NULL-OK: field box is OPTIONAL and therefore it is ok to check for NULL
5927
- e.worker = box === undefined ? await world.launch(e, board, record) : await world.spill(e, board, box, record);
6037
+ const inFlight = startInFlightKey(board, e.storyId);
6038
+ startsInFlight.add(inFlight);
6039
+ try {
6040
+ // NULL-OK: field box is OPTIONAL and therefore it is ok to check for NULL
6041
+ e.worker = box === undefined ? await world.launch(e, board, record) : await world.spill(e, board, box, record);
6042
+ }
6043
+ finally {
6044
+ startsInFlight.delete(inFlight);
6045
+ }
5928
6046
  // 🔴 #4642 — the same clearance for a world that hands its worker back instead of recording it through `record`
5929
6047
  delete e.wedgeGives;
5930
6048
  // NULL-OK: field box is OPTIONAL and therefore it is ok to check for NULL
@@ -6201,6 +6319,7 @@ function pendingPresses(board) {
6201
6319
  * story's entry, where the queue's row shows it.
6202
6320
  */
6203
6321
  async function takePendingPresses(board, now) {
6322
+ refuseAbandonedWrite(board);
6204
6323
  const answered = new Map();
6205
6324
  const records = pendingPresses(board).map((name) => {
6206
6325
  let pending;
@@ -6255,8 +6374,8 @@ async function takePendingPresses(board, now) {
6255
6374
  }
6256
6375
  catch (err) {
6257
6376
  if (!(err instanceof StoryPressRefused) && !(err instanceof NotInQueue)) {
6258
- // a refusal of the disk keeps the record for the next pass; a defect in the press itself drops it, so one bad record never stalls the board
6259
- if (!diskRefusal(err))
6377
+ // a refusal of the disk, or a pass that no longer holds the board, keeps the record for the next pass; a defect in the press itself drops it, so one bad record never stalls the board
6378
+ if (!diskRefusal(err) && !(err instanceof QueuePassAbandoned))
6260
6379
  release();
6261
6380
  throw err;
6262
6381
  }
@@ -7520,7 +7639,7 @@ export async function wakeStoryWorker(sessionId, message, cwd, cli, now, model)
7520
7639
  fenceStart("claude", `claude --bg --resume ${sessionId}`);
7521
7640
  const start = await trustLaunchFolder(cwd);
7522
7641
  return new Promise((resolve, reject) => {
7523
- execFile(cli.cmd, [...cli.args, "--bg", "--resume", sessionId, ...(model === undefined ? [] : ["--model", model]), argvBrief(message)], { cwd: start, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
7642
+ execFile(cli.cmd, [...cli.args, "--bg", "--resume", sessionId, ...(model === undefined ? [] : ["--model", model]), "--settings", JOB_CALL_BOUNDS, argvBrief(message)], { cwd: start, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
7524
7643
  const said = `${stdout}${stderr}`;
7525
7644
  const copy = STARTED_A_COPY.exec(said);
7526
7645
  if (copy !== null) {
@@ -7978,6 +8097,12 @@ export function purgeStoryWorker(sessions, home = claudeHome(), temp = tmpdir())
7978
8097
  }
7979
8098
  // GATE: how long a provider CLI is given to answer a worker start before the start is read as refused
7980
8099
  const LAUNCH_TIMEOUT_MS = 60_000;
8100
+ // GATE: the longest one shell call of a `claude --bg` job holds its turn — past it Claude Code moves the call to the background and hands the turn back, so a queued FleetView message reaches the job within this bound
8101
+ export const JOB_SHELL_CALL_MS = 120_000;
8102
+ // GATE: the longest one MCP call of a `claude --bg` job holds its turn — past it the call fails back to the job as timed out
8103
+ export const JOB_MCP_CALL_MS = 1_800_000;
8104
+ /** 🔴 #4822 — the settings every `claude --bg` job is launched with: Claude Code itself bounds each shell and MCP call, so no call a job makes can hold its turn past its bound, whatever timeout the job asked for. */
8105
+ export const JOB_CALL_BOUNDS = JSON.stringify({ env: { BASH_DEFAULT_TIMEOUT_MS: String(JOB_SHELL_CALL_MS), BASH_MAX_TIMEOUT_MS: String(JOB_SHELL_CALL_MS), MCP_TOOL_TIMEOUT: String(JOB_MCP_CALL_MS) } });
7981
8106
  // GATE: the longest brief carried whole on a launch command line; past it the line is cut to its head and the rest is read from a file, because a Windows command line refuses a long one with ENAMETOOLONG
7982
8107
  const ARGV_BRIEF_MAX = 6_000;
7983
8108
  /** 🔴 #4600 — the brief as a launch carries it: whole when it fits a command line, else its head and the path of a file holding all of it, so a story body of any size starts. */
@@ -8038,8 +8163,8 @@ export function claudeConfigFile(env = process.env, homeDir = homedir()) {
8038
8163
  return legacy;
8039
8164
  return path.join(env.CLAUDE_CONFIG_DIR || homeDir, ".claude.json");
8040
8165
  }
8041
- // GATE: the waits for Claude's settings lock, Claude's own first three backoff steps; once they are spent the folder is reported unmarked because the settings are busy
8042
- const CONFIG_LOCK_WAITS_MS = [200, 400, 800];
8166
+ // GATE: the waits for Claude's settings lock, together longer than its 10 s stale window; once spent with the lock refreshed inside the last 10 s, the folder is reported unmarked and the start is retried on its backoff
8167
+ const CONFIG_LOCK_WAITS_MS = [200, 400, 800, 1600, 3200, 3200, 3200];
8043
8168
  // GATE: a settings lock untouched this long is a dead holder's, Claude's own proper-lockfile stale window of 10 s; past it the lock is taken over
8044
8169
  const CONFIG_LOCK_STALE_MS = 10_000;
8045
8170
  export class ClaudeConfigBusyError extends Error {
@@ -8063,12 +8188,40 @@ function projectMcpServers(start) {
8063
8188
  return [];
8064
8189
  }
8065
8190
  }
8066
- function approvedAlready(entry, declared) {
8191
+ /** The approvals a project's own Claude Code settings carry (`.claude/settings.json`, `.claude/settings.local.json`): Claude Code reads a server approved there, and keeps it there instead of in its config's project entry. */
8192
+ function projectApprovals(start) {
8193
+ const kept = { enabled: [], disabled: [], all: false };
8194
+ for (const name of ["settings.json", "settings.local.json"]) {
8195
+ const file = path.join(start, ".claude", name);
8196
+ if (!fs.existsSync(file))
8197
+ continue;
8198
+ let settings;
8199
+ try {
8200
+ settings = JSON.parse(fs.readFileSync(file, "utf8"));
8201
+ }
8202
+ catch (err) {
8203
+ if (!(err instanceof SyntaxError))
8204
+ throw err;
8205
+ throw new SyntaxError(`${file} is not JSON, so the MCP servers it approves cannot be read: ${err.message}`);
8206
+ }
8207
+ if (Array.isArray(settings.enabledMcpjsonServers))
8208
+ kept.enabled.push(...settings.enabledMcpjsonServers);
8209
+ if (Array.isArray(settings.disabledMcpjsonServers))
8210
+ kept.disabled.push(...settings.disabledMcpjsonServers);
8211
+ if (settings.enableAllProjectMcpServers === true)
8212
+ kept.all = true;
8213
+ }
8214
+ return kept;
8215
+ }
8216
+ function approvedAlready(entry, declared, start) {
8067
8217
  // NULL-OK: field entry is OPTIONAL and therefore it is ok to check for NULL
8068
8218
  if (entry?.hasTrustDialogAccepted !== true)
8069
8219
  return false;
8070
- const enabled = Array.isArray(entry.enabledMcpjsonServers) ? entry.enabledMcpjsonServers : [];
8071
- const disabled = Array.isArray(entry.disabledMcpjsonServers) ? entry.disabledMcpjsonServers : [];
8220
+ const local = projectApprovals(start);
8221
+ if (local.all)
8222
+ return true;
8223
+ const enabled = [...(Array.isArray(entry.enabledMcpjsonServers) ? entry.enabledMcpjsonServers : []), ...local.enabled];
8224
+ const disabled = [...(Array.isArray(entry.disabledMcpjsonServers) ? entry.disabledMcpjsonServers : []), ...local.disabled];
8072
8225
  // a server Meni switched off stays off: it is neither asked about nor re-enabled
8073
8226
  return declared.every((name) => enabled.includes(name) || disabled.includes(name));
8074
8227
  }
@@ -8081,7 +8234,7 @@ export async function trustFolder(configFile, folder) {
8081
8234
  const key = start.split(path.sep).join("/");
8082
8235
  // NULL-OK: field projects[key] is OPTIONAL and therefore it is ok to check for NULL
8083
8236
  const servers = projectMcpServers(start);
8084
- if (approvedAlready(trustedProjects(configFile)[key], servers))
8237
+ if (approvedAlready(trustedProjects(configFile)[key], servers, start))
8085
8238
  return start;
8086
8239
  const lockDir = `${configFile}.lock`;
8087
8240
  await takeConfigLock(lockDir);
@@ -8090,7 +8243,7 @@ export async function trustFolder(configFile, folder) {
8090
8243
  // NULL-OK: field projects is OPTIONAL and therefore it is ok to check for NULL
8091
8244
  const projects = config.projects ?? {};
8092
8245
  // NULL-OK: field projects[key] is OPTIONAL and therefore it is ok to check for NULL
8093
- if (!approvedAlready(projects[key], servers)) {
8246
+ if (!approvedAlready(projects[key], servers, start)) {
8094
8247
  // NULL-OK: field projects[key] is OPTIONAL and therefore it is ok to check for NULL
8095
8248
  const enabled = Array.isArray(projects[key]?.enabledMcpjsonServers) ? projects[key].enabledMcpjsonServers : [];
8096
8249
  config.projects = { ...projects, [key]: { ...projects[key], hasTrustDialogAccepted: true, enabledMcpjsonServers: [...new Set([...enabled, ...servers.filter((name) => !(Array.isArray(projects[key]?.disabledMcpjsonServers) && projects[key].disabledMcpjsonServers.includes(name)))])] } };
@@ -8175,7 +8328,7 @@ export async function launchClaudeJob(name, model, brief, cwd, cli, now, env = l
8175
8328
  fenceStart("claude", `claude --bg ${name}`);
8176
8329
  const start = await trustLaunchFolder(cwd);
8177
8330
  return new Promise((resolve, reject) => {
8178
- execFile(cli.cmd, [...cli.args, "--bg", "--name", name, "--model", model, "--permission-mode", "bypassPermissions", argvBrief(brief)], { cwd: start, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
8331
+ execFile(cli.cmd, [...cli.args, "--bg", "--name", name, "--model", model, "--permission-mode", "bypassPermissions", "--settings", JOB_CALL_BOUNDS, argvBrief(brief)], { cwd: start, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
8179
8332
  const said = `${stdout}${stderr}`;
8180
8333
  const job = BACKGROUNDED.exec(said);
8181
8334
  if (job !== null)
@@ -18,16 +18,110 @@ import { basename, dirname, join, resolve } from "path";
18
18
  import { CliSession, endsWithTyped, folderKey, lastRowHolding, plain, sameText } from "./cliSession.js";
19
19
  import { AgentTurnFailed } from "./provider.js";
20
20
  import { claudeConfigFile } from "../agentSession.js";
21
+ /** An end notice Claude Code queues for its background tasks: every task id it names before its status, one notice per block. */
22
+ const TASK_NOTICE_ENDS = /<status>(completed|failed|killed|stopped)<\/status>/;
23
+ /**
24
+ * The background tasks a Claude CLI process started and has not seen end, read from its session transcript: a subagent's start is its
25
+ * `async_launched` result, a subagent continued is a `resumedAgentId`, a background shell is a `backgroundTaskId`; each ends with the
26
+ * `<task-notification>` Claude Code queues for it, or with the `TaskStop` result that stopped it, which no notice follows. Only starts since
27
+ * `since` count — a task of an earlier process of the session died with it — and the transcript is read from where it ended when this
28
+ * process started. An end can be written before its own start (a background shell that finishes at once), so ends are kept by id and time.
29
+ */
30
+ export class BackgroundTasks {
31
+ since;
32
+ /** Each running task's id and when its latest run started. */
33
+ running = new Map();
34
+ /** Each ended task's id and when its latest end was written. */
35
+ ended = new Map();
36
+ offset;
37
+ constructor(since, transcript) {
38
+ this.since = since;
39
+ // NULL-OK: field transcript is OPTIONAL and therefore it is ok to check for NULL
40
+ this.offset = transcript === undefined ? 0 : statSync(transcript).size;
41
+ }
42
+ /** Reads the complete lines the transcript gained since the last read. */
43
+ read(transcript) {
44
+ const size = statSync(transcript).size;
45
+ if (size < this.offset) {
46
+ this.offset = 0;
47
+ this.running.clear();
48
+ this.ended.clear();
49
+ }
50
+ if (size === this.offset)
51
+ return;
52
+ const tail = Buffer.alloc(size - this.offset);
53
+ const file = openSync(transcript, "r");
54
+ try {
55
+ readSync(file, tail, 0, tail.length, this.offset);
56
+ }
57
+ finally {
58
+ closeSync(file);
59
+ }
60
+ const complete = tail.lastIndexOf(0x0a) + 1;
61
+ this.offset += complete;
62
+ for (const line of tail.subarray(0, complete).toString("utf8").split("\n")) {
63
+ if (!BackgroundTasks.speaksOfTasks(line))
64
+ continue;
65
+ let row;
66
+ try {
67
+ row = JSON.parse(line);
68
+ }
69
+ catch (torn) {
70
+ if (!(torn instanceof SyntaxError))
71
+ throw torn;
72
+ // OWNER: ITER/LOOP — a line torn by an earlier CLI process killed mid-write is passed over; the next line is read.
73
+ continue;
74
+ }
75
+ this.hear(row, line);
76
+ }
77
+ }
78
+ static speaksOfTasks(line) {
79
+ return ['"async_launched"', '"resumedAgentId"', '"backgroundTaskId"', '"task_id"', "<task-notification>"].some((word) => line.includes(word));
80
+ }
81
+ hear(row, line) {
82
+ const at = typeof row.timestamp === "string" ? Date.parse(row.timestamp) : NaN;
83
+ const result = row.toolUseResult;
84
+ if (typeof result === "object" && result !== null) {
85
+ for (const id of [result.status === "async_launched" ? result.agentId : undefined, result.success === true ? result.resumedAgentId : undefined, result.backgroundTaskId]) {
86
+ if (typeof id === "string" && at >= this.since)
87
+ this.start(id, at);
88
+ }
89
+ if (typeof result.task_id === "string" && typeof result.message === "string" && result.message.startsWith("Successfully stopped task"))
90
+ this.end(result.task_id, at);
91
+ }
92
+ for (const notice of line.split("<task-notification>").slice(1)) {
93
+ const status = TASK_NOTICE_ENDS.exec(notice);
94
+ if (status === null)
95
+ continue;
96
+ for (const [, id] of notice.slice(0, status.index).matchAll(/<task-id>([^<]+)<\/task-id>/g))
97
+ this.end(id, at);
98
+ }
99
+ }
100
+ start(id, at) {
101
+ const ended = this.ended.get(id);
102
+ // NULL-OK: field ended is OPTIONAL and therefore it is ok to check for NULL
103
+ if (ended !== undefined && ended >= at)
104
+ return;
105
+ this.running.set(id, at);
106
+ }
107
+ end(id, at) {
108
+ this.ended.set(id, Math.max(at, this.ended.get(id) ?? Number.NEGATIVE_INFINITY));
109
+ const started = this.running.get(id);
110
+ // NULL-OK: field started is OPTIONAL and therefore it is ok to check for NULL
111
+ if (started !== undefined && !(at < started))
112
+ this.running.delete(id);
113
+ }
114
+ }
21
115
  export function createClaudeDriver(runtime) {
22
116
  /** The CLI's own config folder, where its sessions and its config file live. */
23
117
  function configDir() {
24
118
  return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
25
119
  }
26
- /** The same environment and settings sources the native CLI will load. */
120
+ /** #4771 — only configuration BN cannot override per spawn: the settings files the native CLI loads. The daemon's own inherited environment is no evidence, since the spawn env follows the chosen rung. */
27
121
  function usesKey(project) {
28
- const hasKey = (env) => Boolean(env.ANTHROPIC_BASE_URL || env.ANTHROPIC_API_KEY);
122
+ const hasKey = (env) => Boolean(env.ANTHROPIC_BASE_URL || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN);
29
123
  const settings = [join(configDir(), "settings.json"), join(project, ".claude", "settings.json"), join(project, ".claude", "settings.local.json")];
30
- return hasKey(process.env) || settings.some((file) => existsSync(file) && hasKey(JSON.parse(readFileSync(file, "utf8")).env ?? {}));
124
+ return settings.some((file) => existsSync(file) && hasKey(JSON.parse(readFileSync(file, "utf8")).env ?? {}));
31
125
  }
32
126
  function projectsDir() {
33
127
  return join(configDir(), "projects");
@@ -236,6 +330,8 @@ export function createClaudeDriver(runtime) {
236
330
  seen = new Set();
237
331
  /** Settles once the CLI has drawn its first output: its input editor is up, so a typed paste reaches it. */
238
332
  drawn;
333
+ /** The background tasks this CLI process started: one started by an earlier process of the session died with it. */
334
+ background = new BackgroundTasks(Date.now(), transcriptOf(this.spec.sessionId));
239
335
  constructor(spec) {
240
336
  if (!folderTrusted(spec.project))
241
337
  throw spec.failures.fail(`Claude Code has not been trusted in ${spec.project}, so its CLI would stop on "Do you trust this folder?" before reading any message — run claude in that folder once and answer "Yes, I trust this folder", then send the message again`);
@@ -274,6 +370,15 @@ export function createClaudeDriver(runtime) {
274
370
  released(turn) {
275
371
  turn.watcher?.close();
276
372
  }
373
+ /** Whether a subagent or background shell this CLI started is still running: its transcript records each start and each end notice, read past what was read before. */
374
+ get backgroundWork() {
375
+ const transcript = transcriptOf(this.spec.sessionId);
376
+ // NULL-OK: field transcript is OPTIONAL and therefore it is ok to check for NULL
377
+ if (transcript === undefined)
378
+ return false;
379
+ this.background.read(transcript);
380
+ return this.background.running.size > 0;
381
+ }
277
382
  adopt(conversation) {
278
383
  this.terminal.rekey(conversation);
279
384
  }
@@ -69,7 +69,7 @@ export class CliSession {
69
69
  }
70
70
  /** Starts the CLI with its own arguments for this session, held by the person BN's door serves. */
71
71
  launch(args, env) {
72
- this.terminal = this.runtime.terminals.openDrivenTerminal(this.runtime.personId(), { id: this.spec.id, provider: this.provider, project: this.spec.project, cmd: this.spec.cli.cmd, args: [...this.spec.cli.args, ...args], env, cols: 100, rows: 30 });
72
+ this.terminal = this.runtime.terminals.openDrivenTerminal(this.runtime.personId(), { id: this.spec.id, provider: this.provider, project: this.spec.project, cmd: this.spec.cli.cmd, args: [...this.spec.cli.args, ...args], env, payer: this.spec.payer, cols: 100, rows: 30 });
73
73
  this.terminal.onClosing(() => { this.ending = true; clearInterval(this.turn?.enter); });
74
74
  }
75
75
  /** Called last in a session's constructor, once all it reads is set: the CLI ending ends the turn it held. */
@@ -186,7 +186,7 @@ export function createCodexDriver(runtime) {
186
186
  if (login.auth_mode === "apikey" || login.OPENAI_API_KEY)
187
187
  return true;
188
188
  }
189
- return Boolean(process.env.OPENAI_API_KEY);
189
+ return false;
190
190
  }
191
191
  /** Codex's workspace-root session loads a project's instructions before acting there. */
192
192
  function rootArgs(project) {
@@ -7,7 +7,6 @@ function makeConversationOwner(host) {
7
7
  const terminals = createTerminalOwner(host);
8
8
  const runtime = {
9
9
  get configDir() { return host.configDir; },
10
- startOwner: host.startOwner,
11
10
  personId: () => host.personId(),
12
11
  store, terminals,
13
12
  get registry() { return registry; },
@@ -17,7 +17,6 @@ import { basename, dirname, join, resolve } from "path";
17
17
  import autoSwitch from "../webhost/autoSwitch.cjs";
18
18
  import { proveStartProviders } from "./providerProof.js";
19
19
  import { sameRoot, workspacesFile, workspacesHere } from "../webhost/workspaceList.js";
20
- import { CLUSTER_OWNER, OwnershipUnreadable, startOwnerOf } from "../providerOwnership.js";
21
20
  /** Thrown for a request the caller got wrong; the door turns it into the status code. */
22
21
  export class GatewayError extends Error {
23
22
  status;
@@ -34,21 +33,6 @@ export const CONVERSATION_SWITCH_FILE = "conversation-switch.json";
34
33
  export const CONVERSATION_OFF_MESSAGE = "The BN agent conversation is switched off. Turn the On switch beside Agent conversations on BN's Settings page to use it; nothing was started.";
35
34
  // GATE: the longest a read may wait for a new event, one second under the 55 s BLOCKING_TOOL_MAX_SECONDS in notify.ts so no call is held past it.
36
35
  export const MAX_WAIT_SECONDS = 54;
37
- /** #4230/#4231 — whether `name`'s agents are started by the OTHER owner now (the agent cluster for BN's owner, the fleet for the cluster's), so this owner starts none of them; an unread authority refuses the start. */
38
- export function heldElsewhere(owner, name) {
39
- try {
40
- return startOwnerOf(name) !== owner;
41
- }
42
- catch (err) {
43
- if (!(err instanceof OwnershipUnreadable))
44
- throw err;
45
- throw new GatewayError(503, err.message);
46
- }
47
- }
48
- /** The refusal of a start this owner does not make: `name` is started by the other owner now. */
49
- export const heldBy = (owner, name) => owner === CLUSTER_OWNER
50
- ? new GatewayError(409, `${name} agents are started by the fleet (BullseyeNotif) now; hand ${name} to the agent cluster first (POST /v1/handover), or leave the provider out for one the cluster starts`, { provider: name, owner })
51
- : new GatewayError(409, `${name} agents are started by the agent cluster now (handed over under #4230); start this one through the cluster's own door, or leave the provider out for one this gateway still starts`, { provider: name, owner: CLUSTER_OWNER });
52
36
  export function createConversationStore(host, registry) {
53
37
  /** The title the agent's session carries in Claude's session list: the project and the first request, so one session is told from another at a glance. A conversation opened with no message yet is named by its project alone. */
54
38
  function titleOf(meta, events) {
@@ -745,16 +729,12 @@ export function createConversationStore(host, registry) {
745
729
  async function pickedCli(provider, folder, model) {
746
730
  if (provider !== undefined && provider !== "auto" && !(typeof provider === "string" && provider.trim() === "")) {
747
731
  const named = namedProvider(provider);
748
- if (heldElsewhere(host.startOwner, named))
749
- throw heldBy(host.startOwner, named);
750
732
  const [proof] = await proveStartProviders(folder, [named], deepagentDoor());
751
733
  if (proof !== undefined && proof.state === "failed")
752
734
  throw new GatewayError(503, `${named} does not answer now — ${proof.line}. Your choice was not replaced with another CLI: pick a different provider, or repair this one in DeepAgent, and start again.`);
753
735
  return { provider: named };
754
736
  }
755
- const startable = (isRootFolder(folder) ? registry().names.filter((name) => registry().get(name).routesAtRoot === true) : registry().names).filter((name) => !heldElsewhere(host.startOwner, name));
756
- if (startable.length === 0)
757
- throw new GatewayError(409, `every agent CLI this owner could start in ${folder} is started by the other owner now: ${heldBy(host.startOwner, "each").message}`, { owner: host.startOwner });
737
+ const startable = (isRootFolder(folder) ? registry().names.filter((name) => registry().get(name).routesAtRoot === true) : registry().names);
758
738
  let rooms;
759
739
  let unreadBecause;
760
740
  try {
@@ -767,18 +747,32 @@ export function createConversationStore(host, registry) {
767
747
  rooms = autoSwitch.unreadRooms(err.message);
768
748
  unreadBecause = err.message;
769
749
  }
770
- const picked = autoSwitch.autoProvider(registry().names, rooms, startable, {
750
+ const pickRung = (eligible) => autoSwitch.autoRung(registry().names, rooms, eligible, {
771
751
  home: homedir(),
772
752
  usesKey: (name) => registry().get(name)?.usesKey?.(folder, model) ?? false,
753
+ keyInEnv: (name) => autoSwitch.daemonEnvCarriesKey(name),
773
754
  });
755
+ // #4771 — DEGRADE BEFORE ANY 503: a rung whose CLI refuses to start here is dropped and the next rung is picked, every refusal kept for the one 503 that names them all.
756
+ const refusals = [];
757
+ let open = startable;
758
+ let rung = pickRung(open);
759
+ while (rung !== undefined) {
760
+ const refusal = registry().get(rung.provider)?.refusal?.(folder, model);
761
+ if (refusal === undefined)
762
+ break;
763
+ refusals.push(`${rung.provider} (${rung.payer} rung) cannot start — ${refusal}`);
764
+ open = open.filter((name) => name !== rung.provider);
765
+ rung = pickRung(open);
766
+ }
774
767
  // #4621 — a provider whose route the ping refused reads `out` on its own reading, so the pick has already moved past it; name every refusal so a start that lands nowhere says why.
775
768
  const refused = Object.entries(rooms).flatMap(([id, r]) => (r?.proof?.state === "failed" ? [`${id} does not answer now — ${r.proof.line}`] : []));
776
- if (picked === undefined)
777
- throw new GatewayError(503, refused.length > 0 ? `no agent CLI answers now: ${refused.join("; ")}` : "Auto has no subscription with room and no permitted, funded key for the eligible CLIs.");
769
+ if (rung === undefined)
770
+ throw new GatewayError(503, `no agent CLI rung can start in ${folder}: ${startable.map((id) => `${id} ${rooms[id]?.state === "unread" ? `unread (${rooms[id]?.reason})` : (rooms[id]?.state ?? "not read")}${rooms[id]?.proof?.state === "failed" ? ` — does not answer: ${rooms[id]?.proof?.line}` : ""}`).join("; ")}${refusals.length === 0 ? "" : `; ${refusals.join("; ")}`}`);
771
+ const picked = rung.provider;
778
772
  const unread = [...new Set(Object.values(rooms).flatMap((r) => (r?.state === "unread" ? [r.reason] : [])))];
779
773
  const words = Object.entries(rooms).map(([id, r]) => `${id} ${r?.state}`).join(", ") + (unread.length === 0 ? "" : ` — unread: ${unread.join("; ")}`);
780
- process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick over ${words}${refused.length === 0 ? "" : ` — refused by the ping: ${refused.join("; ")}`}\n`);
781
- return { provider: picked, ...(unreadBecause === undefined ? {} : { unreadBecause }) };
774
+ process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick, on its ${rung.payer} rung, over ${words}${refused.length === 0 ? "" : ` — refused by the ping: ${refused.join("; ")}`}\n`);
775
+ return { provider: picked, payer: rung.payer, ...(unreadBecause === undefined ? {} : { unreadBecause }) };
782
776
  }
783
777
  /** #4157 — the creations still waiting on their CLI pick, by the chat they are made for: an ask from that chat routes only once they exist, so it is never doubled beside one nor sent past it. */
784
778
  const creating = new Map();
@@ -801,7 +795,7 @@ export function createConversationStore(host, registry) {
801
795
  */
802
796
  function createdIn(folder, provider, chatOf, make, model, scope) {
803
797
  const creation = pickedCli(provider, folder, model).then((pick) => {
804
- const made = make({ project: folder, provider: pick.provider, model, scope });
798
+ const made = make({ project: folder, provider: pick.provider, ...(pick.payer === undefined ? {} : { payer: pick.payer }), model, scope });
805
799
  // NULL-OK: field unreadBecause is OPTIONAL and therefore it is ok to check for NULL
806
800
  if (pick.unreadBecause === undefined)
807
801
  return { made };
@@ -854,7 +848,7 @@ export function createConversationStore(host, registry) {
854
848
  // NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
855
849
  const beside = input.chat === undefined ? undefined : openConversationOf(input.chat)?.id;
856
850
  const meta = {
857
- id: randomUUID(), platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project: input.project, workspace: input.workspace, provider: input.provider, model: input.model,
851
+ id: randomUUID(), platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project: input.project, workspace: input.workspace, provider: input.provider, payer: input.payer, model: input.model,
858
852
  state: input.state, createdAt: now, updatedAt: now, lastMessageAt: now, sessionId: randomUUID(), started: false, consumed: 0, beside, forkOf: input.forkOf,
859
853
  };
860
854
  writeMeta(meta);
@@ -866,7 +860,7 @@ export function createConversationStore(host, registry) {
866
860
  const project = createdFolder(input.project);
867
861
  const provider = namedProvider(input.provider);
868
862
  const workspace = conversationWorkspace(project, input.scope);
869
- const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, workspace, provider, model: input.model, forkOf: input.forkOf, state: "queued" });
863
+ const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, workspace, provider, payer: input.payer, model: input.model, forkOf: input.forkOf, state: "queued" });
870
864
  appendEvent(meta.id, { role: "user", text: input.text, receivedMs: input.receivedMs, ...input.arrival });
871
865
  return meta;
872
866
  }
@@ -881,7 +875,7 @@ export function createConversationStore(host, registry) {
881
875
  const project = createdFolder(input.project);
882
876
  const provider = namedProvider(input.provider);
883
877
  const workspace = conversationWorkspace(project, input.scope);
884
- return newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, project, workspace, provider, model: input.model, state: "idle" });
878
+ return newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, project, workspace, provider, payer: input.payer, model: input.model, state: "idle" });
885
879
  }
886
880
  /**
887
881
  * Sets or switches the folder the conversation's agent works in (#2723), reached by every door that offers it: the Web
@@ -153,7 +153,7 @@ export function createTerminalOwner(host) {
153
153
  this.events.emit("change");
154
154
  this.reap();
155
155
  });
156
- const env = nativeAgentEnv(spec.project, spec.env);
156
+ const env = nativeAgentEnv(spec.project, spec.env, spec.payer);
157
157
  this.child.send({ kind: "start", command: spec.cmd, args: spec.args, project: spec.project, cols: spec.cols, rows: spec.rows, env, ownerPid: process.pid });
158
158
  }
159
159
  /** The record this CLI answers for. */
@@ -16,15 +16,7 @@ export class AgentTurnFailed extends Error {
16
16
  this.shown = shown;
17
17
  }
18
18
  }
19
- const TOOL_MARKS = { shell: "🔧", bash: "🔧", read: "📖", edit: "✏️", write: "✏️", patch: "✏️", apply_patch: "✏️", grep: "🔎", glob: "🔎", webfetch: "🌐", websearch: "🌐", task: "🧩", skill: "🧩", question: "❓" };
20
- const TOOL_ARGUMENTS = ["description", "command", "filePath", "file_path", "path", "pattern", "url", "query", "prompt"];
21
- /** A tool call as a CLI prints it: its mark, its name and what it works on ("🔧 shell — npm run build"). */
22
- export function toolLine(name, input) {
23
- const given = TOOL_ARGUMENTS.map((key) => input?.[key]).find((value) => typeof value === "string" && value.trim() !== "");
24
- // NULL-OK: field given is OPTIONAL and therefore it is ok to check for NULL
25
- const on = given === undefined ? "" : ` — \`${given.replace(/\s+/g, " ").replace(/`/g, "'").slice(0, 90)}\``;
26
- return `${TOOL_MARKS[name.toLowerCase()] ?? "🔧"} ${name}${on}`;
27
- }
19
+ export { toolLine } from "./toolLine.js";
28
20
  /**
29
21
  * The environment every provider starts its CLI in (#2336): the daemon's own, with the project binding pinned to the
30
22
  * folder the agent runs in. BN is ONE daemon on the machine, started by whichever window bound the gateway port first, so
@@ -35,11 +27,16 @@ export function toolLine(name, input) {
35
27
  export function agentEnv(project) {
36
28
  return { ...process.env, CLAUDE_PROJECT_DIR: project };
37
29
  }
38
- /** The native PTY and its preflight use exactly this process environment. */
39
- export function nativeAgentEnv(project, extra) {
30
+ // GATE: the variables that put a CLI on a metered key — a subscription rung strips them from the daemon's inherited environment so the payer is the rung chosen, never whatever the launching window left there; a key rung keeps them
31
+ const KEY_ENV = Object.freeze(["ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_API_KEY"]);
32
+ /** The native PTY and its preflight use exactly this process environment; the chosen rung's `payer` decides whether the key variables stay (#4771). */
33
+ export function nativeAgentEnv(project, extra, payer) {
40
34
  const env = agentEnv(project);
41
35
  env.TERM = "xterm-256color";
42
36
  delete env.CLAUDE_CODE_CHILD_SESSION;
37
+ if (payer === "subscription")
38
+ for (const name of KEY_ENV)
39
+ delete env[name];
43
40
  return Object.assign(env, extra);
44
41
  }
45
42
  export function nativeCliRefusal(command, project, cli = { cmd: command, args: [] }, env) {
@@ -25,7 +25,7 @@ import { basename } from "path";
25
25
  import { DEFAULT_CAPACITY } from "../agentSession.js";
26
26
  import { AgentTurnFailed } from "./provider.js";
27
27
  import { problemOf, reapAgents } from "./agentReaper.js";
28
- import { GatewayError, heldBy, heldElsewhere } from "./conversations.js";
28
+ import { GatewayError } from "./conversations.js";
29
29
  // GATE: a conversation silent this long (10 minutes, Meni 2026-11-29: a finished or idle agent is cleaned up at once) frees its process; its next message resumes the session.
30
30
  export const IDLE_MS = 10 * 60_000;
31
31
  // GATE: Meni's ruling 6A — a turn that has said nothing for this long posts one status line, and another after each such spell.
@@ -54,20 +54,6 @@ export function sessionDriverClass(runtime) {
54
54
  const RESUME_PREAMBLE = "(BN restarted while you were working on the message below, and your work on it was cut off. If this session's history shows what you had already done for it, carry on from where you stopped rather than starting over, then answer it.)";
55
55
  // GATE: the longest the driver waits before trying again to warm a spare agent once no spare is standing — after its process died, or an open was refused because BN is switched off, or the project it is needed in holds no board; at the boundary the next beat tries again.
56
56
  const SPARE_RETRY_MS = 10_000;
57
- /** #4230/#4231 — refuses the start of `name`'s agent when this owner does not make it: the other owner starts that provider now, or the ownership authority is unread. */
58
- function refuseClusterStart(name) {
59
- let held;
60
- try {
61
- held = heldElsewhere(runtime.startOwner, name);
62
- }
63
- catch (err) {
64
- if (!(err instanceof GatewayError))
65
- throw err;
66
- throw new AgentTurnFailed(err.message);
67
- }
68
- if (held)
69
- throw new AgentTurnFailed(heldBy(runtime.startOwner, name).message);
70
- }
71
57
  /** The project the next cold first turn needs: that of the most recently active conversation holding no process of its own and written to within the spare's idle bound, so one spare serves the project the next turn lands in; none when no conversation is expecting a turn or its project holds no board. */
72
58
  function spareProjectOf(conversations, holding) {
73
59
  const cold = conversations.filter((c) => c.state !== "closed" && c.shelf === undefined && !holding.has(c.id)).sort((a, b) => b.lastMessageAt.localeCompare(a.lastMessageAt));
@@ -80,7 +66,7 @@ export function sessionDriverClass(runtime) {
80
66
  }
81
67
  /** A turn of the driver's is running in the session, or one the person typed into its CLI: its process is not idle. */
82
68
  function inUse(live) {
83
- return live.busy || live.session.working === true || live.session.pendingInput === true;
69
+ return live.busy || live.session.working === true || live.session.pendingInput === true || live.session.backgroundWork === true;
84
70
  }
85
71
  const NEVER = { isCancellationRequested: false, onCancellationRequested: () => ({ dispose: () => { } }) };
86
72
  class SessionDriver {
@@ -115,8 +101,6 @@ export function sessionDriverClass(runtime) {
115
101
  /** A Claude process already started in the project the next cold first turn needs, with nothing asked of it, so that turn skips the process start and the MCP servers' connect wait. */
116
102
  spare;
117
103
  nextSpareTryAt = 0;
118
- /** The last reason a warm spare was refused, so the refusal is logged once each time it changes, not on every beat. */
119
- spareRefused;
120
104
  wakePending = false;
121
105
  bootedAt = 0;
122
106
  reaper;
@@ -224,23 +208,6 @@ export function sessionDriverClass(runtime) {
224
208
  this.spare = undefined;
225
209
  return;
226
210
  }
227
- try {
228
- refuseClusterStart("claude");
229
- }
230
- catch (err) {
231
- // OWNER: a warm spare is only a head start, so a refused one must not end the scan — any spare standing is ended, the next beat reads the owner again, and the reason is logged once per change.
232
- if (!(err instanceof AgentTurnFailed))
233
- throw err;
234
- this.spare?.session.end();
235
- this.spare = undefined;
236
- if (this.spareRefused !== err.message)
237
- process.stderr.write(`[agent-gateway] no warm Claude session: ${err.message}
238
- `);
239
- this.spareRefused = err.message;
240
- this.dueBy(Date.now() + SPARE_RETRY_MS);
241
- return;
242
- }
243
- this.spareRefused = undefined;
244
211
  if (this.spare?.project === project)
245
212
  return;
246
213
  if (this.spare === undefined && Date.now() < this.nextSpareTryAt) {
@@ -269,7 +236,7 @@ export function sessionDriverClass(runtime) {
269
236
  };
270
237
  let session;
271
238
  try {
272
- session = claude.open(this.specFor({ project, sessionId, started: false, forkOf: undefined, name: "bn-warm", title: undefined, model: undefined, provider: claude, target }));
239
+ session = claude.open(this.specFor({ project, sessionId, started: false, forkOf: undefined, name: "bn-warm", title: undefined, model: undefined, payer: "subscription", provider: claude, target }));
273
240
  }
274
241
  catch (err) {
275
242
  if (!(err instanceof AgentTurnFailed))
@@ -284,7 +251,7 @@ export function sessionDriverClass(runtime) {
284
251
  /** The spare, if it fits this conversation's first turn in `project`; it is taken out of the pool and the record is given its session id. */
285
252
  takeSpare(c, provider, project) {
286
253
  const spare = this.spare;
287
- if (spare === undefined || provider.name !== "claude" || c.started || c.forkOf !== undefined || this.resuming.has(c.id) || c.model !== undefined || project !== spare.project)
254
+ if (spare === undefined || provider.name !== "claude" || c.started || c.forkOf !== undefined || this.resuming.has(c.id) || c.model !== undefined || c.payer !== "subscription" || project !== spare.project)
288
255
  return undefined;
289
256
  this.spare = undefined;
290
257
  updateConversation(c.id, { sessionId: spare.sessionId });
@@ -301,6 +268,10 @@ export function sessionDriverClass(runtime) {
301
268
  const pid = terminal?.pid;
302
269
  return { working: live !== undefined && (live.busy || live.session.working === true), pendingInput: live?.session.pendingInput === true, nativePid: pid !== undefined && pidAlive(pid) ? pid : undefined, inputVersion: terminal?.inputVersion, nativeModel: live?.session.nativeModel, startupDiagnostic: live?.session.startupDiagnostic };
303
270
  }
271
+ /** The conversations whose CLI is running a background subagent or shell: ending that CLI ends the work, which no later build can take up again. */
272
+ backgroundHolders() {
273
+ return [...this.lives].filter(([, live]) => live.session.backgroundWork === true).map(([id]) => id);
274
+ }
304
275
  /** Hands the store back: the beat stops, every held session's process is ended and awaited, and each conversation keeps its record until the next boot resets it to idle. */
305
276
  async shutdown() {
306
277
  this.stopping = true;
@@ -443,22 +414,14 @@ export function sessionDriverClass(runtime) {
443
414
  if (held !== undefined && held.project === project)
444
415
  return consoleSession(id);
445
416
  if (held !== undefined && inUse(held))
446
- throw new GatewayError(409, `${held.busy ? `Turn ${held.turn} is` : "A prompt typed into its CLI is"} still running in ${basename(held.project)}; this conversation's CLI opens in its new folder once that ends.`);
447
- try {
448
- refuseClusterStart(provider.name);
449
- }
450
- catch (err) {
451
- if (!(err instanceof AgentTurnFailed))
452
- throw err;
453
- throw new GatewayError(409, err.message);
454
- }
417
+ throw new GatewayError(409, `${held.busy ? `Turn ${held.turn} is` : held.session.working === true || held.session.pendingInput === true ? "A prompt typed into its CLI is" : "A background subagent or shell its CLI started is"} still running in ${basename(held.project)}; this conversation's CLI opens in its new folder once that ends.`);
455
418
  if (held !== undefined)
456
419
  this.free(id, "idle");
457
420
  while (this.lives.size >= this.capacity) {
458
421
  const idle = [...this.lives.entries()].filter(([key, l]) => !inUse(l) && !this.watched(key)).sort(([, a], [, b]) => a.usedAt - b.usedAt)[0];
459
422
  // NULL-OK: field idle is OPTIONAL and therefore it is ok to check for NULL
460
423
  if (idle === undefined)
461
- throw new GatewayError(503, `All ${this.capacity} agent slots are mid-turn or open in a browser, so this conversation's CLI cannot be started now — open it again once one finishes.`);
424
+ throw new GatewayError(503, `All ${this.capacity} agent slots are mid-turn, open in a browser or running background subagents, so this conversation's CLI cannot be started now — open it again once one finishes.`);
462
425
  this.free(idle[0], "idle");
463
426
  }
464
427
  let live;
@@ -575,7 +538,7 @@ export function sessionDriverClass(runtime) {
575
538
  if (c.providerArchived !== true || !c.started || unarchive === undefined)
576
539
  return;
577
540
  const target = { id: c.id, onGone: () => { }, isStarted: () => c.started };
578
- const spec = this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
541
+ const spec = this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, payer: c.payer, provider, target });
579
542
  await unarchive(spec, c.sessionId).then(() => { updateConversation(c.id, { providerArchived: undefined }); }, (error) => {
580
543
  appendEvent(c.id, { role: "system", kind: "status", text: `${provider.label} history could not be restored from its archive: ${error.message}` });
581
544
  });
@@ -598,7 +561,7 @@ export function sessionDriverClass(runtime) {
598
561
  this.free(c.id, "idle");
599
562
  const target = { id: c.id, onGone: () => { }, isStarted: () => c.started };
600
563
  const archived = Promise.resolve().then(() => {
601
- const spec = this.specFor({ project: allowedFolder(c.project), sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
564
+ const spec = this.specFor({ project: allowedFolder(c.project), sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, payer: c.payer, provider, target });
602
565
  return archive(spec, c.sessionId);
603
566
  }).then(() => { updateConversation(c.id, { providerArchived: true }); shelve(); }, (error) => {
604
567
  appendEvent(c.id, { role: "system", kind: "status", text: "Codex history could not be archived: " + error.message });
@@ -820,6 +783,7 @@ export function sessionDriverClass(runtime) {
820
783
  name: o.name,
821
784
  title: o.title,
822
785
  model: o.model,
786
+ payer: o.payer,
823
787
  remote: o.remote,
824
788
  ownerPid: this.ownerPid,
825
789
  guardDir: this.guardDir,
@@ -831,7 +795,6 @@ export function sessionDriverClass(runtime) {
831
795
  }
832
796
  /** Opens the conversation's session on the provider its record names, or takes the spare already started for it. */
833
797
  launch(c, provider, project) {
834
- refuseClusterStart(provider.name);
835
798
  let live;
836
799
  const spare = this.takeSpare(c, provider, project);
837
800
  const target = spare?.target ?? { id: c.id, onGone: () => { }, isStarted: () => readConversation(c.id).started === true };
@@ -840,7 +803,7 @@ export function sessionDriverClass(runtime) {
840
803
  if (live !== undefined)
841
804
  this.gone(c.id, live);
842
805
  };
843
- const session = spare?.session ?? provider.open(this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: titleOf({ ...c, project }, transcript(c.id)), model: c.model, remote: c.chat !== undefined, provider, target }));
806
+ const session = spare?.session ?? provider.open(this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: titleOf({ ...c, project }, transcript(c.id)), model: c.model, payer: c.payer, remote: c.chat !== undefined, provider, target }));
844
807
  live = {
845
808
  session, provider, project, busy: true, usedAt: Date.now(), turn: 0, turnStartedAt: Date.now(), logAt: transcript(c.id).at(-1)?.n ?? 0,
846
809
  ended: () => { }, settleStalled: () => { }, stalled: false, lastOutputAt: Date.now(),
@@ -911,7 +874,7 @@ export function sessionDriverClass(runtime) {
911
874
  live.idleTimer = setTimeout(() => {
912
875
  if (this.lives.get(id) !== live || live.busy)
913
876
  return;
914
- if (live.session.working === true || live.session.pendingInput === true || this.watched(id))
877
+ if (inUse(live) || this.watched(id))
915
878
  this.idleLater(id, live);
916
879
  else
917
880
  this.free(id, "idle");
@@ -0,0 +1,13 @@
1
+ /**
2
+ * How a CLI prints one tool call (#4671): a leaf with no imports, so a chat front end that reads a CLI transcript itself
3
+ * (BullseyeNotif) syncs this one file and prints a step the way the session driver does.
4
+ */
5
+ const TOOL_MARKS = { shell: "🔧", bash: "🔧", read: "📖", edit: "✏️", write: "✏️", patch: "✏️", apply_patch: "✏️", grep: "🔎", glob: "🔎", webfetch: "🌐", websearch: "🌐", task: "🧩", skill: "🧩", question: "❓" };
6
+ const TOOL_ARGUMENTS = ["description", "command", "filePath", "file_path", "path", "pattern", "url", "query", "prompt"];
7
+ /** A tool call as a CLI prints it: its mark, its name and what it works on ("🔧 shell — npm run build"). */
8
+ export function toolLine(name, input) {
9
+ const given = TOOL_ARGUMENTS.map((key) => input?.[key]).find((value) => typeof value === "string" && value.trim() !== "");
10
+ // NULL-OK: field given is OPTIONAL and therefore it is ok to check for NULL
11
+ const on = given === undefined ? "" : ` — \`${given.replace(/\s+/g, " ").replace(/`/g, "'").slice(0, 90)}\``;
12
+ return `${TOOL_MARKS[name.toLowerCase()] ?? "🔧"} ${name}${on}`;
13
+ }
@@ -611,6 +611,12 @@ function codexUsesKey(home = os.homedir(), env = process.env) {
611
611
  }
612
612
  return Boolean(env.OPENAI_API_KEY);
613
613
  }
614
+ /** Whether the daemon's own environment carries the key a provider's CLI would run its KEY rung on: the only key BN can hand a CLI it starts. @param {string} provider @param {NodeJS.ProcessEnv} [env] */
615
+ function daemonEnvCarriesKey(provider, env = process.env) {
616
+ if (provider === "claude")
617
+ return anthropicEnvUsesKey(env);
618
+ return provider === "codex" && Boolean(env.OPENAI_API_KEY?.trim());
619
+ }
614
620
  /** The model and key registration the user's configuration supplies to Copilot CLI. */
615
621
  function copilotModelRoute(home = os.homedir(), env = process.env) {
616
622
  const current = path.join(home, ".copilot");
@@ -667,37 +673,52 @@ function roomsOf(answer, now) {
667
673
  function unreadRooms(reason) {
668
674
  return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, { state: "unread", reason }]));
669
675
  }
676
+ // GATE: the order the key rungs are tried in once every subscription is spent — Claude's key, Codex's key, then Copilot, then OpenCode on the keys DeepAgent hands it
677
+ const KEY_RUNG_ORDER = Object.freeze(["claude", "codex", "copilot", "opencode"]);
670
678
  /**
671
- * THE one pick of an agent CLI when the caller named none: of `order` the ones `startable` can run, a provider with room
672
- * first. An automatic conversation can draw on keys only when the eligible subscriptions are spent and DeepAgent's fallback is enabled for a compatible funded key.
679
+ * THE one pick of an agent CLI when the caller named none, as a RUNG (provider x payer): of `order` the ones `startable` can run, a provider with room
680
+ * first on its subscription. An automatic conversation can draw on keys only when the eligible subscriptions are spent and DeepAgent's fallback is enabled for a compatible funded key;
681
+ * that key rung is then the spent provider on its own key, in KEY_RUNG_ORDER.
673
682
  *
674
683
  * 🔴 #14742 — MENI'S OWN RULING IS A THIRD WAY ONTO A KEY, and the caller that owns the story's priority and board says so
675
684
  * with `permittedFundedKey`: he ruled 2026-11-28 that a funded API key may start a P0 money-path story while his Claude
676
685
  * subscription is at its weekly limit. It stands in for "every eligible subscription is spent" and nothing else — a
677
686
  * subscription with room still wins, DeepAgent's fallback box must still be on for that provider, and the key must still
678
687
  * have usable funds, so the allowance can only ever reach a key that was already permitted and funded.
688
+ * A spent provider is offered on its key rung only where `keyInEnv` says the key reaches its CLI (BN hands a CLI no key of its own); a caller passing none keeps the metered-only key rung.
679
689
  * @param {readonly string[]} order @param {ProviderRooms} rooms @param {readonly string[]} startable
680
- * @param {{ home: string, usesKey: (provider: string) => boolean, confirmedRoom?: boolean, permittedFundedKey?: boolean }} [billing]
681
- * @returns {string | undefined}
690
+ * @param {{ home: string, usesKey: (provider: string) => boolean, keyInEnv?: (provider: string) => boolean, confirmedRoom?: boolean, permittedFundedKey?: boolean }} [billing]
691
+ * @returns {{ provider: string, payer: "subscription" | "key" } | undefined}
682
692
  */
683
- function autoProvider(order, rooms, startable, billing) {
693
+ function autoRung(order, rooms, startable, billing) {
684
694
  let candidates = order.filter((p) => startable.includes(p));
685
695
  const metered = new Set(candidates.filter((p) => billing ? billing.usesKey(p) || (runsOnKeys(p) && rooms[p]?.payer !== "subscription") : billsAKey(p, rooms)));
696
+ let keyRung = false;
686
697
  if (billing) {
687
698
  const paid = candidates.filter((p) => !metered.has(p));
688
699
  const withRoom = paid.filter((p) => rooms[p]?.state === "room");
689
700
  const unread = paid.filter((p) => rooms[p]?.state !== "room" && rooms[p]?.state !== "out");
690
701
  const allSpent = billing.permittedFundedKey === true || candidates.every((p) => metered.has(p) && runsOnKeys(p) || rooms[p]?.state === "out");
691
- const allowedKey = (p) => metered.has(p) && readByokFallback(billing.home, AGENT_CLIS.find((cli) => cli.id === p).subscriptionProvider) && rooms[p]?.keys?.some((k) => k.funds === "usable");
702
+ const allowedKey = (p) => (metered.has(p) || (rooms[p]?.state === "out" && billing.keyInEnv?.(p) === true)) && readByokFallback(billing.home, AGENT_CLIS.find((cli) => cli.id === p).subscriptionProvider) && rooms[p]?.keys?.some((k) => k.funds === "usable");
703
+ keyRung = withRoom.length === 0 && !(unread.length > 0 && !billing.confirmedRoom) && allSpent;
692
704
  candidates = withRoom.length > 0 ? withRoom : unread.length > 0 && !billing.confirmedRoom ? unread : allSpent ? candidates.filter(allowedKey) : [];
705
+ if (keyRung && billing.keyInEnv !== undefined)
706
+ candidates.sort((x, y) => KEY_RUNG_ORDER.indexOf(x) - KEY_RUNG_ORDER.indexOf(y));
693
707
  if (billing.confirmedRoom)
694
- return candidates[0];
708
+ return candidates.length === 0 ? undefined : { provider: candidates[0], payer: keyRung ? "key" : "subscription" };
695
709
  }
710
+ if (keyRung)
711
+ return candidates.length === 0 ? undefined : { provider: candidates[0], payer: "key" };
696
712
  const tierOf = (p) => (metered.has(p) ? p + "-byok" : p + "-cli");
697
713
  const rank = (p) => (rooms[p]?.state === "room" ? 0 : 1);
698
714
  const chain = [...candidates].sort((x, y) => rank(x) - rank(y)).map(tierOf);
699
715
  const first = subscriptionFirst({ chain, keyFallback: false })[0];
700
- return candidates.find((p) => tierOf(p) === first);
716
+ const provider = candidates.find((p) => tierOf(p) === first);
717
+ return provider === undefined ? undefined : { provider, payer: metered.has(provider) ? "key" : "subscription" };
718
+ }
719
+ /** The provider of {@link autoRung}'s pick, for a caller that spawns nothing itself. @param {readonly string[]} order @param {ProviderRooms} rooms @param {readonly string[]} startable @param {Parameters<typeof autoRung>[3]} [billing] @returns {string | undefined} */
720
+ function autoProvider(order, rooms, startable, billing) {
721
+ return autoRung(order, rooms, startable, billing)?.provider;
701
722
  }
702
723
  /** @param {string} url @param {string} project @returns {Promise<{ status: number, body: string }>} */
703
724
  async function roomDoorAnswer(url, project) {
@@ -2326,9 +2347,11 @@ module.exports = {
2326
2347
  billsAKey,
2327
2348
  claudeUsesKey,
2328
2349
  codexUsesKey,
2350
+ daemonEnvCarriesKey,
2329
2351
  copilotModelRoute,
2330
2352
  unreadRooms,
2331
2353
  autoProvider,
2354
+ autoRung,
2332
2355
  readProviderRooms,
2333
2356
  coverageOf,
2334
2357
  transientRetried,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.483",
3
+ "version": "1.3.487",
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",