omni-notify-mcp 1.3.489 → 1.3.491

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.
@@ -385,6 +385,8 @@ class TranscriptTail {
385
385
  file;
386
386
  offset = 0;
387
387
  rest = "";
388
+ /** When the turn began: a transcript found only after it began — a resumed or forked session's file is written whole, history first — is read from its start, so only an entry stamped from this time on is this turn's (#4927). */
389
+ since = Date.now();
388
390
  timer;
389
391
  /** Why the transcript could not be read on the last tick, named once until a read succeeds again. */
390
392
  unread;
@@ -470,7 +472,7 @@ class TranscriptTail {
470
472
  this.log(`transcript ${this.sessionId}: a line is not JSON (${err.message}) — it is left out of the chat's preview`);
471
473
  return;
472
474
  }
473
- if (!Array.isArray(entry.message?.content))
475
+ if (!Array.isArray(entry.message?.content) || typeof entry.timestamp !== "string" || Date.parse(entry.timestamp) < this.since)
474
476
  return;
475
477
  for (const block of entry.message.content) {
476
478
  if (entry.type === "assistant" && block.type === "text" && typeof block.text === "string")
@@ -498,8 +500,7 @@ export function streamedChat(messenger, log) {
498
500
  return {
499
501
  say: async (text) => { await messenger.send(text); },
500
502
  turn(turn) {
501
- const chat = turn.parallel === true ? messenger.alongside() : messenger;
502
- const reply = new StreamedReply(chat, log);
503
+ const reply = new StreamedReply(messenger, log);
503
504
  let tail;
504
505
  const ended = () => {
505
506
  // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
@@ -555,7 +556,7 @@ export function streamedChat(messenger, log) {
555
556
  case "restored":
556
557
  return;
557
558
  default:
558
- await chat.send(event.text);
559
+ await messenger.send(event.text);
559
560
  return;
560
561
  }
561
562
  },
package/dist/daemon.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * inbox files under the config dir: nothing is held only in its memory, so a restart of this process loses no message.
10
10
  */
11
11
  import { spawn } from "child_process";
12
- import { existsSync, readFileSync, mkdirSync } from "fs";
12
+ import { createWriteStream, existsSync, readFileSync, mkdirSync, renameSync } from "fs";
13
13
  import { join } from "path";
14
14
  import { fileURLToPath } from "url";
15
15
  import { DAEMON_BEAT_PATH, CONFIG_DIR, DAEMON_TAG, PACKAGE_VERSION, startNotifyServer, takePendingInbox, writeRecordFile, yieldGateway } from "./notify.js";
@@ -84,10 +84,46 @@ if (stoppedByHand()) {
84
84
  console.log("[BOOT] BullseyeNotify daemon — a Stop was pressed on this machine; nothing started, and nothing beats until Start is pressed in the panel or the machine reboots.");
85
85
  process.exit(0);
86
86
  }
87
+ /** Where this daemon's console goes as well as to its own (#4927): every owner starts it with no console kept, so its output is otherwise lost. Each run begins the file and moves the run before it to the previous file, which that run, a build handing over, goes on writing — so the hand-over and the crash before a start both read whole. */
88
+ const LOG_FILE = join(CONFIG_DIR, "bn-daemon.log");
89
+ const PREVIOUS_LOG_FILE = join(CONFIG_DIR, "bn-daemon.previous.log");
90
+ function keepConsole() {
91
+ mkdirSync(CONFIG_DIR, { recursive: true });
92
+ try {
93
+ if (existsSync(LOG_FILE))
94
+ renameSync(LOG_FILE, PREVIOUS_LOG_FILE);
95
+ }
96
+ catch (err) {
97
+ if (!(err instanceof Error) || !("code" in err))
98
+ throw err;
99
+ // OWNER: the console copy is for reading afterwards — a previous file the disk will not move (locked, denied) leaves the daemon without a copy this run, named once, and it serves on.
100
+ process.stderr.write(`[BOOT] no console copy this run: ${LOG_FILE} could not be moved aside — ${err.message}
101
+ `);
102
+ return;
103
+ }
104
+ const file = createWriteStream(LOG_FILE, { flags: "w" });
105
+ let kept = true;
106
+ // OWNER: the daemon's console is a copy for reading afterwards — a file the disk refuses (full, locked, denied) ends the copy, named once on the console itself, and the daemon serves on.
107
+ file.on("error", (err) => {
108
+ kept = false;
109
+ process.stderr.write(`[BOOT] the console copy in ${LOG_FILE} stopped — ${err.message}
110
+ `);
111
+ });
112
+ for (const stream of [process.stdout, process.stderr]) {
113
+ const write = stream.write.bind(stream);
114
+ stream.write = ((chunk, ...rest) => {
115
+ if (kept)
116
+ file.write(chunk);
117
+ return write(chunk, ...rest);
118
+ });
119
+ }
120
+ console.log(`[BOOT] BullseyeNotify daemon pid ${process.pid} v${PACKAGE_VERSION} at ${new Date().toISOString()} — console kept in ${LOG_FILE}`);
121
+ }
87
122
  // The shared hand-over (src/shared/webhost/originHandover.js ensureResidentDoor) puts a later release on the chat door: the new build is started with --takeover over an IPC channel, says it waits, and binds once this build lets the door go.
88
123
  const takeover = process.argv.includes("--takeover");
89
124
  /** Whether this process writes the heartbeat: the next release only from the moment it holds the chat door, so a takeover that never lands leaves the serving build's beat alone; and a build that let the door go no longer, so the release that took it is the one beat. */
90
125
  let beating = !takeover;
126
+ keepConsole();
91
127
  // The server's own timers are unref'd, so this beat and the door hold the process until it is stopped.
92
128
  if (beating)
93
129
  beat();
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import { spawn } from "child_process";
15
15
  import { createHash } from "crypto";
16
- import { existsSync } from "fs";
16
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "fs";
17
17
  import { createRequire } from "module";
18
18
  import { isAbsolute, join, relative } from "path";
19
19
  import { createServer, request as httpRequest } from "http";
@@ -39,7 +39,7 @@ const CLUSTER_ROUTE = /^\/v1\/(?:(?:conversations|terminals)(?:\/.*)?|projects|p
39
39
  /** The header a caller names its workspace in (#4120). */
40
40
  const SCOPE_HEADER = "x-bullseye-project";
41
41
  /** The caller's headers AB is handed as they came (#4231 wire); the credential is replaced by the gateway bearer. */
42
- const PASSED_HEADERS = [SCOPE_HEADER, "x-request-id", "content-type", "content-length", "accept", "mcp-protocol-version"];
42
+ const PASSED_HEADERS = [SCOPE_HEADER, "x-bn-opened-by", "x-request-id", "content-type", "content-length", "accept", "mcp-protocol-version"];
43
43
  /** The headers of one hop, which this door's own connection sets for itself. */
44
44
  const HOP_HEADERS = new Set(["connection", "keep-alive", "transfer-encoding"]);
45
45
  const PLATFORMS = new Set(["telegram", "slack", "discord", "teams", "ntfy", "sms", "email"]);
@@ -178,24 +178,47 @@ function stagedLifecycle() {
178
178
  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`);
179
179
  return file;
180
180
  }
181
- /** The press itself, run in a process of its own: the row's own act, whose outcome is read afterwards with act=state. */
182
- const LIFECYCLE_ACTOR = "require(process.argv[1]).row().act(process.argv[2]).then(() => process.exit(0), () => process.exit(1))";
181
+ /** Where the last Start, Stop or Restart press writes what became of it (#4927): pressed, then its outcome in the row's own words, so act=state answers a press that did nothing with its reason. */
182
+ const LIFECYCLE_PRESS_FILE = join(CONFIG_DIR, "lifecycle-press.json");
183
+ /** The press itself, run in a process of its own: the row's own act, its outcome — done, refused or failed, with the row's words — written to the press file for act=state to read. */
184
+ const LIFECYCLE_ACTOR = `const fs = require("fs"); const [file, press, record, pressedAt] = process.argv.slice(1);
185
+ const write = (outcome) => { fs.writeFileSync(record + ".tmp", JSON.stringify({ press, pressedAt: Number(pressedAt), endedAt: Date.now(), ...outcome })); fs.renameSync(record + ".tmp", record); };
186
+ require(file).row().act(press).then((o) => write({ ok: o.ok, said: o.text }), (e) => write({ ok: false, said: String((e && e.message) || e) })).then(() => process.exit(0), () => process.exit(1));`;
183
187
  /** 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. */
184
188
  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()`;
185
189
  /** 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. */
186
190
  function pressLifecycle(file, press) {
187
191
  return new Promise((resolve, reject) => {
188
- const launcher = spawn(process.execPath, ["-e", LIFECYCLE_LAUNCHER, file, press], { stdio: "ignore", windowsHide: true });
189
- launcher.once("error", (err) => reject(new GatewayError(500, `the ${press} could not be launched — ${err.message}`)));
190
- 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}`))));
192
+ const pressedAt = Date.now();
193
+ writePress({ press, pressedAt });
194
+ const unlaunched = (said) => {
195
+ writePress({ press, pressedAt, endedAt: Date.now(), ok: false, said });
196
+ reject(new GatewayError(500, said));
197
+ };
198
+ const launcher = spawn(process.execPath, ["-e", LIFECYCLE_LAUNCHER, file, press, LIFECYCLE_PRESS_FILE, String(pressedAt)], { stdio: "ignore", windowsHide: true });
199
+ launcher.once("error", (err) => unlaunched(`the ${press} could not be launched — ${err.message}`));
200
+ launcher.once("exit", (code) => (code === 0 ? resolve({ pressed: press, running: true, next: "read the outcome with bn_lifecycle act=state: its lastPress says done, or not done with the reason" }) : unlaunched(`the ${press} could not be launched — its launcher exited ${code}`)));
191
201
  });
192
202
  }
193
- /** `POST /v1/lifecycle {act}`, what AB's bn_lifecycle tool runs: act=state reads the measured state; start, stop and restart are pressed in a process that outlives this call. */
203
+ /** The press file written whole: staged beside it and renamed over it, so act=state never reads half of it. */
204
+ function writePress(press) {
205
+ writeFileSync(`${LIFECYCLE_PRESS_FILE}.tmp`, JSON.stringify(press));
206
+ renameSync(`${LIFECYCLE_PRESS_FILE}.tmp`, LIFECYCLE_PRESS_FILE);
207
+ }
208
+ /** The last press and what became of it, from the press file: still running while it holds no outcome; none before the first press on this machine. */
209
+ function lastPress() {
210
+ // NULL-OK: field lifecycle-press.json is OPTIONAL and therefore it is ok to check for NULL
211
+ if (!existsSync(LIFECYCLE_PRESS_FILE))
212
+ return undefined;
213
+ const press = JSON.parse(readFileSync(LIFECYCLE_PRESS_FILE, "utf8"));
214
+ return { ...press, outcome: press.ok === undefined ? "running" : press.ok ? "done" : "not done" };
215
+ }
216
+ /** `POST /v1/lifecycle {act}`, what AB's bn_lifecycle tool runs: act=state reads the measured state with the last press and its outcome; start, stop and restart are pressed in a process that outlives this call. */
194
217
  async function lifecycle(act) {
195
218
  if (typeof act !== "string" || !LIFECYCLE_PRESSES.has(act))
196
219
  throw new GatewayError(400, "act must be state, start, stop or restart");
197
220
  const file = stagedLifecycle();
198
- return act === "state" ? createRequire(file)(file).row().state() : pressLifecycle(file, act);
221
+ return act === "state" ? { ...(await createRequire(file)(file).row().state()), lastPress: lastPress() } : pressLifecycle(file, act);
199
222
  }
200
223
  /** `POST /v1/chat/reply`: one part of a chat turn AB carries back, sent on to its thread — `{replyId, platform, conversation, part, final}` — or AB's release of a settled turn's held reply, `{replyId, release: true}`. */
201
224
  async function chatReply(body) {
@@ -219,13 +242,13 @@ async function chatReply(body) {
219
242
  await AgentGateway.instance().carry(replyId, platform, conversation, part, final);
220
243
  return {};
221
244
  }
222
- /** The relayed turn as the wire names it, `{id, n, queued, parallel?, provider, sessionId}`; anything else is AB's request gone wrong, refused 400. */
245
+ /** The relayed turn as the wire names it, `{id, n, queued, provider, sessionId}`; anything else is AB's request gone wrong, refused 400. */
223
246
  function streamedTurnOf(turn) {
224
247
  const t = turn;
225
- if (t === null || typeof t !== "object" || typeof t.id !== "string" || !Number.isInteger(t.n) || typeof t.queued !== "boolean" || (t.parallel !== undefined && typeof t.parallel !== "boolean") || typeof t.provider !== "string" || typeof t.sessionId !== "string") {
226
- throw new GatewayError(400, "turn must be {id, n, queued, parallel?, provider, sessionId}: the conversation, its user event, whether it waits behind another, whether it runs beside the busy main conversation, and its CLI and session");
248
+ if (t === null || typeof t !== "object" || typeof t.id !== "string" || !Number.isInteger(t.n) || typeof t.queued !== "boolean" || typeof t.provider !== "string" || typeof t.sessionId !== "string") {
249
+ throw new GatewayError(400, "turn must be {id, n, queued, provider, sessionId}: the conversation, its user event, whether it waits behind another, and its CLI and session");
227
250
  }
228
- return { id: t.id, n: t.n, queued: t.queued, parallel: t.parallel === true, provider: t.provider, sessionId: t.sessionId };
251
+ return { id: t.id, n: t.n, queued: t.queued, provider: t.provider, sessionId: t.sessionId };
229
252
  }
230
253
  /** `POST /v1/chat/relay {replyId, turn, event?, close?}` (#4453): one event of a streamed turn AB relays whole to the chat its message is held with, or that turn's close. */
231
254
  async function chatRelay(body) {
@@ -218,6 +218,12 @@ function headersOf(headers) {
218
218
  headers.forEach((value, name) => { all.push(`${name}: ${value}`); });
219
219
  return all.join("; ");
220
220
  }
221
+ /** A send that went unanswered within its time-out: Telegram may have shown it, so it is never sent a second time (#4927). */
222
+ export class TelegramSendUnconfirmed extends Error {
223
+ constructor(method, timeoutMs) {
224
+ super(`Telegram did not answer ${method} within ${timeoutMs} ms — it may have been shown, so it is not sent again`);
225
+ }
226
+ }
221
227
  /** An answer the Bot API documents no meaning for: carried whole so it can be read, never retried. */
222
228
  export class TelegramUnknown extends Error {
223
229
  constructor(method, status, body, headers) {
@@ -228,7 +234,7 @@ const DOCUMENTED_REFUSALS = new Set([400, 401, 403, 404, 409]);
228
234
  // GATE: tries of one Bot API call before a network failure, a 5xx or a 429 is given up as unreachable — each wait doubles from 1 s, a 429 waits the retry_after Telegram names.
229
235
  const TELEGRAM_TRIES = 4;
230
236
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
231
- /** One Bot API call — a JSON POST, or a GET of `url` as it is when there is no body: retried on a network failure, a 5xx or a 429 (after its retry_after), refused on a documented 4xx, thrown whole on anything else. */
237
+ /** One Bot API call — a JSON POST, or a GET of `url` as it is when there is no body: retried on a network failure, a 5xx or a 429 (after its retry_after), refused on a documented 4xx, thrown whole on anything else. A send that timed out is never sent again: Telegram may already have shown it, and a second copy is the repeated reply (#4927), so it throws TelegramSendUnconfirmed for the sender to name once and take as sent. */
232
238
  export async function telegramCall(url, method, body, tries = TELEGRAM_TRIES, timeoutMs = 15_000) {
233
239
  for (let attempt = 1;; attempt++) {
234
240
  const last = attempt >= tries;
@@ -240,6 +246,8 @@ export async function telegramCall(url, method, body, tries = TELEGRAM_TRIES, ti
240
246
  catch (err) {
241
247
  if (!(err instanceof TypeError) && !(err instanceof DOMException))
242
248
  throw err;
249
+ if (body !== undefined && method.startsWith("send") && err.name === "TimeoutError")
250
+ throw new TelegramSendUnconfirmed(method, timeoutMs);
243
251
  if (last)
244
252
  throw new TelegramUnreachable(`Telegram could not be reached for ${method} after ${attempt} tries: ${err.message}`);
245
253
  await sleep(1000 * 2 ** (attempt - 1));
@@ -341,6 +349,18 @@ export class TelegramMessenger {
341
349
  }
342
350
  /** Sends `text` in the chosen formatting; a formatting Telegram cannot parse is sent again once as plain text, and said. */
343
351
  async formatted(method, payload, text) {
352
+ try {
353
+ return await this.formattedOnce(method, payload, text);
354
+ }
355
+ catch (err) {
356
+ if (!(err instanceof TelegramSendUnconfirmed))
357
+ throw err;
358
+ // OWNER: a send Telegram may already have shown is never sent twice — the repeated reply (#4927) — so it is named once on the daemon's console with its chat and taken as sent.
359
+ this.log(`${method} to ${this.chatId} UNCONFIRMED — ${err.message}`);
360
+ return undefined;
361
+ }
362
+ }
363
+ async formattedOnce(method, payload, text) {
344
364
  if (!this.switchedOn())
345
365
  throw new ChannelOff("Telegram");
346
366
  const mode = this.mode();
package/dist/notify.js CHANGED
@@ -1096,7 +1096,7 @@ function ingestDropFolder() {
1096
1096
  rejectDrop(path, name, err instanceof Error ? err.message : String(err));
1097
1097
  continue;
1098
1098
  }
1099
- taken.push({ path, marker, entry });
1099
+ taken.push({ path, marker, name, entry });
1100
1100
  queued = true;
1101
1101
  }
1102
1102
  finally {
@@ -1112,6 +1112,8 @@ function ingestDropFolder() {
1112
1112
  retryUnreadDrops(unread);
1113
1113
  if (taken.length === 0)
1114
1114
  return;
1115
+ for (const { entry, name } of taken)
1116
+ copyUrgentAlertToChat(entry.text, name);
1115
1117
  persistInboxQueue(taken.map(({ entry }) => entry));
1116
1118
  for (const { path, marker } of taken) {
1117
1119
  unlinkSync(path);
@@ -1120,6 +1122,32 @@ function ingestDropFolder() {
1120
1122
  log("·", "inbox-drop", `queued ${taken.length} message${taken.length === 1 ? "" : "s"} from ${INBOX_DROP_IN_DIR}`);
1121
1123
  syncInboxFromDisk();
1122
1124
  }
1125
+ const URGENT_ALERT_TIER = /\[(WARN|CRITICAL)\]/;
1126
+ // GATE: the largest slice of an urgent alert sent in one chat message, under Telegram's 4096-character cap; slices are cut at exact offsets so the chat receives the drop's text unchanged.
1127
+ const COPY_PART_CHARS = 4000;
1128
+ function copyUrgentAlertToChat(text, drop) {
1129
+ const headline = text.split("\n")[0];
1130
+ const refuse = (where, err) => recordReach("telegram", false, "an urgent alert copy", `NOT copied from ${drop} to ${where} (${headline}): ${err instanceof Error ? err.message : String(err)}`);
1131
+ void (async () => {
1132
+ const tg = loadConfig().telegram;
1133
+ if (tg?.copyUrgentAlerts !== true || !URGENT_ALERT_TIER.test(text))
1134
+ return;
1135
+ if (!Array.isArray(tg.chatIds))
1136
+ throw new Error("telegram.chatIds is not a list");
1137
+ for (const chat of tg.chatIds) {
1138
+ void (async () => {
1139
+ for (let at = 0; at < text.length;) {
1140
+ let end = Math.min(at + COPY_PART_CHARS, text.length);
1141
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]))
1142
+ end--; // never cut a surrogate pair (an emoji) in two
1143
+ await telegramSendTo(tg.token, chat, text.slice(at, end));
1144
+ at = end;
1145
+ }
1146
+ recordReach("telegram", true, "an urgent alert copy", `copied to chat ${chat}: ${headline}`);
1147
+ })().catch((err) => refuse(`chat ${chat}`, err)); // OWNER: the copy is an extra leg; its refusal is recorded with the drop and the headline while Slack and email keep their own legs
1148
+ }
1149
+ })().catch((err) => refuse("the telegram chats", err)); // OWNER: a config that cannot be read or a chat list that is not a list is the copy's own refusal, recorded; the drop still queues
1150
+ }
1123
1151
  function ingestInboxEntry(entry, source) {
1124
1152
  const waiters = takeWaitersFor(entry.tag);
1125
1153
  if (waiters.length > 0) {
@@ -1303,6 +1331,14 @@ function telegramContext(msg) {
1303
1331
  // NULL-OK: field replied is OPTIONAL and therefore it is ok to check for NULL
1304
1332
  if (replied !== undefined)
1305
1333
  lines.push(`He is replying to this earlier message in the chat: «${replied.slice(0, 800)}»`);
1334
+ const sender = msg.from;
1335
+ // NULL-OK: field sender is OPTIONAL and therefore it is ok to check for NULL
1336
+ if (sender !== undefined) {
1337
+ const name = [sender.first_name, sender.last_name].filter((part) => typeof part === "string" && part.length > 0).join(" ");
1338
+ const username = typeof sender.username === "string" && sender.username.length > 0 ? ` @${sender.username}` : "";
1339
+ const senderId = sender.id === undefined ? "" : ` (id ${String(sender.id)})`;
1340
+ lines.push(`Telegram sender: ${name || "unnamed"}${username}${senderId}`);
1341
+ }
1306
1342
  return [...lines, ...openAsksContext()];
1307
1343
  }
1308
1344
  /** Every question another session waits on, told to the one chat's conversation so it can pass his answer on. */
@@ -1605,14 +1641,18 @@ async function startTelegramListener() {
1605
1641
  tgLastErrorCount = 0;
1606
1642
  }
1607
1643
  for (const update of updates) {
1608
- POLL_CURSORS.set(cursorKey, String(update.update_id));
1609
- tgPollOffset = update.update_id + 1;
1610
1644
  tgLastUpdateAt = Date.now();
1645
+ let acted = true;
1611
1646
  await takeTelegramUpdate(token, update).catch((err) => {
1612
- // OWNER: ITER/LOOP — one update that cannot be acted on is logged with its reason (with its stack when it is no failure Telegram's own answer explains), and the next update is still read.
1647
+ acted = false;
1648
+ // OWNER: ITER/LOOP — one update that cannot be acted on is logged with its reason and remains pending for retry before later updates are read.
1613
1649
  const classified = err instanceof TelegramRefused || err instanceof TelegramUnreachable || err instanceof TelegramUnknown;
1614
1650
  log("·", "telegram", `update ${update.update_id} was not acted on, its reply NOT DELIVERED: ${err instanceof Error ? err.message : String(err)}${classified || !(err instanceof Error) ? "" : `\n${err.stack}`}`);
1615
1651
  });
1652
+ if (!acted)
1653
+ break;
1654
+ POLL_CURSORS.set(cursorKey, String(update.update_id));
1655
+ tgPollOffset = update.update_id + 1;
1616
1656
  }
1617
1657
  }
1618
1658
  catch (err) {
@@ -492,7 +492,7 @@ class ServedWebview {
492
492
  * message runs under. `saidOnce` says a failure that persists across the watch's ticks is told to this browser once.
493
493
  */
494
494
  viewerOf(socket) {
495
- const viewer = { search: socket.at, base: socket.base, signal: socket.viewLife.signal, post: (message) => postTo([socket], message, this.served) };
495
+ const viewer = { search: socket.at, base: socket.base, ownerApproved: socket.ownerApproved === true, signal: socket.viewLife.signal, post: (message) => postTo([socket], message, this.served) };
496
496
  viewer.guard = (work, options = {}) => this.guarded(socket, viewer, work, options.saidOnce === true);
497
497
  return viewer;
498
498
  }
@@ -1133,6 +1133,18 @@ class WebHost {
1133
1133
  socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
1134
1134
  return;
1135
1135
  }
1136
+ if (this.screenOwnerProved) {
1137
+ try {
1138
+ socket.ownerApproved = this.screenOwnerProved(request, this.port);
1139
+ }
1140
+ catch (err) {
1141
+ if (!(err instanceof Error))
1142
+ throw err;
1143
+ console.error("Screen owner proof refused:", err.message);
1144
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
1145
+ return;
1146
+ }
1147
+ }
1136
1148
  socket.base = base;
1137
1149
  const accept = crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
1138
1150
  socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
@@ -1179,6 +1191,7 @@ class ServiceHost extends WebHost {
1179
1191
  this.listed = options.workspaces;
1180
1192
  this.current = options.currentOf;
1181
1193
  this.machine = options.machine === true;
1194
+ this.screenOwnerProved = options.screenOwnerProved;
1182
1195
  }
1183
1196
  /** Takes the page requests and sockets of `server`, which already listens on `port` for the service. */
1184
1197
  answerOn(server, port) {
@@ -1247,32 +1260,32 @@ function indexPage(host, base) {
1247
1260
  const rows = [...host.pages.values()]
1248
1261
  .map((page) => `<li><a href="${escapeAttribute(base === undefined ? page.url : `${base}/${encodeURIComponent(page.name)}/${page.search}`)}">${page.live ? "🟢" : "⚪"} ${escapeAttribute(page.title)}</a></li>`)
1249
1262
  .join("");
1250
- return `<!DOCTYPE html><html><head><meta charset="utf-8">${PHONE_VIEWPORT}<title>${escapeAttribute(host.extension)}</title></head>
1263
+ return `<!DOCTYPE html><html><head><meta charset="utf-8">${PHONE_VIEWPORT}<title>${escapeAttribute(host.extension)}</title></head>
1251
1264
  <body style="font:14px system-ui,sans-serif;padding:24px;background:#1e1e1e;color:#ccc"><div>${escapeAttribute(host.extension)} · ${escapeAttribute(host.label)}</div><ul>${rows}</ul></body></html>`;
1252
1265
  }
1253
1266
  function closedPage(extension, page) {
1254
- return `<!DOCTYPE html><html><head><meta charset="utf-8">${PHONE_VIEWPORT}<title>${escapeAttribute(extension)} · ${escapeAttribute(page.title)}</title></head>
1255
- <body style="font:14px system-ui,sans-serif;padding:24px;background:#1e1e1e;color:#ccc">⚪ ${escapeAttribute(page.title)} is not open in VS Code right now, so there is nothing to show here — this page loads it the moment it opens.<div id="said" style="margin-top:8px"></div>
1256
- <script>${CONNECTION_SOURCE}</script><script>(function () {
1257
- var WHAT = "this page's live connection to its host";
1258
- var kept = window.bullseyeConnection.keep({
1259
- what: WHAT, path: "/__bullseye/health",
1260
- open: function () { return new WebSocket((location.protocol === "https:" ? "wss:" : "ws:") + "//" + location.host + "/__bullseye/ws?page=${encodeURIComponent(page.name)}"); },
1261
- attach: function (connect, later) {
1262
- fetch("/__bullseye/health", { cache: "no-store", signal: AbortSignal.timeout(8000) }).then(function (r) {
1263
- if (r.ok) connect(); else if (r.status === 401) window.bullseyeConnection.signInAgain(); else later();
1264
- }, later);
1265
- },
1266
- opened: function () {
1267
- document.getElementById("said").textContent = "";
1268
- fetch("/__bullseye/health", { cache: "no-store" }).then(function (r) { return r.json(); }).then(function (health) { if (health.pages[${JSON.stringify(page.name)}].live) location.reload(); }, function (error) { console.warn("[Bullseye connection] Page availability unread: " + error.message); });
1269
- },
1270
- message: function (socket, event) { if (JSON.parse(String(event.data)).type === "reload") location.reload(); },
1271
- down: function () { document.getElementById("said").textContent = "⏳ Reconnecting"; },
1272
- closed: function () { return false; },
1273
- ping: function (socket) { socket.send('{"type":"ping"}'); }
1274
- });
1275
- kept.connect();
1267
+ return `<!DOCTYPE html><html><head><meta charset="utf-8">${PHONE_VIEWPORT}<title>${escapeAttribute(extension)} · ${escapeAttribute(page.title)}</title></head>
1268
+ <body style="font:14px system-ui,sans-serif;padding:24px;background:#1e1e1e;color:#ccc">⚪ ${escapeAttribute(page.title)} is not open in VS Code right now, so there is nothing to show here — this page loads it the moment it opens.<div id="said" style="margin-top:8px"></div>
1269
+ <script>${CONNECTION_SOURCE}</script><script>(function () {
1270
+ var WHAT = "this page's live connection to its host";
1271
+ var kept = window.bullseyeConnection.keep({
1272
+ what: WHAT, path: "/__bullseye/health",
1273
+ open: function () { return new WebSocket((location.protocol === "https:" ? "wss:" : "ws:") + "//" + location.host + "/__bullseye/ws?page=${encodeURIComponent(page.name)}"); },
1274
+ attach: function (connect, later) {
1275
+ fetch("/__bullseye/health", { cache: "no-store", signal: AbortSignal.timeout(8000) }).then(function (r) {
1276
+ if (r.ok) connect(); else if (r.status === 401) window.bullseyeConnection.signInAgain(); else later();
1277
+ }, later);
1278
+ },
1279
+ opened: function () {
1280
+ document.getElementById("said").textContent = "";
1281
+ fetch("/__bullseye/health", { cache: "no-store" }).then(function (r) { return r.json(); }).then(function (health) { if (health.pages[${JSON.stringify(page.name)}].live) location.reload(); }, function (error) { console.warn("[Bullseye connection] Page availability unread: " + error.message); });
1282
+ },
1283
+ message: function (socket, event) { if (JSON.parse(String(event.data)).type === "reload") location.reload(); },
1284
+ down: function () { document.getElementById("said").textContent = "⏳ Reconnecting"; },
1285
+ closed: function () { return false; },
1286
+ ping: function (socket) { socket.send('{"type":"ping"}'); }
1287
+ });
1288
+ kept.connect();
1276
1289
  })();</script></body></html>`;
1277
1290
  }
1278
1291
  function codeDefect(err) {
@@ -29,7 +29,7 @@ function run(file, args) {
29
29
  if (failed === null)
30
30
  resolve(out);
31
31
  else
32
- reject(failed.killed ? new OsCallTimedOut(callFailed(file, args, failed, err).message) : callFailed(file, args, failed, err));
32
+ reject(failed.killed ? new OsCallTimedOut(callFailed(file, args, failed, err).message) : Object.assign(callFailed(file, args, failed, err), { exitCode: failed.code }));
33
33
  });
34
34
  });
35
35
  }
@@ -46,9 +46,10 @@ async function runRepeatable(file, args) {
46
46
  await new Promise((resolve) => setTimeout(resolve, 1_000 * tried));
47
47
  }
48
48
  }
49
- /** The tasklist query whose rows are this account's processes in any session but 0 — a console or remote desktop logon, a disconnected one too; an ssh-only box has none, because its ssh logons run in session 0. */
50
- const sessionQuery = () => [path.join(system32(), "tasklist.exe"), ["/fi", `USERNAME eq ${os.userInfo().username}`, "/fi", "SESSION ne 0", "/fo", "csv", "/nh"]];
51
- const listsAProcess = (rows) => rows.trimStart().startsWith('"');
49
+ /** The quser query whose rows are the logon sessions on this machine, console, remote desktop and disconnected alike; an ssh-only box has none, because its ssh logons run in session 0. It replaces a tasklist USERNAME filter, which opens every process's owner and does not return under the Least-privilege token on a busy box. */
50
+ const sessionQuery = () => [path.join(system32(), "quser.exe"), []];
51
+ /** Whether quser's rows name a logon session of this account — "No User exists" (exit 1, no rows) is none. */
52
+ const listsThisAccount = (rows) => rows.split(/\r?\n/).slice(1).some((row) => row.replace(/^[\s>]+/, "").split(/\s+/)[0].toLowerCase() === os.userInfo().username.toLowerCase());
52
53
  /** The tasklist query of this process's own row, which any token may read: the account's USERNAME filter opens every process's owner and does not return under the login session's own Least-privilege token. */
53
54
  const ownRowQuery = () => [path.join(system32(), "tasklist.exe"), ["/fi", `PID eq ${process.pid}`, "/fo", "csv", "/nh"]];
54
55
  /** The Windows session in this process's own tasklist row. */
@@ -66,7 +67,14 @@ async function userSessionOpen() {
66
67
  if (sessionIn(await runRepeatable(own, ownArgs)) !== 0)
67
68
  return true;
68
69
  const [file, args] = sessionQuery();
69
- return listsAProcess(await runRepeatable(file, args));
70
+ try {
71
+ return listsThisAccount(await runRepeatable(file, args));
72
+ }
73
+ catch (failed) {
74
+ if (failed.exitCode === 1)
75
+ return false;
76
+ throw failed;
77
+ }
70
78
  }
71
79
  /** userSessionOpen, for a caller that cannot wait on the event loop. */
72
80
  function userSessionOpenSync() {
@@ -75,19 +83,26 @@ function userSessionOpenSync() {
75
83
  const call = ([file, args]) => execFileSync(file, args, { windowsHide: true, encoding: "utf8", timeout: OS_CALL_MS });
76
84
  if (sessionIn(call(ownRowQuery())) !== 0)
77
85
  return true;
78
- return listsAProcess(call(sessionQuery()));
86
+ try {
87
+ return listsThisAccount(call(sessionQuery()));
88
+ }
89
+ catch (failed) {
90
+ if (failed.status === 1)
91
+ return false;
92
+ throw failed;
93
+ }
79
94
  }
80
95
  const xmlText = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
81
96
  const quoted = (part) => (/[\s"]/.test(part) ? `"${part.replace(/"/g, '\\"')}"` : part);
82
97
  /** The task's definition: the account's interactive token at the Least-privilege run level and Normal priority — the default below-normal priority leaves a program it starts unscheduled on a busy box — no trigger; the program runs under a headless console host, so a console program draws no window. A definition file, never /tr, because /tr stops at 261 characters. */
83
98
  function taskXml(user, file, args) {
84
- return `<?xml version="1.0" encoding="UTF-16"?>
85
- <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
86
- <RegistrationInfo><Description>Starts a Bullseye program in the logged-on user's own session, from a resident server that runs with no window.</Description></RegistrationInfo>
87
- <Principals><Principal id="Author"><UserId>${xmlText(user)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
88
- <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority><Enabled>true</Enabled></Settings>
89
- <Actions Context="Author"><Exec><Command>${xmlText(path.join(system32(), "conhost.exe"))}</Command><Arguments>${xmlText(["--headless", file, ...args].map(quoted).join(" "))}</Arguments></Exec></Actions>
90
- </Task>
99
+ return `<?xml version="1.0" encoding="UTF-16"?>
100
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
101
+ <RegistrationInfo><Description>Starts a Bullseye program in the logged-on user's own session, from a resident server that runs with no window.</Description></RegistrationInfo>
102
+ <Principals><Principal id="Author"><UserId>${xmlText(user)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
103
+ <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority><Enabled>true</Enabled></Settings>
104
+ <Actions Context="Author"><Exec><Command>${xmlText(path.join(system32(), "conhost.exe"))}</Command><Arguments>${xmlText(["--headless", file, ...args].map(quoted).join(" "))}</Arguments></Exec></Actions>
105
+ </Task>
91
106
  `;
92
107
  }
93
108
  let launches = 0;
@@ -2,6 +2,7 @@
2
2
  const { execFile } = require("child_process");
3
3
  const crypto = require("crypto");
4
4
  const fs = require("fs");
5
+ const { isIP } = require("net");
5
6
  const os = require("os");
6
7
  const path = require("path");
7
8
  /** #3849 — the BullseyeVSC checkout, which owns every Bullseye service and holds the one workspace list they all read. */
@@ -773,4 +774,65 @@ function savedSettings(tool) {
773
774
  throw err;
774
775
  }
775
776
  }
776
- module.exports = { vscRoot, workspacesFile, publishWorkspaces, WorkspacesUndefined, listedWorkspaces, workspacesHere, listBase, saveWorkspaces, sameRoot, SettingsUndefined, SettingsMoved, SettingsLocked, WorkspaceNotListed, settingsFile, readSettings, savedSettings, AutoStartUnread, savedAutoStart, writeAutoStart, autoStartOnAt, autoStartOff, toolHome, settingsBase, writeSettings, setSettings, publishSettings, alive };
777
+ const SSH_ALIAS = /^[a-z0-9_.][a-z0-9_.-]*$/i;
778
+ const remoteHostsFile = () => path.join(os.homedir(), ".bullseye", "settings", "fv-hosts.json");
779
+ const sshDestination = (name) => SSH_ALIAS.test(name) || isIP(name) === 6;
780
+ function remoteAlias(name) {
781
+ return sshDestination(name)
782
+ && name.toLowerCase() !== os.hostname().toLowerCase()
783
+ && !/^(?:localhost\.?|0\.0\.0\.0|::1?)$/i.test(name)
784
+ && !(isIP(name) === 4 && name.startsWith("127."));
785
+ }
786
+ function sshHostAliases(config = path.join(os.homedir(), ".ssh", "config")) {
787
+ const raw = readBytesOf(config, "SSH config");
788
+ if (raw === undefined)
789
+ return [];
790
+ const names = new Map();
791
+ for (const line of raw.toString("utf8").split(/\r?\n/)) {
792
+ const name = /^\s*Host\s+(\S+)/i.exec(line)?.[1];
793
+ if (name !== undefined && sshDestination(name) && !/^hp-laptop$/i.test(name) && !names.has(name.toLowerCase()))
794
+ names.set(name.toLowerCase(), name);
795
+ }
796
+ return [...names.values()];
797
+ }
798
+ function readRemoteHostChoices(file) {
799
+ const bytes = readBytesOf(file, "FleetView hosts");
800
+ if (bytes === undefined)
801
+ return {};
802
+ const choices = parsedBox(file, bytes);
803
+ if (Object.entries(choices).some(([name, enabled]) => !sshDestination(name) || name !== name.toLowerCase() || typeof enabled !== "boolean")) {
804
+ throw new SyntaxError(`FleetView hosts in ${file} must map lowercase SSH aliases to true or false`);
805
+ }
806
+ return choices;
807
+ }
808
+ function remoteHostChoices() {
809
+ const current = workspaceTurn();
810
+ current.remoteHostChoices ??= readRemoteHostChoices(remoteHostsFile());
811
+ return current.remoteHostChoices;
812
+ }
813
+ function remoteHosts() {
814
+ const hosts = new Map(sshHostAliases().map((name) => [name.toLowerCase(), name]));
815
+ for (const [name, enabled] of Object.entries(remoteHostChoices())) {
816
+ const alias = name.toLowerCase();
817
+ if (enabled && remoteAlias(alias))
818
+ hosts.set(alias, hosts.get(alias) ?? alias);
819
+ else
820
+ hosts.delete(alias);
821
+ }
822
+ return [...hosts.values()];
823
+ }
824
+ function setRemoteHost(typed, enabled) {
825
+ const name = typeof typed === "string" ? typed.trim().toLowerCase() : "";
826
+ if (!sshDestination(name))
827
+ throw new SyntaxError("Enter an SSH alias, hostname or IP address without a user name, port, spaces or wildcards.");
828
+ if (enabled && !remoteAlias(name))
829
+ throw new SyntaxError("Enter a host other than this machine.");
830
+ const file = remoteHostsFile();
831
+ underLock(file, () => {
832
+ const choices = readRemoteHostChoices(file);
833
+ writeAtomically(file, `${JSON.stringify({ schema: SETTINGS_SCHEMA, box: { ...choices, [name]: enabled } }, null, 2)}\n`);
834
+ });
835
+ delete workspaceTurn().remoteHostChoices;
836
+ return name;
837
+ }
838
+ module.exports = { vscRoot, workspacesFile, publishWorkspaces, WorkspacesUndefined, listedWorkspaces, workspacesHere, listBase, saveWorkspaces, sameRoot, SettingsUndefined, SettingsMoved, SettingsLocked, WorkspaceNotListed, settingsFile, readSettings, savedSettings, AutoStartUnread, savedAutoStart, writeAutoStart, autoStartOnAt, autoStartOff, toolHome, settingsBase, writeSettings, setSettings, publishSettings, alive, sshHostAliases, remoteHostsFile, remoteHostChoices, remoteHosts, setRemoteHost };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.489",
3
+ "version": "1.3.491",
4
4
  "homepage": "https://www.npmjs.com/package/omni-notify-mcp",
5
5
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
6
6
  "main": "dist/daemon.js",