omni-notify-mcp 1.3.376 → 1.3.377

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.
@@ -12,9 +12,8 @@
12
12
  import { fileURLToPath } from "url";
13
13
  import { splitForNotify } from "./chunk.js";
14
14
  import { masterMuted } from "./notify.js";
15
- import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
15
+ import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
16
16
  import { SessionDriver } from "./gateway/sessionDriver.js";
17
- import { DEFAULT_PROVIDER } from "./gateway/provider.js";
18
17
  import { clearOpenCodeLogs } from "./gateway/opencodeProvider.js";
19
18
  import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
20
19
  export const AGENT_PREFIX = "!";
@@ -54,7 +53,7 @@ function driverOptions() {
54
53
  guardDir,
55
54
  spare: process.env.NOTIFY_AGENT_SPARE === "1" ? true : undefined,
56
55
  clis: {
57
- ...(script ? { [DEFAULT_PROVIDER]: { cmd: process.execPath, args: [script] } } : {}),
56
+ ...(script ? { claude: { cmd: process.execPath, args: [script] } } : {}),
58
57
  ...(copilot ? { copilot: { cmd: process.execPath, args: [copilot] } } : {}),
59
58
  ...(codex ? { codex: { cmd: process.execPath, args: [codex] } } : {}),
60
59
  ...(opencode ? { opencode: { cmd: process.execPath, args: [opencode] } } : {}),
@@ -112,9 +111,9 @@ export class AgentGateway {
112
111
  void this.awaitTurn(c.id, Number(turn), (part) => door(c, part), CARRIAGE[c.platform], pending).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)}` }));
113
112
  }
114
113
  }
115
- /** No turn running or queued, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
114
+ /** No turn running or queued, no chat message waiting on its conversation's creation, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
116
115
  quiet() {
117
- return this.driver.quiet() && [...this.turns.values()].every((turns) => turns.size === 0);
116
+ return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
118
117
  }
119
118
  /** Gives the store back when this process hands the gateway over. */
120
119
  async shutdown() {
@@ -177,6 +176,9 @@ export class AgentGateway {
177
176
  return;
178
177
  if (refusal !== undefined)
179
178
  return reply(refusal);
179
+ // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
180
+ for (let pending = creationPending(key); pending !== undefined; pending = creationPending(key))
181
+ await pending;
180
182
  const open = carriage.conversationOf(key);
181
183
  if (act.kind === "stop") {
182
184
  const stopped = carriage.stopOf(key);
@@ -212,10 +214,28 @@ export class AgentGateway {
212
214
  // A conversation opened in a thread the chat already reads starts reading after what was read, never from the thread's root again.
213
215
  // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
214
216
  const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
215
- const created = startConversation({ platform, chat: key, slack, email: origin.email, project, provider: DEFAULT_PROVIDER, text: act.text, receivedMs: monotonicMs() - arrived });
216
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
217
- const told = open === undefined ? [] : [this.told(created.id, 1, `🆕 An independent ask: it runs in its own conversation ${created.id.slice(0, 8)} while ${open.id.slice(0, 8)} keeps working.`)];
218
- return this.awaitTurn(created.id, 1, reply, carriage, told);
217
+ const turn = {};
218
+ const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
219
+ const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
220
+ // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
221
+ const told = open === undefined ? [] : [this.told(created.id, 1, `🆕 An independent ask: it runs in its own conversation ${created.id.slice(0, 8)} while ${open.id.slice(0, 8)} keeps working.`)];
222
+ turn.answered = this.awaitTurn(created.id, 1, reply, carriage, told);
223
+ turn.id = created.id;
224
+ return created;
225
+ })]);
226
+ if (creation.status === "rejected") {
227
+ // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
228
+ if (turn.id === undefined)
229
+ throw creation.reason;
230
+ const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
231
+ process.stderr.write(`[agent-gateway] conversation ${turn.id.slice(0, 8)}: the unread-room notice could not be written (${reason}); the turn runs on and its answer is delivered\n`);
232
+ this.deliver(this.told(turn.id, 1, `⚠️ No CLI was named and DeepAgent's subscription room could not be read; that notice could not be written to this conversation: ${reason}`));
233
+ return turn.answered;
234
+ }
235
+ // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
236
+ if (creation.value.notice !== undefined)
237
+ this.deliver({ ...creation.value.notice, id: creation.value.made.id });
238
+ return turn.answered;
219
239
  }
220
240
  // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
221
241
  if (origin.email !== undefined)
@@ -349,6 +349,7 @@ export const claudeProvider = {
349
349
  name: "claude",
350
350
  label: "Claude Code",
351
351
  command: "claude",
352
+ routesAtRoot: true,
352
353
  nativeArgs: (model) => model ? ["--model", model] : [],
353
354
  open: (spec) => new ClaudeCliSession(spec),
354
355
  };
@@ -15,7 +15,7 @@ import { EventEmitter } from "events";
15
15
  import { basename, dirname, join, resolve } from "path";
16
16
  import { CONFIG_DIR, masterMuted } from "../notify.js";
17
17
  import { PROVIDER_NAMES, providerFor } from "./providers.js";
18
- import { DEFAULT_PROVIDER } from "./provider.js";
18
+ import autoSwitch from "../shared/webhost/autoSwitch.cjs";
19
19
  import { workspacesFile, workspacesHere } from "../shared/webhost/workspaceList.js";
20
20
  /** 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. */
21
21
  export function titleOf(meta, events) {
@@ -211,6 +211,10 @@ export function inScope(meta, viewer) {
211
211
  // NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
212
212
  return meta.chat !== undefined && meta.chat === viewer.creator;
213
213
  }
214
+ /** The creator a scoped caller stamps on a conversation it creates outside its own folder — at the workspace root (#4157) — so it still reads it; one in its own folder is in its scope already and carries none. */
215
+ export function creatorOf(viewer, folder) {
216
+ return viewer === undefined || sameFolder(folder, viewer.folder) ? undefined : viewer.creator;
217
+ }
214
218
  /** A viewer is refused a conversation outside its scope in the words a missing one gets: it never learns another workspace's work exists. */
215
219
  export function requireInScope(meta, viewer) {
216
220
  if (!inScope(meta, viewer))
@@ -609,14 +613,97 @@ export function createdFolder(project) {
609
613
  throw new GatewayError(400, `a new session needs the workspace it runs in: send project as exactly one of ${allowedProjects().join(", ")}`);
610
614
  return allowedFolder(project);
611
615
  }
612
- /** The agent CLI a session is CREATED on, from the name its creation supplied (#3640); a creation that names none runs on the default provider (#4157). */
616
+ /** The agent CLI a session is CREATED on, as its creation named it (#3640): one this gateway runs, or the refusal saying which. */
613
617
  export function namedProvider(provider) {
614
- if (provider === undefined || (typeof provider === "string" && provider.trim() === ""))
615
- return DEFAULT_PROVIDER;
616
618
  if (typeof provider !== "string" || providerFor(provider) === undefined)
617
- throw new GatewayError(400, `provider must be exactly one of ${PROVIDER_NAMES.join(", ")}, or left out for ${DEFAULT_PROVIDER}`);
619
+ throw new GatewayError(400, `provider must be exactly one of ${PROVIDER_NAMES.join(", ")}, or left out for the one with subscription room`);
618
620
  return provider;
619
621
  }
622
+ // GATE: DeepAgent's door, which a creation naming no provider asks for each provider's room, may be moved ONLY under the test gate — to NOTIFY_DEEPAGENT_API, or with none named to the discard port, which refuses at once so a suite never reads this box's live accounts; without the gate it is DeepAgent's own door.
623
+ function deepagentDoor() {
624
+ if (process.env.NOTIFY_MCP_TEST_ENDPOINTS !== "1")
625
+ return undefined;
626
+ return process.env.NOTIFY_DEEPAGENT_API ?? "http://127.0.0.1:9/mcp";
627
+ }
628
+ /**
629
+ * The agent CLI a session is CREATED on (#3640): the one its creation named, or — named none (#4157) — the shared
630
+ * subscription-first pick (`autoProvider`, the one FleetView's AUTO runs) over every CLI this gateway runs — at the
631
+ * workspace root only those that load every project's rules there — weighed by DeepAgent's `provider_room` read for the folder.
632
+ */
633
+ async function pickedCli(provider, folder) {
634
+ if (provider !== undefined && !(typeof provider === "string" && provider.trim() === ""))
635
+ return { provider: namedProvider(provider) };
636
+ const startable = isRootFolder(folder) ? PROVIDER_NAMES.filter((name) => providerFor(name).routesAtRoot === true) : PROVIDER_NAMES;
637
+ if (startable.length === 1) {
638
+ process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${startable[0]}, the one CLI that routes from there\n`);
639
+ return { provider: startable[0] };
640
+ }
641
+ let rooms;
642
+ let unreadBecause;
643
+ try {
644
+ rooms = await autoSwitch.readProviderRooms(folder, deepagentDoor());
645
+ }
646
+ catch (err) {
647
+ if (!(err instanceof autoSwitch.RoomReadError))
648
+ throw err;
649
+ // OWNER: a room DeepAgent could not read is a reading, never a refusal of the creation — every provider is taken as unread with the reason (never as spent), the pick lands on the first subscription in the order, and the conversation it makes carries the reason on its own page.
650
+ rooms = autoSwitch.unreadRooms(err.message);
651
+ unreadBecause = err.message;
652
+ }
653
+ const picked = autoSwitch.autoProvider(PROVIDER_NAMES, rooms, startable);
654
+ const unread = [...new Set(Object.values(rooms).flatMap((r) => (r?.state === "unread" ? [r.reason] : [])))];
655
+ const words = Object.entries(rooms).map(([id, r]) => `${id} ${r?.state}`).join(", ") + (unread.length === 0 ? "" : ` — unread: ${unread.join("; ")}`);
656
+ process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick over ${words}\n`);
657
+ return { provider: picked, ...(unreadBecause === undefined ? {} : { unreadBecause }) };
658
+ }
659
+ /** #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. */
660
+ const creating = new Map();
661
+ /** What an ask from `chat` waits on before it routes: every creation for it still picking its CLI, or undefined — returned without yielding — when there is none. */
662
+ export function creationPending(chat) {
663
+ const pending = creating.get(chat);
664
+ // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
665
+ return pending === undefined ? undefined : Promise.allSettled([...pending]);
666
+ }
667
+ /** Every creation still picking its CLI, whichever chat it is for or none: the gateway does not pass to another process while one is, or the call it carries is dropped. */
668
+ const inFlight = new Set();
669
+ /** Whether any creation is still picking its CLI. */
670
+ export function creationsPending() {
671
+ return inFlight.size > 0;
672
+ }
673
+ /**
674
+ * Creates a session in `folder` with `make` once its CLI is picked (#3640, #4157), registered under the chat `chatOf` names for the folder from the
675
+ * moment it is called, so an ask from that chat waits for it. A room DeepAgent could not read is written onto the session it makes, and that
676
+ * notice is handed back so a chat that started it hears it too.
677
+ */
678
+ export function createdIn(folder, provider, chatOf, make) {
679
+ const creation = pickedCli(provider, folder).then((pick) => {
680
+ const made = make({ project: folder, provider: pick.provider });
681
+ // NULL-OK: field unreadBecause is OPTIONAL and therefore it is ok to check for NULL
682
+ if (pick.unreadBecause === undefined)
683
+ return { made };
684
+ const notice = appendEvent(made.id, { role: "system", kind: "status", ...(readEvents(made.id).some((e) => e.role === "user") ? { turn: 1 } : {}), text: `⚠️ No CLI was named, and DeepAgent's subscription room could not be read (${pick.unreadBecause}), so this runs on ${pick.provider}, the first subscription in the order.` });
685
+ return { made, notice };
686
+ });
687
+ inFlight.add(creation);
688
+ const chat = chatOf(folder);
689
+ // NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
690
+ const pending = chat === undefined ? new Set() : (creating.get(chat) ?? new Set());
691
+ pending.add(creation);
692
+ // NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
693
+ if (chat !== undefined)
694
+ creating.set(chat, pending);
695
+ return creation.finally(() => {
696
+ inFlight.delete(creation);
697
+ pending.delete(creation);
698
+ // NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
699
+ if (chat !== undefined && pending.size === 0 && creating.get(chat) === pending)
700
+ creating.delete(chat);
701
+ });
702
+ }
703
+ /** A session CREATED on the folder and the agent CLI its creation named or left out (#3640, #4157): see `createdIn`. */
704
+ export function createdOn(project, provider, chatOf, make) {
705
+ return createdIn(namedProject(project), provider, chatOf, make);
706
+ }
620
707
  /**
621
708
  * Refuses, in words, a conversation with no CLI of its own to open or stream (#3845, #3916): its record names an agent this gateway does not run.
622
709
  */
@@ -21,7 +21,7 @@ import { performance } from "perf_hooks";
21
21
  import { z } from "zod";
22
22
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
23
23
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24
- import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, namedProject, namedProvider, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversations.js";
24
+ import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, createdOn, creationPending, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversations.js";
25
25
  import { workspacesFile } from "../shared/webhost/workspaceList.js";
26
26
  import { PROVIDER_NAMES } from "./providers.js";
27
27
  import { iconsFor } from "./iconDoor.js";
@@ -90,7 +90,7 @@ function projectField(offer) {
90
90
  }
91
91
  const instructions = (offer) => `BullseyeNotify (BN) runs a Claude Code agent on this machine, with access to the user's files, git repositories, shell, MCP servers, skills and rules.
92
92
  agent_prompt sends the user's request to that agent and returns its answer. It covers questions about the user's projects, files, code, builds and servers.
93
- A NEW conversation needs no project: leave project out whatever the request is about, and the agent runs at the workspace root (${offer.under}), the folder holding every project, exactly as a VS Code window with no workspace would, loading each project's rules so it routes the request to the right project by itself — never choose a project for the user. Name a project only when the user names one: project is exactly one of ${offer.list}, never a path, and agent_projects lists them with their paths. provider is exactly one of ${PROVIDER_NAMES.join(", ")} and defaults when left out. A call that goes on with a conversation that already exists needs neither, because both were bound when it was created.
93
+ A NEW conversation needs no project: leave project out whatever the request is about, and the agent runs at the workspace root (${offer.under}), the folder holding every project, exactly as a VS Code window with no workspace would, loading each project's rules so it routes the request to the right project by itself — never choose a project for the user. Name a project only when the user names one: project is exactly one of ${offer.list}, never a path, and agent_projects lists them with their paths. provider is exactly one of ${PROVIDER_NAMES.join(", ")}; left out, it is the agent CLI whose subscription has room, by DeepAgent's provider_room, subscription before any key. A call that goes on with a conversation that already exists needs neither, because both were bound when it was created.
94
94
  agent_open opens a conversation with no message and starts nothing: it takes project and provider as above, both optional, spends nothing and returns the id of a session to ask with agent_send and read with agent_wait. The folder of an existing conversation is switched with agent_project, which never starts a new agent and never makes a new conversation.
95
95
  An agent that runs in a project works on that project: its own folder is the board it writes to, so work belonging to another project is never done from it — tell the user in one line which project the work belongs to, then start that project's own agent: agent_start with project naming the project and text carrying the request (agent_prompt with project for a quick answer), read its answer with agent_wait and relay it.
96
96
  A request that changes a project is a Story, and the Story belongs on that project's own board: the agent of that project — this conversation's own agent when the work is this project's, the agent this conversation starts with agent_start as above when it belongs to another project — files it or joins it with the bullseye-backlog MCP server that project's folder declares, before any work is done on it. Once a Story is on the board the normal BB → FleetView workflow owns its execution and dispatches the subagents that run it, so BN stays free for the user's questions and follows the Story's progress on the board. A short read-only question or a status check is answered directly. Every agent respects the shared claim store, the one claims file this machine's doors write, so no Story is executed twice: the lane that works a Story claims it when that lane is dispatched, and a message that only names a Story — a question about it, a status check — claims nothing, so it never stands in the way of the lane that works it. The long task in the example below goes the same way: agent_start and agent_wait are how such a request is sent and read, and the Story it becomes is filed and run as above.
@@ -214,7 +214,7 @@ function buildServer(caller, base, offer) {
214
214
  conversation: z.string().min(1).optional().describe("A 'conversation' id an earlier agent_prompt returned, to address that agent; without it the call goes on with this connection's current agent"),
215
215
  new: z.boolean().optional().describe("true starts a fresh agent instead of going on with the current one; with a conversation named it is ignored, because that conversation is addressed as usual"),
216
216
  project: projectField(offer).optional().describe(`The workspace of a NEW conversation: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never taken from the request text`),
217
- provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the default`),
217
+ provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the one whose subscription has room, picked by DeepAgent's provider_room subscription first`),
218
218
  model: z.string().min(1).optional(),
219
219
  }, ({ text, conversation, new: fresh, project, provider, model }) => act(async () => {
220
220
  const call = randomUUID().slice(0, 8);
@@ -222,10 +222,15 @@ function buildServer(caller, base, offer) {
222
222
  const arrival = arrivalOf(requestIdOf(), call);
223
223
  process.stderr.write(`[agent-gateway] agent_prompt ${call} recv trace=${arrival.trace}\n`);
224
224
  // NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
225
- const target = conversation !== undefined ? seen(conversation) : (fresh === true ? undefined : routeAsk(caller, text)?.id);
225
+ const routes = conversation === undefined && fresh !== true;
226
+ // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
227
+ for (let pending = routes ? creationPending(caller) : undefined; pending !== undefined; pending = creationPending(caller))
228
+ await pending;
229
+ // NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
230
+ const target = conversation !== undefined ? seen(conversation) : (routes ? routeAsk(caller, text)?.id : undefined);
226
231
  // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
227
232
  const sent = target === undefined
228
- ? { id: startConversation({ platform: "mcp", technical: true, chat: caller, project: namedProject(project), provider: namedProvider(provider), model, text, receivedMs: Math.round(performance.now() - arrived), arrival }).id, turn: 1 }
233
+ ? { id: (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, model, text, receivedMs: Math.round(performance.now() - arrived), arrival }))).made.id, turn: 1 }
229
234
  : { id: seen(target), turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival).n };
230
235
  const { events, ended, turn } = await waitForTurn(sent.id, sent.turn, MAX_WAIT_SECONDS);
231
236
  const meta = readConversation(sent.id);
@@ -252,15 +257,15 @@ function buildServer(caller, base, offer) {
252
257
  return { ...head, stopped: true, waitedMs, events: others, after };
253
258
  return { ...head, working: true, waitedMs, events: others, after, next: `call agent_wait with id="${sent.id}", after=${after}, wait=${MAX_WAIT_SECONDS} until an event of kind answer, failed or stopped arrives` };
254
259
  }));
255
- server.tool("agent_projects", `The project folders on this machine (the folders under ${offer.under}), each with its absolute path and whether it is a git repository.`, {}, () => act(() => listProjects(viewerNow())));
256
- server.tool("agent_start", `Creates a new conversation AND submits text as its first task (turn 1) in one call, and returns {id, state} at once without waiting for the agent. The way to run a long or autonomous task: read its progress and answer with agent_wait {id, after:1, wait:${MAX_WAIT_SECONDS}}, again with the after each reply returned, until an event of kind answer or failed with turn 1, or of kind stopped, arrives. The task is already submitted, so do not also agent_send the same text, and do not call agent_start again for it — each call starts another agent on the task. agent_prompt sends and waits in one blocking call instead.`, { project: projectField(offer).optional().describe(`The workspace this conversation runs in: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never resolved from the text`), text: z.string().min(1).describe("The first task, submitted by this call itself"), provider: z.string().min(1).optional().describe(`The agent CLI this conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the default`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(() => {
260
+ server.tool("agent_projects", `The project folders on this machine (the folders under ${offer.under}), each with its absolute path and whether it is a git repository. A new conversation need not name one: with no project it runs at ${offer.under} itself, the folder holding them all, and the rules of each project route the request to it.`, {}, () => act(() => listProjects(viewerNow())));
261
+ server.tool("agent_start", `Creates a new conversation AND submits text as its first task (turn 1) in one call, and returns {id, state} at once without waiting for the agent. The way to run a long or autonomous task: read its progress and answer with agent_wait {id, after:1, wait:${MAX_WAIT_SECONDS}}, again with the after each reply returned, until an event of kind answer or failed with turn 1, or of kind stopped, arrives. The task is already submitted, so do not also agent_send the same text, and do not call agent_start again for it — each call starts another agent on the task. agent_prompt sends and waits in one blocking call instead.`, { project: projectField(offer).optional().describe(`The workspace this conversation runs in: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never resolved from the text`), text: z.string().min(1).describe("The first task, submitted by this call itself"), provider: z.string().min(1).optional().describe(`The agent CLI this conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the one whose subscription has room, picked by DeepAgent's provider_room subscription first`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(async () => {
257
262
  const arrived = performance.now();
258
263
  const arrival = arrivalOf(requestIdOf(), randomUUID().slice(0, 8));
259
- const meta = startConversation({ platform: "mcp", technical: true, chat: caller, project: namedProject(project), provider: namedProvider(provider), model, text, receivedMs: Math.round(performance.now() - arrived), arrival });
264
+ const meta = (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, model, text, receivedMs: Math.round(performance.now() - arrived), arrival }))).made;
260
265
  return { id: meta.id, state: meta.state };
261
266
  }));
262
- server.tool("agent_open", `Opens a new conversation with no message and starts no agent: no text, no process started and nothing spent. It returns {id, state} at once. It names the workspace and the agent CLI the conversation opens on — project and provider are both optional: a conversation with no project runs at the workspace root, whose rules route each request to its project, and one with no provider runs on the default CLI. Ask it with agent_send and read it with agent_wait; the folder can be switched afterwards with agent_project, and the conversation keeps its id and its whole transcript.`, { project: projectField(offer).optional().describe(`Exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out for the workspace root (${offer.under}), where the rules of every project route the request; it is never resolved from anything else`), provider: z.string().min(1).optional().describe(`The agent CLI the conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the default`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(() => {
263
- const meta = openConversation({ platform: "mcp", technical: true, chat: caller, project: namedProject(project), provider: namedProvider(provider), model });
267
+ server.tool("agent_open", `Opens a new conversation with no message and starts no agent: no text, no process started and nothing spent. It returns {id, state} at once. It names the workspace and the agent CLI the conversation opens on — project and provider are both optional: a conversation with no project runs at the workspace root, whose rules route each request to its project, and one with no provider runs on the agent CLI whose subscription has room. Ask it with agent_send and read it with agent_wait; the folder can be switched afterwards with agent_project, and the conversation keeps its id and its whole transcript.`, { project: projectField(offer).optional().describe(`Exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out for the workspace root (${offer.under}), where the rules of every project route the request; it is never resolved from anything else`), provider: z.string().min(1).optional().describe(`The agent CLI the conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the one whose subscription has room, picked by DeepAgent's provider_room subscription first`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(async () => {
268
+ const meta = (await createdOn(project, provider, () => caller, (on) => openConversation({ platform: "mcp", technical: true, chat: caller, ...on, model }))).made;
264
269
  return { id: meta.id, state: meta.state };
265
270
  }));
266
271
  server.tool("agent_send", `Sends a message to a conversation that already exists (agent_start or agent_prompt made it) and returns {n} at once without waiting for the agent. n is the message's position in the log and the number of the turn it starts: read its answer with agent_wait {id, after:n, wait:${MAX_WAIT_SECONDS}}. A message sent while a turn runs is queued behind that turn, not an interrupt — also while a conversation's agent waits on a question on its own CLI screen, which the user answers there by opening the conversation in BN, never by a message to it. A stopped or archived conversation resumes. Each call submits its text once more, so do not repeat a send that returned.`, { id: z.string().min(1).describe("The conversation id agent_start returned, or the 'conversation' agent_prompt returned"), text: z.string().min(1).describe("The follow-up message; the first task belongs in agent_start") }, ({ id, text }) => act(() => {
@@ -324,7 +329,7 @@ function buildServer(caller, base, offer) {
324
329
  server.tool("agent_archive", "Archive a conversation: it is stopped and moved off the default list to the Archived list with its transcript kept. agent_list archived=true shows it; a message to it (agent_send or agent_prompt) brings it back and resumes it.", { id: z.string().min(1), restore: z.boolean().default(false).describe("true moves an archived conversation back to the default list instead") }, ({ id, restore }) => act(() => (seen(id), restore ? unarchiveConversation(id) : archiveConversation(id))));
325
330
  server.tool("agent_delete", "Delete a conversation for good: a running agent is stopped first, then the conversation and its transcript are removed from BN. It cannot be undone — agent_archive keeps the transcript instead.", { id: z.string().min(1) }, ({ id }) => act(() => deleteConversation(seen(id))));
326
331
  server.tool("agent_terminals", "The agent CLIs this person has open on this machine (what the CLI page lists) with the CLIs New Agent can open and whether each takes a model; id names one terminal and answers only its facts. A read — it starts nothing.", { id: z.string().min(1).optional().describe("One terminal's conversation id; without it every open terminal is listed beside the CLIs New Agent offers") }, ({ id }) => act(async () => (id === undefined ? scopedListing(await terminalListing(personId())) : (seen(id), nativeTerminal(personId(), id).info()))));
327
- server.tool("agent_terminal_open", `New Agent, as the CLI page's button runs it: opens a conversation's own agent CLI and sizes its screen. Name conversation to open the CLI of one that exists (agent_open or agent_start made it); otherwise a new empty conversation is made on project (exactly one of ${offer.either}, or none for the workspace root) and provider (one of ${PROVIDER_NAMES.join(", ")}, or none for the default), with no turn and nothing spent.`, {
332
+ server.tool("agent_terminal_open", `New Agent, as the CLI page's button runs it: opens a conversation's own agent CLI and sizes its screen. Name conversation to open the CLI of one that exists (agent_open or agent_start made it); otherwise a new empty conversation is made on project (exactly one of ${offer.either}, or none for the workspace root) and provider (one of ${PROVIDER_NAMES.join(", ")}, or none for the one whose subscription has room), with no turn and nothing spent.`, {
328
333
  conversation: z.string().min(1).optional().describe("An existing conversation id whose own CLI to open"),
329
334
  project: projectField(offer).optional(),
330
335
  provider: z.string().min(1).optional(),
@@ -332,7 +337,7 @@ function buildServer(caller, base, offer) {
332
337
  cols: z.number().int().min(1).max(1000).default(100),
333
338
  rows: z.number().int().min(1).max(500).default(30),
334
339
  }, (body) => act(() => { if (typeof body.conversation === "string")
335
- seen(body.conversation.trim()); return openTerminal(body, caller); }));
340
+ seen(body.conversation.trim()); return openTerminal(body, viewerNow()); }));
336
341
  server.tool("agent_terminal_close", "Ends a terminal's CLI process, as the CLI page's Close does; the conversation and its transcript stay and a later message resumes it.", { id: z.string().min(1).describe("The terminal's conversation id") }, ({ id }) => act(() => closeNativeTerminal(personId(), seen(id))));
337
342
  server.tool("agent_terminal_input", "Types raw keystrokes into a terminal's live CLI — what the CLI page sends for every key, answering a question the CLI waits on included. data is text; binary=true means data is base64 bytes. agent_send is the message door; this one is the keyboard.", { id: z.string().min(1), data: z.string().min(1), binary: z.boolean().default(false) }, ({ id, data, binary }) => act(async () => { seen(id); await nativeTerminal(personId(), id).input(data, binary); return { id, sent: true }; }));
338
343
  server.tool("agent_terminal_resize", "Resizes a terminal's screen to whole columns 1-1000 and rows 1-500, as the CLI page does when its window changes.", { id: z.string().min(1), cols: z.number().int(), rows: z.number().int() }, ({ id, cols, rows }) => act(async () => { seen(id); const size = dimensions({ cols, rows }); await nativeTerminal(personId(), id).resize(size.cols, size.rows); return { id, ...size }; }));
@@ -7,8 +7,6 @@ export class AgentTurnFailed extends Error {
7
7
  this.shown = shown;
8
8
  }
9
9
  }
10
- /** The provider a conversation that names none runs on. */
11
- export const DEFAULT_PROVIDER = "claude";
12
10
  /**
13
11
  * The environment every provider starts its CLI in (#2336): the daemon's own, with the project binding pinned to the
14
12
  * folder the agent runs in. BN is ONE daemon on the machine, started by whichever window bound the gateway port first, so
@@ -9,7 +9,7 @@
9
9
  * once a passkey is enrolled the gateway token is honoured only on a request from this machine.
10
10
  */
11
11
  import { createServer } from "http";
12
- import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, namedProject, namedProvider, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversations.js";
12
+ import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversations.js";
13
13
  import { CHAT_HEADERS } from "./chatPage.js";
14
14
  import { isIconPath, serveIcon } from "./iconDoor.js";
15
15
  import { handleMcp } from "./mcpDoor.js";
@@ -138,17 +138,16 @@ async function route(req, url, arrivedAt) {
138
138
  return { status: 200, body: { conversations: shelvedConversations(shelfOf(url), viewer) } };
139
139
  if (method === "POST") {
140
140
  const body = await readJson(req);
141
- const provider = namedProvider(body.provider);
142
141
  const model = typeof body.model === "string" && body.model.length > 0 ? body.model : undefined;
143
- const receivedMs = monotonicMs() - arrivedAt;
144
- const project = namedProject(body.project);
145
142
  // A text that is left out opens an empty conversation (#2723); one that is sent must carry something, so a blank text is still refused.
146
143
  const text = body.text === undefined ? undefined : requiredText(body, "text");
147
- // The workspace and the agent CLI are bound by this call (#3640): the text never resolves either; a call that names none runs at the workspace root on the default CLI (#4157), and a scoped caller is stamped as its creator so it still reads what it started there.
148
- const chat = viewer?.creator;
149
- const meta = text === undefined
150
- ? openConversation({ platform: "rest", chat, project, provider, model })
151
- : startConversation({ platform: "rest", chat, project, provider, model, text, receivedMs });
144
+ // The workspace and the agent CLI are bound by this call (#3640): the text never resolves either; a call that names none runs at the workspace root on the CLI with subscription room (#4157).
145
+ let receivedMs = 0;
146
+ const { made: meta } = await createdOn(body.project, body.provider, (folder) => creatorOf(viewer, folder), (on) => {
147
+ receivedMs = monotonicMs() - arrivedAt;
148
+ const chat = creatorOf(viewer, on.project);
149
+ return text === undefined ? openConversation({ platform: "rest", chat, ...on, model }) : startConversation({ platform: "rest", chat, ...on, model, text, receivedMs });
150
+ });
152
151
  return { status: 201, body: { id: meta.id, state: meta.state, receivedMs } };
153
152
  }
154
153
  }
@@ -1,5 +1,5 @@
1
1
  import { WebSocketServer, WebSocket } from "ws";
2
- import { GatewayError, deleteConversation, namedProject, namedProvider, openConversation, requireOwnCli, requireConversationEnabled, scopedConversation, conversationInScope, viewerOfHeaders } from "./conversations.js";
2
+ import { GatewayError, createdOn, creatorOf, deleteConversation, openConversation, requireOwnCli, requireConversationEnabled, scopedConversation, conversationInScope, viewerOfHeaders } from "./conversations.js";
3
3
  import { closeNativeTerminal, consoleSession, nativeTerminal, nativeTerminals, terminalArriving } from "./nativeTerminal.js";
4
4
  import { AgentGateway } from "../agentGateway.js";
5
5
  import { bearer, bearerAdmitted, fromThisMachine, personId, sessionExpiresAt } from "./passkeyDoor.js";
@@ -182,12 +182,11 @@ export function nativeCatalog() {
182
182
  return PROVIDER_NAMES.map((name) => providerFor(name)).map((provider) => ({ name: provider.name, label: provider.label, model: provider.nativeArgs !== undefined }));
183
183
  }
184
184
  /** The conversation New Agent makes: an empty one on the CLI and folder the form named, with no turn and nothing spent. */
185
- function newAgent(body, chat) {
186
- const provider = providerFor(namedProvider(body.provider));
185
+ async function newAgent(body, viewer) {
187
186
  const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined;
188
187
  if (model !== undefined && !/^[a-zA-Z0-9._:/-]+$/.test(model))
189
188
  throw new GatewayError(400, "Model must be its CLI name, without spaces or shell characters.");
190
- return openConversation({ platform: "rest", chat, project: namedProject(body.project), provider: provider.name, model }).id;
189
+ return (await createdOn(body.project, body.provider, (folder) => creatorOf(viewer, folder), (on) => openConversation({ platform: "rest", chat: creatorOf(viewer, on.project), ...on, model }))).made.id;
191
190
  }
192
191
  /** The conversation's own CLI, opened by the session driver — never a second one — once it is running, or the reason this machine could not start it. */
193
192
  async function opened(id) {
@@ -209,11 +208,11 @@ export async function terminalListing(owner) {
209
208
  return { terminals: await nativeTerminals(owner), providers: nativeCatalog() };
210
209
  }
211
210
  /** New Agent, whole: a conversation made on the CLI and folder the body names (or the one it names), its own CLI opened and sized — what the page's New Agent and agent_terminal_open both run. */
212
- export async function openTerminal(body, creator) {
213
- // New Agent makes a conversation exactly as agent_open does — it names BOTH the CLI that runs and the folder it runs
214
- // in (#3640), neither defaulted — and opens that conversation's own CLI, so a session the browser started and one MCP
211
+ export async function openTerminal(body, viewer) {
212
+ // New Agent makes a conversation exactly as agent_open does — on the CLI and the folder it names, or with none named at
213
+ // the workspace root on the CLI with subscription room (#4157) — and opens that conversation's own CLI, so a session the browser started and one MCP
215
214
  // started are one kind: the same driven CLI, typed into by agent_send and shown here (#3916).
216
- const terminal = typeof body.conversation === "string" && body.conversation.trim().length > 0 ? await opened(body.conversation.trim()) : await openedNew(newAgent(body, creator));
215
+ const terminal = typeof body.conversation === "string" && body.conversation.trim().length > 0 ? await opened(body.conversation.trim()) : await openedNew(await newAgent(body, viewer));
217
216
  const size = dimensions(body);
218
217
  await terminal.resize(size.cols, size.rows);
219
218
  return terminal.info();
@@ -233,7 +232,7 @@ export async function terminalRoute(req, url, readJson) {
233
232
  const body = await readJson();
234
233
  if (typeof body.conversation === "string" && viewer !== undefined)
235
234
  scopedConversation(body.conversation.trim(), viewer);
236
- return { status: 201, body: await openTerminal(body, viewer?.creator) };
235
+ return { status: 201, body: await openTerminal(body, viewer) };
237
236
  }
238
237
  }
239
238
  if (viewer !== undefined)
@@ -181,8 +181,8 @@ async function newAgentView(){
181
181
  var mine=show("new","New Agent");
182
182
  var setup=el("div","setup"),provider=el("select"),project=el("select"),model=el("input"),open=el("button","go","▶ New Agent");
183
183
  provider.setAttribute("aria-label","CLI provider");project.setAttribute("aria-label","Project");model.setAttribute("aria-label","Model");model.placeholder="Model (CLI default if empty)";
184
- // Neither select forces a pick (#4157): no workspace runs the agent at the workspace root, where the rules of every project route each prompt, and no CLI runs the default one.
185
- var cliPlaceholder=el("option","","Default CLI"),folderPlaceholder=el("option","","Workspace root (any project)");
184
+ // Neither select forces a pick (#4157): no workspace runs the agent at the workspace root, where the rules of every project route each prompt, and no CLI runs the one whose subscription has room.
185
+ var cliPlaceholder=el("option","","CLI with room (subscription first)"),folderPlaceholder=el("option","","Workspace root (any project)");
186
186
  cliPlaceholder.value="";folderPlaceholder.value="";provider.append(cliPlaceholder);project.append(folderPlaceholder);
187
187
  setup.append(provider,project,model,open);main.append(setup);
188
188
  var folders=[],catalog=[];
@@ -192,7 +192,7 @@ async function newAgentView(){
192
192
  open.disabled=catalog.length===0;
193
193
  note.textContent=catalog.length===0
194
194
  ?"This gateway lists no CLI to run."
195
- :"Starts a session with "+(chosen?(chosen.label||chosen.name):"the default CLI")+" "+(project.value===""?"at the workspace root, where each prompt is routed to its project":"in "+project.value)+". Its conversation then opens in the same view.";
195
+ :"Starts a session with "+(chosen?(chosen.label||chosen.name):"the CLI whose subscription has room")+" "+(project.value===""?"at the workspace root, where each prompt is routed to its project":"in "+project.value)+". Its conversation then opens in the same view.";
196
196
  }
197
197
  try{var listed=await api("GET","/v1/projects");if(mine!==view)return;folders=listed.projects.filter(function(p){return p.board;});folders.forEach(function(p){var option=el("option","",p.name);option.value=p.name;project.append(option);});
198
198
  var sessions=await api("GET","/v1/terminals");if(mine!==view)return;
@@ -2006,7 +2006,7 @@ export function newerVersion(a, b) {
2006
2006
  /** 🔴 #4156 — a move named an entry that is no longer in line on the board: withdrawn, finished or failed out between the press and the queue's lock. */
2007
2007
  export class NotInQueue extends Error {
2008
2008
  constructor(board, storyId) {
2009
- super(`#${storyId} is not in FleetView's queue on ${board}, so it has no place to move`);
2009
+ super(`#${storyId} is no longer in FleetView's queue on ${board}`);
2010
2010
  this.name = "NotInQueue";
2011
2011
  }
2012
2012
  }
@@ -2594,6 +2594,8 @@ export async function driveStoryQueue(board, world, now) {
2594
2594
  }
2595
2595
  }
2596
2596
  save();
2597
+ // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
2598
+ const halted = store.stopped === undefined ? undefined : `the queue is stopped (${store.stopped.by}), so nothing more starts or wakes until ▶ Run`;
2597
2599
  let lanes = world.lanesRunning();
2598
2600
  for (const e of queueOrder(store)) {
2599
2601
  const sessionId = wakeable.get(e);
@@ -2606,6 +2608,11 @@ export async function driveStoryQueue(board, world, now) {
2606
2608
  e.why = `${held} works it, so its parked worker ${parked.jobId} is not woken beside it`;
2607
2609
  continue;
2608
2610
  }
2611
+ // NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
2612
+ if (halted !== undefined) {
2613
+ e.why = `its worker ${parked.jobId} is parked, and ${halted}`;
2614
+ continue;
2615
+ }
2609
2616
  if (lanes >= world.limit) {
2610
2617
  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`;
2611
2618
  continue;
@@ -2662,10 +2669,18 @@ export async function driveStoryQueue(board, world, now) {
2662
2669
  e.why = `${held} works it, so the queue starts no second worker`;
2663
2670
  continue;
2664
2671
  }
2665
- if (lanes >= world.limit) {
2672
+ // NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
2673
+ if (halted !== undefined && e.forced !== true) {
2674
+ e.why = halted;
2675
+ continue;
2676
+ }
2677
+ if (lanes >= world.limit && e.forced !== true) {
2666
2678
  e.why = `${lanes} lanes run and the lane limit is ${world.limit}, so it starts when one finishes`;
2667
2679
  continue;
2668
2680
  }
2681
+ // NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
2682
+ const forced = e.forced === true && (halted !== undefined || lanes >= world.limit);
2683
+ delete e.forced;
2669
2684
  // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
2670
2685
  if (e.worker !== undefined && world.worker(e, board).alive) {
2671
2686
  e.state = "running";
@@ -2676,7 +2691,7 @@ export async function driveStoryQueue(board, world, now) {
2676
2691
  e.state = "starting";
2677
2692
  e.attempts += 1;
2678
2693
  delete e.worker;
2679
- step(e, now, "selected", `start ${e.attempts}${e.attempts > WORKER_ATTEMPTS ? ", past the attempts a story is given" : ` of ${WORKER_ATTEMPTS}`}, with ${lanes} of ${world.limit} lanes running`);
2694
+ step(e, now, "selected", `start ${e.attempts}${e.attempts > WORKER_ATTEMPTS ? ", past the attempts a story is given" : ` of ${WORKER_ATTEMPTS}`}, with ${lanes} of ${world.limit} lanes running${forced ? ` — his ⚡ Force start, past ${halted === undefined ? "the lane limit" : "the queue's ⏸ Stop"}` : ""}`);
2680
2695
  save();
2681
2696
  lanes += 1;
2682
2697
  try {
@@ -2714,6 +2729,101 @@ export async function driveStoryQueue(board, world, now) {
2714
2729
  return store;
2715
2730
  });
2716
2731
  }
2732
+ /** 🔴 #4156 — a press on one story of the queue that does not apply to it as it stands: the words say why and what it reads. */
2733
+ export class StoryPressRefused extends Error {
2734
+ constructor(message) {
2735
+ super(message);
2736
+ this.name = "StoryPressRefused";
2737
+ }
2738
+ }
2739
+ /**
2740
+ * 🔴 #4156 — HIS PRESS ON ONE STORY OF FLEETVIEW'S QUEUE, under the queue's lock: ✕ Remove takes it out of the line (BullseyeBacklog's
2741
+ * next new request puts it back), ↻ Retry puts a failed or retrying story back in line with its attempts reset, ⚡ Force start starts
2742
+ * it on the next pass past the lane limit and a ⏸ Stop, 🔔 Nudge ends the wait it stands on (a retry's backoff, a parked worker's wake delay), and
2743
+ * 🔓 Unblock answers what holds it — the queue keeps no hold of its own on a story. A press that does not apply throws
2744
+ * {@link StoryPressRefused}; one on a story no longer in line throws {@link NotInQueue}. Answers what it did, in words.
2745
+ */
2746
+ export async function pressStory(board, storyId, press, now) {
2747
+ return withQueueLock(board, now, async () => {
2748
+ const store = readQueueStore(board);
2749
+ const e = store.entries.find((x) => x.storyId === storyId && IN_LINE.has(x.state));
2750
+ if (e === undefined)
2751
+ throw new NotInQueue(board, storyId);
2752
+ const working = e.state === "starting" || e.state === "running";
2753
+ // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
2754
+ const afterStop = store.stopped === undefined ? "" : " after ▶ Run lifts the queue's ⏸ Stop";
2755
+ let did;
2756
+ if (press === "remove") {
2757
+ if (working)
2758
+ throw new StoryPressRefused(`#${storyId} has a worker at work — ✕ Remove takes a waiting story out of the line, and ⛔ Kill on its lane stops a worker`);
2759
+ e.state = "withdrawn";
2760
+ delete e.forced;
2761
+ e.why = "his ✕ Remove took it out of the line — BullseyeBacklog's next new request for it puts it back";
2762
+ step(e, now, "withdrawn", e.why);
2763
+ did = `#${storyId} is out of the line`;
2764
+ }
2765
+ else if (press === "retry") {
2766
+ if (e.state !== "failed" && e.state !== "retrying")
2767
+ throw new StoryPressRefused(`#${storyId} is ${e.state}, and ↻ Retry puts back only a failed or retrying story`);
2768
+ e.state = "queued";
2769
+ e.attempts = 0;
2770
+ delete e.nextTryAt;
2771
+ e.why = "his ↻ Retry put it back in line with its attempts reset";
2772
+ step(e, now, "retry", e.why);
2773
+ did = `#${storyId} is back in line`;
2774
+ }
2775
+ else if (press === "force") {
2776
+ if (working)
2777
+ throw new StoryPressRefused(`#${storyId} already has a worker at work, so there is nothing to force`);
2778
+ e.state = "queued";
2779
+ delete e.nextTryAt;
2780
+ e.forced = true;
2781
+ e.why = "his ⚡ Force start starts it on the next pass, past the lane limit and a ⏸ Stop";
2782
+ step(e, now, "placed", e.why);
2783
+ did = `#${storyId} starts on the next pass, past the lane limit`;
2784
+ }
2785
+ else if (press === "nudge") {
2786
+ const parked = e.state === "running" ? e.worker : undefined;
2787
+ // NULL-OK: field parkedAt is OPTIONAL and therefore it is ok to check for NULL
2788
+ if (parked?.parkedAt !== undefined) {
2789
+ parked.parkedAt = now - wakeDelayMs(parked.wakes ?? 0);
2790
+ e.why = `his 🔔 Nudge ended its parked worker ${parked.jobId}'s wake delay, so it is woken on the next pass${afterStop}`;
2791
+ did = `#${storyId}'s worker is woken on the next pass${afterStop}`;
2792
+ // NULL-OK: field nextTryAt is OPTIONAL and therefore it is ok to check for NULL
2793
+ }
2794
+ else if (e.nextTryAt !== undefined && e.nextTryAt > now) {
2795
+ e.nextTryAt = now;
2796
+ e.why = `his 🔔 Nudge ended its wait, so it is tried on the next pass${afterStop}`;
2797
+ did = `#${storyId} is tried on the next pass${afterStop}`;
2798
+ }
2799
+ else {
2800
+ throw new StoryPressRefused(`#${storyId} waits on nothing a nudge ends — it reads: ${e.why}${e.state === "queued" ? "; ⚡ Force start runs it past the lane limit" : ""}`);
2801
+ }
2802
+ step(e, now, "retry", e.why);
2803
+ }
2804
+ else {
2805
+ throw new StoryPressRefused(`#${storyId} carries no hold — FleetView's queue keeps none of its own on a story; it reads: ${e.why}`);
2806
+ }
2807
+ writeWhole(board, storeFile(board), store);
2808
+ writeAcks(board, store, new Map(), new Map([[e.storyId, e.requestId]]), now);
2809
+ return did;
2810
+ });
2811
+ }
2812
+ /** 🔴 #4156 — his ▶ Run or ⏸ Stop on the board's queue: stopped, nothing more starts or wakes until he runs it again; workers already running carry on. Answers whether it changed. */
2813
+ export async function setStoryQueueStopped(board, stopped, by, now) {
2814
+ return withQueueLock(board, now, async () => {
2815
+ const store = readQueueStore(board);
2816
+ // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
2817
+ if ((store.stopped !== undefined) === stopped)
2818
+ return false;
2819
+ if (stopped)
2820
+ store.stopped = { at: now, by };
2821
+ else
2822
+ delete store.stopped;
2823
+ writeWhole(board, storeFile(board), store);
2824
+ return true;
2825
+ });
2826
+ }
2717
2827
  /** His placement of one story in FleetView's queue: a 0-based place, or `auto` to hand it back to priority and size. */
2718
2828
  export async function placeStory(board, storyId, place, now) {
2719
2829
  return withQueueLock(board, now, async () => {
@@ -2730,6 +2840,37 @@ export async function placeStory(board, storyId, place, now) {
2730
2840
  return e;
2731
2841
  });
2732
2842
  }
2843
+ /** 🔴 #4154 — FleetView's investigator ruled ABORT on the worker `jobId` of this story: its entry leaves the line, so the stopped worker is never woken, and his next Start press brings the story back; undefined when no entry in line runs that worker. */
2844
+ export async function withdrawStory(board, storyId, jobId, why, now) {
2845
+ return withQueueLock(board, now, async () => {
2846
+ const store = readQueueStore(board);
2847
+ const e = store.entries.find((x) => x.storyId === storyId && IN_LINE.has(x.state) && x.worker?.jobId === jobId);
2848
+ if (e === undefined)
2849
+ return undefined;
2850
+ e.state = "withdrawn";
2851
+ e.why = why;
2852
+ step(e, now, "withdrawn", why);
2853
+ writeWhole(board, storeFile(board), store);
2854
+ return e;
2855
+ });
2856
+ }
2857
+ /** 🔴 #4154 — a decision's message put to the queue's own worker `jobId` of this story: the job is stopped and woken in its own session with the message, and the entry carries the woken job, so the queue never reads it as ended and starts a second worker; undefined when no entry in line runs that worker. */
2858
+ export async function rewakeStoryWorker(board, storyId, jobId, sessionId, message, cli, now) {
2859
+ return withQueueLock(board, now, async () => {
2860
+ const store = readQueueStore(board);
2861
+ const e = store.entries.find((x) => x.storyId === storyId && IN_LINE.has(x.state) && x.worker?.jobId === jobId);
2862
+ if (e === undefined)
2863
+ return undefined;
2864
+ const parked = e.worker;
2865
+ await stopStoryWorker(jobId, cli);
2866
+ const woken = await wakeStoryWorker(sessionId, message, board, cli, now);
2867
+ e.worker = { ...woken, wakes: (parked.wakes ?? 0) + 1, ...keptSession(parked) };
2868
+ e.why = `FleetView's investigator redirected its worker ${jobId}, woken in its own session as ${woken.jobId}`;
2869
+ step(e, now, "woken", e.why);
2870
+ writeWhole(board, storeFile(board), store);
2871
+ return woken;
2872
+ });
2873
+ }
2733
2874
  const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? path.join(homedir(), ".claude");
2734
2875
  /** A Claude Code record: its JSON, `gone` when Claude Code has none there (deleted, or an entry that is not a record), or `torn` when it was read mid-rewrite — Claude Code rewrites and deletes them in place. */
2735
2876
  function claudeRecordOf(file) {
@@ -3098,8 +3239,12 @@ export function purgeStoryWorker(sessions, home = claudeHome(), temp = tmpdir())
3098
3239
  const LAUNCH_TIMEOUT_MS = 60_000;
3099
3240
  /** 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. */
3100
3241
  export function launchStoryWorker(entry, board, cli, now) {
3242
+ return launchClaudeJob(entry.name, entry.model, workerBrief(entry), board, cli, now);
3243
+ }
3244
+ /** 🔴 #4154 — one windowless `claude --bg` job started in `cwd` under `name` with `brief` as its opening prompt: a story's worker, or FleetView's investigator of a lane. */
3245
+ export function launchClaudeJob(name, model, brief, cwd, cli, now) {
3101
3246
  return new Promise((resolve, reject) => {
3102
- 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) => {
3247
+ execFile(cli.cmd, [...cli.args, "--bg", "--name", name, "--model", model, "--permission-mode", "bypassPermissions", brief], { cwd, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
3103
3248
  const said = `${stdout}${stderr}`;
3104
3249
  const job = /^backgrounded · (\S+) · /m.exec(said);
3105
3250
  if (job !== null)
@@ -439,6 +439,115 @@ function subscriptionFirst({ chain, kinds = {}, kind, keyFallback }) {
439
439
  const rung = keyFallback ? keyRungOf({ chain, kinds, kind }) : undefined;
440
440
  return [...new Set([...chain.filter(paid), ...chain.filter((tier) => !paid(tier)), ...(rung === undefined ? [] : [rung])])];
441
441
  }
442
+ /** Where DeepAgent's server answers on this machine. */
443
+ const DEEPAGENT_DOOR = "http://127.0.0.1:7473";
444
+ /** Its MCP door — every dispatcher asks it for each provider's token room (`provider_room`). */
445
+ const DEEPAGENT_MCP_URL = `${DEEPAGENT_DOOR}/mcp`;
446
+ // GATE: how long one `provider_room` read may take before it is a failed reading — twenty seconds, the span ChatGPT's own answer needs for every Codex subscription; past it the room is "could not be read" and the caller keeps its own landing.
447
+ const ROOM_READ_TIMEOUT_MS = 20_000;
448
+ /** The agent CLIs whose subscriptions `provider_room` reads; OpenCode runs on keys and is never among them. */
449
+ const ROOM_PROVIDERS = Object.freeze(["claude", "codex", "copilot"]);
450
+ /** `provider_room` answered anything but a reading: the door gave no answer, a non-200, or a body that is no reading. */
451
+ class RoomReadError extends Error {
452
+ }
453
+ /**
454
+ * @typedef {{ state: "room" } | { state: "out", resetsAtMs: number | undefined } | { state: "unread", reason: string }} RoomReading
455
+ * @typedef {Partial<Record<string, RoomReading>>} ProviderRooms
456
+ */
457
+ /** @param {string} provider */
458
+ function runsOnKeys(provider) {
459
+ return provider === "opencode";
460
+ }
461
+ /** @param {string} provider @param {ProviderRooms} rooms */
462
+ function billsAKey(provider, rooms) {
463
+ return runsOnKeys(provider) || rooms[provider]?.state === "out";
464
+ }
465
+ /**
466
+ * One provider's token room out of its `provider_room` entry: some left, spent until a refill, or a reading that could not be taken (never read as spent).
467
+ * @param {any} provider @param {number} now @returns {RoomReading}
468
+ */
469
+ function roomReadingOf(provider, now) {
470
+ // NULL-OK: field provider is OPTIONAL and therefore it is ok to check for NULL
471
+ if (provider === undefined || provider.state !== "read" || !Array.isArray(provider.accounts)) {
472
+ return { state: "unread", reason: typeof provider?.reason === "string" ? provider.reason : "the provider was not read" };
473
+ }
474
+ const accounts = provider.accounts;
475
+ if (accounts.some((a) => a.state === "read" && a.refused !== true && (a.unlimited === true || (typeof a.roomPct === "number" && a.roomPct > 0))))
476
+ return { state: "room" };
477
+ if (accounts.length === 0 || !accounts.every((a) => a.state === "read" && typeof a.roomPct === "number"))
478
+ return { state: "unread", reason: "an account's room could not be read" };
479
+ if (accounts.some((a) => a.refused !== true && typeof a.resetsAt === "number" && a.resetsAt <= now))
480
+ return { state: "unread", reason: "the reading predates an account's refill" };
481
+ const refills = accounts.filter((a) => a.refused !== true).map((a) => a.resetsAt).filter((r) => typeof r === "number");
482
+ return { state: "out", resetsAtMs: refills.length === 0 ? undefined : Math.min(...refills) };
483
+ }
484
+ /**
485
+ * The room of each provider a dispatcher can land on, out of `provider_room`'s own answer. A provider the answer does not carry is unread, never out.
486
+ * @param {{ providers?: Record<string, any> }} answer @param {number} now @returns {ProviderRooms}
487
+ */
488
+ function roomsOf(answer, now) {
489
+ return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, roomReadingOf(answer.providers?.[id], now)]));
490
+ }
491
+ /** Every provider unread, with the reason the whole reading failed. @param {string} reason @returns {ProviderRooms} */
492
+ function unreadRooms(reason) {
493
+ return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, { state: "unread", reason }]));
494
+ }
495
+ /**
496
+ * THE one pick of an agent CLI when the caller named none: of `order` the ones `startable` can run, a provider with room
497
+ * first, and `subscriptionFirst` ranking a subscription with room before anything that bills a key.
498
+ * @param {readonly string[]} order @param {ProviderRooms} rooms @param {readonly string[]} startable @returns {string}
499
+ */
500
+ function autoProvider(order, rooms, startable) {
501
+ const candidates = order.filter((p) => startable.includes(p));
502
+ const tierOf = (p) => (billsAKey(p, rooms) ? p + "-byok" : p + "-cli");
503
+ const rank = (p) => (rooms[p]?.state === "room" ? 0 : 1);
504
+ const chain = [...candidates].sort((x, y) => rank(x) - rank(y)).map(tierOf);
505
+ const first = subscriptionFirst({ chain, keyFallback: false })[0];
506
+ return candidates.find((p) => tierOf(p) === first);
507
+ }
508
+ /** @param {string} url @param {string} project @returns {Promise<{ status: number, body: string }>} */
509
+ async function roomDoorAnswer(url, project) {
510
+ try {
511
+ const res = await fetch(url, {
512
+ method: "POST",
513
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "x-deepagent-project": project },
514
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "provider_room", arguments: {} } }),
515
+ signal: AbortSignal.timeout(ROOM_READ_TIMEOUT_MS),
516
+ });
517
+ return { status: res.status, body: await res.text() };
518
+ }
519
+ catch (err) {
520
+ if (!(err instanceof TypeError) && !(err instanceof Error && err.name === "TimeoutError"))
521
+ throw err;
522
+ const cause = err.cause instanceof Error ? ` (${err.cause.message})` : "";
523
+ throw new RoomReadError(`DeepAgent's door at ${url} gave no answer: ${err.message}${cause}`);
524
+ }
525
+ }
526
+ /** @param {string} text @param {string} what */
527
+ function roomParsedOf(text, what) {
528
+ try {
529
+ return JSON.parse(text);
530
+ }
531
+ catch (err) {
532
+ if (!(err instanceof SyntaxError))
533
+ throw err;
534
+ throw new RoomReadError(`provider_room's ${what} is not JSON (${err.message}): ${text.slice(0, 200)}`);
535
+ }
536
+ }
537
+ /**
538
+ * Asks DeepAgent's `provider_room` over its MCP door, for the folder `project` names. Throws RoomReadError when the door answers anything but a reading.
539
+ * @param {string} project @param {string} [url] @param {() => number} [now] @returns {Promise<ProviderRooms>}
540
+ */
541
+ async function readProviderRooms(project, url = DEEPAGENT_MCP_URL, now = Date.now) {
542
+ const { status, body } = await roomDoorAnswer(url, project);
543
+ if (status !== 200)
544
+ throw new RoomReadError(`provider_room answered HTTP ${status}: ${body.slice(0, 200)}`);
545
+ const reply = roomParsedOf(body, "reply");
546
+ const text = reply.result?.content?.[0]?.text;
547
+ if (reply.result === undefined || reply.result.isError === true || text === undefined)
548
+ throw new RoomReadError(`provider_room gave no reading: ${(text ?? reply.error?.message ?? body).slice(0, 200)}`);
549
+ return roomsOf(roomParsedOf(text, "reading"), now());
550
+ }
442
551
  /**
443
552
  * Whether the live work has an account with room to run on, worked out from the readings alone and never from a
444
553
  * decision's words: covered when the live account read room, uncovered when it read spent (or nobody is logged in and
@@ -1182,7 +1291,7 @@ function sameHome(home) {
1182
1291
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
1183
1292
  }
1184
1293
  /** DeepAgent's resident server, the one process that decides this box's accounts while it answers (#3654). */
1185
- const DECIDER_DOOR = process.env.BULLSEYE_DECIDER_DOOR || "http://127.0.0.1:7473";
1294
+ const DECIDER_DOOR = process.env.BULLSEYE_DECIDER_DOOR || DEEPAGENT_DOOR;
1186
1295
  // GATE: how long a mover waits for DeepAgent's server to answer before it reads the server as not deciding and the pad decides
1187
1296
  const DECIDER_ASK_MS = 5000;
1188
1297
  /**
@@ -1739,6 +1848,12 @@ module.exports = {
1739
1848
  writeByokKey,
1740
1849
  decide,
1741
1850
  subscriptionFirst,
1851
+ RoomReadError,
1852
+ runsOnKeys,
1853
+ billsAKey,
1854
+ unreadRooms,
1855
+ autoProvider,
1856
+ readProviderRooms,
1742
1857
  coverageOf,
1743
1858
  transientRetried,
1744
1859
  firstRefillAt,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.376",
3
+ "version": "1.3.377",
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",