omni-notify-mcp 1.3.340 → 1.3.342

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/daemon.js CHANGED
@@ -104,7 +104,7 @@ let handedOver;
104
104
  // Only the daemon that owns the gateway port runs the connector and publishes its state: a dormant one has nothing for it to reach.
105
105
  const tunnel = new TunnelRunner();
106
106
  const daemonHost = {
107
- clientId: DAEMON_TAG, tag: DAEMON_TAG, queueOnly: true, emit: async () => { },
107
+ clientId: DAEMON_TAG, tag: DAEMON_TAG,
108
108
  onDoorOwned: (port) => {
109
109
  tunnel.beat(port);
110
110
  setInterval(() => tunnel.beat(port), HEARTBEAT_MS);
@@ -112,8 +112,7 @@ const daemonHost = {
112
112
  onSuperseded: () => (handedOver === undefined ? replaceWithInstalledBuild() : void handedOver.then(() => process.exit(0))),
113
113
  };
114
114
  startNotifyServer(daemonHost);
115
- // No MCP client connects here, so nothing can be pushed: the boot take only hands entries to the queue.
116
- takePendingInbox(daemonHost);
115
+ takePendingInbox();
117
116
  startNotifyDoor(() => { beating = true; beat(); }, undefined, {
118
117
  version: PACKAGE_VERSION,
119
118
  takeover,
package/dist/notify.js CHANGED
@@ -37,9 +37,8 @@ function installedVersion() {
37
37
  export const PACKAGE_VERSION = installedVersion();
38
38
  /**
39
39
  * The identity one chat reports and the tag its messages are routed by: `<machine>-<workspace>[-<session>]`.
40
- * The HTTP door derives it from the headers its client sends. A tag the host
41
- * states explicitly wins; otherwise the workspace is walked up from the project folder, skipping launcher and
42
- * system directory names, and a session id (when the host has one) tells two windows on one workspace apart.
40
+ * The HTTP door derives it from the headers its client sends: the workspace is walked up from the project folder,
41
+ * skipping launcher and system directory names, and a session id (when the host has one) tells two windows on one workspace apart.
43
42
  * The session part is only ever what a host ACTUALLY sends: a Claude Code MCP header does not expand
44
43
  * `${CLAUDE_CODE_SESSION_ID}` — measured, the literal string arrives — so an HTTP chat there is named by its
45
44
  * workspace alone and two windows on one workspace share that name.
@@ -51,9 +50,6 @@ const GENERIC_DIRS = new Set([
51
50
  ]);
52
51
  export function sessionIdentity(from) {
53
52
  const cleanId = (s) => s.toLowerCase().replace(/[^a-z0-9_-]/g, "");
54
- const explicit = cleanId(from.explicitTag ?? "");
55
- if (explicit !== "")
56
- return explicit;
57
53
  // A request that names no workspace never inherits the serving process's own folder: the name it falls back to
58
54
  // is the caller's, so a chat is never told it is some other workspace's session.
59
55
  const root = from.projectDir ?? "";
@@ -680,8 +676,6 @@ function takeWaitersFor(entryTag) {
680
676
  const inboxDeliveredTo = new Map();
681
677
  const deliveredKey = (tag) => tag ?? "*";
682
678
  export const DAEMON_TAG = "daemon";
683
- const OLD_DAEMON_TAG = "always-on";
684
- const readerKeys = (tag) => (tag === DAEMON_TAG ? [deliveredKey(tag), OLD_DAEMON_TAG] : [deliveredKey(tag)]);
685
679
  const entryKey = (entry) => `${entry.ts}\u0000${entry.tag ?? ""}\u0000${entry.text}`;
686
680
  function alreadyDelivered(entry, tag) {
687
681
  return inboxDeliveredTo.get(entryKey(entry))?.has(deliveredKey(tag)) ?? false;
@@ -757,22 +751,21 @@ function persistInboxQueue(arrivals = []) {
757
751
  rmSync(join(CONFIG_DIR, other), { force: true });
758
752
  }
759
753
  }
760
- // Entries in the shared queue addressed to THIS host that no process of it has taken yet. Each is
761
- // recorded as taken (in memory and in the shared file, so it is never taken twice) and handed over.
762
- function takeSharedEntriesForSelf(saved) {
754
+ // Entries in the shared queue that the daemon has not taken yet. Each is recorded as taken (in memory
755
+ // and in the shared file, so it is never taken twice) and handed over.
756
+ function takeSharedEntries(saved) {
763
757
  const mine = [];
764
758
  for (const { deliveredTo, ...entry } of saved) {
765
- if (readerKeys(SELF_TAG).some((key) => deliveredTo.includes(key)) || alreadyDelivered(entry, SELF_TAG))
759
+ if (deliveredTo.includes(deliveredKey(SELF_TAG)) || alreadyDelivered(entry, SELF_TAG))
766
760
  continue;
767
761
  // The daemon is the machine's queue: it holds every chat's undelivered entry in memory, tagged ones
768
762
  // included, because the HTTP chats it serves are the only readers of a tagged entry and each drains its own by
769
- // tag. A bridge (one host) takes only what is addressed to it. An entry a chat already drained is marked per tag
770
- // in the shared file, and that mark is what keeps a second reader from delivering it again.
771
- if (matchesSession(entry, SELF_TAG) || QUEUE_ONLY)
772
- mine.push(entry);
763
+ // tag. An entry a chat already drained is marked per tag in the shared file, and that mark is what keeps a
764
+ // second reader from delivering it again.
765
+ mine.push(entry);
773
766
  }
774
767
  if (mine.length === 0)
775
- return mine;
768
+ return;
776
769
  for (const entry of mine) {
777
770
  // Only the entry addressed to this host is recorded as taken by it; a tagged entry another chat owns stays
778
771
  // unmarked here and is marked when that chat drains it.
@@ -784,7 +777,6 @@ function takeSharedEntriesForSelf(saved) {
784
777
  log("·", "inbox", "taken from the shared queue", entry.tag ?? SELF_TAG);
785
778
  }
786
779
  persistInboxQueue();
787
- return mine;
788
780
  }
789
781
  // A message this process took meets its live consumers here: the open question a reply on an
790
782
  // answering channel answers, else every parked wait_for_inbox, else the queue the session's next tool result drains.
@@ -802,7 +794,8 @@ function handOver(entry) {
802
794
  markDelivered(entry, w.tag);
803
795
  w.resolve([entry]);
804
796
  }
805
- if (waiters.length === 0)
797
+ // an untagged entry is every chat's: the ones parked took it, the ones not parked drain it from the queue
798
+ if (waiters.length === 0 || !entry.tag)
806
799
  inboxQueue.push(entry);
807
800
  }
808
801
  // The open question a reply answers: one asked by the session the reply is tagged for, or any
@@ -851,15 +844,10 @@ function matchesSession(entry, sessionTag) {
851
844
  return true; // untagged → everyone
852
845
  return entry.tag === sessionTag; // tagged → only matching session
853
846
  }
854
- // Set once by startNotifyServer() from the identity its host gave it. Every
855
- // routing question below is asked against this, because one process serves one
856
- // host: there is no other session in here to route to.
847
+ // Set once by startNotifyServer() from the tag its host gave it: the daemon's own tag, the one the shared queue keeps its
848
+ // own reads under.
857
849
  let SELF_TAG;
858
- let QUEUE_ONLY = false;
859
- function matchesSelfTag(tag) {
860
- return tag === undefined || tag === SELF_TAG;
861
- }
862
- // ── /btw file-drop bridge ─────────────────────────────────────────────────────
850
+ // ── /btw file-drop ─────────────────────────────────────────────────────
863
851
  // Claude Code has no API for injecting a prompt into a running session while a
864
852
  // tool call is executing (anthropics/claude-code#27441, still open). The only
865
853
  // in-band channel is the `FileChanged` hook: when a watched file changes on
@@ -871,7 +859,7 @@ function matchesSelfTag(tag) {
871
859
  // closest thing to a "/btw" we can get until the client exposes a real inject
872
860
  // endpoint.
873
861
  // Test mode drops to an isolated dir so a smoke run never pollutes the live
874
- // inbox the hook/bridge read (sim/live separation).
862
+ // inbox the hook reads (sim/live separation).
875
863
  const INBOX_DROP_DIR = join(CONFIG_DIR, process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" ? "inbox-test" : "inbox");
876
864
  const INBOX_DROP_TTL_MS = 24 * 60 * 60 * 1000; // 24h — hook should have consumed within seconds
877
865
  function writeInboxDrop(entry) {
@@ -932,7 +920,7 @@ function rejectDrop(path, name, reason) {
932
920
  renameSync(path, `${path}.rejected`);
933
921
  log("·", "inbox-drop", `${name} is not a well-formed drop and was kept as .rejected: ${reason}`);
934
922
  }
935
- function retryUnreadDrops(unread, host) {
923
+ function retryUnreadDrops(unread) {
936
924
  if (unread.length === 0) {
937
925
  dropFailedPasses = 0;
938
926
  return;
@@ -951,7 +939,7 @@ function retryUnreadDrops(unread, host) {
951
939
  log("·", "inbox-drop", `could not read ${which}; they stay in inbox-drop, read again in ${waitMs} ms (retry ${dropFailedPasses} of ${DROP_READ_RETRIES})`);
952
940
  setTimeout(() => {
953
941
  dropRetryPending = false;
954
- ingestDropFolder(host);
942
+ ingestDropFolder();
955
943
  }, waitMs).unref();
956
944
  }
957
945
  function processIsAlive(pid) {
@@ -1021,7 +1009,7 @@ function claimDrop(marker) {
1021
1009
  rmSync(takeover, { force: true });
1022
1010
  }
1023
1011
  }
1024
- function ingestDropFolder(host) {
1012
+ function ingestDropFolder() {
1025
1013
  if (!existsSync(INBOX_DROP_IN_DIR))
1026
1014
  return;
1027
1015
  mkdirSync(INBOX_DROP_CLAIM_DIR, { recursive: true });
@@ -1074,12 +1062,12 @@ function ingestDropFolder(host) {
1074
1062
  log("·", "inbox-drop", `${name} could not be claimed or settled and stays in the folder: ${err instanceof Error ? err.message : String(err)}`);
1075
1063
  }
1076
1064
  }
1077
- retryUnreadDrops(unread, host);
1065
+ retryUnreadDrops(unread);
1078
1066
  if (arrivals.length === 0)
1079
1067
  return;
1080
1068
  persistInboxQueue(arrivals);
1081
1069
  log("·", "inbox-drop", `queued ${arrivals.length} message${arrivals.length === 1 ? "" : "s"} from ${INBOX_DROP_IN_DIR}`);
1082
- syncInboxFromDisk(host);
1070
+ syncInboxFromDisk();
1083
1071
  }
1084
1072
  function ingestInboxEntry(entry, source) {
1085
1073
  const waiters = takeWaitersFor(entry.tag);
@@ -1090,7 +1078,8 @@ function ingestInboxEntry(entry, source) {
1090
1078
  w.resolve([entry]);
1091
1079
  }
1092
1080
  }
1093
- else {
1081
+ // an untagged entry is every chat's: the ones parked took it, the ones not parked drain it from the queue
1082
+ if (waiters.length === 0 || !entry.tag) {
1094
1083
  inboxQueue.push(entry);
1095
1084
  writeInboxDrop(entry);
1096
1085
  }
@@ -1098,7 +1087,6 @@ function ingestInboxEntry(entry, source) {
1098
1087
  markDelivered(entry, SELF_TAG);
1099
1088
  persistInboxQueue();
1100
1089
  log("·", "inbox", `${source}: ${entry.text} (waiters=${waiters.length})`, entry.tag);
1101
- return { waiters: waiters.length };
1102
1090
  }
1103
1091
  // #770's late answer: the reply to a question the caller ASKED, so it is queued
1104
1092
  // for that caller's own inbox rather than pushed at every subscriber — the
@@ -1111,22 +1099,11 @@ function queueInboxEntry(entry) {
1111
1099
  persistInboxQueue();
1112
1100
  }
1113
1101
  function ingestChatEntry(entry) {
1114
- const { waiters } = ingestInboxEntry(entry, entry.origin ?? "telegram");
1102
+ ingestInboxEntry(entry, entry.origin ?? "telegram");
1115
1103
  // The daemon serves no session of its own, so it cannot say who is connected — only that the shared inbox holds the message.
1116
- if (QUEUE_ONLY)
1117
- return entry.tag
1118
- ? `📬 Queued for @${entry.tag}. Delivered when that session is connected.`
1119
- : "📬 Queued. Delivered to every agent session that connects.";
1120
- const listening = waiters > 0 || matchesSelfTag(entry.tag);
1121
- // NULL-OK: field tag is OPTIONAL and therefore it is ok to check for NULL
1122
- if (entry.tag) {
1123
- return listening
1124
- ? `📬 Routed to @${entry.tag}. Waiting for reply.`
1125
- : `📭 No session @${entry.tag} connected. Message queued — next @${entry.tag} to connect will pick it up.`;
1126
- }
1127
- return listening
1128
- ? "📬 Queued for every connected agent. Waiting for reply."
1129
- : "📭 No agents connected. Message queued — next agent to connect will pick it up.";
1104
+ return entry.tag
1105
+ ? `📬 Queued for @${entry.tag}. Delivered when that session is connected.`
1106
+ : "📬 Queued. Delivered to every agent session that connects.";
1130
1107
  }
1131
1108
  async function initTgOffset(token) {
1132
1109
  const r = await fetch(tgApi(token, "getUpdates?offset=-1&timeout=0"));
@@ -1682,20 +1659,25 @@ async function slackSend(text) {
1682
1659
  if (!json.ok)
1683
1660
  throw new Error(`chat.postMessage: ${json.error ?? "unknown"}`);
1684
1661
  }
1685
- // The tags a user can @-address from Slack. This process serves exactly one
1686
- // host, so the only tag it can name is its own.
1662
+ // The tags a user can @-address from Slack: the tags of the chats connected
1663
+ // right now, i.e. the ones holding a live inbox waiter.
1687
1664
  function slackClientTags() {
1688
- return SELF_TAG ? [SELF_TAG] : [];
1665
+ const tags = new Set();
1666
+ for (const [, w] of inboxWaiters)
1667
+ if (w.tag !== undefined)
1668
+ tags.add(w.tag);
1669
+ return [...tags];
1689
1670
  }
1690
1671
  // How many live agents would actually receive a message with this tag (undefined
1691
1672
  // = broadcast). Used to gate the Slack ack: an "ack" posted when nobody is
1692
1673
  // connected is a lie — the message only sits queued for the next connector.
1674
+ // The daemon serves no session of its own, so it is never counted.
1693
1675
  function liveListenerCount(tag) {
1694
1676
  let waiters = 0;
1695
1677
  for (const [, w] of inboxWaiters)
1696
1678
  if (!tag || w.tag === tag)
1697
1679
  waiters++;
1698
- return waiters + (matchesSelfTag(tag) ? 1 : 0);
1680
+ return waiters;
1699
1681
  }
1700
1682
  function slackClientsNumbered() {
1701
1683
  const tags = slackClientTags();
@@ -1892,14 +1874,14 @@ async function routeSlackInbox(m) {
1892
1874
  log("←", "slack", `unknown client: ${handle}`);
1893
1875
  return;
1894
1876
  }
1877
+ const listening = liveListenerCount(tag) > 0; // counted BEFORE ingest, which hands the message to and removes its waiters
1895
1878
  ingestInboxEntry({ text: msg, ts: new Date().toISOString(), tag, origin: "slack" }, "slack");
1896
- if (liveListenerCount(tag) > 0)
1897
- await slackPost("ack");
1879
+ await slackPost(listening ? "ack" : `📭 No session @${displayTag(tag)} connected. Message queued — next @${displayTag(tag)} to connect will pick it up.`);
1898
1880
  }
1899
1881
  else {
1882
+ const listening = liveListenerCount(undefined) > 0; // counted BEFORE ingest, which hands the message to and removes its waiters
1900
1883
  ingestInboxEntry({ text, ts: new Date().toISOString(), origin: "slack" }, "slack");
1901
- if (liveListenerCount(undefined) > 0)
1902
- await slackPost("ack");
1884
+ await slackPost(listening ? "ack" : "📭 No agents connected. Message queued — next agent to connect will pick it up.");
1903
1885
  }
1904
1886
  }
1905
1887
  async function pollSlackOnce(token, channel) {
@@ -2025,13 +2007,20 @@ function drainInboxFor(tag) {
2025
2007
  const taken = [];
2026
2008
  const queuedBefore = inboxQueue.length;
2027
2009
  for (let i = inboxQueue.length - 1; i >= 0; i--) {
2028
- if (!matchesSession(inboxQueue[i], tag))
2010
+ const entry = inboxQueue[i];
2011
+ if (!entry.tag && Date.now() - Date.parse(entry.ts) >= INBOX_ENTRY_TTL_MS) {
2012
+ inboxQueue.splice(i, 1);
2013
+ continue;
2014
+ }
2015
+ if (!matchesSession(entry, tag) || alreadyDelivered(entry, tag))
2029
2016
  continue;
2030
- markDelivered(inboxQueue[i], tag);
2031
- taken.unshift(inboxQueue[i]);
2032
- inboxQueue.splice(i, 1);
2017
+ markDelivered(entry, tag);
2018
+ taken.unshift(entry);
2019
+ // a tagged entry has one reader, so it leaves the queue with it; an untagged one stays for every other chat until its lifetime ends
2020
+ if (entry.tag)
2021
+ inboxQueue.splice(i, 1);
2033
2022
  }
2034
- if (inboxQueue.length !== queuedBefore)
2023
+ if (taken.length > 0 || inboxQueue.length !== queuedBefore)
2035
2024
  persistInboxQueue();
2036
2025
  return taken;
2037
2026
  }
@@ -2382,8 +2371,7 @@ export function createMcpServer(clientId, sessionTag) {
2382
2371
  ? "WAS delivered over telegram"
2383
2372
  : "was NOT delivered over anything";
2384
2373
  // A blocking MCP tool call does not survive longer than the caller's own
2385
- // request timeout — MEASURED 2026-09-20 against a real MCP client over the
2386
- // stdio bridge: `ask` with timeout_seconds=300 threw `MCP error -32001:
2374
+ // request timeout — MEASURED 2026-09-20 against a real MCP client: `ask` with timeout_seconds=300 threw `MCP error -32001:
2387
2375
  // Request timed out` at exactly 60.0s, while the server kept the question
2388
2376
  // parked and any answer went into a promise whose caller was gone. So the
2389
2377
  // WAIT is clamped and the caller is TOLD; the question itself stays open
@@ -2511,9 +2499,6 @@ export function createMcpServer(clientId, sessionTag) {
2511
2499
  "carry, and a channel nothing has measured, each hold it false and are named in " +
2512
2500
  "`reason`. Read `channels` for the ones that can carry and `carriage` for the " +
2513
2501
  "per-channel state. Do NOT report the user as reachable off `process`.", {}, async () => {
2514
- // Deliberately NOT logged: this server's `log()` writes to stdout, which on
2515
- // a stdio server is the JSON-RPC channel, so a line here would interleave
2516
- // with the tool result. See the finding filed against the stdout trail.
2517
2502
  const verdict = deliveryReport();
2518
2503
  return { content: [{ type: "text", text: appendInbox(JSON.stringify(verdict), sessionTag, clientId) }] };
2519
2504
  });
@@ -2641,19 +2626,31 @@ function watchNames(dir, watched, onChange) {
2641
2626
  const OWNERSHIP_PORT_FLOOR = 20_000;
2642
2627
  const OWNERSHIP_PORT_SPAN = 40_000;
2643
2628
  // 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.
2644
- function ownershipPortWithoutDoor() {
2645
- return OWNERSHIP_PORT_FLOOR + createHash("sha256").update(CONFIG_DIR).digest().readUInt32BE(0) % OWNERSHIP_PORT_SPAN;
2629
+ function ownershipPortWithoutDoor(attempt) {
2630
+ const start = createHash("sha256").update(CONFIG_DIR).digest().readUInt32BE(0);
2631
+ return OWNERSHIP_PORT_FLOOR + (start + attempt) % OWNERSHIP_PORT_SPAN;
2646
2632
  }
2647
- async function bindGatewayPort() {
2648
- const settings = readGatewaySettings();
2649
- if (settings)
2650
- return (await import("./gateway/restDoor.js")).startRestDoor(settings);
2633
+ function listenBare(port) {
2651
2634
  return new Promise((resolve, reject) => {
2652
2635
  const bare = createNetServer();
2653
2636
  bare.once("error", reject);
2654
- bare.listen(ownershipPortWithoutDoor(), "127.0.0.1", () => resolve(bare));
2637
+ bare.listen(port, "127.0.0.1", () => resolve(bare));
2655
2638
  });
2656
2639
  }
2640
+ async function bindGatewayPort() {
2641
+ const settings = readGatewaySettings();
2642
+ if (settings)
2643
+ return (await import("./gateway/restDoor.js")).startRestDoor(settings);
2644
+ for (let attempt = 0;; attempt++) {
2645
+ try {
2646
+ return await listenBare(ownershipPortWithoutDoor(attempt));
2647
+ }
2648
+ catch (err) {
2649
+ if (err.code !== "EACCES" || attempt + 1 >= OWNERSHIP_PORT_SPAN)
2650
+ throw err;
2651
+ }
2652
+ }
2653
+ }
2657
2654
  function startOwnedWork() {
2658
2655
  AgentGateway.instance().registerDoor("telegram", (c, part) => telegramSendTo(loadConfig().telegram.token, c.chat.slice("telegram:".length), part));
2659
2656
  AgentGateway.instance().registerDoor("slack", (c, part) => slackPostInThread(slackCreds().token, c.slack.channel, c.slack.threadTs, part));
@@ -2661,33 +2658,8 @@ function startOwnedWork() {
2661
2658
  AgentGateway.instance().boot();
2662
2659
  log("·", "listener", `this process (pid ${process.pid}, build ${PACKAGE_VERSION}) owns the Telegram, Slack, Discord and Teams pollers, the ntfy and SMS pollers, the agent's email door, and the agent conversations`);
2663
2660
  }
2664
- // GATE: a daemon's beat older than this is presumed dead; it is vscode-extension/bnDaemon.js's own STALE_MS.
2665
- const DAEMON_BEAT_STALE_MS = 30_000;
2666
2661
  /** Written by the daemon (daemon.ts) on its beat, read by vscode-extension/bnDaemon.js. */
2667
2662
  export const DAEMON_BEAT_PATH = join(CONFIG_DIR, "daemon.json");
2668
- /** The daemon's last beat, or undefined when it never wrote one. */
2669
- function latestBeat() {
2670
- return existsSync(DAEMON_BEAT_PATH) ? JSON.parse(readFileSync(DAEMON_BEAT_PATH, "utf8")) : undefined;
2671
- }
2672
- /** A daemon is alive and beating — of the given build, when one is named. */
2673
- function daemonBeats(version) {
2674
- const beat = latestBeat();
2675
- if (beat === undefined)
2676
- return false;
2677
- if (Date.now() - beat.at >= DAEMON_BEAT_STALE_MS || (version !== undefined && beat.version !== version))
2678
- return false;
2679
- try {
2680
- process.kill(beat.pid, 0);
2681
- return true;
2682
- }
2683
- catch (err) {
2684
- if (err.code === "ESRCH")
2685
- return false;
2686
- if (err.code === "EPERM")
2687
- return true;
2688
- throw err;
2689
- }
2690
- }
2691
2663
  let lastBindRefusal = "";
2692
2664
  let lastOtherBn = "";
2693
2665
  let lastProbeFailure = "";
@@ -2705,9 +2677,7 @@ export function yieldGateway() {
2705
2677
  }
2706
2678
  /**
2707
2679
  * Once the extension installs a newer build, this process is superseded and the gateway passes to the installed build:
2708
- * a superseded process never takes it while a daemon beats, and one that holds it steps aside once no
2709
- * answer is in flight — the daemon at once, since it starts the installed build in its place, and a
2710
- * bridge once the installed build's daemon beats to take it over.
2680
+ * one that holds it steps aside once no answer is in flight, and then starts the installed build in its place.
2711
2681
  */
2712
2682
  function tryOwnGateway(polling, host) {
2713
2683
  if (ownershipAttempting)
@@ -2718,16 +2688,11 @@ function tryOwnGateway(polling, host) {
2718
2688
  log("·", "listener", `build ${PACKAGE_VERSION} is superseded by ${yielding ? "the release that asked for the chat door" : `the installed ${installed}`}; this process hands the gateway to it`);
2719
2689
  supersededSaid = true;
2720
2690
  if (door !== undefined) {
2721
- if (host.onSuperseded !== undefined || daemonBeats(installed))
2722
- void stepAside(polling, host);
2691
+ void stepAside(polling, host);
2723
2692
  return;
2724
2693
  }
2725
- if (host.onSuperseded !== undefined) {
2726
- host.onSuperseded();
2727
- return;
2728
- }
2729
- if (daemonBeats())
2730
- return;
2694
+ host.onSuperseded();
2695
+ return;
2731
2696
  }
2732
2697
  if (door !== undefined)
2733
2698
  return;
@@ -2799,21 +2764,15 @@ async function stepAside(polling, host) {
2799
2764
  finally {
2800
2765
  ownershipAttempting = false;
2801
2766
  }
2802
- host.onSuperseded?.();
2767
+ host.onSuperseded();
2803
2768
  }
2804
- // Messages another host's poller recorded for THIS host: hand them to the tool
2805
- // layer and to the attached client, and record it in the shared file so no host
2806
- // delivers the same message twice.
2807
- function syncInboxFromDisk(host) {
2808
- for (const entry of takeSharedEntriesForSelf(readSharedQueue())) {
2809
- host.emit(entry).catch((err) =>
2810
- // OWNER: the message is already in this host's inbox and in the shared queue, so a refused push costs the push alone — it is reported once here and the caller's next poll or wait_for_inbox still hands the message over.
2811
- log("·", "inbox", `channel push failed: ${err instanceof Error ? err.message : String(err)}`, host.clientId));
2812
- }
2769
+ // Messages another process's poller recorded: hand them to the tool layer, and
2770
+ // record it in the shared file so no process delivers the same message twice.
2771
+ function syncInboxFromDisk() {
2772
+ takeSharedEntries(readSharedQueue());
2813
2773
  }
2814
2774
  export function startNotifyServer(host) {
2815
2775
  SELF_TAG = host.tag;
2816
- QUEUE_ONLY = host.queueOnly === true;
2817
2776
  importCredsOnStart();
2818
2777
  warnIfNoChannelConfigured(loadConfig());
2819
2778
  refreshReach();
@@ -2844,7 +2803,7 @@ export function startNotifyServer(host) {
2844
2803
  if (dropWatched || !existsSync(INBOX_DROP_IN_DIR))
2845
2804
  return;
2846
2805
  dropWatched = true;
2847
- const drops = watch(INBOX_DROP_IN_DIR, { persistent: false }, () => ingestDropFolder(host));
2806
+ const drops = watch(INBOX_DROP_IN_DIR, { persistent: false }, () => ingestDropFolder());
2848
2807
  // The drop folder was taken away: its watch is gone, and the folder's return is seen on the config folder's own watch.
2849
2808
  drops.on("error", () => { dropWatched = false; });
2850
2809
  };
@@ -2852,10 +2811,10 @@ export function startNotifyServer(host) {
2852
2811
  watchNames(CONFIG_DIR, (name) => INBOX_QUEUE_FILE.test(name) || name === basename(INBOX_DROP_IN_DIR), (name) => {
2853
2812
  if (name === undefined || name === basename(INBOX_DROP_IN_DIR)) {
2854
2813
  watchDrops();
2855
- ingestDropFolder(host);
2814
+ ingestDropFolder();
2856
2815
  }
2857
2816
  if (name !== basename(INBOX_DROP_IN_DIR) && !name?.startsWith(OWN_QUEUE_PREFIX))
2858
- syncInboxFromDisk(host);
2817
+ syncInboxFromDisk();
2859
2818
  });
2860
2819
  watchDrops();
2861
2820
  const reapTimer = setInterval(reapInboxDrops, 60 * 60 * 1000);
@@ -2863,8 +2822,8 @@ export function startNotifyServer(host) {
2863
2822
  reapTimer.unref();
2864
2823
  return createMcpServer(host.clientId, host.tag);
2865
2824
  }
2866
- /** Takes in what was queued or dropped before this process started. Called once the server is connected, because every push needs it. */
2867
- export function takePendingInbox(host) {
2868
- ingestDropFolder(host);
2869
- syncInboxFromDisk(host);
2825
+ /** Takes in what was queued or dropped before this process started. */
2826
+ export function takePendingInbox() {
2827
+ ingestDropFolder();
2828
+ syncInboxFromDisk();
2870
2829
  }
@@ -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.340",
3
+ "version": "1.3.342",
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",