omni-notify-mcp 1.3.366 → 1.3.367
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.
- package/dist/agentGateway.js +296 -0
- package/dist/daemon.js +131 -0
- package/dist/gateway/chatPage.js +727 -0
- package/dist/gateway/conversations.js +792 -0
- package/dist/gateway/lanProbe.js +86 -0
- package/dist/gateway/mcpDoor.js +390 -0
- package/dist/gateway/mcpEvents.js +448 -0
- package/dist/gateway/nativeTerminalWorker.js +170 -0
- package/dist/gateway/notifyDoor.js +165 -0
- package/dist/gateway/oauthDoor.js +345 -0
- package/dist/gateway/opencodeEvents.mjs +13 -0
- package/dist/gateway/opencodeProvider.js +249 -0
- package/dist/gateway/panel.js +189 -0
- package/dist/gateway/panelPage.js +214 -0
- package/dist/gateway/providers.js +16 -0
- package/dist/gateway/publicAccess.js +374 -0
- package/dist/gateway/restDoor.js +283 -0
- package/dist/gateway/sessionDriver.js +1014 -0
- package/dist/gateway/terminalDoor.js +247 -0
- package/dist/gateway/terminalPage.js +306 -0
- package/dist/gateway/tunnel.js +166 -0
- package/dist/messaging/emailInbound.js +292 -0
- package/dist/notify.js +2846 -0
- package/dist/shared/webhost/autoSwitch.cjs +1762 -0
- package/dist/shared/webhost/bullseyeWebHost.js +1329 -0
- package/dist/shared/webhost/originHandover.js +552 -0
- package/dist/shared/webhost/package.json +1 -0
- package/dist/shared/webhost/webviewShim.js +342 -0
- package/dist/shared/webhost/workspaceList.js +633 -0
- package/package.json +1 -1
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "fs";
|
|
2
|
+
import { homedir, hostname, networkInterfaces } from "os";
|
|
3
|
+
import { join } from "path";
|
|
4
|
+
import { BAD_TOKEN_ERROR } from "./restDoor.js";
|
|
5
|
+
// GATE: how long a support host has to accept the connection and answer; past it the host counts as not running BN.
|
|
6
|
+
const PROBE_TIMEOUT_MS = 1_500;
|
|
7
|
+
function sshConfigPath() {
|
|
8
|
+
if (process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1")
|
|
9
|
+
return process.env.NOTIFY_SSH_CONFIG || undefined;
|
|
10
|
+
return join(homedir(), ".ssh", "config");
|
|
11
|
+
}
|
|
12
|
+
function thisMachineNames() {
|
|
13
|
+
const names = new Set();
|
|
14
|
+
const name = hostname().toLowerCase();
|
|
15
|
+
names.add(name);
|
|
16
|
+
names.add(name.split(".")[0]);
|
|
17
|
+
for (const addresses of Object.values(networkInterfaces()))
|
|
18
|
+
for (const address of addresses ?? [])
|
|
19
|
+
if (!address.internal)
|
|
20
|
+
names.add(address.address.toLowerCase());
|
|
21
|
+
return names;
|
|
22
|
+
}
|
|
23
|
+
export function readSupportHosts(path) {
|
|
24
|
+
if (!existsSync(path))
|
|
25
|
+
return [];
|
|
26
|
+
const self = thisMachineNames();
|
|
27
|
+
const hosts = new Set();
|
|
28
|
+
let aliases = [];
|
|
29
|
+
let hostName;
|
|
30
|
+
const flush = () => {
|
|
31
|
+
if (aliases.length === 0)
|
|
32
|
+
return;
|
|
33
|
+
const target = hostName ?? aliases[0];
|
|
34
|
+
const known = [...aliases, ...(hostName ? [hostName] : [])].map((n) => n.toLowerCase());
|
|
35
|
+
if (target && !known.some((n) => self.has(n) || self.has(n.split(".")[0])))
|
|
36
|
+
hosts.add(target);
|
|
37
|
+
};
|
|
38
|
+
for (const raw of readFileSync(path, "utf8").split(/\r?\n/)) {
|
|
39
|
+
const line = raw.trim().split(/\s+/);
|
|
40
|
+
const key = line[0]?.toLowerCase();
|
|
41
|
+
if (key === "host") {
|
|
42
|
+
flush();
|
|
43
|
+
aliases = line.slice(1).filter((a) => !/[*?!]/.test(a));
|
|
44
|
+
hostName = undefined;
|
|
45
|
+
}
|
|
46
|
+
else if (key === "hostname" && line[1]) {
|
|
47
|
+
hostName = line[1];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
flush();
|
|
51
|
+
return [...hosts];
|
|
52
|
+
}
|
|
53
|
+
async function jsonBody(res) {
|
|
54
|
+
try {
|
|
55
|
+
return await res.json();
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
if (err instanceof SyntaxError)
|
|
59
|
+
return {};
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function answersAsBn(host, port) {
|
|
64
|
+
try {
|
|
65
|
+
const res = await fetch(`http://${host}:${port}/v1/health`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
|
|
66
|
+
if (res.status !== 401) {
|
|
67
|
+
await res.body?.cancel();
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return String((await jsonBody(res)).error).startsWith(BAD_TOKEN_ERROR);
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
// OWNER: a refused connection, an unreachable host or a silent one is the documented answer "no BN there"; the ownership timer asks again in a few seconds.
|
|
74
|
+
if (err instanceof TypeError || (err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError")))
|
|
75
|
+
return false;
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export async function findOtherBn(port) {
|
|
80
|
+
const path = sshConfigPath();
|
|
81
|
+
if (!path)
|
|
82
|
+
return undefined;
|
|
83
|
+
const hosts = readSupportHosts(path);
|
|
84
|
+
const answers = await Promise.all(hosts.map(async (host) => (await answersAsBn(host, port)) ? host : undefined));
|
|
85
|
+
return answers.find((host) => host !== undefined);
|
|
86
|
+
}
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP MCP door of the Agent Gateway (design section g): the same acts as the REST door, as MCP tools over the
|
|
3
|
+
* Streamable HTTP transport on the same port and under the same token. It is stateless — every POST is answered on a
|
|
4
|
+
* transport of its own with no session id and reads and writes the one conversations store, so a dropped or
|
|
5
|
+
* reconnected client, or a BN restart, loses nothing; the server a caller leaves behind is taken by that caller's
|
|
6
|
+
* next POST and never by another's, and a second call arriving while it is out builds its own. Every blocking tool is
|
|
7
|
+
* capped at the 54 s every blocking BN call obeys.
|
|
8
|
+
*
|
|
9
|
+
* `agent_prompt` is the one-step door a chat client uses (#2095): any request, as written, to a full Claude Code agent on
|
|
10
|
+
* Meni's machine — in the project the request is about (#2110), else a board-bearing default — answered in the same call when it finishes inside
|
|
11
|
+
* the cap. A call with no conversation id goes on with the caller's own open conversation, so a chat keeps one agent
|
|
12
|
+
* whether or not the client passes the id back; `new: true` starts a fresh one.
|
|
13
|
+
*/
|
|
14
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
15
|
+
import { spawn } from "child_process";
|
|
16
|
+
import { createHash, randomUUID } from "crypto";
|
|
17
|
+
import { existsSync } from "fs";
|
|
18
|
+
import { createRequire } from "module";
|
|
19
|
+
import { join } from "path";
|
|
20
|
+
import { performance } from "perf_hooks";
|
|
21
|
+
import { z } from "zod";
|
|
22
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
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";
|
|
25
|
+
import { workspacesFile } from "../shared/webhost/workspaceList.js";
|
|
26
|
+
import { PROVIDER_NAMES } from "./providers.js";
|
|
27
|
+
import { iconsFor } from "./iconDoor.js";
|
|
28
|
+
import { grantClient, publicBase } from "./oauthDoor.js";
|
|
29
|
+
import { bearer, fromThisMachine, personId, sessionSignIn, tokenProves } from "./passkeyDoor.js";
|
|
30
|
+
import { closeNativeTerminal, consoleSession, nativeTerminal, terminalArriving } from "./nativeTerminal.js";
|
|
31
|
+
import { dimensions, openTerminal, terminalListing, validFiles } from "./terminalDoor.js";
|
|
32
|
+
import { conversationSwitchRead, panelState, saveConversationSwitch, saveSetting } from "./panel.js";
|
|
33
|
+
import { wizard } from "./publicAccess.js";
|
|
34
|
+
import { EVENTS_CAPABILITY, serveEvents } from "./mcpEvents.js";
|
|
35
|
+
import { CONFIG_DIR, PACKAGE_VERSION, readGatewaySettings } from "../notify.js";
|
|
36
|
+
const answer = (value) => ({ content: [{ type: "text", text: JSON.stringify(value) }] });
|
|
37
|
+
/** A refused act is the tool's own error result, never a protocol failure, so the calling agent can read why. */
|
|
38
|
+
async function act(run, switchGated = true) {
|
|
39
|
+
try {
|
|
40
|
+
if (switchGated)
|
|
41
|
+
requireConversationEnabled();
|
|
42
|
+
return answer(await run());
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
// OWNER: the tool call is the trigger root — a refused act (GatewayError) is answered to the calling agent as an error result carrying its reason; any other failure is rethrown to the SDK, which answers a protocol error.
|
|
46
|
+
if (err instanceof GatewayError)
|
|
47
|
+
return { content: [{ type: "text", text: err.message }], isError: true };
|
|
48
|
+
throw err;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** A panel route that works with the agent-conversation switch Off — the Settings and Public access pages are what turn it On — so it is answered without the switch check `act` makes. */
|
|
52
|
+
const panelAct = (run) => act(run, false);
|
|
53
|
+
/** BN's lifecycle as the extension stages it beside the boot supervisor (bnDaemon.js LIFECYCLE_FILES): the one code the Uber dashboard row and the panel run. */
|
|
54
|
+
function stagedLifecycle() {
|
|
55
|
+
const file = join(CONFIG_DIR, "bnLifecycle.js");
|
|
56
|
+
if (!existsSync(file))
|
|
57
|
+
throw new GatewayError(503, `BN's lifecycle is not staged at ${file} — the extension stages it at activation, so a build that never activated has none`);
|
|
58
|
+
return file;
|
|
59
|
+
}
|
|
60
|
+
/** The press itself, run in a process of its own: the row's own act, whose outcome is read afterwards with act=state. */
|
|
61
|
+
const LIFECYCLE_ACTOR = "require(process.argv[1]).row(process.argv[2]).act(process.argv[3]).then(() => process.exit(0), () => process.exit(1))";
|
|
62
|
+
/** A launcher that starts the actor detached and exits at once, so no live parent links the actor to this daemon: the Stop inside a Restart ends this daemon's whole process tree, and an actor still in it would die before it started BN again. */
|
|
63
|
+
const LIFECYCLE_LAUNCHER = `require("child_process").spawn(process.execPath, ["-e", ${JSON.stringify(LIFECYCLE_ACTOR)}, ...process.argv.slice(1)], { detached: true, stdio: "ignore", windowsHide: true }).unref()`;
|
|
64
|
+
/** Start, Stop and Restart end or replace the process answering this very call, so they run in a process that outlives it; the outcome is read afterwards with act=state. */
|
|
65
|
+
function pressLifecycle(file, press) {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
const launcher = spawn(process.execPath, ["-e", LIFECYCLE_LAUNCHER, file, process.argv[1], press], { stdio: "ignore", windowsHide: true });
|
|
68
|
+
launcher.once("error", (err) => reject(new GatewayError(500, `the ${press} could not be launched — ${err.message}`)));
|
|
69
|
+
launcher.once("exit", (code) => (code === 0 ? resolve({ pressed: press, running: true, next: "read the outcome with bn_lifecycle act=state" }) : reject(new GatewayError(500, `the ${press} could not be launched — its launcher exited ${code}`))));
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** #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. */
|
|
73
|
+
function projectOffer() {
|
|
74
|
+
try {
|
|
75
|
+
const names = allowedProjects();
|
|
76
|
+
if (names.length === 0)
|
|
77
|
+
return { names: undefined, list: "(no folder on the workspace list is on this machine yet)", either: "(none yet)", under: workspacesFile() };
|
|
78
|
+
return { names: names, list: names.join(", "), either: names.join(" or "), under: workspaceRoot() };
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (!(err instanceof GatewayError))
|
|
82
|
+
throw err;
|
|
83
|
+
// 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
|
|
84
|
+
return { names: undefined, list: `(none yet: ${err.message})`, either: "(none yet)", under: workspacesFile() };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** 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. */
|
|
88
|
+
function projectField(offer) {
|
|
89
|
+
return offer.names === undefined ? z.string().min(1) : z.enum(offer.names);
|
|
90
|
+
}
|
|
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
|
+
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 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.
|
|
94
|
+
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.
|
|
95
|
+
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.
|
|
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.
|
|
97
|
+
Each agent_prompt goes on with the same agent as the previous one from this connection, also when a different project is named; new=true starts a fresh agent. With no conversation named, BN also starts a fresh agent by itself when the newest agent is busy and the ask does not point at the work already under way — so the ask never waits behind that turn. An ask that does point at the work under way (a follow-up, "are you done?", "stop") goes to the agent that is doing that work, even when a later independent ask opened another agent. A stopped conversation resumes on its next message.
|
|
98
|
+
A call that finishes inside the wait returns the end of the turn itself — an answer, a failure, or stopped when the conversation was stopped — and that is shown to the user as it is. When it returns working=true the turn is still running: call agent_wait at once with the id and the after it gave, and call it again the moment each read returns, until an answer or failed event arrives, or the conversation is stopped. The events that end the turn carry kind answer, failed or stopped, so read them by kind. A question the agent asks does not end its turn: it waits on the agent's own CLI screen, a status event says so, and the user answers it there by opening the conversation in BN — a message sent meanwhile is queued behind that turn and is not the answer. The working state is not an answer and neither is a read that brought only progress events — never pass either of them to the user as one.
|
|
99
|
+
Pass new=true whenever the question does not depend on the work already running: a fresh agent takes the question in a conversation of its own instead of waiting behind this connection's current turn, which can be minutes on a long one. Naming a conversation sends the call to that agent whatever new says, so to start a fresh one, pass new=true and leave conversation out.
|
|
100
|
+
Start a fresh conversation with new=true for each independent task as well, so a conversation carries one line of work and stays short of the length where it is compacted — compaction summarises the earlier turns and their detail is lost.
|
|
101
|
+
|
|
102
|
+
Every answer, and every turn that failed, carries its timing, and every figure in it is measured on BN's own machine. A reply's time is three separate figures and never one number, each on BN's own clock: bnMs is the end-to-end elapsed time, the milliseconds from the request arriving at BN's door to the answer being stored; queuedMs is the part of it the message waited for a free slot or the turn ahead, from the message being stored to the turn starting (the stored queue row's own span, absent when nothing measured it); and agentMs is the part of it the agent itself worked, the agent CLI's own share. queued says whether the turn stood in line at all: false is the store's own statement that no queue line was written for that turn, and absent means no queue figure was ever stored for it. totalMs is neither of those two: it is BN's own total from the message being stored to the answer being stored (bnMs minus the door's wait), and it is never the agent's time. rows breaks the turn down layer by layer, each layer with its own ms (a row marked part sits inside the row above it and is never added to the total). What BN did not time — the voice transcription, the ChatGPT dispatch, the plugin's own transit and the client's network — is named UNMEASURED and carries no figure, because BN never works such a figure out by subtracting its own from a total. agent_prompt also returns the ending event's timing and waitedMs, the milliseconds its own call held on BN's own clock; agent_wait returns the events themselves, each with its timing.
|
|
103
|
+
|
|
104
|
+
Which tool to call:
|
|
105
|
+
- agent_prompt: a request you expect answered within about a minute. It sends and then waits up to ${MAX_WAIT_SECONDS} seconds in the same call.
|
|
106
|
+
- agent_start: a long or autonomous task. It creates a new conversation and submits the text as its first task (turn 1) in one call, and returns the id at once without waiting.
|
|
107
|
+
- agent_open: an empty conversation with no agent work — no text, no project, no process and nothing spent. It returns {id, state}; pick its project with agent_project, then ask with agent_send.
|
|
108
|
+
- 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. A switch while a turn is running is refused and says which turn.
|
|
109
|
+
- agent_send: a follow-up to a conversation that already exists. It appends the message and returns its position n at once without waiting; n is the turn to read the answer of. 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 on that screen, never by a message to the conversation.
|
|
110
|
+
- agent_wait: the only way to read what happened. It is a read you call, not a notification BN pushes. wait=0 (the default) returns at once with whatever is there; wait up to ${MAX_WAIT_SECONDS} holds the call until a new event arrives. Pass after = the after the previous reply returned, which already counts the line that reply wrote; after=0 reads the log from the start, earlier turns included. The turn you asked for has ended at the first event whose turn is your n and whose kind is answer or failed, or at an event of kind stopped.
|
|
111
|
+
- agent_stream: what the conversation's agent shows AS IT HAPPENS — not only the finished reply. Every conversation on claude, codex, copilot or opencode runs in ONE interactive CLI of its own, the same process the browser shows: agent_send and agent_prompt type into it and agent_wait reads each turn's answer off it. agent_stream returns the URL of that CLI's own console output, /v1/terminals/<id>/console, a live Server-Sent Events stream on this same door of frames {seq,ts,kind:"output",text,reset} carrying its raw screen bytes, never a second CLI; attach with a plain HTTP GET, and reconnect with ?after=<seq> of the last frame you read to miss nothing. It is a read: it changes nothing and starts nothing.
|
|
112
|
+
For a long autonomous task, call agent_start, then agent_wait with after=1 and wait=${MAX_WAIT_SECONDS}, again and again with the after each reply returned, until the turn ends; your own reply to the user can be written between reads. A follow-up is agent_send to the same id, then the same agent_wait loop with after = the n it returned.
|
|
113
|
+
To avoid submitting a task twice: agent_start already submitted its text, so do not agent_send the same text after it; a call that timed out or returned working=true has been received and is running, so read on with agent_wait instead of calling agent_prompt, agent_start or agent_send again with the same text.
|
|
114
|
+
To avoid blocking: agent_prompt and agent_wait with wait above 0 each hold the call for up to ${MAX_WAIT_SECONDS} seconds; agent_start, agent_send and agent_wait with wait=0 return at once.
|
|
115
|
+
Example, a quick question: agent_prompt {text:"which branch is BullseyeNotif on?"} returns {conversation, answer}.
|
|
116
|
+
Example, a long task: agent_start {text:"run the release for BullseyeNotif"} returns {id:"c1"}; agent_wait {id:"c1", after:1, wait:${MAX_WAIT_SECONDS}} returns progress events up to n=7; agent_wait {id:"c1", after:7, wait:${MAX_WAIT_SECONDS}} returns the event of kind answer with turn 1. A follow-up, agent_send {id:"c1", text:"now push it"}, returns {n:12}; agent_wait {id:"c1", after:12, wait:${MAX_WAIT_SECONDS}} until the answer with turn 12.`;
|
|
117
|
+
/** The field of an agent_prompt result that carries the event which ended its turn. */
|
|
118
|
+
const REPLY_FIELD = { answer: "answer", failed: "failed" };
|
|
119
|
+
const callerKey = (kind, id) => `mcp:${kind}${createHash("sha256").update(id).digest("hex").slice(0, 12)}`;
|
|
120
|
+
/** Who is calling, decided once from the bearer the door let in: the gateway token's one holder, a door sign-in, or the OAuth client the connector registered, the same across its token refreshes. */
|
|
121
|
+
function callerOf(req) {
|
|
122
|
+
const given = bearer(req);
|
|
123
|
+
if (tokenProves(given, readGatewaySettings().token))
|
|
124
|
+
return "mcp:gateway-token";
|
|
125
|
+
const signedIn = sessionSignIn(given);
|
|
126
|
+
// NULL-OK: field signedIn is OPTIONAL and therefore it is ok to check for NULL
|
|
127
|
+
if (signedIn !== undefined)
|
|
128
|
+
return callerKey("passkey-", signedIn);
|
|
129
|
+
return callerKey("", grantClient(given));
|
|
130
|
+
}
|
|
131
|
+
function headerOf(req, name) {
|
|
132
|
+
const value = req.headers[name];
|
|
133
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
134
|
+
}
|
|
135
|
+
function arrivalOf(requestId, call) {
|
|
136
|
+
return { trace: requestId ?? call, bnTrace: requestId === undefined ? true : undefined };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The POST being served. A caller's server is kept between its calls, so the request's own trace header travels
|
|
140
|
+
* beside the call instead of being fixed inside the server the first call built.
|
|
141
|
+
*/
|
|
142
|
+
const serving = new AsyncLocalStorage();
|
|
143
|
+
/** The workspace the POST being served is scoped to (#4120), or undefined for the machine view of a phone or the public gateway: read at call time, because a caller's server outlives the POST that built it. */
|
|
144
|
+
const viewerNow = () => serving.getStore()?.viewer;
|
|
145
|
+
/** The id of a conversation the caller may see: a scoped caller is refused another workspace's, the machine view is not asked, so a CLI console session that is no conversation still answers it. */
|
|
146
|
+
const seen = (id) => { const viewer = viewerNow(); if (viewer !== undefined)
|
|
147
|
+
scopedConversation(id, viewer); return id; };
|
|
148
|
+
/** The trace header of the POST this tool call arrived on: the call's own, never the one of the call that built the server. */
|
|
149
|
+
const requestIdOf = () => serving.getStore()?.requestId;
|
|
150
|
+
/** How many servers the door has built in this process: a caller's next POST adds none, because it takes the server its previous call left behind. */
|
|
151
|
+
let built = 0;
|
|
152
|
+
/** The servers built so far, which a test reads to prove a caller's second POST reused the server its first left behind. */
|
|
153
|
+
export const serversBuilt = () => built;
|
|
154
|
+
/**
|
|
155
|
+
* The conversation's own agent CLI, when this machine is running it (#3434, #3845, #3916): the one process its turns run
|
|
156
|
+
* in and the browser shows. The registry that holds the CLI is the one truth for it; its output is what `agent_stream`
|
|
157
|
+
* serves, so a stream is the real CLI's own bytes.
|
|
158
|
+
*/
|
|
159
|
+
function liveConsole(id) {
|
|
160
|
+
const terminal = consoleSession(id);
|
|
161
|
+
// NULL-OK: field terminal is OPTIONAL and therefore it is ok to check for NULL
|
|
162
|
+
if (terminal === undefined)
|
|
163
|
+
return undefined;
|
|
164
|
+
// The session belongs to the person (#3370): another person's CLI is refused here with the console route's own 404, never driven.
|
|
165
|
+
if (terminal.owner !== personId())
|
|
166
|
+
throw new GatewayError(404, "Native terminal not found for this person.");
|
|
167
|
+
return terminal;
|
|
168
|
+
}
|
|
169
|
+
/** A conversation's own CLI the driver has not opened yet: the moment it is, within `wait` seconds, or nothing. */
|
|
170
|
+
async function consoleArriving(id, wait) {
|
|
171
|
+
const waited = new AbortController();
|
|
172
|
+
const timer = setTimeout(() => waited.abort(), Math.max(0, Math.min(wait, MAX_WAIT_SECONDS)) * 1000);
|
|
173
|
+
try {
|
|
174
|
+
const arrived = await terminalArriving(id, waited.signal);
|
|
175
|
+
// NULL-OK: field arrived is OPTIONAL and therefore it is ok to check for NULL
|
|
176
|
+
return arrived === undefined ? undefined : liveConsole(id);
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
clearTimeout(timer);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** One bounded read of a conversation's CLI output since `after`, the same frames `agent_stream` serves. */
|
|
183
|
+
async function consoleRead(live, after, wait) {
|
|
184
|
+
const disconnected = new AbortController();
|
|
185
|
+
const timer = setTimeout(() => disconnected.abort(), Math.max(0, Math.min(wait, MAX_WAIT_SECONDS)) * 1000);
|
|
186
|
+
try {
|
|
187
|
+
const frame = await live.read(after, disconnected.signal);
|
|
188
|
+
return { conversation: live.id, console: true, text: frame.data, reset: frame.reset, ended: frame.ended, after: frame.n };
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** The open terminals a viewer may see: its workspace's, and the ones of conversations it created. */
|
|
195
|
+
function scopedListing(listing) {
|
|
196
|
+
if (viewerNow() === undefined)
|
|
197
|
+
return listing;
|
|
198
|
+
return { ...listing, terminals: listing.terminals.filter((t) => { try {
|
|
199
|
+
seen(t.id);
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
if (err instanceof GatewayError)
|
|
204
|
+
return false;
|
|
205
|
+
throw err;
|
|
206
|
+
} }) };
|
|
207
|
+
}
|
|
208
|
+
function buildServer(caller, base, offer) {
|
|
209
|
+
built += 1;
|
|
210
|
+
const server = new McpServer({ name: "notify-agent-gateway", version: PACKAGE_VERSION, icons: iconsFor(base) }, { instructions: instructions(offer), capabilities: EVENTS_CAPABILITY });
|
|
211
|
+
serveEvents(server.server, caller);
|
|
212
|
+
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.`, {
|
|
213
|
+
text: z.string().min(1).describe("The user's request, as the user wrote it"),
|
|
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
|
+
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
|
+
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`),
|
|
217
|
+
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`),
|
|
218
|
+
model: z.string().min(1).optional(),
|
|
219
|
+
}, ({ text, conversation, new: fresh, project, provider, model }) => act(async () => {
|
|
220
|
+
const call = randomUUID().slice(0, 8);
|
|
221
|
+
const arrived = performance.now();
|
|
222
|
+
const arrival = arrivalOf(requestIdOf(), call);
|
|
223
|
+
process.stderr.write(`[agent-gateway] agent_prompt ${call} recv trace=${arrival.trace}\n`);
|
|
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);
|
|
226
|
+
// NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
|
|
227
|
+
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 }
|
|
229
|
+
: { id: seen(target), turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival).n };
|
|
230
|
+
const { events, ended, turn } = await waitForTurn(sent.id, sent.turn, MAX_WAIT_SECONDS);
|
|
231
|
+
const meta = readConversation(sent.id);
|
|
232
|
+
const reply = events.filter((e) => e.turn === turn && REPLY_FIELD[e.kind] !== undefined).at(-1);
|
|
233
|
+
/** Every other event read on the way — an earlier turn's answer included — so nothing past `after` is lost to the client. */
|
|
234
|
+
const others = events.filter((e) => e !== reply).map((e) => ({ n: e.n, role: e.role, kind: e.kind, turn: e.turn, text: e.text }));
|
|
235
|
+
const behind = events.find((e) => e.kind === "queued" && e.turn === sent.turn && e.behind !== undefined)?.behind;
|
|
236
|
+
/** The milliseconds this very call held, from its request arriving to now — the hold it also writes onto its `returned` line. */
|
|
237
|
+
const waitedMs = Math.round(performance.now() - arrived);
|
|
238
|
+
// NULL-OK: field reply is OPTIONAL and therefore it is ok to check for NULL
|
|
239
|
+
const stamped = reply === undefined ? undefined : stampWaitReturn(sent.id, "agent_prompt", [reply], waitedMs, sent.turn, sent.turn);
|
|
240
|
+
const readTo = events.at(-1)?.n ?? sent.turn;
|
|
241
|
+
/** The position the client has read: the stamp this call just wrote is folded in only when it sits right after the last event read, so its next read does not return that line alone and an event another writer put in between is never skipped. */
|
|
242
|
+
const after = stamped !== undefined && stamped.n === readTo + 1 ? stamped.n : readTo;
|
|
243
|
+
const head = { conversation: sent.id, project: meta.project, state: meta.state, ...(behind === undefined ? {} : { queuedBehind: behind }) };
|
|
244
|
+
const started = events.find((e) => e.kind === "start" && e.turn === turn);
|
|
245
|
+
// NULL-OK: field reply is OPTIONAL and therefore it is ok to check for NULL
|
|
246
|
+
const agentMs = started !== undefined && reply !== undefined ? Date.parse(reply.ts) - Date.parse(started.ts) : "none";
|
|
247
|
+
process.stderr.write(`[agent-gateway] agent_prompt ${call} send trace=${arrival.trace} conv=${sent.id} turn=${turn} ended=${ended} gatewayMs=${waitedMs} agentMs=${agentMs}\n`);
|
|
248
|
+
// NULL-OK: field reply is OPTIONAL and therefore it is ok to check for NULL
|
|
249
|
+
if (ended && reply !== undefined)
|
|
250
|
+
return { ...head, [REPLY_FIELD[reply.kind]]: reply.text, timing: reply.timing, waitedMs, events: others, after };
|
|
251
|
+
if (ended)
|
|
252
|
+
return { ...head, stopped: true, waitedMs, events: others, after };
|
|
253
|
+
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
|
+
}));
|
|
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. 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(() => {
|
|
257
|
+
const arrived = performance.now();
|
|
258
|
+
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 });
|
|
260
|
+
return { id: meta.id, state: meta.state };
|
|
261
|
+
}));
|
|
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 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(() => {
|
|
263
|
+
const meta = openConversation({ platform: "mcp", technical: true, chat: caller, project: namedProject(project), provider: namedProvider(provider), model });
|
|
264
|
+
return { id: meta.id, state: meta.state };
|
|
265
|
+
}));
|
|
266
|
+
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(() => {
|
|
267
|
+
const arrived = performance.now();
|
|
268
|
+
return { n: sendToConversation(seen(id), text, Math.round(performance.now() - arrived), arrivalOf(requestIdOf(), randomUUID().slice(0, 8))).n };
|
|
269
|
+
}));
|
|
270
|
+
server.tool("agent_wait", `Reads a conversation's events past position 'after' — a long-poll read the caller repeats, not a notification BN pushes. With wait=0 (the default) it returns at once with whatever is there; with wait above 0 it holds the call until a new event arrives or the wait (at most ${MAX_WAIT_SECONDS} seconds) runs out, and an empty events list means nothing new yet. Repeat the call with the reply's after value (the position it leaves you at, a line it wrote itself included) until the turn you wait on ends: an event of kind answer or failed whose turn is that turn's number (1 after agent_start, the n agent_send returned), or an event of kind stopped. A question the agent asks does not end the turn: a status event says it waits on its own CLI screen, and the turn goes on once the user answers there. after=0 reads the log from the start, earlier turns' answers included. The state is not the end of the turn, because a conversation stays running until its idle process is freed. Reading sends nothing, so it is always safe to call again. Each answer or failed event carries its 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.`, { id: z.string().min(1), after: z.number().int().min(0).default(0).describe("The last event position n already read; events past it are returned. 1 right after agent_start, the n agent_send returned after a send"), wait: z.number().min(0).default(0).describe(`Seconds to hold the call for a new event, capped at ${MAX_WAIT_SECONDS}; 0 returns at once`) }, ({ id, after, wait }) => {
|
|
271
|
+
const arrived = performance.now();
|
|
272
|
+
let outcome;
|
|
273
|
+
const row = (returned) => {
|
|
274
|
+
const line = `[agent-gateway] agent_wait id=${id} after=${after} wait=${wait} returned=${returned} ms=${Math.round(performance.now() - arrived)}`;
|
|
275
|
+
process.stderr.write(`${line.length > 200 ? `${line.slice(0, 197)}...` : line}\n`);
|
|
276
|
+
};
|
|
277
|
+
return act(async () => {
|
|
278
|
+
try {
|
|
279
|
+
seen(id);
|
|
280
|
+
const arrivedAt = lastEventNumber(id);
|
|
281
|
+
const events = await waitForEvents(id, after, wait);
|
|
282
|
+
const last = events.at(-1);
|
|
283
|
+
// NULL-OK: field last is OPTIONAL and therefore it is ok to check for NULL
|
|
284
|
+
const served = { trace: last?.trace, waitedMs: Math.round(performance.now() - arrived), lastEventAgeMs: last === undefined ? undefined : Date.now() - Date.parse(last.ts) };
|
|
285
|
+
const stamped = stampWaitReturn(id, "agent_wait", events, served.waitedMs, after, arrivedAt);
|
|
286
|
+
const readTo = events.at(-1)?.n ?? after;
|
|
287
|
+
outcome = `${events.length} trace=${served.trace} lastEventAgeMs=${served.lastEventAgeMs}`;
|
|
288
|
+
/** The position to send back next: the stamp this call just wrote is folded in only when it sits right after the last event read, so its next read does not return that line alone and an event another writer put in between is never skipped. */
|
|
289
|
+
return { state: readConversation(id).state, events, served, after: stamped !== undefined && stamped.n === readTo + 1 ? stamped.n : readTo };
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
outcome = `refused why=${err instanceof Error ? err.message : String(err)}`;
|
|
293
|
+
throw err;
|
|
294
|
+
}
|
|
295
|
+
}).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; });
|
|
296
|
+
});
|
|
297
|
+
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(seen(id), project)));
|
|
298
|
+
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(scopedConversation(id, viewerNow()))));
|
|
299
|
+
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. Every conversation on claude, codex, copilot or opencode runs in ONE interactive CLI of its own — the same process the browser shows and agent_send types into — and this returns {conversation, url, after, console:true}, url being that CLI's own console output at /v1/terminals/<id>/console. Attach with a plain HTTP GET; the answer is a Server-Sent Events stream of frames {seq, ts, kind:"output", text, reset} carrying its raw screen bytes (its prompt, tool traces and any question it waits on). Reconnect with ?after=<seq> of the last frame you read and you are handed every byte past it. It is a read — it starts no agent, spends nothing and changes nothing.`, { 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(() => {
|
|
300
|
+
seen(id);
|
|
301
|
+
requireOwnCli(id);
|
|
302
|
+
const url = new URL(`/v1/terminals/${id}/console`, base);
|
|
303
|
+
// NULL-OK: field after is OPTIONAL and therefore it is ok to check for NULL
|
|
304
|
+
if (after !== undefined)
|
|
305
|
+
url.searchParams.set("after", String(after));
|
|
306
|
+
return { conversation: id, url: url.toString(), after: after ?? 0, console: true };
|
|
307
|
+
}));
|
|
308
|
+
server.tool("agent_stream_read", `Reads a conversation's LIVE stream as a tool call, as it happens — the same bytes agent_stream's url carries, for a caller that invokes tools and cannot hold a Server-Sent Events connection. Each call returns the conversation's own CLI console output past 'after' as one frame {seq, ts, kind:"output", text, reset}: its raw screen bytes. The reply's 'after' is the value to pass next, so nothing is ever repeated and nothing between two calls is missed. wait=0 (the default) returns at once with whatever is there, and an empty frames list means nothing new yet; wait above 0 holds the call until output arrives, at most ${MAX_WAIT_SECONDS} seconds, also while the conversation's CLI is still being opened. It is a read — it starts no agent, spends nothing and changes nothing. A conversation on a provider whose CLI answers each turn in a process of its own has no CLI to read, and the call says so.`, {
|
|
309
|
+
id: z.string().min(1).describe("The conversation id agent_start, agent_prompt or agent_open returned"),
|
|
310
|
+
after: z.number().int().min(0).default(0).describe("The last frame seq already read; frames past it are returned. 0 reads the stream from its start"),
|
|
311
|
+
wait: z.number().min(0).default(0).describe(`Seconds to hold the call for a new frame, capped at ${MAX_WAIT_SECONDS}; 0 returns at once`),
|
|
312
|
+
}, ({ id, after, wait }) => act(async () => {
|
|
313
|
+
seen(id);
|
|
314
|
+
requireOwnCli(id);
|
|
315
|
+
const asked = Date.now();
|
|
316
|
+
const live = liveConsole(id) ?? await consoleArriving(id, wait);
|
|
317
|
+
// NULL-OK: field live is OPTIONAL and therefore it is ok to check for NULL
|
|
318
|
+
const read = live === undefined ? { text: "", reset: false, after } : await consoleRead(live, after, Math.max(0, wait - (Date.now() - asked) / 1000));
|
|
319
|
+
const frames = read.text === "" && !read.reset ? [] : [{ seq: read.after, ts: new Date().toISOString(), kind: "output", text: read.text, reset: read.reset }];
|
|
320
|
+
return { conversation: id, console: true, frames, seq: read.after, after: read.after };
|
|
321
|
+
}));
|
|
322
|
+
server.tool("agent_list", "Every agent conversation BN holds on this machine, newest first (conversations, not projects — agent_projects lists projects), each with its title, lifecycle (active, idle or completed) and beside as agent_status gives them. archived=true lists the archived ones instead; BN archives a conversation by itself once it has sat 8 hours with no turn in flight, and a message to it brings it back.", { archived: z.boolean().default(false).describe("true lists the Archived conversations instead of the default list") }, ({ archived }) => act(() => ({ conversations: shelvedConversations(archived ? "archived" : "active", viewerNow()).map(describeConversation) })));
|
|
323
|
+
server.tool("agent_stop", "Stop a conversation and free its agent; a later message resumes it.", { id: z.string().min(1) }, ({ id }) => act(() => stopConversation(seen(id))));
|
|
324
|
+
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
|
+
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
|
+
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 name BOTH project (exactly one of ${offer.either}) and provider (one of ${PROVIDER_NAMES.join(", ")}) and a new empty conversation is made on them, with no turn and nothing spent.`, {
|
|
328
|
+
conversation: z.string().min(1).optional().describe("An existing conversation id whose own CLI to open"),
|
|
329
|
+
project: projectField(offer).optional(),
|
|
330
|
+
provider: z.string().min(1).optional(),
|
|
331
|
+
model: z.string().min(1).optional(),
|
|
332
|
+
cols: z.number().int().min(1).max(1000).default(100),
|
|
333
|
+
rows: z.number().int().min(1).max(500).default(30),
|
|
334
|
+
}, (body) => act(() => { if (typeof body.conversation === "string")
|
|
335
|
+
seen(body.conversation.trim()); return openTerminal(body); }));
|
|
336
|
+
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
|
+
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
|
+
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 }; }));
|
|
339
|
+
server.tool("agent_terminal_files", "Hands files to a terminal's CLI as the CLI page's drop does: each file is written where the CLI can read it and its path is returned, to be named in a message. Each file is a name and its base64 contents.", { id: z.string().min(1), files: z.array(z.object({ name: z.string().min(1), data: z.string() })).min(1) }, ({ id, files }) => act(async () => {
|
|
340
|
+
seen(id);
|
|
341
|
+
if (!validFiles(files))
|
|
342
|
+
throw new GatewayError(400, "File transfer failed: expected file names and base64 contents.");
|
|
343
|
+
return { id, paths: await nativeTerminal(personId(), id).inputFiles(files) };
|
|
344
|
+
}));
|
|
345
|
+
server.tool("settings_get", "Everything the Settings page draws, in one reading: the channel state, every group with its rows' current values and next-step line, and the agent-conversation switch. Secrets are returned as stored, as the page shows them to the person who owns this machine.", {}, () => panelAct(() => panelState()));
|
|
346
|
+
server.tool("settings_save", "Saves one Settings row, as the page does: path is the row's key list from settings_get (for example [\"dnd\",\"enabled\"] or [\"telegram\",\"chatIds\"]) and value is checked against that row's kind (on/off, text, list, whole number, HH:MM, days 0-6) before config.json is written and read back. A path that is not a listed row is refused.", { path: z.array(z.string()).min(1), value: z.unknown() }, ({ path, value }) => panelAct(() => saveSetting(path, value)));
|
|
347
|
+
server.tool("conversation_switch", "The agent-conversation On/Off switch the Settings page holds. With no enabled it reads it; enabled=true or false flips it and reads it back. While Off every agent_* act is refused.", { enabled: z.boolean().optional() }, ({ enabled }) => panelAct(() => (enabled === undefined ? conversationSwitchRead() : saveConversationSwitch(enabled))));
|
|
348
|
+
server.tool("public_access", "The Public access wizard's model and its steps. With no step it reads the model. A step is one click: ready (re-look at the machine), createGatewayToken, saveToken (paste = the tunnel token or the command that carries it), install (cloudflared), restartConnector, turnOff, saveHostname (hostname) or check. It answers the model after the step, whose notes say what the step did.", { step: z.enum(["ready", "createGatewayToken", "saveToken", "install", "restartConnector", "turnOff", "saveHostname", "check"]).optional(), paste: z.string().optional(), hostname: z.string().optional() }, ({ step, paste, hostname }) => panelAct(async () => {
|
|
349
|
+
if (step !== undefined)
|
|
350
|
+
await wizard.handle(step, { paste, hostname });
|
|
351
|
+
return wizard.model();
|
|
352
|
+
}));
|
|
353
|
+
server.tool("bn_lifecycle", "BN's own Start, Stop and Restart as the dashboard row and the panel run them. act=state reads the measured state (running, stopped, unreachable ...) with its words and what a Stop would cut. start, stop and restart are pressed in a process that outlives this call — a Stop or Restart ends the process answering you — and the outcome is read afterwards with act=state; a Stop stays until Start. Restart takes and builds the newest main first, exactly as the row does.", { act: z.enum(["state", "start", "stop", "restart"]) }, ({ act: press }) => panelAct(async () => {
|
|
354
|
+
const file = stagedLifecycle();
|
|
355
|
+
return press === "state" ? createRequire(file)(file).row(process.argv[1]).state() : pressLifecycle(file, press);
|
|
356
|
+
}));
|
|
357
|
+
return server;
|
|
358
|
+
}
|
|
359
|
+
const ready = new Map();
|
|
360
|
+
export async function handleMcp(req, res) {
|
|
361
|
+
if (req.method !== "POST")
|
|
362
|
+
throw new GatewayError(405, "the MCP door takes POST only; it holds no session to stream or close");
|
|
363
|
+
const machineCaller = callerOf(req);
|
|
364
|
+
const folder = namedWorkspace(req.headers, fromThisMachine(req));
|
|
365
|
+
// The caller's name carries its workspace, so two workspaces sharing the gateway token never share a current agent or each other's created conversations.
|
|
366
|
+
const caller = folder === undefined ? machineCaller : `${machineCaller}@${folder}`;
|
|
367
|
+
const viewer = folder === undefined ? undefined : { folder, creator: caller };
|
|
368
|
+
const base = publicBase(req);
|
|
369
|
+
const pooled = ready.get(caller);
|
|
370
|
+
ready.delete(caller);
|
|
371
|
+
const offer = projectOffer();
|
|
372
|
+
const offered = JSON.stringify(offer);
|
|
373
|
+
const server = pooled?.base === base && pooled.offered === offered ? pooled.server : buildServer(caller, base, offer);
|
|
374
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
375
|
+
/** 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. */
|
|
376
|
+
let answered = false;
|
|
377
|
+
res.on("close", () => { if (!answered)
|
|
378
|
+
void transport.close(); });
|
|
379
|
+
await server.connect(transport);
|
|
380
|
+
try {
|
|
381
|
+
await serving.run({ requestId: headerOf(req, "x-request-id"), viewer }, () => transport.handleRequest(req, res));
|
|
382
|
+
}
|
|
383
|
+
finally {
|
|
384
|
+
answered = true;
|
|
385
|
+
// Closing the transport frees this server to be connected again: the caller's next POST takes it from the map.
|
|
386
|
+
await transport.close();
|
|
387
|
+
}
|
|
388
|
+
if (!ready.has(caller))
|
|
389
|
+
ready.set(caller, { base, offered, server });
|
|
390
|
+
}
|