omni-notify-mcp 1.3.412 → 1.3.414

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
  }
@@ -748,7 +748,11 @@ async function home() {
748
748
  if (res.status === 401) { signIn("You are signed out. Sign in again."); return; }
749
749
  if (!res.ok) throw new Error("The gateway answered " + res.status + ": " + await res.text());
750
750
  var opened = await res.json();
751
- if (mine === view) location.replace(opened.page);
751
+ if (mine === view) {
752
+ var back = sessionStorage.getItem("bullseye-return-to");
753
+ sessionStorage.removeItem("bullseye-return-to");
754
+ location.replace(back !== null && back.charAt(0) === "/" && back.charAt(1) !== "/" && back.charAt(1) !== "\\" ? back : opened.page);
755
+ }
752
756
  } catch (err) { if (!(err instanceof Error)) throw err; if (mine === view) said.replaceWith(el("div", "err", err.message)); }
753
757
  }
754
758
  `;
@@ -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); });
@@ -160,7 +160,7 @@ function show(name,heading){
160
160
  return view;
161
161
  }
162
162
 
163
- function down(what,method,path){if(method==="GET"&&path==="/v1/conversations")window.bullseyeConnection.reconnecting(what,8000);else if(method==="GET"&&path==="/v1/panel")window.bullseyeConnection.reconnecting(what,5000);else if(method==="GET"&&path.indexOf("/v1/terminals/")===0)window.bullseyeConnection.reconnecting(what,1000);else window.bullseyeConnection.disconnected(what,"this request did not go through — repeat it");}function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}async function api(method,path,body,signal){var response;try{response=await fetch(path,{method:method,headers:scoped({authorization:"Bearer "+token,"content-type":"application/json"}),body:body===undefined?undefined:JSON.stringify(body),signal:signal});}catch(e){if(e.name!=="AbortError")down("the connection to the Notify service",method,path);throw e;}if(response.status>=502)down("the connection to the Notify service (HTTP "+response.status+")",method,path);else if(!socketDown)window.bullseyeConnection.live();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;}
163
+ function down(what,method,path){if(method==="GET"&&path==="/v1/conversations")window.bullseyeConnection.reconnecting(what,8000);else if(method==="GET"&&path==="/v1/panel")window.bullseyeConnection.reconnecting(what,5000);else if(method==="GET"&&path.indexOf("/v1/terminals/")===0)window.bullseyeConnection.reconnecting(what,1000);}function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}async function api(method,path,body,signal){var response;try{response=await fetch(path,{method:method,headers:scoped({authorization:"Bearer "+token,"content-type":"application/json"}),body:body===undefined?undefined:JSON.stringify(body),signal:signal});}catch(e){if(e.name!=="AbortError")down("the connection to the Notify service",method,path);throw e;}if(response.status>=502)down("the connection to the Notify service (HTTP "+response.status+")",method,path);else if(!socketDown)window.bullseyeConnection.live();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;}
164
164
  function fail(error){note.textContent=error.message;}
165
165
  function ordered(id,act,body){if(!socket||socket.readyState!==WebSocket.OPEN)return;socket.send(JSON.stringify(Object.assign({kind:act},body)));}
166
166
  /** The last folder of a path, so a row names its project without printing the whole path. */
@@ -371,23 +371,41 @@ async function cliAttach(id,origin){
371
371
  else b.onclick=function(){sendKey(key.seq[term.modes.applicationCursorKeysMode?1:0]);term.focus();};
372
372
  keybar.append(b);
373
373
  });
374
- term.onData(function(data){if(ctrlHeld&&data.length===1){disarm();data=ctrlByte(data);}ordered(id,"input",{data:data});});term.onBinary(function(data){ordered(id,"input",{data:btoa(data),binary:true});});
374
+ var pending=[];function typed(body){if(socket&&socket.readyState===WebSocket.OPEN)ordered(id,"input",body);else pending.push(body);}
375
+ term.onData(function(data){if(ctrlHeld&&data.length===1){disarm();data=ctrlByte(data);}typed({data:data});});term.onBinary(function(data){typed({data:btoa(data),binary:true});});
375
376
  refit=function(){if(mine!==view||!socket||socket.readyState!==WebSocket.OPEN)return;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});};
376
377
  if(observer)observer.disconnect();observer=new ResizeObserver(refit);host.addEventListener("pointerdown",refit);host.addEventListener("touchstart",refit,{passive:true});var wake=function(){if(!document.hidden)refit();},off=observer.disconnect.bind(observer);window.addEventListener("focus",wake);document.addEventListener("visibilitychange",wake);observer.disconnect=function(){window.removeEventListener("focus",wake);document.removeEventListener("visibilitychange",wake);off();};
377
378
  reattach.onclick=function(){cliAttach(id,origin);};
378
379
  back.onclick=goBack;
379
380
  close.onclick=async function(){close.disabled=true;try{await api("DELETE","/v1/terminals/"+id);swap("list");}catch(error){close.disabled=false;fail(error);}};
380
381
  observer.observe(host);
382
+ var WHAT="the terminal connection to the CLI",reattached=false;
381
383
  function connect(){
382
384
  if(mine!==view)return;
383
- term.options.disableStdin=true;
384
385
  var ws=new WebSocket((location.protocol==="https:"?"wss://":"ws://")+location.host+"/v1/terminals/"+id+"/ws",["bn-terminal","bn-bearer."+token]);socket=ws;
385
386
  var frames=Promise.resolve(),opened=false;
386
- ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;window.bullseyeConnection.live();term.options.disableStdin=false;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});term.focus();};
387
+ ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;window.bullseyeConnection.opened(function(){return socket===ws&&ws.readyState===WebSocket.OPEN;},window.bullseyeConnection.live);term.options.disableStdin=false;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});while(pending.length)ordered(id,"input",pending.shift());term.focus();};
387
388
  ws.onmessage=function(event){frames=frames.then(async function(){if(mine!==view)return;var frame=JSON.parse(event.data);if(frame.files){fileNotice=frame.error||"Sent to CLI: "+frame.paths.join(" · ");note.textContent=fileNotice;return;}if(frame.error){note.textContent=frame.error;return;}var behind=frame.reset?term.buffer.active.baseY-term.buffer.active.viewportY:0;if(frame.reset)term.reset();await new Promise(function(done){term.write(frame.data,done);});if(mine!==view)return;if(behind>0)term.scrollLines(-behind);note.textContent=frame.provider+" · "+(phone?base(frame.project):frame.project)+(frame.ended?" · CLI ended":" · connected")+(frame.failure?" · "+frame.failure:"")+(fileNotice?" · "+fileNotice:"");}).catch(fail);};
388
- ws.onclose=function(event){if(mine!==view)return;term.options.disableStdin=true;if(event.code===1000){socketDown=false;window.bullseyeConnection.live();note.textContent="CLI ended.";return;}if(event.code===1008){socketDown=true;window.bullseyeConnection.disconnected("the terminal connection to the CLI",event.reason+" — press Reattach or sign in again");note.textContent="Disconnected: "+event.reason+". Press Reattach or sign in again.";return;}socketDown=true;window.bullseyeConnection.reconnecting("the terminal connection to the CLI",1000);note.textContent="Disconnected. Reattaching to the same CLI…";if(opened){reconnect=setTimeout(connect,1000);return;}api("GET","/v1/terminals/"+id).then(function(){if(mine===view)reconnect=setTimeout(connect,1000);},function(error){if(mine!==view)return;if(error.status!==404){reconnect=setTimeout(connect,1000);return;}window.bullseyeConnection.disconnected("the terminal connection to the CLI","this CLI no longer exists — press Back to pick another");note.textContent="This CLI no longer exists. Press Back to pick another.";});};
389
- ws.onerror=function(){socketDown=true;window.bullseyeConnection.reconnecting("the terminal connection to the CLI",1000);note.textContent="Terminal connection failed. Reconnecting…";};
389
+ ws.onclose=function(event){if(mine!==view)return;var ending=event.code===1000||(event.code===1008&&event.reason==="Sign in again");if(ending){term.options.disableStdin=true;pending.length=0;}if(event.code===1000){socketDown=false;window.bullseyeConnection.live();note.textContent="CLI ended.";return;}if(event.code===1008&&event.reason==="Sign in again"){socketDown=false;window.bullseyeConnection.live();signIn("Your sign-in expired. Sign in again to return to this CLI.");return;}socketDown=true;var wait=opened?window.bullseyeConnection.closed(reattached):window.bullseyeConnection.failed();reattached=true;window.bullseyeConnection.reconnecting(WHAT,wait);note.textContent="Disconnected. Reattaching to the same CLI…";reconnect=setTimeout(findCli,wait);};
390
+ ws.onerror=function(){socketDown=true;note.textContent="Terminal connection failed. Reconnecting…";};
390
391
  }
392
+ // GATE: a reattach's read of its CLI that has not answered in this long is abandoned and asked again with backoff, so a dead link never leaves the page waiting on it
393
+ var FIND_MS=8000;
394
+ // GATE: opening the CLI again that has not answered in this long is abandoned and asked again with backoff; it covers a CLI's own start
395
+ var START_MS=30000;
396
+ function findCli(){
397
+ if(mine!==view)return;
398
+ api("GET","/v1/terminals/"+id,undefined,AbortSignal.timeout(FIND_MS)).then(connect,function(error){
399
+ if(mine!==view)return;
400
+ if(error.status!==404)return later();
401
+ api("POST","/v1/terminals",{conversation:id,cols:term.cols,rows:term.rows},AbortSignal.timeout(START_MS)).then(function(started){if(mine!==view)return;if(started.id!==id){swap("term",started.id);return;}connect();},function(failure){
402
+ if(mine!==view)return;
403
+ if(failure.status!==404)return later();
404
+ swap("term",id);
405
+ });
406
+ });
407
+ }
408
+ function later(){var wait=window.bullseyeConnection.failed();window.bullseyeConnection.reconnecting(WHAT,wait);reconnect=setTimeout(findCli,wait);}
391
409
  connect();
392
410
  }
393
411
  ${CONVERSATIONS_VIEWS}
@@ -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 () => {
@@ -3178,8 +3178,8 @@ export function fenceStart(provider, what) {
3178
3178
  export const WAKE_BASE_MS = 60_000;
3179
3179
  // GATE: how many times the wait doubles — past it a parked worker is woken every WAKE_BASE_MS * 2^WAKE_DOUBLINGS (32 min)
3180
3180
  export const WAKE_DOUBLINGS = 5;
3181
- // GATE: the free physical memory below which no story worker is started or woken — the story waits in line and starts on the first pass the box has this much free again; it leaves the trade JVM room for its whole -Xmx2048m heap, one more agent's tree and the servers on 7470-7481 room to grow
3182
- export const START_MEMORY_FLOOR_BYTES = 4 * 2 ** 30;
3181
+ // GATE: the free physical memory below which no story worker is started or woken — the story waits in line and starts on the first pass the box has this much free again
3182
+ export const START_MEMORY_FLOOR_BYTES = 1.5 * 2 ** 30;
3183
3183
  // GATE: the memory one started worker's process tree is taken to reach (the largest working tree measured), reserved out of the free reading for each worker started or woken within START_MEMORY_GROWTH_MS, whose growth that reading cannot see yet
3184
3184
  export const AGENT_TREE_BYTES = 830 * 2 ** 20;
3185
3185
  // GATE: how long a started worker's growth is reserved before the free reading is trusted to carry it
@@ -1352,6 +1352,7 @@ function closedPage(extension, page) {
1352
1352
  function connect() {
1353
1353
  var opened = false;
1354
1354
  var socket = new WebSocket((location.protocol === "https:" ? "wss:" : "ws:") + "//" + location.host + "/__bullseye/ws?page=${encodeURIComponent(page.name)}&peek=1");
1355
+ setTimeout(function () { if (socket.readyState === 0) socket.close(); }, 10000);
1355
1356
  socket.addEventListener("open", function () {
1356
1357
  opened = true;
1357
1358
  var mine = socket;
@@ -1362,12 +1363,11 @@ function closedPage(extension, page) {
1362
1363
  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(); });
1363
1364
  });
1364
1365
  socket.addEventListener("message", function (event) { if (JSON.parse(String(event.data)).type === "reload") location.reload(); });
1365
- socket.addEventListener("close", function () { if (opened) { var w = window.bullseyeConnection.closed(reconnected); reconnected = true; window.bullseyeConnection.reconnecting(WHAT, w); setTimeout(awaitHost, w); } else if (reconnected) { var refused = window.bullseyeConnection.failed(); window.bullseyeConnection.reconnecting(WHAT, refused); setTimeout(awaitHost, refused); } else { window.bullseyeConnection.disconnected(WHAT, "the host did not accept the connection — reload this page to try again"); document.getElementById("said").textContent = "⚠️ This page could not reach its host, so it cannot load the page when it opens — reload it to try again"; } });
1366
+ socket.addEventListener("close", function () { if (opened) { var w = window.bullseyeConnection.closed(reconnected); reconnected = true; window.bullseyeConnection.reconnecting(WHAT, w); document.getElementById("said").textContent = "⏳ This page's host is not answering — this page reconnects the moment it does"; setTimeout(awaitHost, w); } else { var refused = window.bullseyeConnection.failed(); window.bullseyeConnection.reconnecting(WHAT, refused); document.getElementById("said").textContent = "⏳ This page's host did not accept its connection — this page tries again by itself"; setTimeout(awaitHost, refused); } });
1366
1367
  }
1367
1368
  function awaitHost() {
1368
1369
  window.bullseyeConnection.reconnecting(WHAT, 250);
1369
- document.getElementById("said").textContent = "⏳ This page's host is not answering — this page reconnects the moment it does";
1370
- fetch("/__bullseye/health", { cache: "no-store" }).then(function (r) { if (r.ok) { connect(); } else if (r.status === 401) location.assign("/"); else setTimeout(awaitHost, 250); }, function () { setTimeout(awaitHost, 250); });
1370
+ fetch("/__bullseye/health", { cache: "no-store", signal: AbortSignal.timeout(8000) }).then(function (r) { if (r.ok) { connect(); } else if (r.status === 401) window.bullseyeConnection.signInAgain(); else setTimeout(awaitHost, 250); }, function () { setTimeout(awaitHost, 250); });
1371
1371
  }
1372
1372
  connect();
1373
1373
  })();</script></body></html>`;
@@ -278,8 +278,8 @@ const CONNECTION_SOURCE = String.raw `(function () {
278
278
  return;
279
279
  }
280
280
  var COVER = "__bullseye-connection";
281
- var MARKS = { reconnecting: "🔄 RECONNECTING", disconnected: "🔴 DISCONNECTED", live: "✅ LIVE" };
282
- var COLOURS = { reconnecting: "#7a5200", disconnected: "#8a1f1f", live: "#1d5a2c" };
281
+ var MARKS = { reconnecting: "🔄 RECONNECTING", live: "✅ LIVE" };
282
+ var COLOURS = { reconnecting: "#7a5200", live: "#1d5a2c" };
283
283
  var current = null;
284
284
  var ticker = 0;
285
285
  var clearer = 0;
@@ -294,8 +294,6 @@ const CONNECTION_SOURCE = String.raw `(function () {
294
294
  var lines = ["What dropped: " + current.what, "Since: " + clock(current.since) + " (" + Math.round((now - current.since) / 1000) + " s ago)"];
295
295
  if (current.state === "reconnecting" && current.retryAt !== undefined) {
296
296
  lines.push("Next retry: " + (current.retryAt > now ? "in " + Math.ceil((current.retryAt - now) / 1000) + " s" : "now"));
297
- } else if (current.state === "disconnected") {
298
- lines.push("Next retry: none — " + (current.why || "reload this page to try again"));
299
297
  } else if (current.state === "live") {
300
298
  lines.push("Live again after " + Math.round((now - current.since) / 1000) + " s");
301
299
  }
@@ -401,8 +399,9 @@ const CONNECTION_SOURCE = String.raw `(function () {
401
399
  reconnecting: function (what, retryInMs) {
402
400
  show("reconnecting", what, { retryAt: Date.now() + retryInMs });
403
401
  },
404
- disconnected: function (what, why) {
405
- show("disconnected", what, { why: why });
402
+ signInAgain: function () {
403
+ window.sessionStorage.setItem("bullseye-return-to", window.location.pathname + window.location.search + window.location.hash);
404
+ window.location.assign("/");
406
405
  },
407
406
  live: function () {
408
407
  if (current === null || current.state === "live") {
@@ -456,7 +455,7 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
456
455
  var WHAT = "this page's live connection to its service";
457
456
  // GATE: one health read is abandoned after this times the square of the tries so far (capped at 8000), then asked again
458
457
  var ANSWER_MS = 700;
459
- // GATE: how long a reopened socket may stay connecting before it is given up and the host is asked again, times the give-ups in a row (capped at 30000)
458
+ // GATE: how long a socket may stay connecting, or its sign-in check go unanswered, before it is given up and asked again, times the give-ups in a row (capped at 30000)
460
459
  var CONNECT_MS = 5000;
461
460
  var healthTries = 0;
462
461
  var lastHeard = Date.now();
@@ -473,19 +472,25 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
473
472
  awaitHost();
474
473
  }
475
474
 
475
+ function askAgainLater() {
476
+ var wait = window.bullseyeConnection.failed();
477
+ window.bullseyeConnection.reconnecting(WHAT, wait);
478
+ window.setTimeout(awaitHost, wait);
479
+ }
480
+
476
481
  function unreached(err) {
477
482
  if (err.name === "AbortError") {
478
483
  awaitHost();
479
484
  } else if (err instanceof TypeError) {
480
485
  window.setTimeout(awaitHost, 250);
481
486
  } else {
482
- window.bullseyeConnection.disconnected(WHAT, "the host answered its health read with something that is not its own reply — reload this page to try again");
487
+ askAgainLater();
483
488
  }
484
489
  }
485
490
 
486
491
  function reconnectOrReload(health) {
487
492
  if (health.pages === undefined) {
488
- window.bullseyeConnection.disconnected(WHAT, "the host answered its health read with something that is not its own reply — reload this page to try again");
493
+ askAgainLater();
489
494
  return;
490
495
  }
491
496
  var served = health.pages[page];
@@ -516,7 +521,7 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
516
521
  window.clearTimeout(abandon);
517
522
  healthTries = 0;
518
523
  if (response.status === 401) {
519
- window.location.assign("/");
524
+ window.bullseyeConnection.signInAgain();
520
525
  } else {
521
526
  window.setTimeout(awaitHost, 250);
522
527
  }
@@ -530,18 +535,15 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
530
535
  var scheme = window.location.protocol === "https:" ? "wss:" : "ws:";
531
536
  var mine = new WebSocket(scheme + "//" + window.location.host + "/__bullseye/ws?page=" + encodeURIComponent(page) + "&at=" + encodeURIComponent(window.location.search) + "&drawn=" + encodeURIComponent(drawn) + (new URLSearchParams(window.location.search).get("bullseye-peek") === null ? "" : "&peek=1"));
532
537
  socket = mine;
533
- if (reconnects > 0) {
534
- window.setTimeout(function () {
535
- if (socket === mine && mine.readyState === 0) {
536
- window.bullseyeConnection.failed();
537
- socket = null;
538
- mine.close();
539
- awaitHost();
540
- }
541
- }, Math.min(CONNECT_MS * (window.bullseyeConnection.attempts() + 1), 30000));
542
- }
543
538
  var opened = false;
544
539
  var reopened = reconnects > 0;
540
+ window.setTimeout(function () {
541
+ if (socket === mine && mine.readyState === 0) {
542
+ socket = null;
543
+ mine.close();
544
+ notAccepted(reopened);
545
+ }
546
+ }, Math.min(CONNECT_MS * (window.bullseyeConnection.attempts() + 1), 30000));
545
547
  mine.addEventListener("open", function () {
546
548
  opened = true;
547
549
  lastHeard = Date.now();
@@ -555,11 +557,9 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
555
557
  while (queue.length > 0) {
556
558
  mine.send(queue.shift());
557
559
  }
558
- if (reconnects > 0) {
559
- window.bullseyeConnection.opened(function () {
560
- return socket === mine && mine.readyState === 1;
561
- }, window.bullseyeConnection.live);
562
- }
560
+ window.bullseyeConnection.opened(function () {
561
+ return socket === mine && mine.readyState === 1;
562
+ }, window.bullseyeConnection.live);
563
563
  });
564
564
  mine.binaryType = "blob";
565
565
  var unpacking = Promise.resolve();
@@ -615,19 +615,25 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
615
615
  window.setTimeout(awaitHost, wait);
616
616
  return;
617
617
  }
618
- if (reopened) {
619
- var refusedWait = window.bullseyeConnection.failed();
620
- window.bullseyeConnection.reconnecting(WHAT, refusedWait);
621
- window.setTimeout(awaitHost, refusedWait);
622
- return;
618
+ notAccepted(reopened);
619
+ });
620
+ }
621
+
622
+ function notAccepted(reopened) {
623
+ var wait = window.bullseyeConnection.failed();
624
+ window.bullseyeConnection.reconnecting(WHAT, wait);
625
+ window.setTimeout(reopened ? awaitHost : openUnlessSignedOut, wait);
626
+ }
627
+
628
+ function openUnlessSignedOut() {
629
+ window.fetch("/__bullseye/health", { cache: "no-store", signal: AbortSignal.timeout(Math.min(CONNECT_MS * (window.bullseyeConnection.attempts() + 1), 30000)) }).then(function (response) {
630
+ if (response.status === 401) {
631
+ window.bullseyeConnection.signInAgain();
632
+ } else {
633
+ open();
623
634
  }
624
- window.fetch("/__bullseye/health", { cache: "no-store" }).then(function (response) {
625
- if (response.ok) {
626
- window.bullseyeConnection.disconnected(WHAT, "the host did not accept the connection — reload this page to try again");
627
- } else {
628
- awaitHost();
629
- }
630
- }, awaitHost);
635
+ }, function () {
636
+ notAccepted(false);
631
637
  });
632
638
  }
633
639