omni-notify-mcp 1.3.427 → 1.3.428

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/README.md CHANGED
@@ -105,8 +105,8 @@ entirely server-side.
105
105
 
106
106
  | Tool | Arguments | Behaviour |
107
107
  |---|---|---|
108
- | `notify` | `message` (≤5000), `priority` = `low`\|`normal`\|`high` | Fan out per the routing table below. The result states `outcome=` with the `attempted` and `delivered` channels, and carries any queued inbox messages for this session. |
109
- | `ask` | `question` (≤500), `timeout_seconds` (30–3600, default 300) | Sends the question over Telegram and **blocks** until you answer. The wait is clamped to the caller's own transport limit, so it returns `NO REPLY YET` and leaves the question open rather than reporting it as ignored; the answer arrives in the inbox. |
108
+ | `notify` | `message` (≤5000), `priority` = `low`\|`normal`\|`high`, `answers` | Carries only a board decision (the message holds the board's decision link) or an answer to something you asked (`answers` = your own words); anything else is refused with `outcome=blocked` and reaches nobody. Fan out per the routing table below. The result states `outcome=` with the `attempted` and `delivered` channels, and carries any queued inbox messages for this session. |
109
+ | `ask` | `question` (≤500), `answers`, `timeout_seconds` (30–3600, default 300) | Only a question you asked to be put to you (`answers` = your words), else `outcome=blocked`; an agent's own decision goes as the story's board decision instead. Sends the question over Telegram and **blocks** until you answer. The wait is clamped to the caller's own transport limit, so it returns `NO REPLY YET` and leaves the question open rather than reporting it as ignored; the answer arrives in the inbox. |
110
110
  | `poll` | — | Drains queued inbox messages for this session; returns `inbox:empty` when there are none. |
111
111
  | `wait_for_inbox` | `timeout_seconds` (5–55, default 50) | Blocks and returns the moment you type, as a tool *result* — the delivery path that works in every MCP client. Returns already-queued messages immediately. |
112
112
  | `get_idle_seconds` | — | How long since the logged-on user's last keyboard/mouse input, read in his own session, as one of two DIFFERENT answers: `idle: measured N seconds …`, or `idle: could not measure — <why> — user activity unknown, so activity gating is skipped`. |
@@ -114,7 +114,7 @@ entirely server-side.
114
114
  | `get_delivery_status` | — | `{ process, healthy, channels, carriage, reason }` from real transport readings, not from config or from the process being alive. `healthy` is true only when every enabled channel has been MEASURED able to carry. |
115
115
  | `get_dnd_status` | — | `{ active, reason }` where reason is `disabled`, `manual`, `schedule` or `off`. |
116
116
  | `update_instructions` | `instructions` (≤4000), `target` = `global`\|`project` | Rewrites a marker-delimited block in `~/.claude/CLAUDE.md` (global) or `./.claude/CLAUDE.md` (project). |
117
- | `reply` | `message` (≤2000) | The return path for your most recent channel message, routed back through `notify` so it lands on whichever channel you are reading. |
117
+ | `reply` | `message` (≤2000), `answers` | The return path for your most recent channel message, routed back through `notify` so it lands on whichever channel you are reading; `answers` carries the words of the message it answers, else `outcome=blocked`. |
118
118
 
119
119
  **Message size and chunking.** `notify` accepts up to 5000 characters and splits
120
120
  anything over 500 into numbered `(1/N) …` chunks (word-aware where a break lands past
@@ -1,12 +1,38 @@
1
1
  /** #4494 — the BullseyeBacklog service's loopback door that takes a digit he replied to one of its decision messages with. */
2
- export const BOARD_DIGIT_DOOR = "http://127.0.0.1:7471/board/decisionDigit";
2
+ // GATE: the board's digit door may be moved ONLY under the test gate, so a suite drives a board stand-in on a socket it owns; without the gate it is 7471 and no environment can redirect it
3
+ export const BOARD_DIGIT_DOOR = process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" && process.env.NOTIFY_BOARD_DIGIT_DOOR ? process.env.NOTIFY_BOARD_DIGIT_DOOR : "http://127.0.0.1:7471/board/decisionDigit";
3
4
  /** The board's door answered something other than a ruling or a reason it ruled nothing. */
4
5
  export class BoardDoorRefused extends Error {
5
6
  }
7
+ /** The board decision link a message carries, or undefined when it carries none. */
8
+ export function decisionLink(text) {
9
+ return /https?:\/\/\S+\/board\/decision\?\S+/.exec(text)?.[0];
10
+ }
6
11
  /** His reply as a decision pick: a lone digit 1-4 (an optional `.` or `)` after it) sent as a reply to a message carrying a board decision link; else undefined. */
7
12
  export function decisionReply(text, repliedTo) {
8
13
  const digit = /^\s*([1-4])[.)]?\s*$/.exec(text)?.[1];
9
- const link = /https?:\/\/\S+\/board\/decision\?\S+/.exec(repliedTo ?? "")?.[0];
14
+ const link = decisionLink(repliedTo ?? "");
15
+ return digit === undefined || link === undefined ? undefined : { digit, link };
16
+ }
17
+ const KEYCAPS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣"];
18
+ /** The `callback_data` a decision button carries: the digit it picks, the decision itself named by the message the button sits on. */
19
+ const PICK_DATA = "pick:";
20
+ /** Telegram's inline keyboard for a single-pick board decision message: one button per numbered option line, in order; undefined for any other message, a pick-several decision included. */
21
+ export function decisionButtons(text) {
22
+ if (decisionLink(text) === undefined)
23
+ return undefined;
24
+ const rows = text.split("\n").flatMap((line) => {
25
+ const i = KEYCAPS.findIndex((k) => line.startsWith(`${k} `));
26
+ if (i < 0)
27
+ return [];
28
+ return [[{ text: line.trim(), callback_data: `${PICK_DATA}${i + 1}` }]];
29
+ });
30
+ return rows.length >= 2 && !/PICK ONE OR MORE/.test(text) ? { inline_keyboard: rows } : undefined;
31
+ }
32
+ /** A tap on a decision button as a pick: its digit and the decision link of the message it sits on; else undefined. */
33
+ export function buttonPick(data, messageText) {
34
+ const digit = /^pick:([1-4])$/.exec(data ?? "")?.[1];
35
+ const link = decisionLink(messageText ?? "");
10
36
  return digit === undefined || link === undefined ? undefined : { digit, link };
11
37
  }
12
38
  /** The door's answer as a ruling and a report, or why it is not one. */
package/dist/notify.js CHANGED
@@ -27,7 +27,7 @@ import { idleNow, playVoice, showBanner } from "./desk.js";
27
27
  import { AgentGateway, AGENT_PREFIX } from "./agentGateway.js";
28
28
  import { PollCursors, DiscordPlatform, TeamsPlatform, NtfyPlatform, SmsPlatform, listenForever, pollForever } from "./messaging/chatInbound.js";
29
29
  import { EmailAgentInbox } from "./messaging/emailInbound.js";
30
- import { BoardDoorRefused, decisionReply, pickByDigit } from "./messaging/decisionDigit.js";
30
+ import { BoardDoorRefused, buttonPick, decisionButtons, decisionLink, decisionReply, pickByDigit } from "./messaging/decisionDigit.js";
31
31
  import { z } from "zod";
32
32
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
33
33
  const MANIFEST_PATH = fileURLToPath(new URL("../package.json", import.meta.url));
@@ -403,7 +403,7 @@ export const textOwner = (message) => smsEveryNumber(loadConfig(), message);
403
403
  export function masterMuted() {
404
404
  return loadConfig().muteAll === true;
405
405
  }
406
- async function sendNotification(message, priority, client) {
406
+ async function sendNotification(message, priority, client, buttons) {
407
407
  const cfg = loadConfig();
408
408
  if (cfg.muteAll === true) {
409
409
  log("·", "notify", `BLOCKED — all notifications disabled (master mute), priority=${priority}`, client);
@@ -464,6 +464,9 @@ async function sendNotification(message, priority, client) {
464
464
  const mode = telegramParseMode(cfg);
465
465
  for (const chatId of cfg.telegram.chatIds) {
466
466
  const body = { chat_id: chatId, text: message };
467
+ // NULL-OK: field buttons is OPTIONAL and therefore it is ok to check for NULL
468
+ if (buttons !== undefined)
469
+ body.reply_markup = buttons;
467
470
  // reply_to only resolves in the chat the last inbound came from.
468
471
  if (lastUserMessageId && chatId === lastUserChatId)
469
472
  body.reply_to_message_id = lastUserMessageId;
@@ -1123,6 +1126,60 @@ async function telegramSendTo(token, chatId, text, replyTo) {
1123
1126
  if (unformatted)
1124
1127
  log("→", "telegram:format", `reply to ${chatId} went out UNFORMATTED — Telegram refused the formatting (can't parse entities)`);
1125
1128
  }
1129
+ /** One Bot API call answered by its response; a non-2xx is logged with Telegram's reason, never read as done. */
1130
+ async function tgCall(token, method, body) {
1131
+ let r;
1132
+ try {
1133
+ r = await fetch(tgApi(token, method), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) });
1134
+ }
1135
+ catch (err) {
1136
+ if (!(err instanceof TypeError || (err instanceof DOMException && err.name === "TimeoutError")))
1137
+ throw err;
1138
+ // OWNER: one step of answering his tap or digit could not reach Telegram — it is logged NOT DONE and the steps after it still run, so the ruling he made is never hidden by a failed button removal.
1139
+ log("→", `telegram:${method}`, `NOT DONE: Telegram could not be reached: ${err.message}`);
1140
+ return;
1141
+ }
1142
+ if (!r.ok)
1143
+ log("→", `telegram:${method}`, `NOT DONE: ${await telegramSendErrorHint(r)}`);
1144
+ }
1145
+ /** Takes the option buttons off a decision message once it is ruled, so a second tap cannot land on an answered decision. */
1146
+ async function dropDecisionButtons(token, chatId, messageId) {
1147
+ await tgCall(token, "editMessageReplyMarkup", { chat_id: chatId, message_id: messageId, reply_markup: { inline_keyboard: [] } });
1148
+ }
1149
+ /**
1150
+ * A tap on one of a board decision message's buttons: from one of his configured chats (his own, or a group of his) it rules that option on the story the tapped message names,
1151
+ * whatever other decisions are open, answers the tap, takes the buttons off a ruled decision and replies to that message with what the
1152
+ * board said; a tap in any other chat, or on a message carrying no decision, is answered and ruled nowhere.
1153
+ */
1154
+ async function takeDecisionTap(token, chatIds, tap) {
1155
+ const chatId = tap.message?.chat?.id?.toString();
1156
+ const pick = chatIds.includes(chatId) ? buttonPick(tap.data, tap.message?.text) : undefined;
1157
+ // NULL-OK: field pick is OPTIONAL and therefore it is ok to check for NULL
1158
+ if (pick === undefined) {
1159
+ log("←", "decision:button", `not ruled: tap ${tap.data} from ${tap.from?.id} in chat ${chatId} is not his tap on a decision`);
1160
+ await tgCall(token, "answerCallbackQuery", { callback_query_id: tap.id, text: "Not a decision of yours" });
1161
+ return;
1162
+ }
1163
+ let said;
1164
+ try {
1165
+ said = await pickByDigit(pick);
1166
+ }
1167
+ catch (err) {
1168
+ if (!(err instanceof BoardDoorRefused))
1169
+ throw err;
1170
+ // OWNER: his tap is an unsolicited callback and this is its root — the board could not take it, so he is told on the tap itself to reply with the digit instead and why is logged.
1171
+ log("·", "decision:button", `the board did not take tap ${pick.digit}: ${err.message}`);
1172
+ await tgCall(token, "answerCallbackQuery", { callback_query_id: tap.id, text: "The board could not take it now. Reply to the message with the digit.", show_alert: true });
1173
+ return;
1174
+ }
1175
+ log("←", "decision:button", `${pick.digit} → ${said.report}`);
1176
+ await tgCall(token, "answerCallbackQuery", { callback_query_id: tap.id, text: said.ruled ? "✅ Ruled" : "❌ Not ruled" });
1177
+ if (said.ruled)
1178
+ await dropDecisionButtons(token, chatId, tap.message.message_id);
1179
+ if (masterMuted())
1180
+ return;
1181
+ await telegramSendTo(token, chatId, `${said.ruled ? "✅ RULED" : "❌ NOT RULED"}\n${said.report}`, tap.message.message_id);
1182
+ }
1126
1183
  async function startTelegramListener() {
1127
1184
  while (pollersWanted) {
1128
1185
  try {
@@ -1149,7 +1206,7 @@ async function startTelegramListener() {
1149
1206
  }
1150
1207
  log("·", "telegram", `listener ready for bot ${bot}, offset=${tgPollOffset}`);
1151
1208
  }
1152
- const r = await fetch(tgApi(token, `getUpdates?offset=${tgPollOffset}&timeout=10`), { signal: AbortSignal.timeout(15_000) });
1209
+ const r = await fetch(tgApi(token, `getUpdates?offset=${tgPollOffset}&timeout=10&allowed_updates=${encodeURIComponent(JSON.stringify(["message", "callback_query"]))}`), { signal: AbortSignal.timeout(15_000) });
1153
1210
  // Reset error state on any successful fetch.
1154
1211
  if (tgConsecutiveErrors > 0) {
1155
1212
  log("·", "telegram", `recovered after ${tgConsecutiveErrors} failed attempt(s)`);
@@ -1161,6 +1218,11 @@ async function startTelegramListener() {
1161
1218
  for (const update of json.result ?? []) {
1162
1219
  POLL_CURSORS.set(cursorKey, String(update.update_id));
1163
1220
  tgPollOffset = update.update_id + 1;
1221
+ // NULL-OK: field callback_query is OPTIONAL and therefore it is ok to check for NULL
1222
+ if (update.callback_query !== undefined) {
1223
+ await takeDecisionTap(token, chatIds, update.callback_query);
1224
+ continue;
1225
+ }
1164
1226
  const msg = update.message;
1165
1227
  const fromChatId = msg?.chat?.id?.toString();
1166
1228
  if (fromChatId && chatIds.includes(fromChatId) && msg.text) {
@@ -1198,6 +1260,8 @@ async function startTelegramListener() {
1198
1260
  const said = await pickByDigit(pick);
1199
1261
  ruling = `${said.ruled ? "✅ RULED" : "❌ NOT RULED"}\n${said.report}`;
1200
1262
  log("←", "decision:digit", `${pick.digit} → ${said.report}`);
1263
+ if (said.ruled)
1264
+ await dropDecisionButtons(token, fromChatId, msg.reply_to_message.message_id);
1201
1265
  }
1202
1266
  catch (err) {
1203
1267
  if (!(err instanceof BoardDoorRefused))
@@ -2014,8 +2078,10 @@ function drainInboxFor(tag) {
2014
2078
  // nobody must not be swallowed by the part before it.
2015
2079
  async function sendChunked(message, priority, clientId) {
2016
2080
  const outcomes = [];
2017
- for (const chunk of splitForNotify(message)) {
2018
- outcomes.push(await sendNotification(withLead(`[${clientId}]`, chunk), priority, clientId));
2081
+ const parts = splitForNotify(message);
2082
+ const buttons = decisionButtons(message);
2083
+ for (const [i, chunk] of parts.entries()) {
2084
+ outcomes.push(await sendNotification(withLead(`[${clientId}]`, chunk), priority, clientId, i === parts.length - 1 ? buttons : undefined));
2019
2085
  }
2020
2086
  return outcomes;
2021
2087
  }
@@ -2041,54 +2107,42 @@ function appendInbox(baseText, sessionTag, clientId) {
2041
2107
  return `${baseText}\n\n⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${inbox}`;
2042
2108
  }
2043
2109
  const MCP_INSTRUCTIONS = `
2044
- This server is how you reach the user — and only you can decide to use it:
2045
- nothing here delivers a message the user never asked for unless you or your
2046
- own loop calls a tool. The channels are configured on the server side, so
2047
- just call 'notify' or 'ask' with a generic message and let the server route
2048
- it.
2110
+ This server is how a board decision, or an answer to something the user
2111
+ asked, reaches him. The channels are configured on the server side; it
2112
+ refuses every other message.
2049
2113
 
2050
2114
  BEHAVIORAL RULES for every client that connects:
2051
2115
 
2052
- 1. ALWAYS call 'notify' in these three situations — idle or not, DND or not,
2053
- the server decides routing, you decide whether to fire:
2054
-
2055
- (a) LONG PROCESSING FINISHED. Any single task that took more than ~60
2056
- seconds of wall-clock time (long build, test run, backtest, migration,
2057
- big refactor, multi-step plan) gets a 'notify' the moment it completes
2058
- — success OR failure. Rule of thumb: if the user could have reasonably
2059
- walked away to grab coffee while you ran, they need a ping on the way
2060
- back. Don't try to guess whether they were watching. Just notify.
2116
+ 1. NOTHING THE USER DID NOT ASK FOR. 'notify' carries exactly two kinds of
2117
+ message, and the SERVER REFUSES every other one (outcome=blocked):
2061
2118
 
2062
- (b) YOU HAVE A QUESTION OR NEED A DECISION. Any time you're about to ask
2063
- the user something — "should I delete these?", "which branch?",
2064
- "proceed with plan B?" — fire 'notify' (or 'ask' for blocking
2065
- two-way). Silent questions in the terminal get missed; a notification
2066
- does not.
2119
+ (a) A DECISION ONLY THE USER CAN MAKE — raised on its story as the
2120
+ board's decision; the board itself sends it, carrying its decision
2121
+ link, and the user answers it from the page, by tapping one of its
2122
+ buttons, or by replying to it with one digit. Never type a decision
2123
+ into 'notify' yourself.
2067
2124
 
2068
- (c) SOMETHING IMPORTANT HAPPENED that the user needs to know about right
2069
- now. Examples: a test suddenly failed after being green, a destructive
2070
- operation is about to run, you found a security issue, a deploy
2071
- succeeded, a production service looks degraded, you hit an
2072
- unrecoverable error. When in doubt on importance, ERR ON THE SIDE OF
2073
- NOTIFYING — the server's idle gating automatically holds a mis-judged
2074
- 'normal' back to local delivery while the user is active, so the
2075
- cost of over-notifying is near zero. The cost of missing a
2076
- real event is that the user finds out 4 hours later.
2125
+ (b) AN ANSWER TO SOMETHING THE USER ASKED FOR — he asked a question, or
2126
+ asked in so many words to be told when a thing happens. Pass his own
2127
+ words, verbatim, in 'answers'; a call without them that carries no
2128
+ board decision link is refused.
2077
2129
 
2078
- The SERVER handles all routing (DND, idle threshold, channel selection,
2079
- priority escalation). You do NOT need to pre-flight with
2080
- 'get_idle_seconds' before these three triggers — fire 'notify' and let
2081
- the server decide. get_idle_seconds is the HEARTBEAT primitive (rule 6),
2082
- not a gate on legitimate milestones.
2130
+ NEVER notify: a task finished, progress, status, a build or test result,
2131
+ "busy on X", an acknowledgement, a heartbeat, anything "important" he did
2132
+ not ask to hear. That belongs on the story, where he reads it when he
2133
+ chooses. Several messages at once flood his phone: send one message per
2134
+ answer, never a running commentary.
2083
2135
 
2084
- 2. Use priority correctly. Channels each priority reaches, when enabled:
2136
+ 2. Priority: channels each priority reaches, when enabled:
2085
2137
  ${describePriorityRouting()}
2086
- - 'low' = low-stakes status (background completion).
2087
- - 'normal' = the default.
2088
- - 'high' = bypasses idle gating (never DND — while DND is on, every
2089
- priority is held). Use ONLY for catastrophic findings or
2090
- decisions that block progress. Misuse will train the user to
2091
- ignore your notifs.
2138
+ - 'normal' = the default for an answer he asked for.
2139
+ - 'high' = only when his own request says it is urgent.
2140
+
2141
+ 2a. PHONE FORMAT — his phone shows emoji, short paragraphs and bullets, and
2142
+ nothing else reads well there: one headline line opening with an emoji
2143
+ that says what this is (✅ done, ❌ failed, ❓ question, ℹ️ answer), then
2144
+ "• " bullets, one fact each, a blank line between sections. No tables,
2145
+ no code blocks, no long paragraphs.
2092
2146
 
2093
2147
  3. Echo the COMPLETE, UNTRUNCATED message body in your own chat / conversation
2094
2148
  output as well as sending it through 'notify'. The user may be reading the
@@ -2119,27 +2173,19 @@ BEHAVIORAL RULES for every client that connects:
2119
2173
  5. When the user sends you an unsolicited message (visible as INBOX items in
2120
2174
  the 'notify' response, via 'poll', via 'wait_for_inbox', via
2121
2175
  'get_idle_seconds' piggy-back), reply to
2122
- them THROUGH 'notify' — or 'reply', which routes the same way — so the
2176
+ them THROUGH 'reply' — or 'notify' with his words in 'answers' — so the
2123
2177
  reply actually reaches them — not just in your chat output. Multiple agents may
2124
2178
  be connected simultaneously — the server broadcasts every untagged inbox
2125
- message to all of them, so the user can see who is listening. Your reply
2179
+ message to all of them. Your reply
2126
2180
  MUST identify which session you are (start with your own tag or client id,
2127
- e.g. "[@alphawave]" or "[sess-abcd]") and give a brief status so the user
2128
- can pick whom to respond to. If the user tagged their message (@<tag>),
2129
- only the session with that tag should reply. If you are untagged and
2130
- another session with the same project/workdir is already tagged, let the
2131
- tagged one reply.
2181
+ e.g. "[@alphawave]" or "[sess-abcd]"). Only the session his message is for
2182
+ answers it: if he tagged it (@<tag>), only that session; if it is untagged,
2183
+ only a session whose own work it is about — every other listener stays
2184
+ silent, so one message never brings back several answers.
2132
2185
 
2133
- 5a. BUSY-ACK RULE (hard requirement): The moment you notice a user inbox
2134
- message — whether via notify response, heartbeat piggy-back, or poll —
2135
- REPLY IMMEDIATELY via 'notify' with a terse status, EVEN IF YOU CAN'T
2136
- ACT ON THE REQUEST YET. Do not finish the current tool/task first.
2137
- Drop what you're doing long enough to fire one 'notify' call, THEN
2138
- resume. Format: "[<your-session-id>] busy on <current-task>; will
2139
- respond at <milestone>". The user needs to know (a) you heard them,
2140
- (b) you're not the stuck one, (c) when to expect a real answer. An
2141
- inbox message that gets a delayed reply is worse than no reply — it
2142
- wastes the user's time waiting on silence.
2186
+ 5a. ONE ANSWER PER MESSAGE: answer his message once, when you have the
2187
+ answer — no "busy on X" acknowledgement first; the server already tells
2188
+ him his message was received.
2143
2189
 
2144
2190
  6. The 'get_idle_seconds', 'get_idle_config', and 'get_dnd_status' tools are
2145
2191
  informational reads, but they ALSO drain pending inbox messages. Use them
@@ -2149,8 +2195,7 @@ BEHAVIORAL RULES for every client that connects:
2149
2195
  piggy-backed on the response — you don't need to separately call 'poll'.
2150
2196
  This is a lightweight local read (no network, no DND or channel routing),
2151
2197
  so the cost is near zero. Without this heartbeat pattern, a busy agent is
2152
- deaf to the user until its next 'notify' call — which may be minutes or
2153
- hours away during long work. Treat 'get_idle_seconds' as the "check for
2198
+ deaf to the user's messages for the whole of its long work. Treat 'get_idle_seconds' as the "check for
2154
2199
  user input" primitive, not an idle-gate check.
2155
2200
 
2156
2201
  If your work is naturally idle (waiting for the user, between loop iters),
@@ -2169,9 +2214,6 @@ BEHAVIORAL RULES for every client that connects:
2169
2214
  host's window — there is no port to probe and no second server to start.
2170
2215
  Never tell the user "notify is down" without first trying one more tool call.
2171
2216
 
2172
- Bottom line: rule #1 still applies. If you owe the user a notify and your
2173
- MCP client is broken, you owe them the bypass — not an excuse.
2174
-
2175
2217
  8. THE REST OF THIS SERVER, stated here because a dispatcher that never reads
2176
2218
  a tool list cannot know it exists:
2177
2219
 
@@ -2179,7 +2221,9 @@ BEHAVIORAL RULES for every client that connects:
2179
2221
  message through the same delivery path as 'notify', with the same
2180
2222
  'outcome=' contract. Use it when you are answering a message rather than
2181
2223
  starting one.
2182
- - 'ask(question, timeout_seconds?)' puts ONE question to the user and waits.
2224
+ - 'ask(question, answers, timeout_seconds?)' puts ONE question to the user
2225
+ and waits — only a question he asked to be put to him ('answers' = his
2226
+ words); a decision of yours goes as the story's board decision, never here.
2183
2227
  Telegram is its only carrier today, and when nothing can carry the
2184
2228
  question it REFUSES BEFORE PARKING, naming the channel and why — it never
2185
2229
  parks a question into the void and calls the silence an unanswered one.
@@ -2197,20 +2241,38 @@ BEHAVIORAL RULES for every client that connects:
2197
2241
  whole. Call it when the user asks you to remember a rule or change how
2198
2242
  you act.
2199
2243
 
2200
- A CLIENT'S OWN RULES FILE DECIDES WHEN THIS CHANNEL IS THE ONE THAT REACHES
2201
- ITS OWNER. Where that file names another surface — its own prompt, its own
2202
- tracked UI — that rule, not rule #1 above, decides whether and when to call
2203
- 'notify'; this server states what its tools do, never a claim on a user's
2204
- attention that the user's own rules contradict.
2244
+ A CLIENT'S OWN RULES FILE MAY NARROW RULE #1, NEVER WIDEN IT: where that
2245
+ file names another surface — its own prompt, its own tracked UI — that
2246
+ surface carries the message instead, and nothing it says makes an unasked
2247
+ notification one he asked for.
2205
2248
  `.trim();
2249
+ /**
2250
+ * 🔴 #4123 — the user is sent only a board decision (the text carries the board's decision link) or an answer to something he asked
2251
+ * (his own words in `answers`); any other text is refused here, for every tool that reaches him, and reaches nobody. Answers the
2252
+ * refusal, or undefined when the text may go.
2253
+ */
2254
+ function refusedUnasked(text, answers, sessionTag, clientId) {
2255
+ const asked = answers?.trim() ?? "";
2256
+ if (asked !== "") {
2257
+ log("·", "notify", `answers his request: ${asked.slice(0, 200)}`, clientId);
2258
+ return undefined;
2259
+ }
2260
+ if (decisionLink(text) !== undefined)
2261
+ return undefined;
2262
+ log("·", "notify", `REFUSED — neither a board decision nor an answer to his request: ${text.slice(0, 160)}`, clientId);
2263
+ return withInbox("NOT SENT — the user gets only a board decision (the message carries the board's decision link) or an answer to something he asked "
2264
+ + "(pass his own words in `answers`). This message is neither, so it reached nobody; put it on its story instead.\n"
2265
+ + "outcome=blocked attempted=[] delivered=[]", false, sessionTag, clientId);
2266
+ }
2206
2267
  /** The notify tool surface itself, built for one chat: each session on the HTTP door gets its own. */
2207
2268
  export function createMcpServer(clientId, sessionTag) {
2208
2269
  const identity = `@${clientId}`;
2209
2270
  const identityLine = `\nYOUR SESSION IDENTITY: "${identity}" — use this as your prefix in all notify replies (e.g. "[${identity}] done with build").\n`;
2210
2271
  const server = new McpServer({ name: "notify-mcp", version: PACKAGE_VERSION }, { instructions: identityLine + MCP_INSTRUCTIONS });
2211
2272
  server.tool("notify", "Send a notification to the user. Delivery channels and DND are server-configured. " +
2212
- "The server applies DND and user-activity gating itself, so call it whenever a trigger fires — never pre-check idle. " +
2213
- "Use for: task milestones, questions needing input, catastrophic findings, long task completion. " +
2273
+ "It carries ONLY a board decision (the message holds the board's decision link) or an answer to something the user asked " +
2274
+ "(his own words, verbatim, in `answers`); every other message — a finished task, progress, status, an acknowledgement — " +
2275
+ "is refused with outcome=blocked and reaches nobody. " +
2214
2276
  "The result always carries an explicit outcome: \`outcome=delivered\` means at least one " +
2215
2277
  "channel carried the message, while \`outcome=failed\` or \`outcome=blocked\` means it " +
2216
2278
  "reached NOBODY — never assume the user was told. " +
@@ -2221,7 +2283,12 @@ export function createMcpServer(clientId, sessionTag) {
2221
2283
  message: z.string().max(5000).describe("Notification message — up to 5000 chars; the server splits it into numbered parts"),
2222
2284
  priority: z.enum(["low", "normal", "high"]).default("normal")
2223
2285
  .describe(`Channels per priority, each only when enabled: ${describePriorityRouting()} — high also bypasses activity gating (it never overrides DND)`),
2224
- }, async ({ message, priority }) => {
2286
+ answers: z.string().max(2000).optional()
2287
+ .describe("The user's own words, verbatim, of the request this notification answers. Required unless the message is a board decision carrying its decision link."),
2288
+ }, async ({ message, priority, answers }) => {
2289
+ const unasked = refusedUnasked(message, answers, sessionTag, clientId);
2290
+ if (unasked !== undefined)
2291
+ return unasked;
2225
2292
  const outcomes = await sendChunked(message, priority, clientId);
2226
2293
  const notDelivered = outcomes.some((o) => o.outcome !== "delivered");
2227
2294
  const held = notDelivered && outcomes.every((o) => o.outcome === "blocked");
@@ -2238,22 +2305,32 @@ export function createMcpServer(clientId, sessionTag) {
2238
2305
  return withInbox(summary, notDelivered && !held, sessionTag, clientId);
2239
2306
  });
2240
2307
  server.tool("reply", "Reply to the user's most recent channel message. Routes through notify so " +
2241
- "the response reaches whichever channel the user is reading. The result " +
2308
+ "the response reaches whichever channel the user is reading. Like notify it carries only an answer to what he asked: " +
2309
+ "pass his message's words in `answers`, or it is refused with outcome=blocked. The result " +
2242
2310
  "carries the same \`outcome=\` contract as notify — an error means it reached nobody.", {
2243
2311
  message: z.string().max(2000).describe("The reply text to deliver"),
2244
2312
  priority: z.enum(["low", "normal", "high"]).default("normal"),
2245
- }, async ({ message, priority }) => {
2313
+ answers: z.string().max(2000).optional().describe("The user's own words, verbatim, of the message this reply answers."),
2314
+ }, async ({ message, priority, answers }) => {
2315
+ const unasked = refusedUnasked(message, answers, sessionTag, clientId);
2316
+ if (unasked !== undefined)
2317
+ return unasked;
2246
2318
  const outcomes = await sendChunked(message, priority, clientId);
2247
2319
  const notDelivered = outcomes.every((o) => o.outcome !== "delivered");
2248
2320
  const summary = outcomes.map((o) => o.text).join(" ");
2249
2321
  return withInbox(summary, notDelivered, sessionTag, clientId);
2250
2322
  });
2251
- server.tool("ask", "Send a question to the user and wait for their reply. Channels are server-configured. " +
2252
- "Use when a decision is needed before continuing — e.g. 'Should I delete these files?'", {
2323
+ server.tool("ask", "Put a question the user ASKED to be put to him and wait for his reply. Channels are server-configured. " +
2324
+ "A decision of yours is never asked here — raise it as the story's board decision, which reaches him with its link and buttons. " +
2325
+ "Without his words in `answers` (or a board decision link in the question) it is refused with outcome=blocked.", {
2253
2326
  question: z.string().max(500).describe("The question to ask the user"),
2327
+ answers: z.string().max(2000).optional().describe("The user's own words, verbatim, of the request this question carries out."),
2254
2328
  timeout_seconds: z.number().min(30).max(3600).default(300)
2255
2329
  .describe(`How long the question stays open, in seconds (default 5 min). The WAIT is clamped to ${BLOCKING_TOOL_MAX_SECONDS}s because the caller's own transport kills a longer call; a question still unanswered then is NOT lost — it stays open and the answer arrives as an unsolicited message.`),
2256
- }, async ({ question, timeout_seconds = 300 }) => {
2330
+ }, async ({ question, answers, timeout_seconds = 300 }) => {
2331
+ const unasked = refusedUnasked(question, answers, sessionTag, clientId);
2332
+ if (unasked !== undefined)
2333
+ return unasked;
2257
2334
  const token = randomUUID();
2258
2335
  const cfg = loadConfig();
2259
2336
  if (cfg.muteAll === true) {
@@ -4,6 +4,7 @@ import * as fs from "node:fs";
4
4
  import { Agent } from "node:http";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import * as path from "node:path";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
7
8
  import { Duplex } from "node:stream";
8
9
  import { CLUSTER_OWNER, OwnershipUnreadable, startOwnerOf } from "./providerOwnership.js";
9
10
  import { readSettings, settingsFile, SettingsUndefined } from "./workspaceList.js";
@@ -2797,37 +2798,101 @@ export class QueueBusy extends Error {
2797
2798
  this.name = "QueueBusy";
2798
2799
  }
2799
2800
  }
2800
- /** Runs `drive` holding the board's queue lock, which one process holds at a time; a lock whose process is gone is taken over, and a live holder's never is. */
2801
- export async function withQueueLock(board, now, drive) {
2801
+ // GATE: how long a press of this process waits in line behind this process's own queue pass before it is refused as busy
2802
+ const PASS_WAIT_MS = 5_000;
2803
+ /**
2804
+ * 🔴 #4336 — this process's line on each lock file: settled once the last holder in it lets go. A pass ({@link driveStoryQueue}) opens it, and
2805
+ * every press that meets it joins its end, so presses that arrive while a pass lets the thread go run one after another once it ends.
2806
+ */
2807
+ const lineHere = new Map();
2808
+ /** 🔴 #4336 — the lock files the running async context already holds, so a call made from inside a pass never waits on that pass. */
2809
+ const locksHeld = new AsyncLocalStorage();
2810
+ /**
2811
+ * 🔴 #4336 — joins the end of this process's line on the lock file and waits up to {@link PASS_WAIT_MS} for the one ahead to let go;
2812
+ * returns the act that lets the next one in line through. A pass lets the thread go between entries, so a press can arrive mid-pass;
2813
+ * before, the pass held the thread and the press simply ran after it.
2814
+ */
2815
+ async function joinLine(file, ahead) {
2816
+ let done = () => undefined;
2817
+ const mine = new Promise((resolve) => { done = resolve; });
2818
+ const tail = ahead.then(() => mine);
2819
+ lineHere.set(file, tail);
2820
+ let timer;
2821
+ let aheadLeft = false;
2822
+ await Promise.race([ahead.then(() => { aheadLeft = true; }), new Promise((resolve) => { timer = setTimeout(resolve, PASS_WAIT_MS); })]);
2823
+ clearTimeout(timer);
2824
+ const forget = () => { if (lineHere.get(file) === tail)
2825
+ lineHere.delete(file); };
2826
+ return () => {
2827
+ done();
2828
+ // 🔴 #4336 — one that gave up while the one ahead still holds leaves the line standing until it settles, so a later press still waits behind the pass
2829
+ if (aheadLeft)
2830
+ forget();
2831
+ else
2832
+ void tail.then(forget);
2833
+ };
2834
+ }
2835
+ /**
2836
+ * Runs `drive` holding the board's queue lock, which one process holds at a time; a lock whose process is gone is taken over, and a live holder's never is.
2837
+ * 🔴 #4336 — a call other than a pass that meets this process's line waits its turn in it (see {@link joinLine}) before it is refused; a pass never waits.
2838
+ */
2839
+ export async function withQueueLock(board, now, drive, pass = false) {
2802
2840
  const file = lockFile(board);
2803
2841
  fs.mkdirSync(path.dirname(file), { recursive: true });
2804
- for (let attempt = 0;; attempt++) {
2805
- const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
2806
- fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: now }));
2807
- try {
2808
- fs.linkSync(tmp, file);
2809
- break;
2842
+ // 🔴 #4336 — a call that meets no line of this process takes the lock at once, as before, never a tick later
2843
+ const ahead = pass || locksHeld.getStore()?.has(file) === true ? undefined : lineHere.get(file);
2844
+ // NULL-OK: field ahead is OPTIONAL and therefore it is ok to check for NULL
2845
+ const leave = ahead === undefined ? () => undefined : await joinLine(file, ahead);
2846
+ try {
2847
+ for (let attempt = 0;; attempt++) {
2848
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
2849
+ fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: now }));
2850
+ try {
2851
+ fs.linkSync(tmp, file);
2852
+ break;
2853
+ }
2854
+ catch (err) {
2855
+ if (err.code !== "EEXIST")
2856
+ throw err;
2857
+ if (attempt > 0)
2858
+ throw new QueueBusy(board, "a driver that took the lock as this one cleared a dead holder's");
2859
+ const held = readJson(file);
2860
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
2861
+ if (held !== undefined && isProcessAlive(held.pid))
2862
+ throw new QueueBusy(board, `process ${held.pid} since ${new Date(held.at).toISOString()}`);
2863
+ takeDeadLock(board, file, held);
2864
+ }
2865
+ finally {
2866
+ fs.rmSync(tmp, { force: true });
2867
+ }
2810
2868
  }
2811
- catch (err) {
2812
- if (err.code !== "EEXIST")
2813
- throw err;
2814
- if (attempt > 0)
2815
- throw new QueueBusy(board, "a driver that took the lock as this one cleared a dead holder's");
2816
- const held = readJson(file);
2817
- // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
2818
- if (held !== undefined && isProcessAlive(held.pid))
2819
- throw new QueueBusy(board, `process ${held.pid} since ${new Date(held.at).toISOString()}`);
2820
- takeDeadLock(board, file, held);
2869
+ let passEnded = () => undefined;
2870
+ let line;
2871
+ if (pass) {
2872
+ const ended = new Promise((resolve) => { passEnded = resolve; });
2873
+ const before = lineHere.get(file);
2874
+ // NULL-OK: field before is OPTIONAL and therefore it is ok to check for NULL
2875
+ line = before === undefined ? ended : before.then(() => ended);
2876
+ lineHere.set(file, line);
2877
+ }
2878
+ try {
2879
+ return await locksHeld.run(new Set([...(locksHeld.getStore() ?? []), file]), drive);
2821
2880
  }
2822
2881
  finally {
2823
- fs.rmSync(tmp, { force: true });
2882
+ try {
2883
+ fs.rmSync(file, { force: true });
2884
+ }
2885
+ finally {
2886
+ // 🔴 #4336 — the line settles even when the lock file cannot be removed, so no press waits out its whole bound on a pass that ended
2887
+ passEnded();
2888
+ // NULL-OK: field line is OPTIONAL and therefore it is ok to check for NULL
2889
+ if (line !== undefined && lineHere.get(file) === line)
2890
+ lineHere.delete(file);
2891
+ }
2824
2892
  }
2825
2893
  }
2826
- try {
2827
- return await drive();
2828
- }
2829
2894
  finally {
2830
- fs.rmSync(file, { force: true });
2895
+ leave();
2831
2896
  }
2832
2897
  }
2833
2898
  /** A dead holder's lock moved aside under a name of this process's own; a lock that is not the one read (another driver took it meanwhile) is put back and the pass leaves the queue to that driver. */
@@ -3367,10 +3432,28 @@ export const ARCHIVE_KEPT_DAYS = 7;
3367
3432
  const ACCOUNT_REFUSAL = /API Error: 402\b|\b402 (?:Payment Required|Insufficient Balance|You need positive balance|You have exceeded your monthly quota)|hit your (?:weekly|5-hour|five-hour|session|usage|monthly)? ?limit|Credit balance is too low|issue with the selected model \(claude-|account (?:has been |is )?(?:suspended|disabled)/i;
3368
3433
  /** 🔴 #4123 — how long after the queue gave up on a story it is offered to the line again. */
3369
3434
  export const rearmDelayMs = (attempts) => REARM_BASE_MS * 2 ** Math.min(Math.max(attempts - WORKER_ATTEMPTS, 0), REARM_DOUBLINGS);
3370
- /** The acks the passes' requests call for: one per request read, carrying its entry's state and place, rewritten only when one of them changed. */
3371
- function writeAcks(board, store, refusals, applied, now) {
3435
+ // GATE: how long one stretch of a queue pass may hold the resident service's thread before it lets a waiting request through
3436
+ const QUEUE_SLICE_MS = 16;
3437
+ /** 🔴 #4336 — a pause point for a long queue pass: it yields the thread once the stretch since its last yield reaches {@link QUEUE_SLICE_MS}. */
3438
+ function queueSlicer() {
3439
+ let sliceStart = performance.now();
3440
+ return async () => {
3441
+ if (performance.now() - sliceStart < QUEUE_SLICE_MS)
3442
+ return;
3443
+ await new Promise((resolve) => setImmediate(resolve));
3444
+ sliceStart = performance.now();
3445
+ };
3446
+ }
3447
+ /**
3448
+ * The acks the passes' requests call for: one per request read, carrying its entry's state and place, rewritten only when one of them changed.
3449
+ * 🔴 #4336 — one entry leaving the line moves every place behind it, and on Windows each whole-file write costs milliseconds: a board of
3450
+ * 150 requests held the service's thread for a second. The writes now yield the thread every {@link QUEUE_SLICE_MS}, inside the pass's lock.
3451
+ */
3452
+ async function writeAcks(board, store, refusals, applied, now) {
3372
3453
  const order = queueOrder(store);
3454
+ const slice = queueSlicer();
3373
3455
  for (const [storyId, requestId] of applied) {
3456
+ await slice();
3374
3457
  const e = store.entries.find((x) => x.storyId === storyId);
3375
3458
  const refused = refusals.get(storyId);
3376
3459
  const at = e === undefined ? -1 : order.indexOf(e);
@@ -3601,6 +3684,8 @@ export async function driveStoryQueue(board, world, now) {
3601
3684
  const refusals = new Map();
3602
3685
  const applied = new Map();
3603
3686
  const wakeable = new Map();
3687
+ // 🔴 #4336 — each entry's liveness reads cost milliseconds on a board of 150 entries: the pass yields the thread between entries once a stretch runs long
3688
+ const slice = queueSlicer();
3604
3689
  for (const id of requestedStories(board)) {
3605
3690
  const r = readableRequestView(board, id);
3606
3691
  // NULL-OK: field r is OPTIONAL and therefore it is ok to check for NULL
@@ -3615,6 +3700,7 @@ export async function driveStoryQueue(board, world, now) {
3615
3700
  applied.set(id, r.requestId);
3616
3701
  }
3617
3702
  for (const e of store.entries) {
3703
+ await slice();
3618
3704
  try {
3619
3705
  if (IN_LINE.has(e.state) && inArchive(e.worker) && world.closedWhy(e.storyId) === undefined) {
3620
3706
  const worker = e.worker;
@@ -4183,6 +4269,7 @@ export async function driveStoryQueue(board, world, now) {
4183
4269
  // NULL-OK: field lanes is OPTIONAL and therefore it is ok to check for NULL
4184
4270
  const laneHeld = (e) => (lanes === undefined || e.forced === true || running < lanes.limit ? undefined : `⏳ ${running} lanes run, this workspace's limit is ${lanes.limit}`);
4185
4271
  for (const e of queueOrder(store)) {
4272
+ await slice();
4186
4273
  try {
4187
4274
  const sessionId = wakeable.get(e);
4188
4275
  // NULL-OK: field sessionId is OPTIONAL and therefore it is ok to check for NULL
@@ -4475,9 +4562,9 @@ export async function driveStoryQueue(board, world, now) {
4475
4562
  }
4476
4563
  }
4477
4564
  save();
4478
- writeAcks(board, store, refusals, applied, now);
4565
+ await writeAcks(board, store, refusals, applied, now);
4479
4566
  return store;
4480
- });
4567
+ }, true);
4481
4568
  }
4482
4569
  /** 🔴 #4188 — whose press a queue act records when no agent session made it: Meni's own, from the panel or the gateway-signed web page. */
4483
4570
  export const HIS_PRESS = "his";
@@ -4585,7 +4672,7 @@ export async function pressStory(board, storyId, press, now, by, requestHandledB
4585
4672
  throw new StoryPressRefused(`${String(press)} is not a press FleetView's queue knows; #${storyId} reads: ${e.why}`);
4586
4673
  }
4587
4674
  writeStore(board, store);
4588
- writeAcks(board, store, new Map(), new Map([[e.storyId, e.requestId]]), now);
4675
+ await writeAcks(board, store, new Map(), new Map([[e.storyId, e.requestId]]), now);
4589
4676
  return did;
4590
4677
  });
4591
4678
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.427",
3
+ "version": "1.3.428",
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",