omni-notify-mcp 1.3.317 → 1.3.319

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.
@@ -727,13 +727,9 @@ async function listView(shelf) {
727
727
  run();
728
728
  }
729
729
  `;
730
- /** What a service page adds to the shared look: one card per VS Code window, with its screens. */
731
- const SERVICE_STYLE = `.win{border:1px solid var(--line);border-radius:10px;margin:0 0 8px;padding:10px}
732
- .win h3{margin:0 0 6px;font-size:15px;overflow-wrap:anywhere}.win p{color:var(--mut);font-size:14px;margin:4px 0}
733
- .win .screens{display:flex;flex-wrap:wrap;gap:8px}`;
734
- /** A service page's own half (#2877): every VS Code window running this extension on the machine, and in each the
735
- * extension's own screens. A press opens that screen itself — the page VS Code shows, with the same buttons answered by
736
- * the same extension code — through the gateway's `/screen/open`, which keeps the sign-in for the screen's own requests. */
730
+ /** A service page's own half (#3849): once signed in, the gateway's `/screen/open` keeps the sign-in for the page's own
731
+ * requests and names the one page this host's always-on service draws, and the visitor goes straight to it — no VS Code
732
+ * window is chosen or needed. */
737
733
  const SERVICE_SCRIPT = String.raw `
738
734
  var main = document.getElementById("main"), title = document.getElementById("title"), btnRefresh = document.getElementById("refresh");
739
735
  var view = 0;
@@ -747,70 +743,28 @@ function show(name, heading) {
747
743
  main.replaceChildren();
748
744
  return view;
749
745
  }
750
- async function windows() {
751
- var res = await fetch("/screen/list", { headers: { authorization: "Bearer " + token } });
752
- if (res.status === 401) { signIn("You are signed out. Sign in again."); throw new Error("signed out"); }
753
- if (!res.ok) throw new Error("The gateway answered " + res.status + ": " + await res.text());
754
- return (await res.json()).windows;
755
- }
756
- async function openScreen(win, page, button, note) {
757
- button.disabled = true; note.textContent = "";
758
- try {
759
- var res = await fetch("/screen/open", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer " + token }, body: JSON.stringify({ window: win }) });
760
- if (res.status === 401) { signIn("You are signed out. Sign in again."); return; }
761
- if (!res.ok) { note.textContent = "The gateway answered " + res.status + ": " + await res.text(); button.disabled = false; return; }
762
- location.assign("/" + encodeURIComponent(page) + "/?window=" + win);
763
- } catch (err) { if (!(err instanceof Error)) throw err; note.textContent = err.message; button.disabled = false; }
764
- }
765
- async function windowState(win) {
766
- var res = await fetch("/screen/state?window=" + win, { headers: { authorization: "Bearer " + token } });
767
- if (res.status === 401) { signIn("You are signed out. Sign in again."); throw new Error("signed out"); }
768
- if (!res.ok) throw new Error("The gateway answered " + res.status + ": " + await res.text());
769
- return res.json();
770
- }
771
- function windowCard(win, mine) {
772
- var box = el("section", "win"), row = el("div", "screens"), said = el("p", "", "⏳ Checking this window…"), note = el("div", "err");
773
- box.append(el("h3", "", win.label), said);
774
- var buttons = win.pages.map(function (page) {
775
- var button = el("button", "", "⏳ " + page.title);
776
- button.disabled = true;
777
- button.onclick = function () { openScreen(win.window, page.name, button, note); };
778
- row.append(button);
779
- return button;
780
- });
781
- box.append(row, note);
782
- windowState(win.window).then(function (state) {
783
- if (mine !== view) return;
784
- said.textContent = state.answering ? "🟢 open in VS Code · ⚪ not open there — its page offers to open it" : "⚪ This window does not answer: " + state.reason + ".";
785
- win.pages.forEach(function (page, i) {
786
- var live = state.answering && state.pages[page.name];
787
- buttons[i].textContent = (live ? "🟢 " : "⚪ ") + page.title;
788
- buttons[i].className = live ? "go" : "";
789
- buttons[i].disabled = !state.answering;
790
- });
791
- }, function (err) { if (mine === view && err.message !== "signed out") said.textContent = "⛔ Could not check this window: " + err.message; });
792
- return box;
793
- }
794
746
  async function home() {
795
747
  var mine = show("screens", TITLE);
796
748
  btnRefresh.onclick = function () { home(); };
749
+ var said = el("p", "system", "⏳ Opening " + TITLE + "…");
750
+ main.append(said);
797
751
  try {
798
- var found = await windows();
799
- if (mine !== view) return;
800
- if (!found.length) { main.append(el("p", "system", TITLE + " is not running in any VS Code window on this machine right now.")); return; }
801
- found.forEach(function (win) { main.append(windowCard(win, mine)); });
802
- } catch (err) { if (!(err instanceof Error)) throw err; if (mine === view && err.message !== "signed out") main.append(el("div", "err", err.message)); }
752
+ var res = await fetch("/screen/open", { method: "POST", headers: { authorization: "Bearer " + token } });
753
+ if (res.status === 401) { signIn("You are signed out. Sign in again."); return; }
754
+ if (!res.ok) throw new Error("The gateway answered " + res.status + ": " + await res.text());
755
+ var opened = await res.json();
756
+ if (mine === view) location.replace(opened.page);
757
+ } catch (err) { if (!(err instanceof Error)) throw err; if (mine === view) said.replaceWith(el("div", "err", err.message)); }
803
758
  }
804
759
  `;
805
- /** The page each service host of the public gateway serves (#2873): BN's look and BN's sign-in, with the service's own
806
- * screens where BN shows its one page. The line under the header names the process that answered. */
760
+ /** The page each service host of the public gateway serves (#2873): BN's look and BN's sign-in, then the page the
761
+ * service's always-on process draws. The line under the header names the process that answered. */
807
762
  export function serviceHtml({ name, host }) {
808
763
  const me = servingIdentity();
809
764
  const safe = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
810
765
  const facts = JSON.stringify({ name }).replace(/</g, "\\u003c");
811
766
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
812
- <title>${safe(name)}</title>${ICON_HEAD}<style>${PAGE_STYLE}
813
- ${SERVICE_STYLE}</style></head><body>
767
+ <title>${safe(name)}</title>${ICON_HEAD}<style>${PAGE_STYLE}</style></head><body>
814
768
  <header><h1 id="title">${safe(name)}</h1><button id="refresh" hidden>🔄 Refresh</button><button id="logout" hidden>🚪 Logout</button></header>
815
769
  <div id="serving" class="idbar" data-be-tip="The process that answered this page — its process id, when it started and the sign-in build its code was loaded from — and when this page's sign-in expires"><span class="srv">${safe(host)} · pid ${me.pid} · started ${storedStamp(me.startedAt)} · sign-in BN ${safe(me.build)}</span><small id="expires" hidden></small></div>
816
770
  <main id="main"></main>
@@ -12,10 +12,10 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renam
12
12
  import { randomUUID } from "crypto";
13
13
  import { performance } from "perf_hooks";
14
14
  import { EventEmitter } from "events";
15
- import { homedir } from "os";
16
15
  import { basename, dirname, join } from "path";
17
16
  import { CONFIG_DIR, masterMuted } from "../notify.js";
18
17
  import { PROVIDER_NAMES, providerFor } from "./providers.js";
18
+ import { workspacesFile, workspacesHere } from "../shared/webhost/workspaceList.js";
19
19
  /** 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. */
20
20
  export function titleOf(meta, events) {
21
21
  // A conversation opened with no message, and one whose project was picked before its first message, hold no user line yet.
@@ -393,48 +393,60 @@ function traceOfTurn(lines, turn) {
393
393
  // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
394
394
  return turn === undefined ? undefined : JSON.parse(lines[turn - 1]).trace;
395
395
  }
396
- /**
397
- * The folder Meni's projects live under, and where a conversation that names no folder runs: `~/Desktop`.
398
- * GATE: NOTIFY_AGENT_WORKSPACE is read ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1, so a test runs in a folder it owns.
399
- */
400
- export function workspaceRoot() {
401
- const stand = process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" ? process.env.NOTIFY_AGENT_WORKSPACE : undefined;
402
- return stand ?? join(homedir(), "Desktop");
403
- }
404
396
  /** A folder is a project with a board when it holds a BACKLOG.md file: the bullseye-backlog MCP refuses to start anywhere else (#2110). */
405
397
  export function hasBoard(folder) {
406
398
  const board = join(folder, "BACKLOG.md");
407
399
  return existsSync(board) && statSync(board).isFile();
408
400
  }
409
- // GATE: only these projects may host an agent, and each one needs `bullseye-backlog` in its OWN `.mcp.json` — there is no user-scope entry — so a project added here without one silently loses the board tools at its boundary.
410
- const CANONICAL_PROJECTS = ["BullseyeVSC", "AlphaWave"];
411
401
  /**
412
- * The only project names an agent may run in: BullseyeVSC and AlphaWave, each resolved under the workspace root.
413
- * GATE: NOTIFY_AGENT_PROJECTS (comma list) replaces them ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1, so a test runs in a tree it owns.
402
+ * #3849 — the projects an agent may run in: every folder on this machine's workspace list (the one list Bullseye Control edits), named by its folder.
403
+ * A list that is not defined or cannot be read is refused with its own reason, never answered as no projects.
404
+ * GATE: NOTIFY_AGENT_PROJECTS (comma list), resolved under NOTIFY_AGENT_WORKSPACE, replaces the list ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1, so a test runs in a tree it owns.
414
405
  */
415
- export function allowedProjects() {
406
+ function projectsHere() {
416
407
  const named = process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" ? process.env.NOTIFY_AGENT_PROJECTS : undefined;
417
408
  // NULL-OK: field NOTIFY_AGENT_PROJECTS is OPTIONAL and therefore it is ok to check for NULL
418
- if (named !== undefined)
419
- return named.split(",");
420
- return [...CANONICAL_PROJECTS];
409
+ if (named !== undefined) {
410
+ const stand = process.env.NOTIFY_AGENT_WORKSPACE;
411
+ // NULL-OK: field NOTIFY_AGENT_WORKSPACE is OPTIONAL and therefore it is ok to check for NULL
412
+ if (stand === undefined)
413
+ throw new Error("NOTIFY_AGENT_PROJECTS names test projects but NOTIFY_AGENT_WORKSPACE names no folder of the test's own to resolve them under — a test never runs agents in real folders");
414
+ return named.split(",").map((name) => ({ name, folder: join(stand, name) }));
415
+ }
416
+ try {
417
+ return workspacesHere().map((w) => ({ name: basename(w.root), folder: w.root }));
418
+ }
419
+ catch (err) {
420
+ if (!(err instanceof SyntaxError))
421
+ throw err;
422
+ throw new GatewayError(503, `no agent can be started yet: ${err.message}`);
423
+ }
424
+ }
425
+ /** The names a project is given by: exactly the folder names on the workspace list, in its order. */
426
+ export function allowedProjects() {
427
+ return projectsHere().map((p) => p.name);
428
+ }
429
+ /** The folder(s) the listed projects sit in, as a reader is told where a name resolves. */
430
+ export function workspaceRoot() {
431
+ return [...new Set(projectsHere().map((p) => dirname(p.folder)))].join(", ");
421
432
  }
422
433
  /** The refusal every door gives for a project outside the allowed ones. */
423
434
  function notAllowedProject() {
424
435
  return new GatewayError(400, `project must be exactly one of: ${allowedProjects().join(", ")} — no other name, path or case variant is accepted`);
425
436
  }
426
- /** The folder a project names: exactly one of the allowed project names (exact case), resolved under the workspace root; any path, other name or case variant is refused. */
437
+ /** The folder a project names: exactly one of the listed folder names (exact case); any path, other name or case variant is refused. */
427
438
  function projectFolder(project) {
428
- if (!allowedProjects().includes(project))
439
+ const listed = projectsHere().find((p) => p.name === project);
440
+ // NULL-OK: field listed is OPTIONAL and therefore it is ok to check for NULL
441
+ if (listed === undefined)
429
442
  throw notAllowedProject();
430
- const folder = join(workspaceRoot(), project);
431
- if (!existsSync(folder) || !statSync(folder).isDirectory())
432
- throw new GatewayError(400, `project ${project} is not a folder on this machine — it is expected at ${folder}`);
433
- return folder;
443
+ if (!existsSync(listed.folder) || !statSync(listed.folder).isDirectory())
444
+ throw new GatewayError(400, `project ${project} is not a folder on this machine — it is expected at ${listed.folder}`);
445
+ return listed.folder;
434
446
  }
435
- /** Whether a folder is one of the allowed projects' folders under the workspace root. */
447
+ /** Whether a folder is one of the listed projects' folders. */
436
448
  export function isAllowedFolder(folder) {
437
- return allowedProjects().some((name) => sameFolder(join(workspaceRoot(), name), folder));
449
+ return projectsHere().some((p) => sameFolder(p.folder, folder));
438
450
  }
439
451
  /** The folder an agent is about to run in, proven to be one of the allowed projects' folders: a stored or resolved path outside them is refused. */
440
452
  export function allowedFolder(folder) {
@@ -447,11 +459,17 @@ function sameFolder(a, b) {
447
459
  const shape = (folder) => folder.replace(/[\\/]+$/, "").replace(/[\\/]/g, "/");
448
460
  return process.platform === "win32" ? shape(a).toLowerCase() === shape(b).toLowerCase() : shape(a) === shape(b);
449
461
  }
450
- /** BN's own home project: the board folder a request that names no project runs in. NOTIFY_AGENT_HOME_PROJECT overrides it, beside NOTIFY_AGENT_WORKSPACE. */
451
- export function homeProject() {
462
+ /** #3849 — BN's own home project, where a request that names no project runs: the first folder on the workspace list, in the list's order, which must hold a board — one that holds none is refused loudly, never passed over for the next board. NOTIFY_AGENT_HOME_PROJECT names another listed folder instead. */
463
+ function homeProject(listed, boards) {
452
464
  const named = process.env.NOTIFY_AGENT_HOME_PROJECT;
453
465
  // NULL-OK: env var NOTIFY_AGENT_HOME_PROJECT is OPTIONAL and therefore it is ok to check for NULL; an empty value counts as unset
454
- return named === undefined || named === "" ? "BullseyeVSC" : named;
466
+ const home = named === undefined || named === "" ? listed[0] : named;
467
+ // NULL-OK: home is undefined exactly when the workspace list names no folder on this machine and NOTIFY_AGENT_HOME_PROJECT is unset
468
+ if (home === undefined)
469
+ throw new GatewayError(400, `the request names no project, and the workspace list (${workspacesFile()}) names no folder on this machine for it to run in — add one on Bullseye Control`);
470
+ if (!boards.includes(home))
471
+ throw new GatewayError(400, `the request names no project, and the home project ${home} (the first folder on the workspace list) holds no BACKLOG.md; name a project (${boards.join(", ")})`);
472
+ return home;
455
473
  }
456
474
  /** The board-bearing project the request text names, by exact-case folder name as a whole token or path segment; the earliest mention wins, the longer name on a tie. */
457
475
  function projectNamedIn(text, names) {
@@ -471,13 +489,9 @@ export function resolveProject(project, text = "") {
471
489
  // NULL-OK: field project is OPTIONAL and therefore it is ok to check for NULL
472
490
  if (project !== undefined)
473
491
  return projectFolder(project);
474
- const names = listProjects().projects.filter((p) => p.board).map((p) => p.name);
475
- const home = homeProject();
476
- const chosen = projectNamedIn(text, names) ?? (names.includes(home) ? home : undefined);
477
- // NULL-OK: chosen is undefined exactly when the request names no board project and the home project holds no board
478
- if (chosen === undefined)
479
- throw new GatewayError(400, `the request names no project and the home project ${home} under ${workspaceRoot()} holds no BACKLOG.md; name a project (${(names.length > 0 ? names : allowedProjects()).join(", ")}) or set NOTIFY_AGENT_HOME_PROJECT`);
480
- return join(workspaceRoot(), chosen);
492
+ const listed = projectsHere().filter((p) => existsSync(p.folder));
493
+ const boards = listed.filter((p) => hasBoard(p.folder)).map((p) => p.name);
494
+ return projectFolder(projectNamedIn(text, boards) ?? homeProject(listed.map((p) => p.name), boards));
481
495
  }
482
496
  /**
483
497
  * The workspace a session is CREATED in, from the name its creation supplied (#3640): exactly one of the allowed project
@@ -509,17 +523,13 @@ export function namedProvider(provider) {
509
523
  export function runsInOwnCli(id) {
510
524
  return providerFor(namedProvider(readConversation(id).provider)).console === true;
511
525
  }
512
- /** Every project folder under the workspace root, by name, with whether it is a Git repository. */
526
+ /** #3849 — every listed project folder present on this machine, by name, with whether it is a Git repository and holds a board; `list` is the workspace list file they come from. */
513
527
  export function listProjects() {
514
- const root = workspaceRoot();
515
- if (!existsSync(root))
516
- throw new GatewayError(500, `the workspace root ${root} is not a folder on this machine`);
517
- const allowed = allowedProjects();
518
- const projects = readdirSync(root, { withFileTypes: true })
519
- .filter((entry) => entry.isDirectory() && allowed.includes(entry.name))
520
- .map((entry) => ({ name: entry.name, path: join(root, entry.name), git: existsSync(join(root, entry.name, ".git")), board: hasBoard(join(root, entry.name)) }))
528
+ const projects = projectsHere()
529
+ .filter((p) => existsSync(p.folder) && statSync(p.folder).isDirectory())
530
+ .map((p) => ({ name: p.name, path: p.folder, git: existsSync(join(p.folder, ".git")), board: hasBoard(p.folder) }))
521
531
  .sort((a, b) => a.name.localeCompare(b.name));
522
- return { root, projects };
532
+ return { list: workspacesFile(), projects };
523
533
  }
524
534
  /** The record every new conversation starts from: one id, one unstarted session of its own, no turn run and nothing spent. Its workspace and its agent CLI are required and are bound HERE, in the one write that mints it (#3640): a record cannot exist without either, so no door can leave one to be filled in later. A console session carries its mode, its owner and its notice here too, so the record is never on disk describing itself as a turn conversation the session driver would read its events for. */
525
535
  function newConversation(input) {
@@ -18,6 +18,7 @@ import { z } from "zod";
18
18
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
19
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
20
20
  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, runsInOwnCli, } from "./conversations.js";
21
+ import { workspacesFile } from "../shared/webhost/workspaceList.js";
21
22
  import { PROVIDER_NAMES } from "./providers.js";
22
23
  import { iconsFor } from "./iconDoor.js";
23
24
  import { grantClient, publicBase } from "./oauthDoor.js";
@@ -40,9 +41,28 @@ async function act(run) {
40
41
  throw err;
41
42
  }
42
43
  }
43
- const INSTRUCTIONS = `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.
44
+ /** #3849 — the project names a connection's tools offer, read from the workspace list when the connection is built; a list that cannot be read is offered as its reason, and every call naming a project is then refused with it. */
45
+ function projectOffer() {
46
+ try {
47
+ const names = allowedProjects();
48
+ if (names.length === 0)
49
+ return { names: undefined, list: "(no folder on the workspace list is on this machine yet)", either: "(none yet)", under: workspacesFile() };
50
+ return { names: names, list: names.join(", "), either: names.join(" or "), under: workspaceRoot() };
51
+ }
52
+ catch (err) {
53
+ if (!(err instanceof GatewayError))
54
+ throw err;
55
+ // OWNER: building a connection's tool list is this read's trigger root — a workspace list that is not defined or cannot be read is offered as its reason, and each call naming a project is refused with it at the call
56
+ return { names: undefined, list: `(none yet: ${err.message})`, either: "(none yet)", under: workspacesFile() };
57
+ }
58
+ }
59
+ /** The schema a project argument takes: exactly the listed names, or, while none can be offered, any name — refused at the call with the list's own reason. */
60
+ function projectField(offer) {
61
+ return offer.names === undefined ? z.string().min(1) : z.enum(offer.names);
62
+ }
63
+ 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.
44
64
  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.
45
- A NEW conversation names the folder it works in and the agent CLI it runs, in the same call that creates it: project and provider are both required, and a call that leaves either out is refused with what to send — nothing is ever started in a folder or on a CLI the caller did not choose. project is exactly one of ${allowedProjects().join(", ")}, under the workspace root (${workspaceRoot()}), never a path, and agent_projects lists them with their paths; provider is exactly one of ${PROVIDER_NAMES.join(", ")}. A call that goes on with a conversation that already exists needs neither, because both were bound when it was created.
65
+ A NEW conversation names the folder it works in and the agent CLI it runs, in the same call that creates it: project and provider are both required, and a call that leaves either out is refused with what to send — nothing is ever started in a folder or on a CLI the caller did not choose. project is exactly one of ${offer.list}, under the workspace root (${offer.under}), never a path, and agent_projects lists them with their paths; provider is exactly one of ${PROVIDER_NAMES.join(", ")}. A call that goes on with a conversation that already exists needs neither, because both were bound when it was created.
46
66
  agent_open opens a conversation with no message and starts nothing: it names its project and provider as above, 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.
47
67
  An agent works on the project it runs in: its own folder is the board it writes to, so work belonging to another project is never done from this agent — 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.
48
68
  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: a message naming a Story claims that Story in its conversation's own name for the length of its turn — a read-only question or a status check included — and a message whose Story another session already claims fails that turn in the claims file's own words, naming the holder. 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.
@@ -148,15 +168,15 @@ async function consoleRead(live, after, wait) {
148
168
  clearTimeout(timer);
149
169
  }
150
170
  }
151
- function buildServer(caller, base) {
171
+ function buildServer(caller, base, offer) {
152
172
  built += 1;
153
- const server = new McpServer({ name: "notify-agent-gateway", version: PACKAGE_VERSION, icons: iconsFor(base) }, { instructions: INSTRUCTIONS, capabilities: EVENTS_CAPABILITY });
173
+ const server = new McpServer({ name: "notify-agent-gateway", version: PACKAGE_VERSION, icons: iconsFor(base) }, { instructions: instructions(offer), capabilities: EVENTS_CAPABILITY });
154
174
  serveEvents(server.server, caller);
155
175
  server.tool("agent_prompt", `Runs a request on this machine's own Claude Code agent — with the user's files, git repositories, shell and MCP servers — and returns the agent's answer. Each call goes on with the same agent as this connection's previous call, so the agent keeps what it already knows (a stopped one resumes); with no conversation named, new=true starts a fresh agent, and so does an ask that does not point at the work already under way while that agent is busy. A message to a conversation whose agent waits on a question on its CLI screen is queued behind that turn and never answers it. Waits up to ${MAX_WAIT_SECONDS} seconds: the answer comes back in this call, or working=true with the id and position to read on with agent_wait. It is the convenience send-and-wait for a request expected to finish within about a minute; for a long or autonomous task use agent_start and then agent_wait, which do not hold a call open while the agent works. A call that returned working=true or timed out was received and is still running: read on with agent_wait, and do not call agent_prompt again with the same text, which would submit the task a second time. The result carries the ending event's timing, in which a reply's time is three separate figures rather than one number: bnMs, the end-to-end elapsed time from the request arriving at BN's door to the answer being stored; queuedMs (beside queued, whether it stood in line at all — false is the store's own statement that it never stood in line, absent is unmeasured), the part of it the message waited for a free slot or the turn ahead; and agentMs, the part the agent itself worked. totalMs is BN's own total from the message being stored to the answer being stored, never the agent's time, and rows carries the turn layer by layer. It also carries waitedMs, the milliseconds this call itself held on BN's own clock. When the id names a CLI console session (a CLI started on its own in the browser and mirrored at /terminal — not a conversation's own CLI opened there), the text is typed into that SAME live CLI and the call returns at once with {console:true, sent:true, stream, after} — there is no turn to wait on, so read the CLI's answer with agent_wait or agent_stream_read at that after, or attach to stream.`, {
156
176
  text: z.string().min(1).describe("The user's request, as the user wrote it"),
157
177
  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"),
158
178
  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"),
159
- project: z.enum(allowedProjects()).optional().describe(`The workspace of a NEW conversation: exactly one of ${allowedProjects().join(" or ")}, resolved under ${workspaceRoot()}; no path is accepted. Required whenever this call creates one — no conversation named and no agent open to go on with, or new=true — and never taken from the request text`),
179
+ project: projectField(offer).optional().describe(`The workspace of a NEW conversation: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Required whenever this call creates one — no conversation named and no agent open to go on with, or new=true — and never taken from the request text`),
160
180
  provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Required whenever this call creates one, beside project`),
161
181
  model: z.string().min(1).optional(),
162
182
  }, ({ text, conversation, new: fresh, project, provider, model }) => act(async () => {
@@ -205,14 +225,14 @@ function buildServer(caller, base) {
205
225
  return { ...head, stopped: true, waitedMs, events: others, after };
206
226
  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` };
207
227
  }));
208
- server.tool("agent_projects", `The project folders on this machine (the folders under ${workspaceRoot()}), each with its absolute path and whether it is a git repository.`, {}, () => act(() => listProjects()));
209
- 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: z.enum(allowedProjects()).optional().describe(`The workspace this conversation runs in: exactly one of ${allowedProjects().join(" or ")}, resolved under ${workspaceRoot()}; no path is accepted. Required here, because this call creates the conversation — 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(", ")}. Required here, beside project`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(() => {
228
+ 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()));
229
+ 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. Required here, because this call creates the conversation — 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(", ")}. Required here, beside project`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(() => {
210
230
  const arrived = performance.now();
211
231
  const arrival = arrivalOf(requestIdOf(), randomUUID().slice(0, 8));
212
232
  const meta = startConversation({ platform: "mcp", technical: true, chat: caller, project: namedProject(project), provider: namedProvider(provider), model, text, receivedMs: Math.round(performance.now() - arrived), arrival });
213
233
  return { id: meta.id, state: meta.state };
214
234
  }));
215
- 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 required here, because a conversation is never minted on either without the caller choosing it. 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: z.enum(allowedProjects()).optional().describe(`Exactly one of ${allowedProjects().join(" or ")}, resolved under ${workspaceRoot()}; no path is accepted. Required here, because this call creates the conversation — 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(", ")}. Required here, beside project`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(() => {
235
+ 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 required here, because a conversation is never minted on either without the caller choosing it. 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. Required here, because this call creates the conversation — 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(", ")}. Required here, beside project`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(() => {
216
236
  const meta = openConversation({ platform: "mcp", technical: true, chat: caller, project: namedProject(project), provider: namedProvider(provider), model });
217
237
  return { id: meta.id, state: meta.state };
218
238
  }));
@@ -259,7 +279,7 @@ function buildServer(caller, base) {
259
279
  }
260
280
  }).then((result) => { row(outcome ?? `refused why=${result.content[0]?.text ?? "the call was refused"}`); return result; }, (err) => { row(outcome ?? `refused why=${err instanceof Error ? err.message : String(err)}`); throw err; });
261
281
  });
262
- server.tool("agent_project", `Sets or switches the project folder a conversation's agent works in — before its first message, or between any two turns, also after work in another project. The next turn's agent runs in that folder and writes to its board, while the conversation's id, its whole transcript and the agent itself stay: the same session carries on in the new folder with its earlier turns in hand, so this NEVER starts a new agent and never makes a new conversation. A switch is refused at two safe boundaries — while a turn is running, named with the running turn's number, and while a browser CLI is running the conversation's own session, because a running process is never moved under itself. Either refusal leaves the record on its old project.`, { id: z.string().min(1).describe("The conversation id agent_open or agent_start returned, or the 'conversation' agent_prompt returned"), project: z.enum(allowedProjects()).describe(`Exactly one of ${allowedProjects().join(" or ")}, resolved under ${workspaceRoot()}; no path is accepted`) }, ({ id, project }) => act(() => setConversationProject(id, project)));
282
+ server.tool("agent_project", `Sets or switches the project folder a conversation's agent works in — before its first message, or between any two turns, also after work in another project. The next turn's agent runs in that folder and writes to its board, while the conversation's id, its whole transcript and the agent itself stay: the same session carries on in the new folder with its earlier turns in hand, so this NEVER starts a new agent and never makes a new conversation. A switch is refused at two safe boundaries — while a turn is running, named with the running turn's number, and while a browser CLI is running the conversation's own session, because a running process is never moved under itself. Either refusal leaves the record on its old project.`, { id: z.string().min(1).describe("The conversation id agent_open or agent_start returned, or the 'conversation' agent_prompt returned"), project: projectField(offer).describe(`Exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted`) }, ({ id, project }) => act(() => setConversationProject(id, project)));
263
283
  server.tool("agent_status", "One conversation's project (absent until one is chosen), provider, model and state, with its title (the name its session carries in Claude's session list), its lifecycle (active while a turn runs, is queued or waits on the user's answer; idle when open with no turn; completed once stopped or archived) and beside (the conversation of the same connection it was opened next to, if any).", { id: z.string().min(1) }, ({ id }) => act(() => describeConversation(readConversation(id))));
264
284
  server.tool("agent_stream", `Where to attach to a conversation's LIVE stream: what its agent shows AS IT HAPPENS, not only the finished reply that agent_prompt and agent_wait carry. It returns {conversation, url, after, console?}. Attach to url with a plain HTTP GET; the answer is a Server-Sent Events stream, one 'data: <frame>' line per frame. While the conversation's CLI is running — every Claude conversation's turns run in its own interactive CLI, and a CLI console session started on its own in the browser and mirrored at /terminal is one too — console is true and the url is that CLI's own console output at /v1/terminals/<id>/console: frames {seq, ts, kind:"output", text, reset} carrying its raw screen bytes (its prompt, tool traces and any question it waits on), never a second CLI. Otherwise the url is the conversation's turn stream: frames {seq, ts, kind, text, turn} where kind is doing (the tool a Codex turn is on) or turn (a start, status, place-in-line, answer or failure line). Reconnect with ?after=<seq> of the last frame you read and you are handed every frame past it: nothing you already received is repeated and nothing new is missed. It is a read — it starts no agent, spends nothing and changes nothing — and it is the live feed of the agent that agent_start or agent_send is running. A CLI console session started on its own in the browser takes agent_send and agent_prompt typed straight into it; a Claude conversation's messages go through its turn queue, which types each one into that same CLI.`, { id: z.string().min(1).describe("The conversation id agent_start, agent_prompt or agent_open returned"), after: z.number().int().min(0).optional().describe("The last frame seq you already have; the stream resumes past it") }, ({ id, after }) => act(() => {
265
285
  const live = liveConsole(id) !== undefined || runsInOwnCli(id);
@@ -304,7 +324,9 @@ export async function handleMcp(req, res) {
304
324
  const base = publicBase(req);
305
325
  const pooled = ready.get(caller);
306
326
  ready.delete(caller);
307
- const server = pooled?.base === base ? pooled.server : buildServer(caller, base);
327
+ const offer = projectOffer();
328
+ const offered = JSON.stringify(offer);
329
+ const server = pooled?.base === base && pooled.offered === offered ? pooled.server : buildServer(caller, base, offer);
308
330
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
309
331
  /** Whether this POST is over: a response that closes after it closed a transport the caller's server may already stand on again must not close that one. */
310
332
  let answered = false;
@@ -320,5 +342,5 @@ export async function handleMcp(req, res) {
320
342
  await transport.close();
321
343
  }
322
344
  if (!ready.has(caller))
323
- ready.set(caller, { base, server });
345
+ ready.set(caller, { base, offered, server });
324
346
  }
@@ -16,6 +16,7 @@ import { handleMcp } from "./mcpDoor.js";
16
16
  import { MCP_PATH, accessGranted, challenge, handleOAuth, isOAuthPath, publicBase } from "./oauthDoor.js";
17
17
  import { bearer, bearerAdmitted, handlePasskey, isPasskeyPath, localOnly, personId } from "./passkeyDoor.js";
18
18
  import { agentStreamFor } from "./agentStream.js";
19
+ import { CLAUDE_HOOK_PATH, claudeHooks } from "./claudeProvider.js";
19
20
  import { terminalConsole, terminalRoute, terminalSockets } from "./terminalDoor.js";
20
21
  import { conversationSwitchRead, panelState, saveConversationSwitch, saveSetting } from "./panel.js";
21
22
  import { PANEL_PAGES, panelHtml } from "./panelPage.js";
@@ -176,7 +177,36 @@ async function route(req, url, arrivedAt) {
176
177
  }
177
178
  throw new GatewayError(405, "method not allowed here");
178
179
  }
179
- /** `GET /v1/conversations/<id>/stream`: the conversation's live agent stream (#3402) — its thinking and its output as they arrive, told apart — as Server-Sent Events on the same owner-authenticated door. `after` is the last frame `seq` the caller read, so a re-attach resumes exactly past it and misses nothing. */
180
+ /**
181
+ * `POST /v1/claude-hooks/<key>`: a conversation's own Claude CLI reports its turns here (#3845) — from this machine only,
182
+ * at a path only that session knows — and the reply is the hook's answer to the CLI.
183
+ */
184
+ async function claudeHookAnswered(req, res, url) {
185
+ if (req.method !== "POST" || !url.pathname.startsWith(CLAUDE_HOOK_PATH))
186
+ return false;
187
+ localOnly(req);
188
+ const answer = claudeHooks.deliver(url.pathname.slice(CLAUDE_HOOK_PATH.length), await readJson(req));
189
+ // NULL-OK: field answer is OPTIONAL and therefore it is ok to check for NULL
190
+ if (answer === undefined)
191
+ throw new GatewayError(404, "no agent CLI of this BN process reports at this path");
192
+ reply(res, 200, answer);
193
+ return true;
194
+ }
195
+ /** A request that failed, answered to its caller: a refusal with its status, anything else logged with its message and answered 500. */
196
+ function answerFailure(req, res, err) {
197
+ if (res.headersSent) {
198
+ process.stderr.write(`[agent-gateway] ${req.method} ${req.url} failed after its headers were sent: ${err instanceof Error ? err.message : String(err)}\n`);
199
+ res.end();
200
+ return;
201
+ }
202
+ if (err instanceof GatewayError) {
203
+ reply(res, err.status, { ...err.facts, error: err.message });
204
+ return;
205
+ }
206
+ process.stderr.write(`[agent-gateway] ${req.method} ${req.url} failed: ${err instanceof Error ? err.message : String(err)}\n`);
207
+ reply(res, 500, { error: "internal error" });
208
+ }
209
+ /** `GET /v1/conversations/<id>/stream`: the conversation's live turn stream (#3402) — the tool a Codex turn is on and each conversation event, as they arrive — as Server-Sent Events on the same owner-authenticated door. `after` is the last frame `seq` the caller read, so a re-attach resumes exactly past it and misses nothing. */
180
210
  async function conversationStream(req, res, url) {
181
211
  const id = url.pathname.split("/").filter((part) => part.length > 0)[2];
182
212
  const afterRaw = url.searchParams.get("after");
@@ -247,6 +277,8 @@ export function startRestDoor(settings) {
247
277
  workspaces.answer(req, res);
248
278
  return;
249
279
  }
280
+ if (await claudeHookAnswered(req, res, url))
281
+ return;
250
282
  if ((url.pathname === "/settings" || url.pathname === "/public-access") && req.method === "GET") {
251
283
  const page = panelHtml(url.pathname);
252
284
  res.writeHead(200, { ...CHAT_HEADERS, "content-length": Buffer.byteLength(page) });
@@ -279,23 +311,16 @@ export function startRestDoor(settings) {
279
311
  }
280
312
  catch (err) {
281
313
  // OWNER: the request's trigger root — a refused act is answered to its caller with its status, and an unknown failure is logged with its message and answered 500, so no caller waits on a dropped socket.
282
- if (res.headersSent) {
283
- process.stderr.write(`[agent-gateway] ${req.method} ${req.url} failed after its headers were sent: ${err instanceof Error ? err.message : String(err)}\n`);
284
- res.end();
285
- return;
286
- }
287
- if (err instanceof GatewayError) {
288
- reply(res, err.status, { ...err.facts, error: err.message });
289
- return;
290
- }
291
- process.stderr.write(`[agent-gateway] ${req.method} ${req.url} failed: ${err instanceof Error ? err.message : String(err)}\n`);
292
- reply(res, 500, { error: "internal error" });
314
+ answerFailure(req, res, err);
293
315
  }
294
316
  })();
295
317
  });
296
318
  terminalSockets(server, settings.token);
297
319
  return new Promise((resolve, reject) => {
298
320
  server.once("error", reject);
299
- server.listen(settings.port, "0.0.0.0", () => resolve(server));
321
+ server.listen(settings.port, "0.0.0.0", () => {
322
+ claudeHooks.listening(server.address().port, personId);
323
+ resolve(server);
324
+ });
300
325
  });
301
326
  }
@@ -103,9 +103,8 @@ function ordered(id,act,body){if(!socket||socket.readyState!==WebSocket.OPEN)ret
103
103
  function base(folder){var parts=String(folder).split(/[/\\\\]+/).filter(function(p){return p;});return parts[parts.length-1]||String(folder);}
104
104
  /** Where a conversation came from: an MCP client, or the person in this page (Telegram, REST and the rest count as User). */
105
105
  function originOf(record){return record.platform==="mcp"?"MCP":"User";}
106
- /** Whether a live CLI is what acts on this conversation (#3614, #3620): a CLI console session of its own, or a CLI this page attached to the conversation's own agent session. Either way that CLI is the session — the row's stop slot CLOSES it, its folder cannot be moved under it, and MCP reaches the same CLI.
107
- * A conversation is being opened ITSELF here, so its record is read afresh: the flag must not come from a listing that may be seconds old. */
108
- function cliLed(record){return record.mode==="interactive-only"||record.cliOwner!==undefined;}
106
+ /** Whether this is a CLI console session of its own (#3614): that CLI is the session with no turn driver behind it, so the row's stop slot CLOSES it and its folder cannot be moved under it. */
107
+ function cliLed(record){return record.mode==="interactive-only";}
109
108
 
110
109
  /** Browser history is the navigation: the root entry is always the Conversations list, and each view pushes one entry. */
111
110
  function rootState(){return {bn:1,view:"list",depth:0};}
@@ -138,12 +137,11 @@ async function openRecordView(name,id){
138
137
  return openCli(meta);
139
138
  }catch(error){if(mine===view){show("new","Conversation");note.textContent=error.message;}}
140
139
  }
141
- /** ONE path for every conversation, whatever made it (#3620, #3640): a session started over MCP and one started by
142
- * + New Agent open the same way, on a CLI of the conversation's OWN session — the CLI runs that session, so this page,
143
- * MCP and the CLI's own transcript are one session with one history. A CLI already running for it is attached; one that
144
- * is not is started here and attached. Nothing is drawn from the conversation's record: its record is not terminal
145
- * output, and MCP reaches the SAME CLI by the same id (agent_send types into it, agent_stream reads its console).
146
- * A conversation the CLI cannot be opened on says why in plain words — never a transcript with a message box. */
140
+ /** ONE path for every conversation, whatever made it (#3640, #3845): a session started over MCP and one started by
141
+ * + New Agent open the same way, on the conversation's OWN CLI — the very process its turns run in, so this page, MCP
142
+ * and the CLI's own transcript are one session with one history. A CLI already running for it is attached, a turn in
143
+ * flight included; one that is not is started with no turn and attached. Nothing is drawn from the conversation's
144
+ * record: its record is not terminal output. A conversation the CLI cannot be opened on says why in plain words. */
147
145
  async function openCli(meta){
148
146
  var mine=view,alive=true;
149
147
  try{await api("GET","/v1/terminals/"+meta.id);}catch(error){if(error.status!==404)throw error;alive=false;}
@@ -160,12 +158,11 @@ async function openCli(meta){
160
158
  goneView(meta,error.message);
161
159
  }
162
160
  }
163
- /** A conversation whose turn is still running opens on that turn's own live output, drawn in the terminal pane (#3662):
164
- * a turn started over MCP runs its CLI headless, so there is no terminal to attach to until it ends, and a second CLI on
165
- * the same session would be two agents on one job. The moment that turn ends, openCli runs again and attaches the
166
- * native CLI of this SAME session — its prompt, its history, its slash commands — with no second agent and nothing stopped. */
161
+ /** A conversation on an agent with no CLI of its own to open (Codex, Copilot: each turn is a process that ends with it)
162
+ * opens, while a turn runs, on that turn's live feed drawn in the terminal pane: the tool it is on and each conversation
163
+ * event. The moment the turn ends, openCli runs again and says in plain words why there is no CLI to show. */
167
164
  function turnMirror(meta,turn){
168
- var mine=show("terminal","Native CLI · "+meta.id),toolbar=el("div","setup"),back=el("button","","↩ Back"),host=el("div");host.id="terminal";
165
+ var mine=show("terminal","Turn feed — not a CLI · "+meta.id),toolbar=el("div","setup"),back=el("button","","↩ Back"),host=el("div");host.id="terminal";
169
166
  main.style.display="flex";main.style.flexDirection="column";host.style.flex="1";host.style.minHeight="0";
170
167
  toolbar.append(back,el("span","origin",originOf(meta)));main.append(toolbar,host);
171
168
  var term=new Terminal({disableStdin:true,theme:{background:"#101217"},allowProposedApi:true}),fit=new FitAddon.FitAddon();
@@ -174,15 +171,8 @@ function turnMirror(meta,turn){
174
171
  var reading=new AbortController();
175
172
  stopStream=function(){reading.abort();resized.disconnect();term.dispose();};
176
173
  back.onclick=goBack;
177
- note.textContent="Turn "+turn+" is running — its live output is shown here, and this session's native CLI opens here the moment it ends.";
178
- var STYLE={thinking:"\\x1b[2;3m",doing:"\\x1b[36m⏺ ",turn:"\\x1b[1m",output:""};
179
- var kindOpen;
180
- function draw(frame){
181
- var delta=frame.kind==="thinking"||frame.kind==="output",text=String(frame.text).replace(/\\r?\\n/g,"\\r\\n");
182
- if(delta&&frame.kind===kindOpen){term.write(text);return;}
183
- term.write((kindOpen?"\\x1b[0m\\r\\n":"")+(STYLE[frame.kind]||"")+text+(delta?"":"\\x1b[0m\\r\\n"));
184
- kindOpen=delta?frame.kind:undefined;
185
- }
174
+ note.textContent="Turn "+turn+" runs in a process of its own with no CLI to open: this is BN's feed of that turn.";
175
+ var STYLE={doing:"\\x1b[36m⏺ ",turn:"\\x1b[1m"};
186
176
  function ends(frame){return frame.kind==="turn"&&frame.turn===turn&&(frame.event==="answer"||frame.event==="failed");}
187
177
  (async function(){
188
178
  var response=await fetch("/v1/conversations/"+meta.id+"/stream",{headers:{authorization:"Bearer "+token},signal:reading.signal});
@@ -196,7 +186,8 @@ function turnMirror(meta,turn){
196
186
  var blocks=pending.split("\\n\\n");pending=blocks.pop();
197
187
  for(var block of blocks){
198
188
  if(block.indexOf("data: ")!==0)continue;
199
- var frame=JSON.parse(block.slice(6));draw(frame);
189
+ var frame=JSON.parse(block.slice(6));
190
+ term.write((STYLE[frame.kind]||"")+String(frame.text).replace(/\\r?\\n/g,"\\r\\n")+"\\x1b[0m\\r\\n");
200
191
  if(!ends(frame))continue;
201
192
  var fresh=await api("GET","/v1/conversations/"+meta.id);
202
193
  if(mine===view)await openCli(fresh);
@@ -906,6 +906,7 @@ class JsonlCliTurn {
906
906
  sink;
907
907
  lineBuffer = "";
908
908
  stderr = "";
909
+ stderrLines = "";
909
910
  turnSpec;
910
911
  cliName;
911
912
  constructor(turnSpec, cliName) {
@@ -919,6 +920,9 @@ class JsonlCliTurn {
919
920
  return undefined;
920
921
  return child.pid;
921
922
  }
923
+ diagnostic(_line) {
924
+ return false;
925
+ }
922
926
  read(line) {
923
927
  this.sink?.stdout();
924
928
  if (!line.startsWith("{") || !line.endsWith("}"))
@@ -945,6 +949,7 @@ class JsonlCliTurn {
945
949
  this.sink = sink;
946
950
  this.lineBuffer = "";
947
951
  this.stderr = "";
952
+ this.stderrLines = "";
948
953
  const launch = ownerBoundLaunch({ cmd: spec.cli.cmd, args: [...spec.cli.args, ...args] }, spec.ownerPid, spec.project, spec.guardDir);
949
954
  return new Promise((resolve, reject) => {
950
955
  let settled = false;
@@ -981,6 +986,14 @@ class JsonlCliTurn {
981
986
  child.stderr.on("data", (chunk) => {
982
987
  this.stderr = (this.stderr + chunk).slice(-4000);
983
988
  this.sink?.alive?.();
989
+ this.stderrLines += chunk;
990
+ for (let i = this.stderrLines.indexOf("\n"); i >= 0; i = this.stderrLines.indexOf("\n")) {
991
+ const line = this.stderrLines.slice(0, i).trim();
992
+ this.stderrLines = this.stderrLines.slice(i + 1);
993
+ if (this.diagnostic(line))
994
+ stop();
995
+ }
996
+ this.stderrLines = this.stderrLines.slice(-4000);
984
997
  });
985
998
  child.stdout.on("data", (chunk) => {
986
999
  this.lineBuffer += chunk;
@@ -1105,7 +1118,7 @@ export class CodexTurn extends JsonlCliTurn {
1105
1118
  }
1106
1119
  }
1107
1120
  export function opencodeRunArgs(spec) {
1108
- return ["run", "--format", "json", "--auto", ...(spec.session === undefined ? [] : ["-s", spec.session]), "-m", spec.model];
1121
+ return ["run", "--print-logs", "--log-level", "ERROR", "--format", "json", "--auto", ...(spec.session === undefined ? [] : ["-s", spec.session]), "-m", spec.model];
1109
1122
  }
1110
1123
  function opencodeToolActivity(tool) {
1111
1124
  if (tool === "read")
@@ -1125,6 +1138,8 @@ function opencodeToolActivity(tool) {
1125
1138
  // GATE: the HTTP statuses on which the provider refused THIS key (unauthorized, payment, forbidden, rate-limited) — the turn moves to the next key; any other failure is the turn's own and moves nothing
1126
1139
  const KEY_REFUSAL_STATUSES = new Set([401, 402, 403, 429]);
1127
1140
  const KEY_REFUSAL_WORDS = /credit balance is too low|insufficient (?:balance|funds|credit|quota)|out of (?:funds|credit)|invalid x-api-key/i;
1141
+ // GATE: OpenCode's own log line for a call of the turn's main agent that the provider rate-limited — the CLI then retries it in silence for as long as the provider's retry-after says, so the turn ends this attempt and moves to the next key
1142
+ const RETRIED_RATE_LIMIT = /level=ERROR .*message="stream error" .*session\.id=(ses_[A-Za-z0-9]+) .*small=false .*mode=primary .*error\.error="(?:AI_APICallError: )?([^"]*(?:rate.?limit|too many requests)[^"]*)"/i;
1128
1143
  const KEY_RETRY_PROMPT = "The provider refused the key your last reply was being written on, so that reply never arrived. Carry on from the last message.";
1129
1144
  export class OpenCodeTurn extends JsonlCliTurn {
1130
1145
  spec;
@@ -1169,6 +1184,18 @@ export class OpenCodeTurn extends JsonlCliTurn {
1169
1184
  this.keyRefusal = this.failure;
1170
1185
  }
1171
1186
  }
1187
+ diagnostic(line) {
1188
+ if (!RETRIED_RATE_LIMIT.test(line))
1189
+ return false;
1190
+ const [, session, said] = RETRIED_RATE_LIMIT.exec(line);
1191
+ if (this.session === undefined) {
1192
+ this.session = session;
1193
+ this.sink?.sessionId(session, true);
1194
+ }
1195
+ this.failure = `${said} (HTTP 429, being retried by the CLI)`;
1196
+ this.keyRefusal = this.failure;
1197
+ return true;
1198
+ }
1172
1199
  verdict(exitCode) {
1173
1200
  // NULL-OK: field failure is OPTIONAL and therefore it is ok to check for NULL
1174
1201
  if (this.failure !== undefined)
@@ -1529,6 +1529,19 @@ function claudeSubscriptions(identities, Failure = Error) {
1529
1529
  return { id: String(row.id), label, token: text(row, 'credential') };
1530
1530
  });
1531
1531
  }
1532
+ /**
1533
+ * Every Claude subscription this box's DeepAgent holds, read from VS Code's user settings (`deepagent.identities`). A box with
1534
+ * no VS Code user directory throws `vscodeUserDir`'s own words naming every path tried; a missing settings file is named here.
1535
+ * `[]` is settings that name no Claude subscription, never a failed read.
1536
+ * @returns {{ id: string, label: string, token: string }[]}
1537
+ */
1538
+ function boxClaudeSubscriptions() {
1539
+ const file = path.join(vscodeUserDir(), 'settings.json');
1540
+ const text = unlessErr('ENOENT', () => fs.readFileSync(file, 'utf8'));
1541
+ if (text === undefined)
1542
+ throw new Error('VS Code user settings ' + file + ' does not exist, so DeepAgent names no Claude subscription');
1543
+ return claudeSubscriptions(settingsIdentities(text, file));
1544
+ }
1532
1545
  module.exports = {
1533
1546
  VSCODE_VARIANTS,
1534
1547
  vscodeDataRoot,
@@ -1536,6 +1549,7 @@ module.exports = {
1536
1549
  jsoncToJson,
1537
1550
  settingsIdentities,
1538
1551
  claudeSubscriptions,
1552
+ boxClaudeSubscriptions,
1539
1553
  chosenSubscriptionOf,
1540
1554
  settingsTokens,
1541
1555
  deepagentMirror,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.317",
3
+ "version": "1.3.319",
4
4
  "description": "Reach your AI agents from anywhere — and let them reach you. One stdio process 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/index.js",
6
6
  "type": "module",
@@ -28,7 +28,13 @@ const caret = (text) => `"${text.replace(/(\\*)"/g, '$1$1""').replace(/(\\+)$/,
28
28
 
29
29
  // The guard itself runs as Node through ELECTRON_RUN_AS_NODE; the target must not inherit it.
30
30
  const { ELECTRON_RUN_AS_NODE: _runAsNode, ...targetEnv } = process.env;
31
- const exe = decode(exeB64);
31
+ const named = decode(exeB64);
32
+ const dirs = process.env.PATH.split(";").map((dir) => dir.replace(/^"(.*)"$/, "$1")).filter((dir) => dir !== "");
33
+ const onPath = /[\\/]/.test(named) || /\.[a-z0-9]+$/i.test(named)
34
+ ? undefined
35
+ : dirs.flatMap((dir) => [".com", ".exe", ".bat", ".cmd"].map((ext) => `${dir}\\${named}${ext}`)).find((file) => fs.existsSync(file));
36
+ // NULL-OK: field onPath is OPTIONAL and therefore it is ok to check for NULL
37
+ const exe = onPath ?? named;
32
38
  const args = JSON.parse(decode(argsB64));
33
39
  const cwd = decode(cwdB64);
34
40
  if (cwd !== "" && !fs.existsSync(cwd)) {