omni-notify-mcp 1.3.395 → 1.3.397

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.
Files changed (42) hide show
  1. package/dist/agentGateway.js +172 -259
  2. package/dist/daemon.js +24 -5
  3. package/dist/gateway/chatPage.js +0 -499
  4. package/dist/gateway/oauthDoor.js +1 -2
  5. package/dist/gateway/panel.js +20 -18
  6. package/dist/gateway/passkeyDoor.js +1 -2
  7. package/dist/gateway/publicAccess.js +1 -2
  8. package/dist/gateway/restDoor.js +241 -144
  9. package/dist/messaging/chatInbound.js +3 -1
  10. package/dist/messaging/emailInbound.js +3 -7
  11. package/dist/notify.js +62 -24
  12. package/dist/shared/webhost/autoSwitch.cjs +9 -1
  13. package/dist/shared/webhost/bullseyeWebHost.js +73 -12
  14. package/dist/shared/webhost/originHandover.js +74 -28
  15. package/dist/shared/webhost/webviewShim.js +101 -41
  16. package/package.json +2 -9
  17. package/dist/gateway/conversationOwner.js +0 -125
  18. package/dist/gateway/mcpDoor.js +0 -395
  19. package/dist/gateway/mcpEvents.js +0 -448
  20. package/dist/gateway/terminalDoor.js +0 -161
  21. package/dist/gateway/terminalPage.js +0 -346
  22. package/dist/shared/agentSession.js +0 -4917
  23. package/dist/shared/conversation/claudeProvider.js +0 -357
  24. package/dist/shared/conversation/cliSession.js +0 -452
  25. package/dist/shared/conversation/codexArchive.js +0 -69
  26. package/dist/shared/conversation/codexProvider.js +0 -193
  27. package/dist/shared/conversation/conversationOwner.js +0 -44
  28. package/dist/shared/conversation/conversations.js +0 -929
  29. package/dist/shared/conversation/copilotProvider.js +0 -150
  30. package/dist/shared/conversation/nativeCliInvocation.js +0 -61
  31. package/dist/shared/conversation/nativeTerminal.js +0 -529
  32. package/dist/shared/conversation/nativeTerminalWorker.js +0 -157
  33. package/dist/shared/conversation/opencodeEvents.mjs +0 -13
  34. package/dist/shared/conversation/opencodeProvider.js +0 -289
  35. package/dist/shared/conversation/ownerContext.js +0 -1
  36. package/dist/shared/conversation/provider.js +0 -38
  37. package/dist/shared/conversation/providers.js +0 -30
  38. package/dist/shared/conversation/sessionDriver.js +0 -1070
  39. package/dist/shared/conversation/terminalTransport.js +0 -106
  40. package/dist/shared/providerOwnership.js +0 -294
  41. package/scripts/shared/ownerGuard.cjs +0 -74
  42. package/scripts/shared/ownerGuard.sh +0 -64
@@ -1,291 +1,204 @@
1
1
  /**
2
- * The agent gateway's chat side (#2052): a Telegram, Slack, Discord or Teams message that starts with `!` goes to
3
- * the agent; everything else is left to the inbox exactly as before.
4
- *
5
- * One conversation per chat or Slack thread, kept in the conversations store (`shared/conversation/conversations.ts`,
6
- * owned by `gateway/conversationOwner.ts`) beside
7
- * the REST door's, and driven by the one session driver (`shared/conversation/sessionDriver.ts`, #2051): the start line, the
8
- * status lines, a permission question and the answer come back to the chat, the answer split at 500 characters
9
- * with (k/N) parts. `/stop` ends the chat's conversation and `/new` ends it so the next `!` opens a fresh one.
10
- * An email thread (#2105) is one conversation for good, and gets only its answer, question or failure, each whole.
11
- * Every conversation starts in Meni's workspace root, as the web page's and the MCP door's do.
2
+ * The agent gateway's chat side (#2052, #4231): a Telegram, Slack, Discord, Teams, ntfy, SMS or email message addressed to
3
+ * the agent goes to AgenticBullseye (AB), the ONE owner of every conversation, through its chat carriage
4
+ * (`POST /v1/chat/<op>`); everything else is left to the inbox exactly as before. BN keeps only the transports: it holds
5
+ * each message's own way back to its thread until AB releases it, and AB sends every part of the turn back through BN's
6
+ * reply door (`POST /v1/chat/reply`), which carries it on that way back — or, with none held, through the platform's
7
+ * registered door, rebuilt from the conversation record alone.
12
8
  */
13
- import { splitForNotify } from "./chunk.js";
14
- import { masterMuted } from "./notify.js";
15
- import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversationOwner.js";
16
- import { conversationOwner } from "./gateway/conversationOwner.js";
17
- import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
18
- import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
9
+ import { randomUUID } from "crypto";
10
+ import { GatewayError, readGatewaySettings } from "./notify.js";
19
11
  export const AGENT_PREFIX = "!";
20
- /** A chat: the newest conversation not stopped (`/new` and `/stop` end it), and every line of the turn, the answer split at 500. */
21
- const CHAT = {
22
- conversationOf: openConversationOf,
23
- routeOf: routeAsk,
24
- stopOf: stopTargetOf,
25
- allOf: openConversationsOf,
26
- carries: (kind) => kind !== "returned",
27
- parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
28
- };
29
- const MAILED_KINDS = new Set(["answer", "failed", "stopped"]);
30
- /** An email thread: its one conversation, a stopped one resumed by the next reply; only what needs Meni is mailed, each whole. */
31
- const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
32
- const MAIL = {
33
- conversationOf: THREADS_ONE,
34
- routeOf: THREADS_ONE,
35
- stopOf: THREADS_ONE,
36
- allOf: (key) => listConversations().filter((c) => c.chat === key),
37
- carries: (kind) => MAILED_KINDS.has(kind),
38
- parts: (event) => [event.text],
39
- };
40
- const CARRIAGE = { telegram: CHAT, slack: CHAT, discord: CHAT, teams: CHAT, ntfy: CHAT, sms: CHAT, email: MAIL };
41
12
  const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
42
- const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
13
+ // GATE: the port AgenticBullseye serves on (#4196 Section 9); NOTIFY_AGENT_CLUSTER_URL names another ONLY under the test gate, so a suite drives the real carriage on a cluster it owns, and without the gate no environment can redirect it.
14
+ const CLUSTER_URL = "http://127.0.0.1:7481";
15
+ /** AgenticBullseye's base URL: the one this machine runs, or the stand-in a suite names under the test gate. */
16
+ export function clusterBase() {
17
+ return process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" && process.env.NOTIFY_AGENT_CLUSTER_URL ? process.env.NOTIFY_AGENT_CLUSTER_URL.replace(/\/+$/, "") : CLUSTER_URL;
18
+ }
19
+ /** The gateway bearer every call to AB carries; with no `agentGateway.token` in config.json BN has no way into AB and says so. */
20
+ export function clusterToken() {
21
+ const settings = readGatewaySettings();
22
+ // NULL-OK: field settings is OPTIONAL and therefore it is ok to check for NULL
23
+ if (settings === undefined)
24
+ throw new GatewayError(503, "no agentGateway.token is set in config.json, so BN cannot reach AgenticBullseye, which runs every agent conversation — create the gateway token on BN's Public access page");
25
+ return settings.token;
26
+ }
27
+ /** The refusal BN answers when AB cannot be reached at all: a 503 naming the cluster and the cause, never a local stand-in. */
28
+ export function clusterUnreachable(err) {
29
+ // NULL-OK: field cause is OPTIONAL and therefore it is ok to check for NULL
30
+ const cause = err.cause?.code ?? err.code ?? err.message;
31
+ return new GatewayError(503, `AgenticBullseye at ${clusterBase()} could not be reached (${cause}); the agent conversations run there`);
32
+ }
33
+ /** One carriage call: AB's JSON answer, or AB's own refusal as a GatewayError carrying its status and words. */
34
+ async function carriage(op, body) {
35
+ let answer;
36
+ try {
37
+ answer = await fetch(`${clusterBase()}/v1/chat/${op}`, { method: "POST", headers: { authorization: `Bearer ${clusterToken()}`, "content-type": "application/json" }, body: JSON.stringify(body) });
38
+ }
39
+ catch (err) {
40
+ if (!(err instanceof TypeError))
41
+ throw err;
42
+ throw clusterUnreachable(err);
43
+ }
44
+ const text = await answer.text();
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(text);
48
+ }
49
+ catch (err) {
50
+ if (!(err instanceof SyntaxError))
51
+ throw err;
52
+ throw new GatewayError(502, `AgenticBullseye answered chat ${op} with HTTP ${answer.status} and a body that is not JSON: ${text.slice(0, 200)}`);
53
+ }
54
+ if (!answer.ok) {
55
+ // NULL-OK: field error is OPTIONAL and therefore it is ok to check for NULL
56
+ const said = parsed?.error;
57
+ throw new GatewayError(answer.status, typeof said === "string" ? said : `AgenticBullseye answered chat ${op} with HTTP ${answer.status}: ${text.slice(0, 200)}`);
58
+ }
59
+ return parsed;
60
+ }
43
61
  export class AgentGateway {
44
- driver;
45
62
  static self;
46
63
  static instance() {
47
- return (AgentGateway.self ??= new AgentGateway(conversationOwner.driver));
64
+ return (AgentGateway.self ??= new AgentGateway());
48
65
  }
49
- /** The messages waiting on their answer, by conversation and user event. */
50
- turns = new Map();
66
+ /** The messages whose turn is still sending, by the reply id handed to AB with them. */
67
+ held = new Map();
51
68
  doors = new Map();
52
- recovered = false;
53
- constructor(driver) {
54
- this.driver = driver;
55
- driver.onEvent((event) => this.deliver(event));
56
- driver.onEvent(turnEnded);
57
- }
58
69
  registerDoor(platform, door) {
59
70
  this.doors.set(platform, door);
60
71
  }
61
- /** Starts the driver in the process that owns the pollers, then takes back every turn the last process owed its thread an answer for. */
62
- boot() {
63
- clearOpenCodeLogs();
64
- this.driver.boot();
65
- if (this.recovered)
66
- return;
67
- this.recovered = true;
68
- resendUndelivered();
69
- for (const c of listConversations())
70
- this.recover(c);
71
- }
72
- /** Re-attaches each turn the record says is still owed: the events written since the last one sent go out now, and the answer still to come follows once. */
73
- recover(c) {
74
- const owed = Object.entries(c.owed ?? {});
75
- if (owed.length === 0)
76
- return;
77
- if (c.state === "closed")
78
- return editOwed(c.id, (o) => { for (const [turn] of owed)
79
- delete o[turn]; });
80
- const door = this.doors.get(c.platform);
81
- if (door === undefined)
82
- throw new Error(`conversation ${c.id} on ${c.platform} is owed an answer and no door of that platform is registered before boot`);
83
- for (const [turn, sent] of owed) {
84
- const pending = readEvents(c.id).filter((e) => e.turn === Number(turn) && e.n > sent && e.role !== "user").map((e) => ({ ...e, id: c.id }));
85
- // OWNER: ITER/LOOP — a thread that cannot be reached is shown on its conversation and the next owed turn is still carried on.
86
- void this.awaitTurn(c.id, Number(turn), (part) => door(c, part), CARRIAGE[c.platform], pending).catch((err) => appendEvent(c.id, { role: "system", kind: "status", text: `❌ The answer could not be sent to this ${c.platform} thread after the BN restart: ${err instanceof Error ? err.message : String(err)}` }));
87
- }
88
- }
89
- /** No turn running or queued, no chat message waiting on its conversation's creation, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
72
+ /** No message's turn is still sending through this process: the gateway can pass to another one without losing a reply's own thread. */
90
73
  quiet() {
91
- return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
92
- }
93
- /** Gives the store back when this process hands the gateway over. */
94
- async shutdown() {
95
- await this.driver.shutdown();
96
- this.recovered = false;
97
- }
98
- /** What this message asks of the agent, or undefined when it is not addressed to it and belongs to the inbox. */
99
- classify(key, raw) {
74
+ return this.held.size === 0;
75
+ }
76
+ /**
77
+ * What this message asks of the agent, or undefined when it is not addressed to it and belongs to the inbox. Only a
78
+ * message that can be addressed to the agent at all — a `!` message, or a bare `/new` or `/stop` — is asked of AB, so
79
+ * the inbox never waits on the cluster.
80
+ */
81
+ async classify(key, raw) {
100
82
  const text = raw.trim();
101
- if (text.startsWith(AGENT_PREFIX)) {
102
- const body = text.slice(AGENT_PREFIX.length).trim();
103
- const cmd = body.match(COMMAND_RE);
104
- if (cmd)
105
- return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
106
- return { kind: "say", text: body };
107
- }
108
- const cmd = text.match(COMMAND_RE);
109
- if (cmd && openConversationOf(key) !== undefined)
110
- return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
111
- return undefined;
83
+ if (!text.startsWith(AGENT_PREFIX) && !COMMAND_RE.test(text))
84
+ return undefined;
85
+ // NULL-OK: field act is OPTIONAL and therefore it is ok to check for NULL
86
+ return (await carriage("classify", { key, raw })).act ?? undefined;
112
87
  }
113
88
  /** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
114
- classifyInThread(key, raw) {
115
- return this.classify(key, raw) ?? { kind: "say", text: raw.trim() };
89
+ async classifyInThread(key, raw) {
90
+ return (await carriage("classifyInThread", { key, raw })).act;
91
+ }
92
+ /**
93
+ * A message's act as AB classifies it; one AB could not classify (unreachable, or refused with its reason) has that
94
+ * reason answered to its chat and reads as "answered", so the poll reads on and the message is never taken for the inbox.
95
+ */
96
+ async classified(classify, reply) {
97
+ try {
98
+ return await classify();
99
+ }
100
+ catch (err) {
101
+ if (!(err instanceof GatewayError))
102
+ throw err;
103
+ // OWNER: the message is the trigger root — a message AgenticBullseye could not classify is answered to the chat with the reason, never thrown past the poll loop and never taken for the inbox
104
+ await reply(`❌ ${err.message}`);
105
+ return "answered";
106
+ }
116
107
  }
117
108
  /** Whether this email message was already taken as a turn of some conversation, so a BN restart never answers it twice. */
118
- emailTaken(messageId) {
119
- // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
120
- return listConversations().some((c) => c.email !== undefined && c.email.messageIds.includes(messageId));
121
- }
122
- /** Shows on this chat key's conversation that its answer never reached the chat, so the web page tells what the chat could not. */
123
- noteUndelivered(key, platform, text) {
124
- const c = CARRIAGE[platform].conversationOf(key);
125
- // NULL-OK: field c is OPTIONAL and therefore it is ok to check for NULL
126
- if (c === undefined)
127
- return;
128
- appendEvent(c.id, { role: "system", kind: "status", text });
109
+ async emailTaken(messageId) {
110
+ return (await carriage("emailTaken", { messageId })).taken;
129
111
  }
130
- openSlackThreads() {
131
- const newestOfThread = new Set();
132
- return listConversations().filter((c) => {
133
- if (c.platform !== "slack" || c.state === "closed" || c.slack === undefined || newestOfThread.has(c.chat ?? c.id))
134
- return false;
135
- newestOfThread.add(c.chat ?? c.id);
136
- return true;
137
- });
112
+ async openSlackThreads() {
113
+ return (await carriage("openSlackThreads", {})).conversations;
138
114
  }
139
115
  /** Records how far a Slack thread has been read. */
140
- markSlackRead(key, readTs) {
141
- for (const c of openConversationsOf(key))
142
- updateConversation(c.id, { slack: { ...c.slack, readTs } });
143
- }
144
- /** Acts on one addressed message. Resolves when its answer (or its failure) has been sent back. */
116
+ async markSlackRead(key, readTs) {
117
+ await carriage("markSlackRead", { key, readTs });
118
+ }
119
+ /**
120
+ * Hands one addressed message to AB with its own way back held under a fresh reply id. Resolves once the turn's final
121
+ * part went out or AB released its reply, and rejects when a part the thread refused is the
122
+ * reason — AB has already shown that on the conversation. An act AB did not take is answered to the chat with AB's reason.
123
+ */
145
124
  async handle(key, platform, act, reply, origin = {}) {
146
- const arrived = monotonicMs();
147
- const carriage = CARRIAGE[platform];
148
- const refusal = conversationRefusal();
149
- // A muted BN answers nobody: the refusal is spoken to the chat only when the switch, not Mute everything, is what is off.
150
- if (refusal === CONVERSATION_MUTED_MESSAGE)
151
- return;
152
- if (refusal !== undefined)
153
- return reply(refusal);
154
- // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
155
- for (let pending = creationPending(key); pending !== undefined; pending = creationPending(key))
156
- await pending;
157
- const open = carriage.conversationOf(key);
158
- if (act.kind === "stop") {
159
- const stopped = carriage.stopOf(key);
160
- // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
161
- if (stopped === undefined)
162
- return reply("Nothing to stop here — no conversation is open.");
163
- this.end(stopped.id);
164
- const others = carriage.allOf(key).filter((c) => c.id !== stopped.id).length;
165
- return reply(others === 0 ? "⏹ Conversation ended. Your next ! message opens a new one." : `⏹ Conversation ${stopped.id.slice(0, 8)} ended. ${others} other conversation${others === 1 ? " stays" : "s stay"} open.`);
125
+ const replyId = randomUUID();
126
+ const answered = new Promise((resolve, reject) => {
127
+ const held = {
128
+ reply,
129
+ settle: () => {
130
+ this.held.delete(replyId);
131
+ // NULL-OK: field failed is OPTIONAL and therefore it is ok to check for NULL
132
+ if (held.failed === undefined)
133
+ resolve();
134
+ else
135
+ reject(held.failed);
136
+ },
137
+ };
138
+ this.held.set(replyId, held);
139
+ });
140
+ try {
141
+ await carriage("handle", { key, platform, act, origin, replyId });
166
142
  }
167
- if (act.kind === "new") {
168
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
169
- if (open !== undefined)
170
- this.end(open.id);
171
- const stay = carriage.allOf(key).length;
172
- return reply(stay === 0 ? "🆕 New conversation. Your next ! message starts it." : `🆕 Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`);
143
+ catch (err) {
144
+ this.held.get(replyId).settle();
145
+ if (!(err instanceof GatewayError))
146
+ throw err;
147
+ // OWNER: the message is the trigger root — an act AgenticBullseye did not take (unreachable, or refused with its reason) is answered to the chat as that reason, never thrown past the poll loop
148
+ return reply(`❌ ${err.message}`);
173
149
  }
174
- if (act.text === "")
175
- return reply("Send `! <your message>` to talk to the agent.");
176
- const target = carriage.routeOf(key, act.text);
177
- // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
178
- if (target === undefined) {
179
- let project;
180
- try {
181
- project = resolveProject(undefined, act.text);
182
- }
183
- catch (err) {
184
- // OWNER: the message is the trigger root — a refused project (no home board) is answered to the chat as its reason, never thrown past the poll loop
185
- if (err instanceof GatewayError)
186
- return reply(err.message);
150
+ return answered;
151
+ }
152
+ /**
153
+ * AB's reply door: one part of a turn, sent through the reply its message is held with, or — none held (BN restarted, or
154
+ * AB recovered an owed turn with no reply id) — through the platform's registered door, from the conversation's record.
155
+ * A part with no conversation (a line that belongs to none, such as a switch refusal) has only its held reply. A part the
156
+ * thread refuses is thrown as a 502 naming why, which AB records on the conversation.
157
+ */
158
+ async carry(replyId, platform, conversation, part, final) {
159
+ // NULL-OK: field replyId is OPTIONAL and therefore it is ok to check for NULL
160
+ const held = replyId === null ? undefined : this.held.get(replyId);
161
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
162
+ if (held === undefined) {
163
+ // NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
164
+ if (conversation === null)
165
+ throw new GatewayError(404, `no ${platform} reply is held under ${replyId} and the part names no conversation, so it has no way to a thread`);
166
+ const door = this.doors.get(platform);
167
+ // NULL-OK: field door is OPTIONAL and therefore it is ok to check for NULL
168
+ if (door === undefined)
169
+ throw new GatewayError(404, `no ${platform} door is registered in this BN process, so the part has no way to its thread`);
170
+ return sent(platform, () => door(conversation, part));
171
+ }
172
+ try {
173
+ await sent(platform, () => held.reply(part));
174
+ }
175
+ catch (err) {
176
+ if (!(err instanceof GatewayError))
187
177
  throw err;
188
- }
189
- // A conversation opened in a thread the chat already reads starts reading after what was read, never from the thread's root again.
190
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
191
- const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
192
- const turn = {};
193
- const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
194
- const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
195
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
196
- const told = open === undefined ? [] : [this.told(created.id, 1, `🆕 An independent ask: it runs in its own conversation ${created.id.slice(0, 8)} while ${open.id.slice(0, 8)} keeps working.`)];
197
- turn.answered = this.awaitTurn(created.id, 1, reply, carriage, told);
198
- turn.id = created.id;
199
- return created;
200
- })]);
201
- if (creation.status === "rejected") {
202
- // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
203
- if (turn.id === undefined)
204
- throw creation.reason;
205
- const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
206
- process.stderr.write(`[agent-gateway] conversation ${turn.id.slice(0, 8)}: the unread-room notice could not be written (${reason}); the turn runs on and its answer is delivered\n`);
207
- this.deliver(this.told(turn.id, 1, `⚠️ No CLI was named and DeepAgent's subscription room could not be read; that notice could not be written to this conversation: ${reason}`));
208
- return turn.answered;
209
- }
210
- // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
211
- if (creation.value.notice !== undefined)
212
- this.deliver({ ...creation.value.notice, id: creation.value.made.id });
213
- return turn.answered;
178
+ held.failed = err;
179
+ throw err;
180
+ }
181
+ finally {
182
+ if (final)
183
+ held.settle();
214
184
  }
215
- // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
216
- if (origin.email !== undefined)
217
- updateConversation(target.id, { email: { ...target.email, messageIds: [...target.email.messageIds, ...origin.email.messageIds] } });
218
- const sent = sendToConversation(target.id, act.text, monotonicMs() - arrived);
219
- // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
220
- const notice = queueNoticeOf(target.id, sent.n);
221
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
222
- const told = open !== undefined && target.id !== open.id ? [this.told(target.id, sent.n, `↪ Conversation ${target.id.slice(0, 8)} is doing that work; your message goes to it.`)] : [];
223
- return this.awaitTurn(target.id, sent.n, reply, carriage, [...told, ...(notice === undefined ? [] : [{ ...notice, id: target.id }])]);
224
185
  }
225
- /** A line to the chat that says where its message went; it rides in the turn's own delivery, so it goes out after the message is stored. */
226
- told(id, n, text) {
227
- return { id, n, turn: n, role: "system", kind: "status", text, ts: new Date().toISOString() };
186
+ /** AB's release once a handled message's turn has settled: its held reply is let go. One no longer held (let go on its final part, or BN restarted since) has nothing left to let go. */
187
+ release(replyId) {
188
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
189
+ this.held.get(replyId)?.settle();
228
190
  }
229
- end(id) {
230
- for (const turn of this.turns.get(id)?.values() ?? [])
231
- turn.close();
232
- this.turns.delete(id);
233
- this.driver.stop(id);
234
- editOwed(id, (o) => { for (const turn of Object.keys(o))
235
- delete o[turn]; });
191
+ /** Asks AB to re-drive every turn it still owes a thread, once this process holds the doors those turns go out through. */
192
+ async recover() {
193
+ await carriage("recover", {});
236
194
  }
237
- /** Sends each event of the turn back in order and resolves on its last; a part the chat refuses rejects it, and its caller logs it NOT DELIVERED. */
238
- awaitTurn(id, n, reply, carriage, pending = []) {
239
- editOwed(id, (o) => { o[n] ??= n; });
240
- let wake = () => { };
241
- let closed = false;
242
- const turns = this.turns.get(id) ?? new Map();
243
- turns.set(n, { push: (event) => { pending.push(event); wake(); }, close: () => { closed = true; wake(); } });
244
- this.turns.set(id, turns);
245
- return (async () => {
246
- for (;;) {
247
- if (pending.length === 0) {
248
- if (closed)
249
- return;
250
- await new Promise((resolve) => { wake = resolve; });
251
- continue;
252
- }
253
- const event = pending.shift();
254
- // A muted BN sends nothing and keeps the answer owed, so the next BN start delivers it once Mute everything is Off.
255
- const muted = masterMuted();
256
- if (!muted && carriage.carries(event.kind))
257
- for (const part of carriage.parts(event))
258
- await reply(part);
259
- const final = FINAL_KINDS.has(event.kind ?? "");
260
- if (!closed && !muted)
261
- editOwed(id, (o) => { if (final)
262
- delete o[n];
263
- else
264
- o[n] = event.n; });
265
- if (final) {
266
- // NULL-OK: field turns is OPTIONAL and therefore it is ok to check for NULL
267
- this.turns.get(id)?.delete(n);
268
- return;
269
- }
270
- }
271
- })();
195
+ }
196
+ /** One part handed to its thread; a refusal of the thread's own platform is thrown as the 502 the reply door answers. */
197
+ async function sent(platform, send) {
198
+ try {
199
+ await send();
272
200
  }
273
- deliver(event) {
274
- const turns = this.turns.get(event.id);
275
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
276
- if (event.turn === undefined && turns !== undefined) {
277
- for (const waiting of turns.values())
278
- waiting.push(event);
279
- this.turns.delete(event.id);
280
- return;
281
- }
282
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
283
- const turn = event.turn === undefined ? undefined : turns?.get(event.turn);
284
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
285
- if (turn === undefined)
286
- return;
287
- turn.push(event);
288
- if (FINAL_KINDS.has(event.kind ?? ""))
289
- turns.delete(event.turn);
201
+ catch (err) {
202
+ throw new GatewayError(502, `the ${platform} thread did not take the part: ${err instanceof Error ? err.message : String(err)}`);
290
203
  }
291
204
  }
package/dist/daemon.js CHANGED
@@ -4,23 +4,42 @@
4
4
  *
5
5
  * It is the only mode BN runs in: started with no argument it serves the chat-tool door on 127.0.0.1:7475, which every
6
6
  * MCP host is pointed at. It runs the server code (`startNotifyServer`) with no MCP client attached, so it competes for
7
- * the gateway port like every other BN process, and the one that binds it polls the channels, serves the REST/MCP door
8
- * and runs the agent conversations whether or not any agent session is open. Everything it hears lands in the shared
7
+ * the gateway port like every other BN process, and the one that binds it polls the channels and serves the REST/MCP door,
8
+ * which carries every agent verb to AgenticBullseye, whether or not any agent session is open. Everything it hears lands in the shared
9
9
  * inbox files under the config dir: nothing is held only in its memory, so a restart of this process loses no message.
10
10
  */
11
11
  import { spawn } from "child_process";
12
- import { existsSync, readFileSync, mkdirSync } from "fs";
12
+ import { existsSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "fs";
13
13
  import { join } from "path";
14
14
  import { fileURLToPath } from "url";
15
15
  import { DAEMON_BEAT_PATH, CONFIG_DIR, DAEMON_TAG, PACKAGE_VERSION, startNotifyServer, takePendingInbox, yieldGateway } from "./notify.js";
16
16
  import { startNotifyDoor } from "./gateway/notifyDoor.js";
17
- import { writeRecordFile } from "./gateway/conversationOwner.js";
18
17
  import { announceTakeover, inThisBoot } from "./shared/webhost/originHandover.js";
19
18
  import { TunnelRunner } from "./gateway/tunnel.js";
20
19
  const HEARTBEAT_MS = 10_000;
20
+ /** A rename Windows refuses while a reader holds the beat file open for a moment. */
21
+ const RENAME_REFUSED = new Set(["EPERM", "EACCES", "EBUSY"]);
22
+ // GATE: five tries, waiting 10, 20, 40 and 80 ms — 150 ms at the outside — so a beat a reader's lock refuses for a moment still lands, and one it refuses for good fails the write exactly as a single attempt did.
23
+ const RENAME_TRIES = 5;
24
+ const RENAME_FIRST_WAIT_MS = 10;
25
+ /** The beat written whole beside the file and renamed over it, so bnDaemon.js never reads half a beat. */
21
26
  function beat(pid = process.pid) {
22
27
  mkdirSync(CONFIG_DIR, { recursive: true });
23
- writeRecordFile(DAEMON_BEAT_PATH, JSON.stringify({ pid, at: Date.now(), version: PACKAGE_VERSION }));
28
+ const staged = `${DAEMON_BEAT_PATH}.${process.pid}.tmp`;
29
+ for (let attempt = 0;; attempt++) {
30
+ try {
31
+ writeFileSync(staged, JSON.stringify({ pid, at: Date.now(), version: PACKAGE_VERSION }));
32
+ renameSync(staged, DAEMON_BEAT_PATH);
33
+ return;
34
+ }
35
+ catch (err) {
36
+ if (!RENAME_REFUSED.has(err.code ?? "") || attempt === RENAME_TRIES - 1) {
37
+ rmSync(staged, { force: true });
38
+ throw err;
39
+ }
40
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RENAME_FIRST_WAIT_MS << attempt);
41
+ }
42
+ }
24
43
  }
25
44
  /** The boot supervisor's login entry: launchd's label and systemd's unit. */
26
45
  const ENTRY_LABEL = "com.bullseye.BullseyeMcpOrigins";