omni-notify-mcp 1.3.339 → 1.3.341

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/notify.js CHANGED
@@ -1,10 +1,9 @@
1
1
  /**
2
- * The notify server — ONE process, spoken to over stdio.
2
+ * The notify server — ONE process per machine, spoken to over its HTTP door.
3
3
  *
4
- * Every MCP host reaches this program the same way: it spawns `node
5
- * dist/index.mjs` and negotiates MCP over the child's stdin/stdout. Nothing
6
- * here listens on a port and nothing here starts a second process — the whole
7
- * tool surface lives in this file.
4
+ * Every MCP host reaches this program the same way: the daemon (`dist/daemon.js`)
5
+ * serves the chat-tool door on 127.0.0.1:7475 and each chat is one MCP session
6
+ * on it — the whole tool surface lives in this file.
8
7
  *
9
8
  * Configuration is the file `~/.notify-mcp/config.json`, edited directly.
10
9
  * Unsolicited user messages arrive on the Telegram and Slack pollers and are
@@ -38,8 +37,7 @@ function installedVersion() {
38
37
  export const PACKAGE_VERSION = installedVersion();
39
38
  /**
40
39
  * The identity one chat reports and the tag its messages are routed by: `<machine>-<workspace>[-<session>]`.
41
- * Both doors derive it from the same place — the stdio bridge from its environment, the HTTP door from the
42
- * headers its client sends — so a chat reads the same name whichever transport carries it. A tag the host
40
+ * The HTTP door derives it from the headers its client sends. A tag the host
43
41
  * states explicitly wins; otherwise the workspace is walked up from the project folder, skipping launcher and
44
42
  * system directory names, and a session id (when the host has one) tells two windows on one workspace apart.
45
43
  * The session part is only ever what a host ACTUALLY sends: a Claude Code MCP header does not expand
@@ -682,8 +680,6 @@ function takeWaitersFor(entryTag) {
682
680
  const inboxDeliveredTo = new Map();
683
681
  const deliveredKey = (tag) => tag ?? "*";
684
682
  export const DAEMON_TAG = "daemon";
685
- const OLD_DAEMON_TAG = "always-on";
686
- const readerKeys = (tag) => (tag === DAEMON_TAG ? [deliveredKey(tag), OLD_DAEMON_TAG] : [deliveredKey(tag)]);
687
683
  const entryKey = (entry) => `${entry.ts}\u0000${entry.tag ?? ""}\u0000${entry.text}`;
688
684
  function alreadyDelivered(entry, tag) {
689
685
  return inboxDeliveredTo.get(entryKey(entry))?.has(deliveredKey(tag)) ?? false;
@@ -764,7 +760,7 @@ function persistInboxQueue(arrivals = []) {
764
760
  function takeSharedEntriesForSelf(saved) {
765
761
  const mine = [];
766
762
  for (const { deliveredTo, ...entry } of saved) {
767
- if (readerKeys(SELF_TAG).some((key) => deliveredTo.includes(key)) || alreadyDelivered(entry, SELF_TAG))
763
+ if (deliveredTo.includes(deliveredKey(SELF_TAG)) || alreadyDelivered(entry, SELF_TAG))
768
764
  continue;
769
765
  // The daemon is the machine's queue: it holds every chat's undelivered entry in memory, tagged ones
770
766
  // included, because the HTTP chats it serves are the only readers of a tagged entry and each drains its own by
@@ -2235,7 +2231,7 @@ BEHAVIORAL RULES for every client that connects:
2235
2231
  'notify'; this server states what its tools do, never a claim on a user's
2236
2232
  attention that the user's own rules contradict.
2237
2233
  `.trim();
2238
- /** The notify tool surface itself, built for one chat: the stdio bridge and the HTTP door both get their own. */
2234
+ /** The notify tool surface itself, built for one chat: each session on the HTTP door gets its own. */
2239
2235
  export function createMcpServer(clientId, sessionTag) {
2240
2236
  const identity = `@${clientId}`;
2241
2237
  const identityLine = `\nYOUR SESSION IDENTITY: "${identity}" — use this as your prefix in all notify replies (e.g. "[${identity}] done with build").\n`;
@@ -2643,19 +2639,31 @@ function watchNames(dir, watched, onChange) {
2643
2639
  const OWNERSHIP_PORT_FLOOR = 20_000;
2644
2640
  const OWNERSHIP_PORT_SPAN = 40_000;
2645
2641
  // With no gateway token configured there is no door to bind, so ownership binds a bare socket on a port derived from the config dir: stable across processes that share it, distinct between config dirs.
2646
- function ownershipPortWithoutDoor() {
2647
- return OWNERSHIP_PORT_FLOOR + createHash("sha256").update(CONFIG_DIR).digest().readUInt32BE(0) % OWNERSHIP_PORT_SPAN;
2642
+ function ownershipPortWithoutDoor(attempt) {
2643
+ const start = createHash("sha256").update(CONFIG_DIR).digest().readUInt32BE(0);
2644
+ return OWNERSHIP_PORT_FLOOR + (start + attempt) % OWNERSHIP_PORT_SPAN;
2648
2645
  }
2649
- async function bindGatewayPort() {
2650
- const settings = readGatewaySettings();
2651
- if (settings)
2652
- return (await import("./gateway/restDoor.js")).startRestDoor(settings);
2646
+ function listenBare(port) {
2653
2647
  return new Promise((resolve, reject) => {
2654
2648
  const bare = createNetServer();
2655
2649
  bare.once("error", reject);
2656
- bare.listen(ownershipPortWithoutDoor(), "127.0.0.1", () => resolve(bare));
2650
+ bare.listen(port, "127.0.0.1", () => resolve(bare));
2657
2651
  });
2658
2652
  }
2653
+ async function bindGatewayPort() {
2654
+ const settings = readGatewaySettings();
2655
+ if (settings)
2656
+ return (await import("./gateway/restDoor.js")).startRestDoor(settings);
2657
+ for (let attempt = 0;; attempt++) {
2658
+ try {
2659
+ return await listenBare(ownershipPortWithoutDoor(attempt));
2660
+ }
2661
+ catch (err) {
2662
+ if (err.code !== "EACCES" || attempt + 1 >= OWNERSHIP_PORT_SPAN)
2663
+ throw err;
2664
+ }
2665
+ }
2666
+ }
2659
2667
  function startOwnedWork() {
2660
2668
  AgentGateway.instance().registerDoor("telegram", (c, part) => telegramSendTo(loadConfig().telegram.token, c.chat.slice("telegram:".length), part));
2661
2669
  AgentGateway.instance().registerDoor("slack", (c, part) => slackPostInThread(slackCreds().token, c.slack.channel, c.slack.threadTs, part));
@@ -902,7 +902,7 @@ function whenApplied(home, sessionId, since) {
902
902
  return "gone";
903
903
  holder = found;
904
904
  }
905
- return fs.existsSync(path.join(sessionsDir(home), `${holder}.json`)) && alive(holder) ? undefined : "gone";
905
+ return fs.existsSync(path.join(sessionsDir(home), `${holder}.json`)) && workspaceStore().alive(holder) ? undefined : "gone";
906
906
  };
907
907
  const finish = () => {
908
908
  fs.rmSync(done, { force: true });
@@ -935,16 +935,6 @@ function whenApplied(home, sessionId, since) {
935
935
  check();
936
936
  });
937
937
  }
938
- /** @param {number} pid */
939
- function alive(pid) {
940
- try {
941
- process.kill(pid, 0);
942
- return true;
943
- }
944
- catch (cause) {
945
- return /** @type {NodeJS.ErrnoException} */ (cause).code === "EPERM";
946
- }
947
- }
948
938
  /**
949
939
  * @template T
950
940
  * @param {string} code @param {() => T} act
@@ -1267,7 +1257,7 @@ function deepagentParts(values) {
1267
1257
  /**
1268
1258
  * #3849 — writes `change` (`deepagent.*` key → value, null takes the key out) into this box's da.json, made from `base` (what
1269
1259
  * `deepagentSettings` returned): split by `deepagentParts`, so a login that stays on its box goes to its box part only. Bytes that
1270
- * moved since `base` THROW the store's SettingsMoved with nothing written. Returns the settings as written.
1260
+ * moved since `base` THROW the store's SettingsMoved with nothing written; with no `base` the keys are set from the file as it stands under its lock, never refused for a move. Returns the settings as written.
1271
1261
  */
1272
1262
  function saveDeepagentSettings(change, base) {
1273
1263
  const store = workspaceStore();
@@ -1278,7 +1268,10 @@ function saveDeepagentSettings(change, base) {
1278
1268
  if (key === IDENTITY_RECORDS)
1279
1269
  parts.box = { [key]: null };
1280
1270
  }
1281
- store.writeSettings(store.toolHome(), 'da', parts, base);
1271
+ if (base === undefined)
1272
+ store.setSettings(store.toolHome(), 'da', parts);
1273
+ else
1274
+ store.writeSettings(store.toolHome(), 'da', parts, base);
1282
1275
  return deepagentSettings();
1283
1276
  }
1284
1277
  function settingsTokens(text) {
@@ -1577,7 +1570,7 @@ if (require.main === module) {
1577
1570
  break;
1578
1571
  }
1579
1572
  case "lock-alive":
1580
- process.exitCode = alive(Number(args[0].split(":")[0])) ? 0 : 1;
1573
+ process.exitCode = workspaceStore().alive(Number(args[0].split(":")[0])) ? 0 : 1;
1581
1574
  break;
1582
1575
  case "deepagent-settings":
1583
1576
  process.stdout.write(JSON.stringify(deepagentSettings()));
@@ -151,6 +151,9 @@ class SettingsUndefined extends SyntaxError {
151
151
  /** A write made from bytes that are no longer the file's: the writer re-reads and makes its change again. */
152
152
  class SettingsMoved extends Error {
153
153
  }
154
+ /** Another process held a settings file's write lock for the whole wait, and its pid is alive: nothing was written, the writer tries again. */
155
+ class SettingsLocked extends Error {
156
+ }
154
157
  /** The settings file of `tool` for a LISTED workspace — a folder off the list, a worktree included, is refused by name. */
155
158
  function settingsFile(root, tool) {
156
159
  if (typeof tool !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(tool))
@@ -227,10 +230,17 @@ function settingsBase(root, tool) {
227
230
  function serialized(value) {
228
231
  return `${JSON.stringify({ schema: SETTINGS_SCHEMA, settings: value.settings, ui: value.ui, secrets: value.secrets }, null, 2)}\n`;
229
232
  }
233
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
230
234
  function writeAtomically(file, text) {
231
235
  fs.mkdirSync(path.dirname(file), { recursive: true });
232
236
  const staged = `${file}.${process.pid}.tmp`;
233
- fs.writeFileSync(staged, text);
237
+ try {
238
+ fs.writeFileSync(staged, text);
239
+ }
240
+ catch (failed) {
241
+ fs.rmSync(staged, { force: true });
242
+ throw failed;
243
+ }
234
244
  for (let attempt = 1;; attempt++) {
235
245
  try {
236
246
  fs.renameSync(staged, file);
@@ -241,19 +251,136 @@ function writeAtomically(file, text) {
241
251
  fs.rmSync(staged, { force: true });
242
252
  throw held;
243
253
  }
244
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50 * 2 ** attempt);
254
+ pause(50 * 2 ** attempt);
255
+ }
256
+ }
257
+ }
258
+ // GATE: how long a writer waits for another process's write lock on one settings file before it throws SettingsLocked; a save holds it for a few milliseconds.
259
+ const LOCK_WAIT_MS = 10000;
260
+ /** What a lock file holds: its holder's pid and a token no other take shares, so a holder releases only its own lock. */
261
+ const lockToken = () => `${process.pid} ${crypto.randomUUID()}`;
262
+ /** The content of lock `name`, or undefined when there is none; any other failure to read THROWS — on Windows EPERM is a name its holder is still removing. */
263
+ function heldBy(name) {
264
+ try {
265
+ return fs.readFileSync(name, "utf8");
266
+ }
267
+ catch (err) {
268
+ if (err.code === "ENOENT")
269
+ return undefined;
270
+ throw err;
271
+ }
272
+ }
273
+ /** Whether process `pid` is running: ESRCH means it is gone, EPERM that it runs under another user; anything else THROWS. */
274
+ function alive(pid) {
275
+ try {
276
+ process.kill(pid, 0);
277
+ return true;
278
+ }
279
+ catch (err) {
280
+ if (err.code === "ESRCH")
281
+ return false;
282
+ if (err.code === "EPERM")
283
+ return true;
284
+ throw err;
285
+ }
286
+ }
287
+ /** Removes lock `name` when its holder's pid is gone — under `name.takeover`, held like any lock, so one taker removes it and logs it once. True when `name` is free to try again. */
288
+ function clearedDead(name, take) {
289
+ const holder = heldBy(name);
290
+ if (holder === undefined)
291
+ return true;
292
+ const pid = Number.parseInt(holder, 10);
293
+ if (alive(pid))
294
+ return false;
295
+ const guard = `${name}.takeover`;
296
+ if (!claimed(guard, take))
297
+ return false;
298
+ try {
299
+ if (heldBy(name) !== holder)
300
+ return true;
301
+ fs.rmSync(name);
302
+ console.error(`[workspace-settings] ${name} was left by pid ${pid}, which is gone — taken over`);
303
+ return true;
304
+ }
305
+ finally {
306
+ released(guard, take);
307
+ }
308
+ }
309
+ /** One attempt to hold lock `name`: `take.staged`, already holding `take.token`, is linked into place — a link of an existing name fails, so one taker wins and no lock is ever seen empty. A dead holder's lock is cleared and the link made again. False while a live process holds it. */
310
+ function claimed(name, take) {
311
+ for (;;) {
312
+ try {
313
+ fs.linkSync(take.staged, name);
314
+ return true;
315
+ }
316
+ catch (err) {
317
+ if (err.code !== "EEXIST")
318
+ throw err;
319
+ }
320
+ if (!clearedDead(name, take))
321
+ return false;
322
+ }
323
+ }
324
+ function released(name, take) {
325
+ if (heldBy(name) === take.token)
326
+ fs.rmSync(name);
327
+ }
328
+ /**
329
+ * Runs `held` while this process alone holds `file`'s write lock (`file.lock`, see claimed), released on every path. A second
330
+ * process waits for it, a dead holder's lock is taken over, and a live one held past LOCK_WAIT_MS THROWS SettingsLocked; a link
331
+ * Windows still refuses at the end of the wait (EPERM, EACCES) THROWS as itself.
332
+ */
333
+ function underLock(file, held) {
334
+ fs.mkdirSync(path.dirname(file), { recursive: true });
335
+ const lock = `${file}.lock`;
336
+ const take = { staged: `${lock}.${process.pid}.tmp`, token: lockToken() };
337
+ fs.writeFileSync(take.staged, take.token);
338
+ try {
339
+ const until = Date.now() + LOCK_WAIT_MS;
340
+ for (;;) {
341
+ let refused;
342
+ try {
343
+ if (claimed(lock, take))
344
+ break;
345
+ }
346
+ catch (err) {
347
+ if (err.code !== "EPERM" && err.code !== "EACCES")
348
+ throw err;
349
+ refused = err;
350
+ }
351
+ if (Date.now() >= until)
352
+ throw refused ?? new SettingsLocked(`${lock} is held by another process that is alive (${heldBy(lock) ?? "just released"}) — nothing was written, save again`);
353
+ pause(10);
245
354
  }
246
355
  }
356
+ finally {
357
+ fs.rmSync(take.staged, { force: true });
358
+ }
359
+ try {
360
+ return held();
361
+ }
362
+ finally {
363
+ released(lock, take);
364
+ }
247
365
  }
248
366
  /**
249
367
  * Applies `change` — `{ settings?, ui?, secrets?, box? }`, each a map of key → value, where null takes the key out — to `tool`'s
250
368
  * settings in `root`, made from `base` (what `readSettings` or `settingsBase` returned); `box` goes to this box's own file and
251
369
  * nowhere else, written before the shared file, so a crash between the two leaves at most a box value no shared record names yet. A file that moved since THROWS
252
- * SettingsMoved and nothing is written. The write is a staged file renamed over the old one. One process writes a file —
253
- * the tool's own service — and the check and the rename run with no await between them, so two of its own callers
254
- * can never both win. Returns the settings as written, with their new base.
370
+ * SettingsMoved and nothing is written. The write is a staged file renamed over the old one. The base check, both reads and both renames run under the file's lock (underLock), so no other process — a second writer of the file —
371
+ * can rename between them; a second one waits and then writes from what the first left, or throws SettingsMoved. Returns the settings as written, with their new base.
255
372
  */
256
373
  function writeSettings(root, tool, change, base) {
374
+ return underLock(settingsFile(root, tool), () => writtenSettings(root, tool, change, base));
375
+ }
376
+ /**
377
+ * Sets keys of `tool`'s settings sections — `change` as in writeSettings — from the file as it stands UNDER its lock: a change made from no read is never
378
+ * refused for a move, so it waits for the other writer and lands on top of its save. Returns the settings as written, with their new base.
379
+ */
380
+ function setSettings(root, tool, change) {
381
+ return underLock(settingsFile(root, tool), () => writtenSettings(root, tool, change, settingsBase(root, tool)));
382
+ }
383
+ function writtenSettings(root, tool, change, base) {
257
384
  const file = settingsFile(root, tool);
258
385
  const local = boxFile(root, tool);
259
386
  const now = settingsBase(root, tool);
@@ -498,4 +625,4 @@ function savedSettings(tool) {
498
625
  throw err;
499
626
  }
500
627
  }
501
- module.exports = { vscRoot, workspacesFile, publishWorkspaces, WorkspacesUndefined, listedWorkspaces, workspacesHere, listBase, saveWorkspaces, sameRoot, SettingsUndefined, SettingsMoved, settingsFile, readSettings, savedSettings, toolHome, settingsBase, writeSettings, publishSettings };
628
+ module.exports = { vscRoot, workspacesFile, publishWorkspaces, WorkspacesUndefined, listedWorkspaces, workspacesHere, listBase, saveWorkspaces, sameRoot, SettingsUndefined, SettingsMoved, SettingsLocked, settingsFile, readSettings, savedSettings, toolHome, settingsBase, writeSettings, setSettings, publishSettings, alive };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.339",
3
+ "version": "1.3.341",
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",
package/dist/index.js DELETED
@@ -1,43 +0,0 @@
1
- #!/usr/bin/env node
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
- import { sessionIdentity, startNotifyServer, takePendingInbox } from "./notify.js";
4
- import { startNotifyDoor } from "./gateway/notifyDoor.js";
5
- // The explicit name wins, so a host whose config can pass arguments (Copilot's
6
- // mcp.json, Codex's config.toml) names its own window instead of inheriting
7
- // whatever directory it happens to be launched from.
8
- function explicitTag() {
9
- const flag = process.argv.find((arg) => arg.startsWith("--tag="));
10
- if (flag)
11
- return flag.slice("--tag=".length);
12
- return process.env.NOTIFY_MCP_TAG ?? "";
13
- }
14
- const TAG = sessionIdentity({
15
- explicitTag: explicitTag(),
16
- projectDir: process.env.CLAUDE_PROJECT_DIR || process.cwd(),
17
- sessionId: process.env.CLAUDE_CODE_SESSION_ID,
18
- });
19
- // Assigned by startNotifyServer() on the next line and never replaced. It is
20
- // read only from emit(), which runs only after mcp.connect below: the watches
21
- // fire on later events, and takePendingInbox runs right after connect.
22
- let mcp;
23
- const host = {
24
- clientId: TAG,
25
- tag: TAG,
26
- emit: async (entry) => {
27
- // Claude Code surfaces this as a synthetic user turn. `wait_for_inbox`
28
- // stays the universal fallback for a host that does not carry it.
29
- const content = entry.tag ? `[@${entry.tag}] ${entry.text}` : entry.text;
30
- await mcp.server.notification({
31
- method: "notifications/claude/channel",
32
- params: { content, meta: { ts: entry.ts, tag: entry.tag ?? null, source: "notify-mcp" } },
33
- });
34
- },
35
- };
36
- mcp = startNotifyServer(host);
37
- startNotifyDoor(() => { });
38
- const transport = new StdioServerTransport();
39
- await mcp.connect(transport);
40
- // A channel push is only read by a host that has finished its initialize handshake, so the boot take waits for it.
41
- mcp.server.oninitialized = () => takePendingInbox(host);
42
- process.stdin.on("end", () => process.exit(0));
43
- process.stdin.on("close", () => process.exit(0));