omni-notify-mcp 1.3.360 → 1.3.362

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,7 @@ 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 { basename, dirname, join } from "path";
15
+ import { basename, dirname, join, resolve } from "path";
16
16
  import { CONFIG_DIR, masterMuted } from "../notify.js";
17
17
  import { PROVIDER_NAMES, providerFor } from "./providers.js";
18
18
  import { workspacesFile, workspacesHere } from "../shared/webhost/workspaceList.js";
@@ -197,8 +197,28 @@ export function listConversations() {
197
197
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
198
198
  }
199
199
  /** The conversations a door shows on one shelf, newest first; a deleted one is on neither. */
200
- export function shelvedConversations(shelf) {
201
- return listConversations().filter((c) => c.shelf !== "deleted" && (c.shelf === "archived") === (shelf === "archived"));
200
+ export function shelvedConversations(shelf, viewer) {
201
+ return listConversations().filter((c) => c.shelf !== "deleted" && (c.shelf === "archived") === (shelf === "archived") && inScope(c, viewer));
202
+ }
203
+ /** Whether a conversation is shown to a viewer: one in the viewer's workspace, or one the viewer itself created. */
204
+ export function inScope(meta, viewer) {
205
+ if (viewer === undefined)
206
+ return true;
207
+ // NULL-OK: field project is OPTIONAL and therefore it is ok to check for NULL
208
+ if (meta.project !== undefined && sameFolder(meta.project, viewer.folder))
209
+ return true;
210
+ // NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
211
+ return meta.chat !== undefined && meta.chat === viewer.creator;
212
+ }
213
+ /** A viewer is refused a conversation outside its scope in the words a missing one gets: it never learns another workspace's work exists. */
214
+ export function requireInScope(meta, viewer) {
215
+ if (!inScope(meta, viewer))
216
+ throw new GatewayError(404, "conversation not found in this workspace");
217
+ return meta;
218
+ }
219
+ /** The conversation an id names, proven to be in the viewer's scope: every door that takes an id reads it through here. */
220
+ export function scopedConversation(id, viewer) {
221
+ return requireInScope(readConversation(id), viewer);
202
222
  }
203
223
  /** The conversation a chat is holding — its newest one not stopped — so the chat's next message goes on with the same agent. */
204
224
  export function openConversationOf(chat) {
@@ -449,6 +469,51 @@ export function allowedFolder(folder) {
449
469
  throw notAllowedProject();
450
470
  return folder;
451
471
  }
472
+ /** The header a caller names the workspace it is scoped to in (#4120) — the one name BB, FV and BN callers carry. */
473
+ export const SCOPE_HEADER = "x-bullseye-project";
474
+ /** Whether `child` is `parent` or sits inside it. */
475
+ function within(child, parent) {
476
+ const shape = (folder) => folder.replace(/[\\/]+$/, "").replace(/[\\/]/g, "/");
477
+ const [c, p] = process.platform === "win32" ? [shape(child).toLowerCase(), shape(parent).toLowerCase()] : [shape(child), shape(parent)];
478
+ return c === p || c.startsWith(`${p}/`);
479
+ }
480
+ /** The repository a lane worktree was cut from: its `.git` file names `<repo>/.git/worktrees/<name>`. A folder with no such file is no worktree. */
481
+ function worktreeRepo(folder) {
482
+ const marker = join(folder, ".git");
483
+ // NULL-OK: field .git is OPTIONAL and therefore it is ok to check for NULL
484
+ if (!existsSync(marker) || !statSync(marker).isFile())
485
+ return undefined;
486
+ const named = /^gitdir:\s*(.+)$/m.exec(readFileSync(marker, "utf8"));
487
+ // NULL-OK: field gitdir is OPTIONAL and therefore it is ok to check for NULL
488
+ return named === null ? undefined : resolve(folder, named[1].trim(), "..", "..", "..");
489
+ }
490
+ /**
491
+ * #4120 — the listed workspace a header's folder belongs to: the folder itself, a folder inside one, or a lane worktree (under .aw-wt or anywhere) cut from a repository inside one.
492
+ * A folder that belongs to no listed workspace is refused without naming any other workspace's path.
493
+ */
494
+ export function workspaceOf(named) {
495
+ const listed = projectsHere().map((p) => p.folder);
496
+ const repo = worktreeRepo(named);
497
+ const owner = listed.find((folder) => within(named, folder) || (repo !== undefined && within(repo, folder)));
498
+ // NULL-OK: field owner is OPTIONAL and therefore it is ok to check for NULL
499
+ if (owner === undefined)
500
+ throw new GatewayError(400, `the ${SCOPE_HEADER} header names a folder that belongs to no workspace on this machine's list`);
501
+ return owner;
502
+ }
503
+ /** Whether the conversation an id names is in the viewer's scope: a terminal whose id names no conversation is not. */
504
+ export function conversationInScope(id, viewer) {
505
+ return listConversations().some((c) => c.id === id && inScope(c, viewer));
506
+ }
507
+ /** The viewer a REST request is scoped to by its header (#4120), or undefined — the machine view — when it names none. A REST caller never creates a conversation outside its workspace, so its creator name matches nothing the MCP door stamps. */
508
+ export function viewerOfHeaders(headers) {
509
+ const raw = headers[SCOPE_HEADER];
510
+ const named = (Array.isArray(raw) ? raw[0] : raw)?.trim();
511
+ // NULL-OK: field header x-bullseye-project is OPTIONAL and therefore it is ok to check for NULL
512
+ if (named === undefined || named === "")
513
+ return undefined;
514
+ const folder = workspaceOf(named);
515
+ return { folder, creator: `rest:${folder}` };
516
+ }
452
517
  /** Whether two folder paths name the same folder: a trailing separator, and on Windows letter case, do not name another folder. */
453
518
  function sameFolder(a, b) {
454
519
  const shape = (folder) => folder.replace(/[\\/]+$/, "").replace(/[\\/]/g, "/");
@@ -525,8 +590,9 @@ export function requireOwnCli(id) {
525
590
  throw new GatewayError(409, `This conversation's agent is "${named}", which this gateway does not run, so it has no CLI to open.`);
526
591
  }
527
592
  /** #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. */
528
- export function listProjects() {
593
+ export function listProjects(viewer) {
529
594
  const projects = projectsHere()
595
+ .filter((p) => viewer === undefined || sameFolder(p.folder, viewer.folder))
530
596
  .filter((p) => existsSync(p.folder) && statSync(p.folder).isDirectory())
531
597
  .map((p) => ({ name: p.name, path: p.folder, git: existsSync(join(p.folder, ".git")), board: hasBoard(p.folder) }))
532
598
  .sort((a, b) => a.name.localeCompare(b.name));
@@ -21,7 +21,7 @@ import { performance } from "perf_hooks";
21
21
  import { z } from "zod";
22
22
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
23
23
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24
- import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, namedProject, namedProvider, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, } from "./conversations.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, workspaceOf, SCOPE_HEADER, } from "./conversations.js";
25
25
  import { workspacesFile } from "../shared/webhost/workspaceList.js";
26
26
  import { PROVIDER_NAMES } from "./providers.js";
27
27
  import { iconsFor } from "./iconDoor.js";
@@ -140,6 +140,11 @@ function arrivalOf(requestId, call) {
140
140
  * beside the call instead of being fixed inside the server the first call built.
141
141
  */
142
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; };
143
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. */
144
149
  const requestIdOf = () => serving.getStore()?.requestId;
145
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. */
@@ -186,6 +191,20 @@ async function consoleRead(live, after, wait) {
186
191
  clearTimeout(timer);
187
192
  }
188
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
+ }
189
208
  function buildServer(caller, base, offer) {
190
209
  built += 1;
191
210
  const server = new McpServer({ name: "notify-agent-gateway", version: PACKAGE_VERSION, icons: iconsFor(base) }, { instructions: instructions(offer), capabilities: EVENTS_CAPABILITY });
@@ -203,11 +222,11 @@ function buildServer(caller, base, offer) {
203
222
  const arrival = arrivalOf(requestIdOf(), call);
204
223
  process.stderr.write(`[agent-gateway] agent_prompt ${call} recv trace=${arrival.trace}\n`);
205
224
  // NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
206
- const target = conversation ?? (fresh === true ? undefined : routeAsk(caller, text)?.id);
225
+ const target = conversation !== undefined ? seen(conversation) : (fresh === true ? undefined : routeAsk(caller, text)?.id);
207
226
  // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
208
227
  const sent = target === undefined
209
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 }
210
- : { id: target, turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival).n };
229
+ : { id: seen(target), turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival).n };
211
230
  const { events, ended, turn } = await waitForTurn(sent.id, sent.turn, MAX_WAIT_SECONDS);
212
231
  const meta = readConversation(sent.id);
213
232
  const reply = events.filter((e) => e.turn === turn && REPLY_FIELD[e.kind] !== undefined).at(-1);
@@ -233,7 +252,7 @@ function buildServer(caller, base, offer) {
233
252
  return { ...head, stopped: true, waitedMs, events: others, after };
234
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` };
235
254
  }));
236
- 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()));
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())));
237
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(() => {
238
257
  const arrived = performance.now();
239
258
  const arrival = arrivalOf(requestIdOf(), randomUUID().slice(0, 8));
@@ -246,7 +265,7 @@ function buildServer(caller, base, offer) {
246
265
  }));
247
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(() => {
248
267
  const arrived = performance.now();
249
- return { n: sendToConversation(id, text, Math.round(performance.now() - arrived), arrivalOf(requestIdOf(), randomUUID().slice(0, 8))).n };
268
+ return { n: sendToConversation(seen(id), text, Math.round(performance.now() - arrived), arrivalOf(requestIdOf(), randomUUID().slice(0, 8))).n };
250
269
  }));
251
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 }) => {
252
271
  const arrived = performance.now();
@@ -257,6 +276,7 @@ function buildServer(caller, base, offer) {
257
276
  };
258
277
  return act(async () => {
259
278
  try {
279
+ seen(id);
260
280
  const arrivedAt = lastEventNumber(id);
261
281
  const events = await waitForEvents(id, after, wait);
262
282
  const last = events.at(-1);
@@ -274,9 +294,10 @@ function buildServer(caller, base, offer) {
274
294
  }
275
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; });
276
296
  });
277
- 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)));
278
- 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))));
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()))));
279
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);
280
301
  requireOwnCli(id);
281
302
  const url = new URL(`/v1/terminals/${id}/console`, base);
282
303
  // NULL-OK: field after is OPTIONAL and therefore it is ok to check for NULL
@@ -289,6 +310,7 @@ function buildServer(caller, base, offer) {
289
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"),
290
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`),
291
312
  }, ({ id, after, wait }) => act(async () => {
313
+ seen(id);
292
314
  requireOwnCli(id);
293
315
  const asked = Date.now();
294
316
  const live = liveConsole(id) ?? await consoleArriving(id, wait);
@@ -297,11 +319,11 @@ function buildServer(caller, base, offer) {
297
319
  const frames = read.text === "" && !read.reset ? [] : [{ seq: read.after, ts: new Date().toISOString(), kind: "output", text: read.text, reset: read.reset }];
298
320
  return { conversation: id, console: true, frames, seq: read.after, after: read.after };
299
321
  }));
300
- 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 15 minutes 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").map(describeConversation) })));
301
- server.tool("agent_stop", "Stop a conversation and free its agent; a later message resumes it.", { id: z.string().min(1) }, ({ id }) => act(() => stopConversation(id)));
302
- 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(() => (restore ? unarchiveConversation(id) : archiveConversation(id))));
303
- 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(id)));
304
- 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 ? terminalListing(personId()) : nativeTerminal(personId(), id).info())));
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 15 minutes 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()))));
305
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.`, {
306
328
  conversation: z.string().min(1).optional().describe("An existing conversation id whose own CLI to open"),
307
329
  project: projectField(offer).optional(),
@@ -309,11 +331,13 @@ function buildServer(caller, base, offer) {
309
331
  model: z.string().min(1).optional(),
310
332
  cols: z.number().int().min(1).max(1000).default(100),
311
333
  rows: z.number().int().min(1).max(500).default(30),
312
- }, (body) => act(() => openTerminal(body)));
313
- 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(), id)));
314
- 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 () => { await nativeTerminal(personId(), id).input(data, binary); return { id, sent: true }; }));
315
- 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 () => { const size = dimensions({ cols, rows }); await nativeTerminal(personId(), id).resize(size.cols, size.rows); return { id, ...size }; }));
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 }; }));
316
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);
317
341
  if (!validFiles(files))
318
342
  throw new GatewayError(400, "File transfer failed: expected file names and base64 contents.");
319
343
  return { id, paths: await nativeTerminal(personId(), id).inputFiles(files) };
@@ -336,7 +360,13 @@ const ready = new Map();
336
360
  export async function handleMcp(req, res) {
337
361
  if (req.method !== "POST")
338
362
  throw new GatewayError(405, "the MCP door takes POST only; it holds no session to stream or close");
339
- const caller = callerOf(req);
363
+ const machineCaller = callerOf(req);
364
+ const named = headerOf(req, SCOPE_HEADER);
365
+ // NULL-OK: field header x-bullseye-project is OPTIONAL and therefore it is ok to check for NULL
366
+ const folder = named === undefined ? undefined : workspaceOf(named);
367
+ // 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.
368
+ const caller = folder === undefined ? machineCaller : `${machineCaller}@${folder}`;
369
+ const viewer = folder === undefined ? undefined : { folder, creator: caller };
340
370
  const base = publicBase(req);
341
371
  const pooled = ready.get(caller);
342
372
  ready.delete(caller);
@@ -350,7 +380,7 @@ export async function handleMcp(req, res) {
350
380
  void transport.close(); });
351
381
  await server.connect(transport);
352
382
  try {
353
- await serving.run({ requestId: headerOf(req, "x-request-id") }, () => transport.handleRequest(req, res));
383
+ await serving.run({ requestId: headerOf(req, "x-request-id"), viewer }, () => transport.handleRequest(req, res));
354
384
  }
355
385
  finally {
356
386
  answered = true;
@@ -85,7 +85,8 @@ function needSignIn(why) {
85
85
  box.append(input, go);
86
86
  }
87
87
  async function call(method, path, body) {
88
- var r = await fetch(path, { method: method, headers: { authorization: "Bearer " + token, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
88
+ function scoped(h) { var p = new URLSearchParams(location.search).get("project"); if (p !== null) h["x-bullseye-project"] = p; return h; }
89
+ var r = await fetch(path, { method: method, headers: scoped({ authorization: "Bearer " + token, "content-type": "application/json" }), body: body === undefined ? undefined : JSON.stringify(body) });
89
90
  var j = await r.json().catch(function () { return {}; });
90
91
  if (r.status === 401) { needSignIn("This sign-in was not accepted. Sign in again."); throw new Error("not signed in"); }
91
92
  if (!r.ok) throw new Error(j.error || ("HTTP " + r.status));
@@ -9,7 +9,7 @@
9
9
  * once a passkey is enrolled the gateway token is honoured only on a request from this machine.
10
10
  */
11
11
  import { createServer } from "http";
12
- import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, namedProject, namedProvider, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversations.js";
12
+ import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, namedProject, namedProvider, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversations.js";
13
13
  import { CHAT_HEADERS } from "./chatPage.js";
14
14
  import { isIconPath, serveIcon } from "./iconDoor.js";
15
15
  import { handleMcp } from "./mcpDoor.js";
@@ -125,13 +125,17 @@ async function route(req, url, arrivedAt) {
125
125
  }
126
126
  // The conversation page's project picker offers the folders that hold a board (#2723), so it reads them from the one list BN resolves projects with.
127
127
  if (resource === "projects" && parts.length === 2 && method === "GET")
128
- return { status: 200, body: listProjects() };
128
+ return { status: 200, body: listProjects(viewerOfHeaders(req.headers)) };
129
129
  if (resource !== "conversations")
130
130
  throw new GatewayError(404, "unknown route");
131
131
  requireConversationEnabled();
132
+ // Every route that names a conversation reads it through the caller's scope (#4120).
133
+ const viewer = viewerOfHeaders(req.headers);
134
+ if (id !== undefined && viewer !== undefined)
135
+ scopedConversation(id, viewer);
132
136
  if (id === undefined) {
133
137
  if (method === "GET")
134
- return { status: 200, body: { conversations: shelvedConversations(shelfOf(url)) } };
138
+ return { status: 200, body: { conversations: shelvedConversations(shelfOf(url), viewer) } };
135
139
  if (method === "POST") {
136
140
  const body = await readJson(req);
137
141
  const provider = namedProvider(body.provider);
@@ -1,5 +1,5 @@
1
1
  import { WebSocketServer, WebSocket } from "ws";
2
- import { GatewayError, deleteConversation, namedProject, namedProvider, openConversation, requireOwnCli, requireConversationEnabled } from "./conversations.js";
2
+ import { GatewayError, deleteConversation, namedProject, namedProvider, openConversation, requireOwnCli, requireConversationEnabled, scopedConversation, conversationInScope, viewerOfHeaders } from "./conversations.js";
3
3
  import { closeNativeTerminal, consoleSession, nativeTerminal, nativeTerminals, terminalArriving } from "./nativeTerminal.js";
4
4
  import { AgentGateway } from "../agentGateway.js";
5
5
  import { bearer, bearerAdmitted, personId, sessionExpiresAt } from "./passkeyDoor.js";
@@ -139,6 +139,9 @@ export async function terminalConsole(req, res, url) {
139
139
  throw new GatewayError(400, "after must be a non-negative whole number");
140
140
  const disconnected = new AbortController();
141
141
  req.on("close", () => disconnected.abort());
142
+ const viewer = viewerOfHeaders(req.headers);
143
+ if (viewer !== undefined)
144
+ scopedConversation(id, viewer);
142
145
  requireOwnCli(id);
143
146
  const running = consoleSession(id) !== undefined ? nativeTerminal(personId(), id) : undefined;
144
147
  res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", connection: "keep-alive", "x-accel-buffering": "no" });
@@ -218,14 +221,23 @@ export async function openTerminal(body) {
218
221
  export async function terminalRoute(req, url, readJson) {
219
222
  requireConversationEnabled();
220
223
  const owner = personId();
224
+ const viewer = viewerOfHeaders(req.headers);
221
225
  const parts = url.pathname.split("/").filter(Boolean);
222
226
  const method = req.method;
223
227
  if (parts.length === 2) {
224
- if (method === "GET")
225
- return { status: 200, body: await terminalListing(owner) };
226
- if (method === "POST")
227
- return { status: 201, body: await openTerminal(await readJson()) };
228
+ if (method === "GET") {
229
+ const listing = await terminalListing(owner);
230
+ return { status: 200, body: viewer === undefined ? listing : { ...listing, terminals: listing.terminals.filter((t) => conversationInScope(t.id, viewer)) } };
231
+ }
232
+ if (method === "POST") {
233
+ const body = await readJson();
234
+ if (typeof body.conversation === "string" && viewer !== undefined)
235
+ scopedConversation(body.conversation.trim(), viewer);
236
+ return { status: 201, body: await openTerminal(body) };
237
+ }
228
238
  }
239
+ if (viewer !== undefined)
240
+ scopedConversation(parts[2], viewer);
229
241
  const terminal = nativeTerminal(owner, parts[2]);
230
242
  if (parts.length === 3 && method === "DELETE")
231
243
  return { status: 200, body: await closeNativeTerminal(owner, parts[2]) };
@@ -67,6 +67,7 @@ var storedStamp = ${storedStamp.toString()};
67
67
  var carried=/(?:^#|&)token=([^&]+)/.exec(location.hash);
68
68
  if(carried){token=decodeURIComponent(carried[1]);keep(token);history.replaceState(history.state,"",location.pathname+location.search);}
69
69
  // A link may name the view to open on arrival: /terminal?view=term&id=<id> or ?view=chat&id=<id>.
70
+ var scope=new URLSearchParams(location.search).get("project");
70
71
  var deepLink=new URLSearchParams(location.search);
71
72
  if(deepLink.get("view")&&deepLink.get("id")){arrival={view:deepLink.get("view"),id:deepLink.get("id")};}
72
73
 
@@ -94,7 +95,7 @@ function show(name,heading){
94
95
  return view;
95
96
  }
96
97
 
97
- async function api(method,path,body,signal){var response=await fetch(path,{method:method,headers:{authorization:"Bearer "+token,"content-type":"application/json"},body:body===undefined?undefined:JSON.stringify(body),signal:signal});var data=await response.json();if(!response.ok){if(response.status===401)signIn("Sign in again to reach your CLI.");var error=Error(data.error||"Request failed");error.status=response.status;throw error;}return data;}
98
+ function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}async function api(method,path,body,signal){var response=await fetch(path,{method:method,headers:scoped({authorization:"Bearer "+token,"content-type":"application/json"}),body:body===undefined?undefined:JSON.stringify(body),signal:signal});var data=await response.json();if(!response.ok){if(response.status===401)signIn("Sign in again to reach your CLI.");var error=Error(data.error||"Request failed");error.status=response.status;throw error;}return data;}
98
99
  function fail(error){note.textContent=error.message;}
99
100
  function ordered(id,act,body){if(!socket||socket.readyState!==WebSocket.OPEN)return;socket.send(JSON.stringify(Object.assign({kind:act},body)));}
100
101
  /** The last folder of a path, so a row names its project without printing the whole path. */
@@ -1,8 +1,10 @@
1
1
  import { execFile, spawn, spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
+ import { Agent } from "node:http";
4
5
  import { homedir, tmpdir } from "node:os";
5
6
  import * as path from "node:path";
7
+ import { Duplex } from "node:stream";
6
8
  export function isProcessAlive(pid) {
7
9
  try {
8
10
  process.kill(pid, 0);
@@ -176,6 +178,258 @@ export function ownerBoundLaunch(invocation, ownerPid, cwd, guardDir) {
176
178
  args: [path.join(guardDir, "ownerGuard.cjs"), String(ownerPid), encoded(invocation.cmd), encoded(JSON.stringify(invocation.args)), encoded(cwd)],
177
179
  };
178
180
  }
181
+ // GATE: how long one request to the native Codex daemon may take before it is refused with that wait named — the daemon answers these in well under a second
182
+ const CODEX_REQUEST_MS = 10_000;
183
+ // GATE: how long one Codex CLI command (`login status`, `app-server daemon start`) may run before its tree is ended and refused with that wait named — each answers in about a second
184
+ const CODEX_CLI_MS = 60_000;
185
+ /** 🔴 #3951 — the Codex CLI or its daemon could not be reached, refused a request, or answered outside its documented outcomes; the message carries its words. */
186
+ export class CodexControlFailed extends Error {
187
+ }
188
+ /** The native Codex daemon answered a request with an error, so what it was asked was not done. */
189
+ export class CodexRefused extends CodexControlFailed {
190
+ }
191
+ /**
192
+ * 🔴 #3504/#3951 — THE ONE CONTROL OF THE NATIVE CODEX DAEMON every Bullseye host shares: FleetView's window posts a press into
193
+ * a Codex main through it, and a host with no window brings the daemon up, reuses the board's live Codex main or opens ONE,
194
+ * and posts into it the same way (Meni, Q796: "Service creates one Codex main, then posts"). It speaks the daemon's own
195
+ * app-server protocol over `codex app-server proxy`, bound to this process by the owner guard, so it never runs a second
196
+ * app server or a `codex exec`.
197
+ */
198
+ export class CodexControl {
199
+ proxy;
200
+ socket;
201
+ opening;
202
+ nextId = 0;
203
+ generation = 0;
204
+ pending = new Map();
205
+ project;
206
+ guardDir;
207
+ cli;
208
+ constructor(project, guardDir, cli = { cmd: "codex", args: [] }) {
209
+ this.project = project;
210
+ this.guardDir = guardDir;
211
+ this.cli = cli;
212
+ }
213
+ /** The Codex CLI's own word on this box's sign-in: signed in, not signed in, or not installed — anything else it says is refused. */
214
+ async login() {
215
+ const ran = await this.run(["login", "status"]);
216
+ if (ran.code === 0)
217
+ return { signedIn: true };
218
+ if (ran.code === 1 && /not logged in/i.test(ran.said))
219
+ return { signedIn: false, why: `the Codex CLI on this box is not signed in ("codex login status" says: ${ran.said.split(/\r?\n/).pop()})` };
220
+ if (ran.code === 96 || ran.code === 127)
221
+ return { signedIn: false, why: `the Codex CLI could not be started on this box, so no Codex login exists here (${ran.said})` };
222
+ throw new CodexControlFailed(`"codex login status" ended ${ran.code}: ${ran.said || "it printed nothing"}`);
223
+ }
224
+ /** The native daemon running on this box: started when it is not, left alone when it is (`codex app-server daemon start` is both). */
225
+ async daemonUp() {
226
+ const ran = await this.run(["app-server", "daemon", "start"]);
227
+ if (ran.code !== 0)
228
+ throw new CodexControlFailed(`"codex app-server daemon start" ended ${ran.code}: ${ran.said || "it printed nothing"}`);
229
+ }
230
+ /** Every Codex main the daemon holds loaded right now, each with the threads it spawned and whether it is mid-turn. */
231
+ async mains() {
232
+ await this.open();
233
+ const loaded = (await this.request("thread/loaded/list", {}));
234
+ const threads = await Promise.all(loaded.data.map(async (threadId) => (await this.request("thread/read", { threadId, includeTurns: false })).thread));
235
+ const rootOf = (thread) => {
236
+ const seen = new Set();
237
+ let current = thread;
238
+ while (!seen.has(current.id)) {
239
+ seen.add(current.id);
240
+ const parentId = typeof current.source === "object" ? current.source.subAgent?.thread_spawn?.parent_thread_id : undefined;
241
+ if (parentId === undefined)
242
+ return current.id;
243
+ const parent = threads.find((candidate) => candidate.id === parentId);
244
+ if (parent === undefined)
245
+ return parentId;
246
+ current = parent;
247
+ }
248
+ throw new CodexControlFailed("the native Codex daemon reported a cycle in its parent links");
249
+ };
250
+ return threads
251
+ .filter((thread) => thread.source === "vscode" || thread.source === "cli")
252
+ .map((thread) => ({
253
+ threadId: thread.id,
254
+ cwd: thread.cwd,
255
+ // NULL-OK: field name is OPTIONAL and therefore it is ok to check for NULL
256
+ name: thread.name ?? `Codex ${thread.id.slice(0, 8)}`,
257
+ ownedThreadIds: threads.filter((child) => child.id !== thread.id && rootOf(child) === thread.id).map((child) => child.id),
258
+ working: thread.status.type === "active",
259
+ }));
260
+ }
261
+ /** A new Codex main opened in `cwd` under `name` — the one a host with no live Codex main for its board opens, idle until a press is posted into it. */
262
+ async startMain(cwd, name) {
263
+ await this.open();
264
+ const started = (await this.request("thread/start", { cwd }));
265
+ await this.request("thread/name/set", { threadId: started.thread.id, name });
266
+ return { threadId: started.thread.id, cwd: started.thread.cwd, name, ownedThreadIds: [], working: false };
267
+ }
268
+ /**
269
+ * 🔴 #3951 — THE ONE CODEX MAIN OF A BOARD, for a host with no window (Meni, Q796: "Service creates one Codex main, then
270
+ * posts"): the daemon is brought up, a live Codex main whose folder `reaches` is reused, and only when none is alive is ONE
271
+ * opened in `cwd` under `name`.
272
+ */
273
+ async mainFor(reaches, cwd, name) {
274
+ await this.daemonUp();
275
+ const live = (await this.mains()).find((m) => reaches(m.cwd));
276
+ // NULL-OK: field live is OPTIONAL and therefore it is ok to check for NULL
277
+ return live !== undefined ? { main: live, opened: false } : { main: await this.startMain(cwd, name), opened: true };
278
+ }
279
+ /** `message` posted into the main's thread as his next turn: steered into the turn it is running, else started as a new one; `beforeSend` runs right before it goes and may refuse it by throwing. */
280
+ async post(threadId, message, beforeSend = () => { }) {
281
+ await this.open();
282
+ const input = [{ type: "text", text: message }];
283
+ const active = await this.activeTurn(threadId);
284
+ beforeSend();
285
+ if (active !== undefined)
286
+ await this.request("turn/steer", { threadId, expectedTurnId: active.id, input });
287
+ else
288
+ await this.request("turn/start", { threadId, input });
289
+ }
290
+ dispose() {
291
+ ++this.generation;
292
+ this.failPending(new CodexControlFailed("the native Codex control connection was closed by its owner"));
293
+ this.socket?.terminate();
294
+ this.proxy?.kill();
295
+ this.socket = undefined;
296
+ this.opening = undefined;
297
+ }
298
+ /** The CLI behind this process's owner guard, which also finds the CLI's .cmd shim on Windows. */
299
+ bound(invocation) {
300
+ return ownerBoundLaunch(invocation, process.pid, this.project, this.guardDir);
301
+ }
302
+ run(args) {
303
+ const launch = this.bound({ cmd: this.cli.cmd, args: [...this.cli.args, ...args] });
304
+ return new Promise((resolve, reject) => {
305
+ const child = spawn(launch.cmd, launch.args, { cwd: this.project, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } });
306
+ let said = "";
307
+ child.stdout.on("data", (chunk) => (said += chunk.toString("utf8")));
308
+ child.stderr.on("data", (chunk) => (said += chunk.toString("utf8")));
309
+ const bound = setTimeout(() => {
310
+ killTree(child);
311
+ reject(new CodexControlFailed(`"codex ${args.join(" ")}" did not end within ${CODEX_CLI_MS / 1000} seconds, so its process tree was ended: ${said.trim() || "it printed nothing"}`));
312
+ }, CODEX_CLI_MS);
313
+ child.on("error", (cause) => {
314
+ clearTimeout(bound);
315
+ reject(cause);
316
+ });
317
+ child.on("exit", (code, signal) => {
318
+ clearTimeout(bound);
319
+ if (code === null)
320
+ reject(new CodexControlFailed(`"codex ${args.join(" ")}" was ended by ${signal}: ${said.trim() || "it printed nothing"}`));
321
+ else
322
+ resolve({ code, said: said.trim() });
323
+ });
324
+ });
325
+ }
326
+ open() {
327
+ // NULL-OK: field opening is OPTIONAL and therefore it is ok to check for NULL
328
+ if (this.opening !== undefined)
329
+ return this.opening;
330
+ if (this.socket !== undefined && this.socket.readyState === this.socket.OPEN)
331
+ return Promise.resolve();
332
+ const generation = ++this.generation;
333
+ this.opening = import("ws").then(({ default: Socket }) => new Promise((resolve, reject) => {
334
+ const launch = this.bound({ cmd: this.cli.cmd, args: [...this.cli.args, "app-server", "proxy"] });
335
+ const proxy = (this.proxy = spawn(launch.cmd, launch.args, { cwd: this.project, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } }));
336
+ const stream = Duplex.from({ readable: proxy.stdout, writable: proxy.stdin });
337
+ const connection = Object.assign(stream, { connecting: false, setTimeout: () => stream, setNoDelay: () => stream, setKeepAlive: () => stream });
338
+ const agent = new Agent();
339
+ agent.createConnection = () => connection;
340
+ const socket = (this.socket = new Socket("ws://localhost/", { agent, handshakeTimeout: CODEX_REQUEST_MS }));
341
+ let said = "";
342
+ proxy.stderr.on("data", (chunk) => (said += chunk.toString("utf8")));
343
+ const ended = new Promise((done) => {
344
+ proxy.once("exit", (code) => done(`the native Codex control proxy ended (exit ${code}): ${said.trim() || "it printed nothing"}`));
345
+ proxy.once("error", (cause) => done(`the native Codex control proxy could not be started: ${cause.message}`));
346
+ });
347
+ let initialized = false;
348
+ const failed = (cause) => {
349
+ if (!initialized)
350
+ void ended.then((why) => reject(new CodexControlFailed(`${cause.message}; ${why}`)));
351
+ if (this.generation === generation) {
352
+ this.socket = undefined;
353
+ this.failPending(cause instanceof CodexControlFailed ? cause : new CodexControlFailed(`the native Codex control connection failed: ${cause.message}`));
354
+ }
355
+ socket.terminate();
356
+ proxy.kill();
357
+ };
358
+ proxy.on("error", failed);
359
+ stream.on("error", failed);
360
+ proxy.on("exit", () => failed(new CodexControlFailed("the native Codex control proxy exited")));
361
+ socket.on("error", failed);
362
+ socket.on("close", () => failed(new CodexControlFailed("the native Codex control connection closed")));
363
+ socket.on("message", (data) => {
364
+ if (this.generation !== generation)
365
+ return;
366
+ let message;
367
+ try {
368
+ message = JSON.parse(data.toString());
369
+ }
370
+ catch (cause) {
371
+ if (!(cause instanceof SyntaxError))
372
+ throw cause;
373
+ failed(cause);
374
+ return;
375
+ }
376
+ // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
377
+ if (message.id === undefined)
378
+ return;
379
+ const pending = this.pending.get(message.id);
380
+ // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
381
+ if (pending === undefined)
382
+ return;
383
+ clearTimeout(pending.timer);
384
+ this.pending.delete(message.id);
385
+ // NULL-OK: field error is OPTIONAL and therefore it is ok to check for NULL
386
+ if (message.error !== undefined)
387
+ pending.reject(new CodexRefused(message.error.message));
388
+ else
389
+ pending.resolve(message.result);
390
+ });
391
+ socket.once("open", () => {
392
+ void this.request("initialize", { clientInfo: { name: "bullseye", version: "1.0.0" }, capabilities: { experimentalApi: true } }).then(() => {
393
+ socket.send(JSON.stringify({ method: "initialized", params: {} }));
394
+ initialized = true;
395
+ resolve();
396
+ }, failed);
397
+ });
398
+ })).finally(() => {
399
+ if (this.generation === generation)
400
+ this.opening = undefined;
401
+ });
402
+ return this.opening;
403
+ }
404
+ failPending(cause) {
405
+ for (const pending of this.pending.values()) {
406
+ clearTimeout(pending.timer);
407
+ pending.reject(cause);
408
+ }
409
+ this.pending.clear();
410
+ }
411
+ request(method, params) {
412
+ const socket = this.socket;
413
+ if (socket === undefined || socket.readyState !== socket.OPEN)
414
+ return Promise.reject(new CodexControlFailed("the native Codex control connection is not open"));
415
+ const id = ++this.nextId;
416
+ return new Promise((resolve, reject) => {
417
+ const timer = setTimeout(() => {
418
+ this.pending.delete(id);
419
+ reject(new CodexControlFailed(`native Codex ${method} did not answer within ${CODEX_REQUEST_MS / 1000} seconds`));
420
+ }, CODEX_REQUEST_MS);
421
+ this.pending.set(id, { resolve, reject, timer });
422
+ socket.send(JSON.stringify({ id, method, params }));
423
+ });
424
+ }
425
+ async activeTurn(threadId) {
426
+ const { thread } = (await this.request("thread/read", { threadId, includeTurns: false }));
427
+ if (thread.status.type !== "active")
428
+ return undefined;
429
+ const turns = (await this.request("thread/turns/list", { threadId, limit: 1, sortDirection: "desc", itemsView: "notLoaded" }));
430
+ return turns.data.find((turn) => turn.status === "inProgress");
431
+ }
432
+ }
179
433
  // GATE: how long a CLI tree gets to exit on SIGTERM before it is SIGKILLed — POSIX only; Windows stops it at once
180
434
  const KILL_GRACE_MS = 2_000;
181
435
  export function killTree(child) {
@@ -1614,6 +1868,13 @@ export function requestedStories(board) {
1614
1868
  return [];
1615
1869
  return fs.readdirSync(dir).filter((f) => /^\d+\.json$/.test(f)).map((f) => Number(f.slice(0, -".json".length)));
1616
1870
  }
1871
+ /** 🔴 #3951 — every story FleetView's story queue stopped on the board, with the queue's own words: the ack that answers its standing request reads `failed`. */
1872
+ export function storyQueueStops(board) {
1873
+ return requestedStories(board).flatMap((id) => {
1874
+ const ack = readStoryAck(board, id);
1875
+ return ack?.state === "failed" && ack.requestId === readStoryRequest(board, id)?.requestId ? [[id, `FleetView's story queue could not start it: ${ack.why}`]] : [];
1876
+ });
1877
+ }
1617
1878
  // GATE: how long a request no ack names waits before BB writes it again — FV acks within one beat, so past this the request or its ack was lost, or FV is down
1618
1879
  export const ACK_LATE_MS = 60_000;
1619
1880
  // GATE: how long an unacknowledged request may stand before the board's OWN SURFACE says FleetView has not answered it — a reading of the page's words, never a re-send, so a beat that lags no longer tells Meni FleetView is down while it is working
@@ -1755,6 +2016,8 @@ function placeAt(store, e, k) {
1755
2016
  const step = (e, at, stage, detail) => {
1756
2017
  e.trace.push({ at, stage, detail });
1757
2018
  };
2019
+ /** The provider values a request may carry: the two the queue starts workers on, and `auto`, which it resolves to one of them at the start. */
2020
+ export const QUEUE_PROVIDER_CHOICES = ["claude", "codex", "auto"];
1758
2021
  /** Why a request cannot be queued at all, or undefined: the wire version and the two fields its order is made of, checked at this boundary. */
1759
2022
  function refusalOf(r) {
1760
2023
  if (r.v !== STORY_QUEUE_WIRE)
@@ -1763,8 +2026,8 @@ function refusalOf(r) {
1763
2026
  return `priority "${r.pri}" is none of ${PRI_ORDER.join(" ")}`;
1764
2027
  if (rankIn(EFFORT_ORDER, r.effort) === -1)
1765
2028
  return `size "${r.effort}" is none of ${EFFORT_ORDER.join(" ")}`;
1766
- if (r.eligible && r.provider !== "claude")
1767
- return `provider "${r.provider}" is not started by this queue — a Codex-owned story goes to FleetView's one Codex main (#3951), never to a worker of its own`;
2029
+ if (r.eligible && !QUEUE_PROVIDER_CHOICES.includes(r.provider))
2030
+ return `provider "${r.provider}" is not started by this queue — it starts Claude workers, posts Codex-owned stories into the board's one Codex main, and starts an AUTO story on whichever of the two has subscription room`;
1768
2031
  return undefined;
1769
2032
  }
1770
2033
  /** One request applied to the store: an entry made, updated, withdrawn or put back in line; answers the refusal when it cannot be queued. */
@@ -1809,11 +2072,24 @@ function applyRequest(store, r, now) {
1809
2072
  }
1810
2073
  /** The provider refused to start a story's worker: its own words, which the entry carries and the queue starts again on its backoff. */
1811
2074
  export class WorkerNotStarted extends Error {
1812
- constructor(message) {
2075
+ /** Whether the queue starts it again on its backoff. */
2076
+ retried = true;
2077
+ /** Whether the provider answered that the start never reached it, so a worker recorded right before the send stands for nothing. */
2078
+ unsent;
2079
+ constructor(message, unsent = false) {
1813
2080
  super(message);
2081
+ this.unsent = unsent;
1814
2082
  this.name = "WorkerNotStarted";
1815
2083
  }
1816
2084
  }
2085
+ /** 🔴 #3951 — the provider cannot start the story as this box stands (its CLI has no login): the entry stops `failed` with the provider's words at once, spends no attempt, and the box is read again after {@link RETRY_BASE_MS}, so a login made later starts it. */
2086
+ export class WorkerRefused extends WorkerNotStarted {
2087
+ retried = false;
2088
+ constructor(message) {
2089
+ super(message);
2090
+ this.name = "WorkerRefused";
2091
+ }
2092
+ }
1817
2093
  // GATE: how many times one story's worker is started before the queue gives up on it and its entry stops in `failed` — each start that ends with the story still open is one
1818
2094
  export const WORKER_ATTEMPTS = 3;
1819
2095
  // GATE: the wait before a story whose worker ended is started again: this, doubled for each earlier attempt
@@ -1838,14 +2114,22 @@ function writeAcks(board, store, refusals, applied, now) {
1838
2114
  writeWhole(board, ackFile(board, storyId), ack);
1839
2115
  }
1840
2116
  }
1841
- /** A worker that ended with its story still open: started again after its backoff, or stopped in `failed` past {@link WORKER_ATTEMPTS}. */
1842
- function afterWorker(e, now, why) {
2117
+ /** A worker that ended with its story still open: started again after its backoff, stopped in `failed` past {@link WORKER_ATTEMPTS}, or at once when its provider refused it as the box stands (`retried` false), read again after the first backoff. */
2118
+ function afterWorker(e, now, why, retried = true) {
1843
2119
  if (!e.eligible) {
1844
2120
  e.state = "withdrawn";
1845
2121
  step(e, now, "withdrawn", e.why);
1846
2122
  }
2123
+ else if (!retried) {
2124
+ e.state = "failed";
2125
+ e.attempts -= 1;
2126
+ e.nextTryAt = now + RETRY_BASE_MS;
2127
+ e.why = `${why}; the box is read again at ${new Date(e.nextTryAt).toISOString()}`;
2128
+ step(e, now, "failed", e.why);
2129
+ }
1847
2130
  else if (e.attempts >= WORKER_ATTEMPTS) {
1848
2131
  e.state = "failed";
2132
+ delete e.nextTryAt;
1849
2133
  e.why = `its worker was started ${e.attempts} times and the story is still open — the last: ${why}`;
1850
2134
  step(e, now, "failed", e.why);
1851
2135
  }
@@ -1940,7 +2224,8 @@ export async function driveStoryQueue(board, world, now) {
1940
2224
  save();
1941
2225
  let lanes = world.lanesRunning();
1942
2226
  for (const e of queueOrder(store)) {
1943
- if (!e.eligible || !(e.state === "queued" || (e.state === "retrying" && e.nextTryAt <= now)))
2227
+ // NULL-OK: field nextTryAt is OPTIONAL and therefore it is ok to check for NULL
2228
+ if (!e.eligible || !(e.state === "queued" || ((e.state === "retrying" || e.state === "failed") && e.nextTryAt !== undefined && e.nextTryAt <= now)))
1944
2229
  continue;
1945
2230
  const held = world.heldBy(e.storyId);
1946
2231
  if (held !== undefined) {
@@ -1954,7 +2239,7 @@ export async function driveStoryQueue(board, world, now) {
1954
2239
  // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
1955
2240
  if (e.worker !== undefined && world.worker(e, board).alive) {
1956
2241
  e.state = "running";
1957
- e.why = `its ${e.provider} worker ${e.worker.jobId} still runs, so no second worker is started`;
2242
+ e.why = `its ${e.worker.provider} worker ${e.worker.jobId} still runs, so no second worker is started`;
1958
2243
  step(e, now, "started", e.why);
1959
2244
  continue;
1960
2245
  }
@@ -1965,27 +2250,32 @@ export async function driveStoryQueue(board, world, now) {
1965
2250
  save();
1966
2251
  lanes += 1;
1967
2252
  try {
1968
- e.worker = await world.launch(e, board);
1969
- e.why = `its ${e.provider} worker ${e.worker.jobId} was started`;
2253
+ e.worker = await world.launch(e, board, (sent) => {
2254
+ e.worker = sent;
2255
+ save();
2256
+ });
2257
+ e.why = `its ${e.worker.provider} worker ${e.worker.jobId} was started`;
1970
2258
  step(e, Date.now(), "started", e.why);
1971
2259
  }
1972
2260
  catch (err) {
1973
2261
  if (!(err instanceof WorkerNotStarted))
1974
2262
  throw err;
2263
+ if (err.unsent)
2264
+ delete e.worker;
1975
2265
  const made = world.worker(e, board);
1976
2266
  // NULL-OK: field found is OPTIONAL and therefore it is ok to check for NULL
1977
2267
  if (made.alive && made.found !== undefined) {
1978
2268
  // OWNER: ITER/LOOP — the start answered no job id, yet the provider made the story's job: that job is the entry's worker, so no second one is started.
1979
2269
  e.worker = made.found;
1980
- e.why = `its ${e.provider} worker ${made.found.jobId} runs, though its start answered: ${err.message}`;
2270
+ e.why = `its ${made.found.provider} worker ${made.found.jobId} runs, though its start answered: ${err.message}`;
1981
2271
  step(e, Date.now(), "started", e.why);
1982
2272
  save();
1983
2273
  continue;
1984
2274
  }
1985
- // OWNER: ITER/LOOP — the provider refused this story's start, so its entry carries the provider's words and is started again on its backoff like a worker that ended; the next entry in line is started.
2275
+ // OWNER: ITER/LOOP — the provider refused this story's start, so its entry carries the provider's words and is started again on its backoff like a worker that ended, or stops failed when the provider refused it for good; the next entry in line is started.
1986
2276
  lanes -= 1;
1987
2277
  step(e, Date.now(), "worker-ended", `its ${e.provider} worker could not be started: ${err.message}`);
1988
- afterWorker(e, now, `its ${e.provider} worker could not be started: ${err.message}`);
2278
+ afterWorker(e, now, `its ${e.provider} worker could not be started: ${err.message}`, err.retried);
1989
2279
  }
1990
2280
  save();
1991
2281
  }
@@ -2109,3 +2399,26 @@ export function launchStoryWorker(entry, board, cli, now) {
2109
2399
  });
2110
2400
  });
2111
2401
  }
2402
+ /**
2403
+ * 🔴 #3951 — A CODEX-OWNED STORY'S START (Meni, Q796: "Service creates one Codex main, then posts"): the box's Codex login is
2404
+ * read, a live Codex main whose folder `reaches` the board is reused or ONE is opened in the board's folder under `name`, and
2405
+ * `message` is posted into it — never a Claude chat, a `codex exec` or a second app server; `record` is handed the worker right
2406
+ * before the post is sent. No login is {@link WorkerRefused}; a daemon that cannot be reached or refuses is
2407
+ * {@link WorkerNotStarted}, started again on the queue's backoff.
2408
+ */
2409
+ export async function postCodexStory(control, board, reaches, name, message, now, record) {
2410
+ try {
2411
+ const login = await control.login();
2412
+ if (!login.signedIn)
2413
+ throw new WorkerRefused(login.why);
2414
+ const { main } = await control.mainFor(reaches, board, name);
2415
+ const worker = { provider: "codex", startedAt: now, jobId: main.threadId };
2416
+ await control.post(main.threadId, message, () => record(worker));
2417
+ return worker;
2418
+ }
2419
+ catch (err) {
2420
+ if (!(err instanceof CodexControlFailed))
2421
+ throw err;
2422
+ throw new WorkerNotStarted(err.message, err instanceof CodexRefused);
2423
+ }
2424
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.360",
3
+ "version": "1.3.362",
4
4
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
5
5
  "main": "dist/daemon.js",
6
6
  "type": "module",