omni-notify-mcp 1.3.413 → 1.3.415

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chunk.js CHANGED
@@ -17,6 +17,10 @@ function packChunks(message, body, wordAware) {
17
17
  chunks.push(rest);
18
18
  return chunks;
19
19
  }
20
+ const BLOCK_START = /^\s*(#{1,6}\s|>|[-*+]\s|\||```)/;
21
+ export function withLead(lead, text) {
22
+ return `${lead}${BLOCK_START.test(text) ? "\n" : " "}${text}`;
23
+ }
20
24
  export function splitForNotify(message, limit = NOTIFY_CHUNK_LIMIT) {
21
25
  if (message.length <= limit)
22
26
  return [message];
@@ -33,5 +37,5 @@ export function splitForNotify(message, limit = NOTIFY_CHUNK_LIMIT) {
33
37
  if (chunks.length > parts)
34
38
  chunks = packChunks(message, body, false);
35
39
  const total = chunks.length;
36
- return chunks.map((chunk, i) => `(${i + 1}/${total}) ${chunk}`);
40
+ return chunks.map((chunk, i) => withLead(`(${i + 1}/${total})`, chunk));
37
41
  }
@@ -4,6 +4,8 @@ import { CONFIG_DIR } from "../notify.js";
4
4
  let personId;
5
5
  void import("./passkeyDoor.js").then((door) => { personId = door.personId; });
6
6
  import { createConversationOwner } from "../shared/conversation/conversationOwner.js";
7
+ import { GatewayError } from "../shared/conversation/conversations.js";
8
+ import { sameRoot } from "../shared/webhost/workspaceList.js";
7
9
  import { FLEET_OWNER } from "../shared/providerOwnership.js";
8
10
  function driverOptions() {
9
11
  const bundledGuard = new URL("../scripts/shared/", import.meta.url);
@@ -124,3 +126,16 @@ export { AgentTurnFailed, agentEnv, nativeAgentEnv, nativeCliRefusal } from "../
124
126
  export { CliSession, CliEnded, LoggedCliSession, folderKey, plain, sameText, endsWithTyped, tailOf, logRow } from "../shared/conversation/cliSession.js";
125
127
  export { nativeCliInvocation } from "../shared/conversation/nativeCliInvocation.js";
126
128
  export { archiveCodexThread } from "../shared/conversation/codexArchive.js";
129
+ /** #4471 — one conversation as the CLI page reads it (`GET /v1/conversations/{id}`) and `agent_status` answers: its record with title and lifecycle, the native CLI state (pid, input version, model, startup diagnostic, pending input) and whether a turn is running — the page and the tool read the one producer. */
130
+ export function conversationReading(meta) {
131
+ const native = conversationOwner.driver.nativeState(meta.id);
132
+ return { ...conversationOwner.store.describeConversation(meta), ...native, working: native.working || conversationOwner.store.turnInFlight(conversationOwner.store.readEvents(meta.id), meta) !== undefined };
133
+ }
134
+ /** #4471 — which agent CLIs can start in a project and why one cannot (`GET /v1/providers`, `agent_providers`): the project named exactly as a creation names it, refused for a scoped caller outside its own workspace. */
135
+ export function providerStartupReading(project, viewer) {
136
+ conversationOwner.store.requireConversationEnabled();
137
+ const folder = conversationOwner.store.namedProject(project);
138
+ if (viewer !== undefined && !sameRoot(conversationOwner.store.workspaceOf(folder), viewer.folder))
139
+ throw new GatewayError(403, "This provider startup reading belongs to another workspace");
140
+ return { providers: conversationOwner.driver.availability(folder) };
141
+ }
@@ -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, createdOn, creationPending, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversationOwner.js";
24
+ import { GatewayError, MAX_WAIT_SECONDS, conversationOwner, conversationReading, providerStartupReading, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, createdOn, creationPending, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversationOwner.js";
25
25
  import { workspacesFile } from "../shared/webhost/workspaceList.js";
26
26
  import { PROVIDER_NAMES } from "./conversationOwner.js";
27
27
  import { iconsFor } from "./iconDoor.js";
@@ -300,7 +300,8 @@ function buildServer(caller, base, offer) {
300
300
  }).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; });
301
301
  });
302
302
  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)));
303
- 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()))));
303
+ server.tool("agent_status", "Read-only. One conversation exactly as the CLI page reads it: its project (absent until one is chosen), provider, model and state, 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), beside (the conversation of the same connection it was opened next to, if any), and the native CLI state: working (a turn runs, also one typed straight into the CLI), pendingInput, nativePid, inputVersion (what agent_stop expectedInputVersion takes), nativeModel and startupDiagnostic. A conversation outside the caller's workspace is refused as not found.", { id: z.string().min(1) }, ({ id }) => act(() => conversationReading(scopedConversation(id, viewerNow()))));
304
+ server.tool("agent_providers", "Read-only. Which agent CLIs can start in a project and why one cannot, as the CLI page's New Agent reads it before offering a CLI: {providers:[{name, label, reason?}]}, reason present only when that CLI cannot start there. The project is named as a new conversation names it (exactly one of the listed projects); a caller scoped to one workspace is refused another workspace's project. Starts nothing and spends nothing.", { project: z.string().min(1).describe("Exactly one of the project names agent_projects lists") }, ({ project }) => act(() => providerStartupReading(project, viewerNow())));
304
305
  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(() => {
305
306
  seen(id);
306
307
  requireOwnCli(id);
@@ -325,7 +326,7 @@ function buildServer(caller, base, offer) {
325
326
  return { conversation: id, console: true, frames, seq: read.after, after: read.after };
326
327
  }));
327
328
  server.tool("agent_list", "Every agent conversation BN holds on this machine, newest first (conversations, not projects — agent_projects lists projects), each with its title, lifecycle (active, idle or completed) and beside as agent_status gives them. archived=true lists the archived ones instead; BN archives a conversation by itself once it has sat 8 hours with no turn in flight, and a message to it brings it back.", { archived: z.boolean().default(false).describe("true lists the Archived conversations instead of the default list") }, ({ archived }) => act(() => ({ conversations: shelvedConversations(archived ? "archived" : "active", viewerNow()).map(describeConversation) })));
328
- 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))));
329
+ server.tool("agent_stop", "Stop a conversation and free its agent; a later message resumes it. Pass expectedConsumed (the conversation's consumed turn count) with expectedInputVersion (the inputVersion agent_status read) to stop it only if nothing newer arrived since that read — the same guarded Stop the REST door runs; a conversation with newer or unfinished work is refused and nothing is stopped.", { id: z.string().min(1), expectedConsumed: z.number().int().min(0).optional(), expectedInputVersion: z.string().optional() }, ({ id, expectedConsumed, expectedInputVersion }) => act(() => (expectedConsumed === undefined ? stopConversation(seen(id)) : conversationOwner.stopIfCurrent(seen(id), { expectedConsumed, expectedInputVersion: expectedInputVersion ?? null }))));
329
330
  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))));
330
331
  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))));
331
332
  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()))));
@@ -8,6 +8,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
8
8
  import { dirname, join } from "path";
9
9
  import { CONFIG_DIR, deliveryReport, isDndActive } from "../notify.js";
10
10
  import { GatewayError, conversationEnabled, setConversationEnabled } from "./conversationOwner.js";
11
+ import { TELEGRAM_PARSE_MODES } from "../messaging/telegramFormat.js";
11
12
  const CHANNEL_KEYS = ["desktop", "telegram", "slack", "sms", "ntfy", "discord", "teams"];
12
13
  const CONFIG_PATH = join(CONFIG_DIR, "config.json");
13
14
  // Every config field the notify server reads, one editable row each. A field the server no longer reads is not listed: a control for it would change nothing.
@@ -24,6 +25,7 @@ export const SETTINGS = [
24
25
  { guide: { summary: "Create a bot (2 min)", steps: ["Open Telegram, search `@BotFather`.", "Send `/newbot` and follow the prompts; copy the token it gives you.", "From each chat or group you want notified, send your bot any message (add the bot to groups first).", "Paste the token below, then add each chat id (see the hint under Chat ids).", "Switch Enabled to On."], need: [["telegram.token"], ["telegram.chatIds"]] }, title: "✈️ Telegram", rows: [
25
26
  { path: ["telegram", "enabled"], label: "Enabled", kind: "toggle" },
26
27
  { path: ["telegram", "token"], label: "Bot token", kind: "secret", hint: "From @BotFather after /newbot, shaped like 123456:ABC-DEF..." },
28
+ { path: ["telegram", "parseMode"], label: "Formatting", kind: "choice", choices: TELEGRAM_PARSE_MODES, fallback: "HTML", hint: "HTML (default) turns an agent's markdown bold, italics, code, links and bullets into Telegram formatting. MarkdownV2 sends the text as written for Telegram's own markdown. none sends plain text." },
27
29
  { path: ["telegram", "chatIds"], label: "Chat ids (comma-separated)", kind: "list", hint: "Numeric ids of the chats or groups to notify (group ids start with -). Send your bot a message, then open https://api.telegram.org/bot<TOKEN>/getUpdates and copy each \"chat\":{\"id\":...}." },
28
30
  ] },
29
31
  { guide: { summary: "Connect Slack", steps: ["Go to api.slack.com/apps, open your app (or Create New App).", "Easiest: Incoming Webhooks, Add New Webhook to Workspace, pick the channel, copy the URL into Webhook URL.", "Or: OAuth & Permissions, add the chat:write scope, install the app, copy the Bot User OAuth Token (xoxb-), invite the bot to the channel, and list the channel id.", "Switch Enabled to On."], need: [["slack.botToken", "slack.webhookUrl"]] }, title: "💬 Slack", rows: [
@@ -97,6 +99,7 @@ function settingValue(row, value) {
97
99
  case "list": return Array.isArray(value) && value.every((v) => typeof v === "string") ? value.map((v) => v.trim()).filter(Boolean) : bad("expected a list");
98
100
  case "number": return Number.isInteger(value) && value > 0 ? value : bad("expected a whole number above 0");
99
101
  case "time": return typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value.trim()) ? value.trim() : bad("expected HH:MM, 00:00 to 23:59");
102
+ case "choice": return typeof value === "string" && row.choices.includes(value) ? value : bad(`expected one of ${row.choices.join(", ")}`);
100
103
  case "days": return Array.isArray(value) && value.every((d) => Number.isInteger(d) && d >= 0 && d <= 6) ? [...new Set(value)].sort() : bad("expected days 0-6");
101
104
  }
102
105
  }
@@ -186,7 +189,7 @@ export function panelState() {
186
189
  groups: unreadable !== undefined ? [] : SETTINGS.map((g) => ({
187
190
  title: g.title,
188
191
  guide: g.guide === undefined ? undefined : { summary: g.guide.summary, steps: g.guide.steps, next: nextStep(g, cfg) },
189
- rows: g.rows.map((r) => ({ path: r.path, label: r.label, kind: r.kind, hint: r.hint, value: readAt(cfg, r.path) })),
192
+ rows: g.rows.map((r) => ({ path: r.path, label: r.label, kind: r.kind, hint: r.hint, choices: r.choices, value: readAt(cfg, r.path) ?? r.fallback })),
190
193
  })),
191
194
  };
192
195
  }
@@ -153,6 +153,10 @@ function control(row) {
153
153
  var seg = el("span", "seg");
154
154
  [[true, "🟢 On"], [false, "⚫ Off"]].forEach(function (o) { var b = el("button", value === o[0] ? "on" : "", o[1]); b.onclick = function () { save(row.path, o[0], b); }; seg.append(b); });
155
155
  wrap.append(seg);
156
+ } else if (row.kind === "choice") {
157
+ var segc = el("span", "seg");
158
+ row.choices.forEach(function (c) { var b = el("button", value === c ? "on" : "", c); b.onclick = function () { save(row.path, c, b); }; segc.append(b); });
159
+ wrap.append(segc);
156
160
  } else if (row.kind === "days") {
157
161
  var days = Array.isArray(value) ? value.slice() : [], names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], segd = el("span", "seg");
158
162
  names.forEach(function (n, i) { var b = el("button", days.indexOf(i) >= 0 ? "on" : "", n); b.onclick = function () { var next = days.slice(), at = next.indexOf(i); if (at >= 0) next.splice(at, 1); else next.push(i); save(row.path, next, b); }; segd.append(b); });
@@ -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, conversationOwner, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, namedProject, workspaceOf, readEvents, turnInFlight, } from "./conversationOwner.js";
12
+ import { GatewayError, conversationReading, providerStartupReading, archiveConversation, conversationOwner, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversationOwner.js";
13
13
  import { CHAT_HEADERS } from "./chatPage.js";
14
14
  import { isIconPath, serveIcon } from "./iconDoor.js";
15
15
  import { handleMcp } from "./mcpDoor.js";
@@ -20,7 +20,6 @@ import { conversationSwitchRead, panelState, saveConversationSwitch, saveSetting
20
20
  import { PANEL_PAGES, panelHtml } from "./panelPage.js";
21
21
  import { wizard } from "./publicAccess.js";
22
22
  import { terminalHtml } from "./terminalPage.js";
23
- import { AgentGateway } from "../agentGateway.js";
24
23
  import { ServiceHost } from "../shared/webhost/bullseyeWebHost.js";
25
24
  import { sameRoot, workspacesHere } from "../shared/webhost/workspaceList.js";
26
25
  export const BAD_TOKEN_ERROR = "missing or wrong token";
@@ -128,12 +127,7 @@ async function route(req, url, arrivedAt) {
128
127
  if (resource === "projects" && parts.length === 2 && method === "GET")
129
128
  return { status: 200, body: listProjects(viewerOfHeaders(req.headers, fromThisMachine(req))) };
130
129
  if (resource === "providers" && parts.length === 2 && method === "GET") {
131
- requireConversationEnabled();
132
- const project = namedProject(url.searchParams.get("project"));
133
- const viewer = viewerOfHeaders(req.headers, fromThisMachine(req));
134
- if (viewer !== undefined && !sameRoot(workspaceOf(project), viewer.folder))
135
- throw new GatewayError(403, "This provider startup reading belongs to another workspace");
136
- return { status: 200, body: { providers: AgentGateway.instance().driver.availability(project) } };
130
+ return { status: 200, body: providerStartupReading(url.searchParams.get("project"), viewerOfHeaders(req.headers, fromThisMachine(req))) };
137
131
  }
138
132
  if (resource !== "conversations")
139
133
  throw new GatewayError(404, "unknown route");
@@ -162,9 +156,7 @@ async function route(req, url, arrivedAt) {
162
156
  }
163
157
  else if (sub === undefined) {
164
158
  if (method === "GET") {
165
- const current = readConversation(id);
166
- const native = AgentGateway.instance().driver.nativeState(id);
167
- return { status: 200, body: { ...current, ...native, working: native.working || turnInFlight(readEvents(id), current) !== undefined } };
159
+ return { status: 200, body: conversationReading(readConversation(id)) };
168
160
  }
169
161
  if (method === "DELETE") {
170
162
  const expected = url.searchParams.get("expectedConsumed");
@@ -122,6 +122,7 @@ export async function sendWithRouting(options) {
122
122
  }
123
123
  const delivered = [];
124
124
  const errors = [];
125
+ const notes = [];
125
126
  const attempted = [];
126
127
  const reach = reachWhileAtKeyboard(decision);
127
128
  for (const route of CHANNEL_ROUTES) {
@@ -130,8 +131,10 @@ export async function sendWithRouting(options) {
130
131
  attempted.push(route.channel);
131
132
  // OWNER: ITER/LOOP — one channel's provider failing must not stop the remaining channels — its reason is recorded per channel and the outcome below reports failed when no channel delivered
132
133
  try {
133
- await senders[route.channel](message, priority);
134
+ const note = await senders[route.channel](message, priority);
134
135
  delivered.push(route.channel);
136
+ if (note)
137
+ notes.push(`${route.channel} ${note}`);
135
138
  }
136
139
  catch (err) {
137
140
  errors.push(`${route.channel}: ${err instanceof Error ? err.message : String(err)}`);
@@ -148,7 +151,7 @@ export async function sendWithRouting(options) {
148
151
  attempted,
149
152
  errors,
150
153
  outcome: "delivered",
151
- summary: `Delivered to ${delivered.length} channel${delivered.length === 1 ? "" : "s"}: ${delivered.join(", ")}${notCarried} — ${decision.reason}.`,
154
+ summary: `Delivered to ${delivered.length} channel${delivered.length === 1 ? "" : "s"}: ${delivered.join(", ")}${notCarried}${notes.length ? `; ${notes.join("; ")}` : ""} — ${decision.reason}.`,
152
155
  };
153
156
  }
154
157
  if (decision.suppressedReason === "idle" && attempted.length === 0) {
@@ -0,0 +1,95 @@
1
+ export const TELEGRAM_PARSE_MODES = ["none", "MarkdownV2", "HTML"];
2
+ export function telegramParseMode(cfg) {
3
+ const configured = cfg.telegram?.parseMode;
4
+ if (configured === undefined)
5
+ return "HTML";
6
+ if (!TELEGRAM_PARSE_MODES.includes(configured))
7
+ throw new Error(`telegram.parseMode is ${JSON.stringify(configured)} — it must be one of ${TELEGRAM_PARSE_MODES.join(", ")}`);
8
+ return configured;
9
+ }
10
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
11
+ function balanced(fragment) {
12
+ const open = [];
13
+ for (const m of fragment.matchAll(/<(\/?)([\w-]+)[^>]*>/g)) {
14
+ if (m[1] === "")
15
+ open.push(m[2]);
16
+ else if (open.pop() !== m[2])
17
+ return false;
18
+ }
19
+ return open.length === 0;
20
+ }
21
+ const wrap = (tag) => (whole, inner) => (balanced(inner) ? `<${tag}>${inner}</${tag}>` : whole);
22
+ function inline(source) {
23
+ const kept = [];
24
+ const hold = (html) => `\uE000${kept.push(html) - 1}\uE001`;
25
+ let s = source.replace(/[\uE000\uE001]/g, "").replace(/`([^`\n]+)`/g, (_, code) => hold(`<code>${esc(code)}</code>`));
26
+ s = s.replace(/\[([^\]\n]+)\]\(((?:https?:\/\/|tg:\/\/|mailto:)[^\s)]+)\)/g, (_, text, url) => hold(`<a href="${esc(url).replace(/"/g, "&quot;")}">${esc(text)}</a>`));
27
+ s = s.replace(/https?:\/\/[^\s<>]+/g, (found) => {
28
+ const tail = /[*_~|+.,;:!?)\]'"]+$/.exec(found)?.[0] ?? "";
29
+ return hold(esc(found.slice(0, found.length - tail.length))) + tail;
30
+ });
31
+ s = esc(s)
32
+ .replace(/\*\*(?=\S)([^\n]+?)(?<=\S)\*\*/g, wrap("b"))
33
+ .replace(/(?<!\w)__(?=\S)([^\n]+?)(?<=\S)__(?!\w)/g, wrap("b"))
34
+ .replace(/~~(?=\S)([^\n]+?)(?<=\S)~~/g, wrap("s"))
35
+ .replace(/\|\|(?=\S)([^\n]+?)(?<=\S)\|\|/g, wrap("tg-spoiler"))
36
+ .replace(/\+\+(?=\S)([^\n]+?)(?<=\S)\+\+/g, wrap("u"))
37
+ .replace(/(?<![\w*])\*(?=[^\s*])([^\n*]+?)(?<=[^\s*])\*(?![\w*])/g, wrap("i"))
38
+ .replace(/(?<!\w)_(?=[^\s_])([^\n_]+?)(?<=[^\s_])_(?!\w)/g, wrap("i"));
39
+ const restore = (html) => html.replace(/\uE000(\d+)\uE001/g, (_, i) => restore(kept[Number(i)]));
40
+ return restore(s);
41
+ }
42
+ const boldLine = (html) => `<b>${html.replace(/<\/?b>/g, "")}</b>`;
43
+ const TABLE_ROW = /^\s*\|.*\|\s*$/;
44
+ const TABLE_RULE = /^\s*\|[\s:|-]+\|\s*$/;
45
+ const cells = (row) => row.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim()));
46
+ export function markdownToTelegramHtml(text) {
47
+ const lines = text.split("\n");
48
+ const out = [];
49
+ for (let i = 0; i < lines.length;) {
50
+ const line = lines[i];
51
+ const fence = /^\s*```([\w+#.-]*)\s*$/.exec(line);
52
+ const close = fence ? lines.findIndex((l, j) => j > i && /^\s*```\s*$/.test(l)) : -1;
53
+ if (fence && close > i) {
54
+ const code = esc(lines.slice(i + 1, close).join("\n"));
55
+ out.push(fence[1] ? `<pre><code class="language-${fence[1]}">${code}</code></pre>` : `<pre>${code}</pre>`);
56
+ i = close + 1;
57
+ }
58
+ else if (/^\s*>/.test(line)) {
59
+ const quoted = [];
60
+ for (; i < lines.length && /^\s*>/.test(lines[i]); i++)
61
+ quoted.push(inline(lines[i].replace(/^\s*>\s?/, "")));
62
+ out.push(`<blockquote>${quoted.join("\n")}</blockquote>`);
63
+ }
64
+ else if (TABLE_ROW.test(line) && i + 1 < lines.length && TABLE_RULE.test(lines[i + 1])) {
65
+ out.push(boldLine(cells(line).join(" · ")));
66
+ for (i += 2; i < lines.length && TABLE_ROW.test(lines[i]); i++)
67
+ out.push(`• ${cells(lines[i]).join(" — ")}`);
68
+ }
69
+ else if (/^\s{0,3}#{1,6}\s+\S/.test(line)) {
70
+ out.push(boldLine(inline(line.replace(/^\s*#{1,6}\s+/, "").replace(/\s+#+\s*$/, ""))));
71
+ i++;
72
+ }
73
+ else {
74
+ out.push(inline(line).replace(/^(\s*)[-*+]\s+(?=\S)/, "$1• "));
75
+ i++;
76
+ }
77
+ }
78
+ return out.join("\n");
79
+ }
80
+ export function stripTelegramMarks(text) {
81
+ return markdownToTelegramHtml(text)
82
+ .replace(/<a href="([^"]*)">(.*?)<\/a>/g, "$2 ($1)")
83
+ .replace(/<[^>]+>/g, "")
84
+ .replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&amp;/g, "&");
85
+ }
86
+ export async function postTelegramMessage(url, payload, mode, signal) {
87
+ const post = (body) => fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal });
88
+ if (mode === "none")
89
+ return { response: await post(payload), unformatted: false };
90
+ const text = mode === "HTML" ? markdownToTelegramHtml(payload.text) : payload.text;
91
+ const response = await post({ ...payload, text, parse_mode: mode });
92
+ if (response.status !== 400 || !/can't parse entities/i.test(await response.clone().text()))
93
+ return { response, unformatted: false };
94
+ return { response: await post({ ...payload, text: stripTelegramMarks(payload.text) }), unformatted: true };
95
+ }
package/dist/notify.js CHANGED
@@ -21,7 +21,8 @@ import { SQSClient } from "@aws-sdk/client-sqs";
21
21
  import { sendWithRouting, formatIdleReading, describePriorityRouting } from "./messaging/notificationEngine.js";
22
22
  import { deliveryVerdict } from "./messaging/deliveryVerdict.js";
23
23
  import { telegramSendErrorHint } from "./messaging/telegramError.js";
24
- import { splitForNotify } from "./chunk.js";
24
+ import { postTelegramMessage, telegramParseMode } from "./messaging/telegramFormat.js";
25
+ import { splitForNotify, withLead } from "./chunk.js";
25
26
  import { idleNow, playVoice, showBanner } from "./desk.js";
26
27
  import { AgentGateway, AGENT_PREFIX } from "./agentGateway.js";
27
28
  import { PollCursors, DiscordPlatform, TeamsPlatform, NtfyPlatform, SmsPlatform, listenForever, pollForever } from "./messaging/chatInbound.js";
@@ -115,7 +116,7 @@ function defaultConfig() {
115
116
  muteAll: false,
116
117
  disabledClients: [],
117
118
  desktop: { enabled: false },
118
- telegram: { enabled: false, token: "", chatIds: [] },
119
+ telegram: { enabled: false, token: "", chatIds: [], parseMode: "HTML" },
119
120
  sms: { enabled: false, accessKeyId: "", secretAccessKey: "", region: "us-east-1", originationNumber: "", to: [], inboundQueueUrl: "" },
120
121
  ntfy: { enabled: false, topic: "", serverUrl: "" },
121
122
  discord: { enabled: false, webhookUrl: "", username: "Claude Notify", clientId: "", clientSecret: "", channelName: "", botToken: "", channelId: "" },
@@ -457,24 +458,25 @@ async function sendNotification(message, priority, client) {
457
458
  telegram: async () => {
458
459
  const errors = [];
459
460
  let sent = 0;
461
+ let unformatted = 0;
462
+ const mode = telegramParseMode(cfg);
460
463
  for (const chatId of cfg.telegram.chatIds) {
461
464
  const body = { chat_id: chatId, text: message };
462
465
  // reply_to only resolves in the chat the last inbound came from.
463
466
  if (lastUserMessageId && chatId === lastUserChatId)
464
467
  body.reply_to_message_id = lastUserMessageId;
465
- const r = await fetch(tgApi(cfg.telegram.token, "sendMessage"), {
466
- method: "POST",
467
- headers: { "Content-Type": "application/json" },
468
- body: JSON.stringify(body),
469
- });
468
+ const { response: r, unformatted: plain } = await postTelegramMessage(tgApi(cfg.telegram.token, "sendMessage"), body, mode);
470
469
  if (r.ok) {
471
470
  sent++;
471
+ if (plain)
472
+ unformatted++;
472
473
  continue;
473
474
  }
474
475
  errors.push(`${chatId}: ${await telegramSendErrorHint(r)}`);
475
476
  }
476
477
  if (sent === 0 && errors.length)
477
478
  throw new Error(errors.join("; "));
479
+ return unformatted ? `went out UNFORMATTED to ${unformatted} chat(s): Telegram refused the formatting (can't parse entities), so the message was re-sent once as plain text` : undefined;
478
480
  },
479
481
  sms: () => smsEveryNumber(cfg, message),
480
482
  ntfy: async (_text, prio) => { await ntfyPublish(cfg, message, prio); },
@@ -1113,13 +1115,11 @@ function logTelegramError(msg) {
1113
1115
  async function telegramSendTo(token, chatId, text, replyTo) {
1114
1116
  if (loadConfig().telegram?.enabled !== true)
1115
1117
  throw new Error("Telegram is switched off in BN settings, so nothing is sent to it");
1116
- const r = await fetch(tgApi(token, "sendMessage"), {
1117
- method: "POST", headers: { "Content-Type": "application/json" },
1118
- body: JSON.stringify({ chat_id: chatId, text, reply_to_message_id: replyTo }),
1119
- signal: AbortSignal.timeout(15_000),
1120
- });
1118
+ const { response: r, unformatted } = await postTelegramMessage(tgApi(token, "sendMessage"), { chat_id: chatId, text, reply_to_message_id: replyTo }, telegramParseMode(loadConfig()), AbortSignal.timeout(15_000));
1121
1119
  if (!r.ok)
1122
1120
  throw new Error(await telegramSendErrorHint(r));
1121
+ if (unformatted)
1122
+ log("→", "telegram:format", `reply to ${chatId} went out UNFORMATTED — Telegram refused the formatting (can't parse entities)`);
1123
1123
  }
1124
1124
  async function startTelegramListener() {
1125
1125
  while (pollersWanted) {
@@ -1200,17 +1200,13 @@ async function startTelegramListener() {
1200
1200
  if (masterMuted())
1201
1201
  continue;
1202
1202
  // OWNER: ITER/LOOP — a non-2xx does not reject a fetch, so a refused acknowledgement would read as delivered; this frame reports it and the next update is read.
1203
- await fetch(tgApi(token, "sendMessage"), {
1204
- method: "POST", headers: { "Content-Type": "application/json" },
1205
- body: JSON.stringify({
1206
- chat_id: fromChatId,
1207
- text: ackText,
1208
- reply_to_message_id: msg.message_id,
1209
- }),
1210
- })
1211
- .then(async (r) => {
1212
- if (r.ok)
1203
+ await postTelegramMessage(tgApi(token, "sendMessage"), { chat_id: fromChatId, text: ackText, reply_to_message_id: msg.message_id }, telegramParseMode(cfg))
1204
+ .then(async ({ response: r, unformatted }) => {
1205
+ if (r.ok) {
1206
+ if (unformatted)
1207
+ log("→", "telegram:ack", `acknowledgement to ${fromChatId} went out UNFORMATTED — Telegram refused the formatting (can't parse entities)`, tag);
1213
1208
  return;
1209
+ }
1214
1210
  log("→", "telegram:ack", `NOT DELIVERED to ${fromChatId} for message ${msg.message_id}: ${await telegramSendErrorHint(r)}`, tag);
1215
1211
  })
1216
1212
  .catch((err) => {
@@ -1551,8 +1547,9 @@ function measuredSends(senders) {
1551
1547
  for (const channel of Object.keys(senders)) {
1552
1548
  measured[channel] = async (message, priority) => {
1553
1549
  try {
1554
- await senders[channel](message, priority);
1550
+ const note = await senders[channel](message, priority);
1555
1551
  recordReach(channel, true, "a notify send", "the message was sent and accepted");
1552
+ return note;
1556
1553
  }
1557
1554
  catch (err) {
1558
1555
  recordReach(channel, false, "a notify send", err instanceof Error ? err.message : String(err));
@@ -1999,7 +1996,7 @@ function drainInboxFor(tag) {
1999
1996
  async function sendChunked(message, priority, clientId) {
2000
1997
  const outcomes = [];
2001
1998
  for (const chunk of splitForNotify(message)) {
2002
- outcomes.push(await sendNotification(`[${clientId}] ${chunk}`, priority, clientId));
1999
+ outcomes.push(await sendNotification(withLead(`[${clientId}]`, chunk), priority, clientId));
2003
2000
  }
2004
2001
  return outcomes;
2005
2002
  }
@@ -2255,6 +2252,7 @@ export function createMcpServer(clientId, sessionTag) {
2255
2252
  // for four months and every question rode it into the void.
2256
2253
  const askCandidates = ["telegram"];
2257
2254
  const askSkipNotes = [];
2255
+ const askFormatNotes = [];
2258
2256
  // Measured now, per candidate: what cannot carry is absent from `canCarry`.
2259
2257
  const reaches = await Promise.all(askCandidates.map((channel) => measureReach(channel, cfg)));
2260
2258
  const canCarry = askCandidates.filter((_channel, i) => reaches[i]?.ok === true);
@@ -2305,17 +2303,14 @@ export function createMcpServer(clientId, sessionTag) {
2305
2303
  // network-level failure does — so this used to silently do nothing
2306
2304
  // on e.g. a revoked token: no error, no log line, just a question
2307
2305
  // the user never saw and no clue why. Story #443: check r.ok too.
2308
- await fetch(tgApi(cfg.telegram.token, "sendMessage"), {
2309
- method: "POST",
2310
- headers: { "Content-Type": "application/json" },
2311
- body: JSON.stringify({
2312
- chat_id: chatId,
2313
- text: `${askPrefix} ${question}${replyHint}`,
2314
- }),
2315
- })
2316
- .then(async (r) => {
2306
+ await postTelegramMessage(tgApi(cfg.telegram.token, "sendMessage"), { chat_id: chatId, text: `${askPrefix} ${question}${replyHint}` }, telegramParseMode(cfg))
2307
+ .then(async ({ response: r, unformatted }) => {
2317
2308
  if (r.ok) {
2318
2309
  telegramSent = true;
2310
+ if (unformatted) {
2311
+ askFormatNotes.push(`the question went out UNFORMATTED to ${chatId}: Telegram refused the formatting (can't parse entities), so it was re-sent once as plain text`);
2312
+ log("→", "ask:telegram", `question to ${chatId} went out UNFORMATTED — Telegram refused the formatting (can't parse entities)`, clientId);
2313
+ }
2319
2314
  return;
2320
2315
  }
2321
2316
  const why = await telegramSendErrorHint(r);
@@ -2331,7 +2326,7 @@ export function createMcpServer(clientId, sessionTag) {
2331
2326
  // there is: a probe can pass on a valid token whose chats no longer work.
2332
2327
  recordReach("telegram", telegramSent, "an ask send", telegramSent ? "the question was sent and accepted" : askSkipNotes.join("; "));
2333
2328
  }
2334
- const askSkipSuffix = askSkipNotes.length ? ` NOT delivered over: ${askSkipNotes.join("; ")}.` : "";
2329
+ const askSkipSuffix = (askSkipNotes.length ? ` NOT delivered over: ${askSkipNotes.join("; ")}.` : "") + (askFormatNotes.length ? ` ${askFormatNotes.join("; ")}.` : "");
2335
2330
  const deliveredOver = telegramSent
2336
2331
  ? "WAS delivered over telegram"
2337
2332
  : "was NOT delivered over anything";
@@ -2390,7 +2385,9 @@ export function createMcpServer(clientId, sessionTag) {
2390
2385
  };
2391
2386
  }
2392
2387
  log("←", "ask:reply", reply, clientId);
2393
- return { content: [{ type: "text", text: reply }] };
2388
+ return { content: [{ type: "text", text: askFormatNotes.length ? `${reply}
2389
+
2390
+ (${askFormatNotes.join("; ")}.)` : reply }] };
2394
2391
  });
2395
2392
  server.tool("poll", "Check for unsolicited messages the user has sent. " +
2396
2393
  "Returns queued messages and clears the queue. Returns 'inbox:empty' if nothing pending.", {}, async () => {
@@ -1005,7 +1005,11 @@ function identitiesHere() {
1005
1005
  read = deepagentSettings();
1006
1006
  }
1007
1007
  catch (absent) {
1008
- if (!(absent instanceof workspaceStore().SettingsUndefined))
1008
+ const store = workspaceStore();
1009
+ // A checkout off the workspace list keeps machine-wide settings unread by design (savedSettings answers undefined for it): OpenCode is told that, never "no key".
1010
+ if (absent instanceof store.WorkspaceNotListed)
1011
+ throw new NoOpenCodeKey("the BullseyeVSC checkout is not on this machine's workspace list, so DeepAgent's keys are not read here and OpenCode is handed none — add it on Bullseye Control");
1012
+ if (!(absent instanceof store.SettingsUndefined))
1009
1013
  throw absent;
1010
1014
  throw new NoOpenCodeKey(`${absent.message}, so this machine holds no DeepAgent key OpenCode could be handed`);
1011
1015
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.413",
3
+ "version": "1.3.415",
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",