omni-notify-mcp 1.3.385 → 1.3.387
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/agentGateway.js +316 -0
- package/dist/chunk.js +37 -0
- package/dist/daemon.js +131 -0
- package/dist/desk.js +268 -0
- package/dist/gateway/agentStream.js +88 -0
- package/dist/gateway/chatPage.js +729 -0
- package/dist/gateway/claudeProvider.js +355 -0
- package/dist/gateway/cliSession.js +434 -0
- package/dist/gateway/codexArchive.js +69 -0
- package/dist/gateway/codexProvider.js +190 -0
- package/dist/gateway/conversations.js +906 -0
- package/dist/gateway/copilotProvider.js +148 -0
- package/dist/gateway/iconData.js +8 -0
- package/dist/gateway/iconDoor.js +23 -0
- package/dist/gateway/lanProbe.js +86 -0
- package/dist/gateway/mcpDoor.js +395 -0
- package/dist/gateway/mcpEvents.js +448 -0
- package/dist/gateway/nativeCliInvocation.js +61 -0
- package/dist/gateway/nativeTerminal.js +506 -0
- package/dist/gateway/nativeTerminalWorker.js +157 -0
- package/dist/gateway/notifyDoor.js +166 -0
- package/dist/gateway/oauthDoor.js +345 -0
- package/dist/gateway/opencodeEvents.mjs +13 -0
- package/dist/gateway/opencodeProvider.js +287 -0
- package/dist/gateway/panel.js +211 -0
- package/dist/gateway/panelPage.js +238 -0
- package/dist/gateway/passkeyClient.js +47 -0
- package/dist/gateway/passkeyDoor.js +973 -0
- package/dist/gateway/provider.js +38 -0
- package/dist/gateway/providers.js +23 -0
- package/dist/gateway/publicAccess.js +374 -0
- package/dist/gateway/restDoor.js +318 -0
- package/dist/gateway/sessionDriver.js +1022 -0
- package/dist/gateway/terminalDoor.js +248 -0
- package/dist/gateway/terminalPage.js +351 -0
- package/dist/gateway/tunnel.js +166 -0
- package/dist/googlehome/foyer-client.js +210 -0
- package/dist/googlehome/foyer-codec.js +318 -0
- package/dist/googlehome/gpsoauth.js +119 -0
- package/dist/googlehome/index.js +267 -0
- package/dist/index.js +41 -0
- package/dist/messaging/chatInbound.js +405 -0
- package/dist/messaging/deliveryVerdict.js +52 -0
- package/dist/messaging/emailInbound.js +292 -0
- package/dist/messaging/inboundPayloads.js +41 -0
- package/dist/messaging/notificationEngine.js +195 -0
- package/dist/messaging/telegramError.js +6 -0
- package/dist/notify.js +2792 -0
- package/dist/shared/agentSession.js +4641 -0
- package/dist/shared/webhost/autoSwitch.cjs +2164 -0
- package/dist/shared/webhost/bullseyeWebHost.js +1394 -0
- package/dist/shared/webhost/openedWorkspaces.js +62 -0
- package/dist/shared/webhost/originHandover.js +607 -0
- package/dist/shared/webhost/package.json +1 -0
- package/dist/shared/webhost/userSession.js +178 -0
- package/dist/shared/webhost/webviewShim.js +434 -0
- package/dist/shared/webhost/workspaceList.js +642 -0
- package/package.json +1 -1
- package/scripts/shared/ownerGuard.cs +665 -0
- package/scripts/shared/ownerGuard.ps1 +31 -0
|
@@ -0,0 +1,316 @@
|
|
|
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 (`gateway/conversations.ts`) beside
|
|
6
|
+
* the REST door's, and driven by the one session driver (`gateway/sessionDriver.ts`, #2051): the start line, the
|
|
7
|
+
* status lines, a permission question and the answer come back to the chat, the answer split at 500 characters
|
|
8
|
+
* with (k/N) parts. `/stop` ends the chat's conversation and `/new` ends it so the next `!` opens a fresh one.
|
|
9
|
+
* An email thread (#2105) is one conversation for good, and gets only its answer, question or failure, each whole.
|
|
10
|
+
* Every conversation starts in Meni's workspace root, as the web page's and the MCP door's do.
|
|
11
|
+
*/
|
|
12
|
+
import { fileURLToPath } from "url";
|
|
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/conversations.js";
|
|
16
|
+
import { SessionDriver } from "./gateway/sessionDriver.js";
|
|
17
|
+
import { clearOpenCodeLogs } from "./gateway/opencodeProvider.js";
|
|
18
|
+
import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
|
|
19
|
+
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
|
+
const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
|
|
42
|
+
const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
|
|
43
|
+
function driverOptions() {
|
|
44
|
+
const guardDir = fileURLToPath(new URL("../scripts/shared/", import.meta.url));
|
|
45
|
+
// GATE: a stand-in CLI, a warm spare a test asks for, a smaller capacity and shorter idle, silent, stall and archive spells are read ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1; without it the CLI is `claude`, the spare is kept, and the numbers are Meni's ten slots, his 8-hour idle spell, his 2- and 15-minute turn bounds and his 8-hour archive bound.
|
|
46
|
+
if (process.env.NOTIFY_MCP_TEST_ENDPOINTS !== "1")
|
|
47
|
+
return { guardDir };
|
|
48
|
+
const script = process.env.NOTIFY_AGENT_CLI_SCRIPT;
|
|
49
|
+
const copilot = process.env.NOTIFY_AGENT_COPILOT_SCRIPT;
|
|
50
|
+
const codex = process.env.NOTIFY_AGENT_CODEX_SCRIPT;
|
|
51
|
+
const opencode = process.env.NOTIFY_AGENT_OPENCODE_SCRIPT;
|
|
52
|
+
return {
|
|
53
|
+
guardDir,
|
|
54
|
+
spare: process.env.NOTIFY_AGENT_SPARE === "1" ? true : undefined,
|
|
55
|
+
clis: {
|
|
56
|
+
...(script ? { claude: { cmd: process.execPath, args: [script] } } : {}),
|
|
57
|
+
...(copilot ? { copilot: { cmd: process.execPath, args: [copilot] } } : {}),
|
|
58
|
+
...(codex ? { codex: { cmd: process.execPath, args: [codex] } } : {}),
|
|
59
|
+
...(opencode ? { opencode: { cmd: process.execPath, args: [opencode] } } : {}),
|
|
60
|
+
},
|
|
61
|
+
capacity: process.env.NOTIFY_AGENT_CAPACITY ? Number(process.env.NOTIFY_AGENT_CAPACITY) : undefined,
|
|
62
|
+
idleMs: process.env.NOTIFY_AGENT_IDLE_MS ? Number(process.env.NOTIFY_AGENT_IDLE_MS) : undefined,
|
|
63
|
+
silentMs: process.env.NOTIFY_AGENT_SILENT_MS ? Number(process.env.NOTIFY_AGENT_SILENT_MS) : undefined,
|
|
64
|
+
stallMs: process.env.NOTIFY_AGENT_STALL_MS ? Number(process.env.NOTIFY_AGENT_STALL_MS) : undefined,
|
|
65
|
+
archiveIdleMs: process.env.NOTIFY_AGENT_ARCHIVE_IDLE_MS ? Number(process.env.NOTIFY_AGENT_ARCHIVE_IDLE_MS) : undefined,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export class AgentGateway {
|
|
69
|
+
driver;
|
|
70
|
+
static self;
|
|
71
|
+
static instance() {
|
|
72
|
+
return (AgentGateway.self ??= new AgentGateway(new SessionDriver(driverOptions())));
|
|
73
|
+
}
|
|
74
|
+
/** The messages waiting on their answer, by conversation and user event. */
|
|
75
|
+
turns = new Map();
|
|
76
|
+
doors = new Map();
|
|
77
|
+
recovered = false;
|
|
78
|
+
constructor(driver) {
|
|
79
|
+
this.driver = driver;
|
|
80
|
+
driver.onEvent((event) => this.deliver(event));
|
|
81
|
+
driver.onEvent(turnEnded);
|
|
82
|
+
}
|
|
83
|
+
registerDoor(platform, door) {
|
|
84
|
+
this.doors.set(platform, door);
|
|
85
|
+
}
|
|
86
|
+
/** Starts the driver in the process that owns the pollers, then takes back every turn the last process owed its thread an answer for. */
|
|
87
|
+
boot() {
|
|
88
|
+
clearOpenCodeLogs();
|
|
89
|
+
this.driver.boot();
|
|
90
|
+
if (this.recovered)
|
|
91
|
+
return;
|
|
92
|
+
this.recovered = true;
|
|
93
|
+
resendUndelivered();
|
|
94
|
+
for (const c of listConversations())
|
|
95
|
+
this.recover(c);
|
|
96
|
+
}
|
|
97
|
+
/** 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. */
|
|
98
|
+
recover(c) {
|
|
99
|
+
const owed = Object.entries(c.owed ?? {});
|
|
100
|
+
if (owed.length === 0)
|
|
101
|
+
return;
|
|
102
|
+
if (c.state === "closed")
|
|
103
|
+
return editOwed(c.id, (o) => { for (const [turn] of owed)
|
|
104
|
+
delete o[turn]; });
|
|
105
|
+
const door = this.doors.get(c.platform);
|
|
106
|
+
if (door === undefined)
|
|
107
|
+
throw new Error(`conversation ${c.id} on ${c.platform} is owed an answer and no door of that platform is registered before boot`);
|
|
108
|
+
for (const [turn, sent] of owed) {
|
|
109
|
+
const pending = readEvents(c.id).filter((e) => e.turn === Number(turn) && e.n > sent && e.role !== "user").map((e) => ({ ...e, id: c.id }));
|
|
110
|
+
// OWNER: ITER/LOOP — a thread that cannot be reached is shown on its conversation and the next owed turn is still carried on.
|
|
111
|
+
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)}` }));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** 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. */
|
|
115
|
+
quiet() {
|
|
116
|
+
return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
|
|
117
|
+
}
|
|
118
|
+
/** Gives the store back when this process hands the gateway over. */
|
|
119
|
+
async shutdown() {
|
|
120
|
+
await this.driver.shutdown();
|
|
121
|
+
this.recovered = false;
|
|
122
|
+
}
|
|
123
|
+
/** What this message asks of the agent, or undefined when it is not addressed to it and belongs to the inbox. */
|
|
124
|
+
classify(key, raw) {
|
|
125
|
+
const text = raw.trim();
|
|
126
|
+
if (text.startsWith(AGENT_PREFIX)) {
|
|
127
|
+
const body = text.slice(AGENT_PREFIX.length).trim();
|
|
128
|
+
const cmd = body.match(COMMAND_RE);
|
|
129
|
+
if (cmd)
|
|
130
|
+
return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
|
|
131
|
+
return { kind: "say", text: body };
|
|
132
|
+
}
|
|
133
|
+
const cmd = text.match(COMMAND_RE);
|
|
134
|
+
if (cmd && openConversationOf(key) !== undefined)
|
|
135
|
+
return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
/** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
|
|
139
|
+
classifyInThread(key, raw) {
|
|
140
|
+
return this.classify(key, raw) ?? { kind: "say", text: raw.trim() };
|
|
141
|
+
}
|
|
142
|
+
/** Whether this email message was already taken as a turn of some conversation, so a BN restart never answers it twice. */
|
|
143
|
+
emailTaken(messageId) {
|
|
144
|
+
// NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
|
|
145
|
+
return listConversations().some((c) => c.email !== undefined && c.email.messageIds.includes(messageId));
|
|
146
|
+
}
|
|
147
|
+
/** Shows on this chat key's conversation that its answer never reached the chat, so the web page tells what the chat could not. */
|
|
148
|
+
noteUndelivered(key, platform, text) {
|
|
149
|
+
const c = CARRIAGE[platform].conversationOf(key);
|
|
150
|
+
// NULL-OK: field c is OPTIONAL and therefore it is ok to check for NULL
|
|
151
|
+
if (c === undefined)
|
|
152
|
+
return;
|
|
153
|
+
appendEvent(c.id, { role: "system", kind: "status", text });
|
|
154
|
+
}
|
|
155
|
+
openSlackThreads() {
|
|
156
|
+
const newestOfThread = new Set();
|
|
157
|
+
return listConversations().filter((c) => {
|
|
158
|
+
if (c.platform !== "slack" || c.state === "closed" || c.slack === undefined || newestOfThread.has(c.chat ?? c.id))
|
|
159
|
+
return false;
|
|
160
|
+
newestOfThread.add(c.chat ?? c.id);
|
|
161
|
+
return true;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
/** Records how far a Slack thread has been read. */
|
|
165
|
+
markSlackRead(key, readTs) {
|
|
166
|
+
for (const c of openConversationsOf(key))
|
|
167
|
+
updateConversation(c.id, { slack: { ...c.slack, readTs } });
|
|
168
|
+
}
|
|
169
|
+
/** Acts on one addressed message. Resolves when its answer (or its failure) has been sent back. */
|
|
170
|
+
async handle(key, platform, act, reply, origin = {}) {
|
|
171
|
+
const arrived = monotonicMs();
|
|
172
|
+
const carriage = CARRIAGE[platform];
|
|
173
|
+
const refusal = conversationRefusal();
|
|
174
|
+
// A muted BN answers nobody: the refusal is spoken to the chat only when the switch, not Mute everything, is what is off.
|
|
175
|
+
if (refusal === CONVERSATION_MUTED_MESSAGE)
|
|
176
|
+
return;
|
|
177
|
+
if (refusal !== undefined)
|
|
178
|
+
return reply(refusal);
|
|
179
|
+
// NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
|
|
180
|
+
for (let pending = creationPending(key); pending !== undefined; pending = creationPending(key))
|
|
181
|
+
await pending;
|
|
182
|
+
const open = carriage.conversationOf(key);
|
|
183
|
+
if (act.kind === "stop") {
|
|
184
|
+
const stopped = carriage.stopOf(key);
|
|
185
|
+
// NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
|
|
186
|
+
if (stopped === undefined)
|
|
187
|
+
return reply("Nothing to stop here — no conversation is open.");
|
|
188
|
+
this.end(stopped.id);
|
|
189
|
+
const others = carriage.allOf(key).filter((c) => c.id !== stopped.id).length;
|
|
190
|
+
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.`);
|
|
191
|
+
}
|
|
192
|
+
if (act.kind === "new") {
|
|
193
|
+
// NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
|
|
194
|
+
if (open !== undefined)
|
|
195
|
+
this.end(open.id);
|
|
196
|
+
const stay = carriage.allOf(key).length;
|
|
197
|
+
return reply(stay === 0 ? "🆕 New conversation. Your next ! message starts it." : `🆕 Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`);
|
|
198
|
+
}
|
|
199
|
+
if (act.text === "")
|
|
200
|
+
return reply("Send `! <your message>` to talk to the agent.");
|
|
201
|
+
const target = carriage.routeOf(key, act.text);
|
|
202
|
+
// NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
|
|
203
|
+
if (target === undefined) {
|
|
204
|
+
let project;
|
|
205
|
+
try {
|
|
206
|
+
project = resolveProject(undefined, act.text);
|
|
207
|
+
}
|
|
208
|
+
catch (err) {
|
|
209
|
+
// 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
|
|
210
|
+
if (err instanceof GatewayError)
|
|
211
|
+
return reply(err.message);
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
// A conversation opened in a thread the chat already reads starts reading after what was read, never from the thread's root again.
|
|
215
|
+
// NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
|
|
216
|
+
const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
|
|
217
|
+
const turn = {};
|
|
218
|
+
const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
|
|
219
|
+
const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
|
|
220
|
+
// NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
|
|
221
|
+
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.`)];
|
|
222
|
+
turn.answered = this.awaitTurn(created.id, 1, reply, carriage, told);
|
|
223
|
+
turn.id = created.id;
|
|
224
|
+
return created;
|
|
225
|
+
})]);
|
|
226
|
+
if (creation.status === "rejected") {
|
|
227
|
+
// NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
|
|
228
|
+
if (turn.id === undefined)
|
|
229
|
+
throw creation.reason;
|
|
230
|
+
const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
|
|
231
|
+
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`);
|
|
232
|
+
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}`));
|
|
233
|
+
return turn.answered;
|
|
234
|
+
}
|
|
235
|
+
// NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
|
|
236
|
+
if (creation.value.notice !== undefined)
|
|
237
|
+
this.deliver({ ...creation.value.notice, id: creation.value.made.id });
|
|
238
|
+
return turn.answered;
|
|
239
|
+
}
|
|
240
|
+
// NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
|
|
241
|
+
if (origin.email !== undefined)
|
|
242
|
+
updateConversation(target.id, { email: { ...target.email, messageIds: [...target.email.messageIds, ...origin.email.messageIds] } });
|
|
243
|
+
const sent = sendToConversation(target.id, act.text, monotonicMs() - arrived);
|
|
244
|
+
// NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
|
|
245
|
+
const notice = queueNoticeOf(target.id, sent.n);
|
|
246
|
+
// NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
|
|
247
|
+
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.`)] : [];
|
|
248
|
+
return this.awaitTurn(target.id, sent.n, reply, carriage, [...told, ...(notice === undefined ? [] : [{ ...notice, id: target.id }])]);
|
|
249
|
+
}
|
|
250
|
+
/** 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. */
|
|
251
|
+
told(id, n, text) {
|
|
252
|
+
return { id, n, turn: n, role: "system", kind: "status", text, ts: new Date().toISOString() };
|
|
253
|
+
}
|
|
254
|
+
end(id) {
|
|
255
|
+
for (const turn of this.turns.get(id)?.values() ?? [])
|
|
256
|
+
turn.close();
|
|
257
|
+
this.turns.delete(id);
|
|
258
|
+
this.driver.stop(id);
|
|
259
|
+
editOwed(id, (o) => { for (const turn of Object.keys(o))
|
|
260
|
+
delete o[turn]; });
|
|
261
|
+
}
|
|
262
|
+
/** 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. */
|
|
263
|
+
awaitTurn(id, n, reply, carriage, pending = []) {
|
|
264
|
+
editOwed(id, (o) => { o[n] ??= n; });
|
|
265
|
+
let wake = () => { };
|
|
266
|
+
let closed = false;
|
|
267
|
+
const turns = this.turns.get(id) ?? new Map();
|
|
268
|
+
turns.set(n, { push: (event) => { pending.push(event); wake(); }, close: () => { closed = true; wake(); } });
|
|
269
|
+
this.turns.set(id, turns);
|
|
270
|
+
return (async () => {
|
|
271
|
+
for (;;) {
|
|
272
|
+
if (pending.length === 0) {
|
|
273
|
+
if (closed)
|
|
274
|
+
return;
|
|
275
|
+
await new Promise((resolve) => { wake = resolve; });
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
const event = pending.shift();
|
|
279
|
+
// A muted BN sends nothing and keeps the answer owed, so the next BN start delivers it once Mute everything is Off.
|
|
280
|
+
const muted = masterMuted();
|
|
281
|
+
if (!muted && carriage.carries(event.kind))
|
|
282
|
+
for (const part of carriage.parts(event))
|
|
283
|
+
await reply(part);
|
|
284
|
+
const final = FINAL_KINDS.has(event.kind ?? "");
|
|
285
|
+
if (!closed && !muted)
|
|
286
|
+
editOwed(id, (o) => { if (final)
|
|
287
|
+
delete o[n];
|
|
288
|
+
else
|
|
289
|
+
o[n] = event.n; });
|
|
290
|
+
if (final) {
|
|
291
|
+
// NULL-OK: field turns is OPTIONAL and therefore it is ok to check for NULL
|
|
292
|
+
this.turns.get(id)?.delete(n);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
})();
|
|
297
|
+
}
|
|
298
|
+
deliver(event) {
|
|
299
|
+
const turns = this.turns.get(event.id);
|
|
300
|
+
// NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
|
|
301
|
+
if (event.turn === undefined && turns !== undefined) {
|
|
302
|
+
for (const waiting of turns.values())
|
|
303
|
+
waiting.push(event);
|
|
304
|
+
this.turns.delete(event.id);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
// NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
|
|
308
|
+
const turn = event.turn === undefined ? undefined : turns?.get(event.turn);
|
|
309
|
+
// NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
|
|
310
|
+
if (turn === undefined)
|
|
311
|
+
return;
|
|
312
|
+
turn.push(event);
|
|
313
|
+
if (FINAL_KINDS.has(event.kind ?? ""))
|
|
314
|
+
turns.delete(event.turn);
|
|
315
|
+
}
|
|
316
|
+
}
|
package/dist/chunk.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const NOTIFY_CHUNK_LIMIT = 500;
|
|
2
|
+
function packChunks(message, body, wordAware) {
|
|
3
|
+
const chunks = [];
|
|
4
|
+
let rest = message;
|
|
5
|
+
while (rest.length > body) {
|
|
6
|
+
let cut = body;
|
|
7
|
+
if (wordAware) {
|
|
8
|
+
const window = rest.slice(0, body + 1);
|
|
9
|
+
const brk = Math.max(window.lastIndexOf(" "), window.lastIndexOf("\n"));
|
|
10
|
+
if (brk >= Math.floor(body * 0.6))
|
|
11
|
+
cut = brk;
|
|
12
|
+
}
|
|
13
|
+
chunks.push(rest.slice(0, cut).replace(/\s+$/, ""));
|
|
14
|
+
rest = rest.slice(cut).replace(/^\s+/, "");
|
|
15
|
+
}
|
|
16
|
+
if (rest.length)
|
|
17
|
+
chunks.push(rest);
|
|
18
|
+
return chunks;
|
|
19
|
+
}
|
|
20
|
+
export function splitForNotify(message, limit = NOTIFY_CHUNK_LIMIT) {
|
|
21
|
+
if (message.length <= limit)
|
|
22
|
+
return [message];
|
|
23
|
+
let parts = Math.ceil(message.length / limit);
|
|
24
|
+
for (;;) {
|
|
25
|
+
const reserve = `(${parts}/${parts}) `.length;
|
|
26
|
+
const needed = Math.ceil(message.length / Math.max(1, limit - reserve));
|
|
27
|
+
if (needed <= parts)
|
|
28
|
+
break;
|
|
29
|
+
parts = needed;
|
|
30
|
+
}
|
|
31
|
+
const body = Math.max(1, limit - `(${parts}/${parts}) `.length);
|
|
32
|
+
let chunks = packChunks(message, body, true);
|
|
33
|
+
if (chunks.length > parts)
|
|
34
|
+
chunks = packChunks(message, body, false);
|
|
35
|
+
const total = chunks.length;
|
|
36
|
+
return chunks.map((chunk, i) => `(${i + 1}/${total}) ${chunk}`);
|
|
37
|
+
}
|
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* notify's daemon — the one process per machine, started by the boot supervisor.
|
|
4
|
+
*
|
|
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
|
+
* 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
|
|
9
|
+
* inbox files under the config dir: nothing is held only in its memory, so a restart of this process loses no message.
|
|
10
|
+
*/
|
|
11
|
+
import { spawn } from "child_process";
|
|
12
|
+
import { existsSync, readFileSync, mkdirSync } from "fs";
|
|
13
|
+
import { join } from "path";
|
|
14
|
+
import { fileURLToPath } from "url";
|
|
15
|
+
import { DAEMON_BEAT_PATH, CONFIG_DIR, DAEMON_TAG, PACKAGE_VERSION, startNotifyServer, takePendingInbox, yieldGateway } from "./notify.js";
|
|
16
|
+
import { startNotifyDoor } from "./gateway/notifyDoor.js";
|
|
17
|
+
import { writeRecordFile } from "./gateway/conversations.js";
|
|
18
|
+
import { announceTakeover, inThisBoot } from "./shared/webhost/originHandover.js";
|
|
19
|
+
import { TunnelRunner } from "./gateway/tunnel.js";
|
|
20
|
+
const HEARTBEAT_MS = 10_000;
|
|
21
|
+
function beat(pid = process.pid) {
|
|
22
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
23
|
+
writeRecordFile(DAEMON_BEAT_PATH, JSON.stringify({ pid, at: Date.now(), version: PACKAGE_VERSION }));
|
|
24
|
+
}
|
|
25
|
+
/** The boot supervisor's login entry: launchd's label and systemd's unit. */
|
|
26
|
+
const ENTRY_LABEL = "com.bullseye.BullseyeMcpOrigins";
|
|
27
|
+
const ENTRY_UNIT = "bullseye-mcp-origins.service";
|
|
28
|
+
/** BN's lifecycle in the config dir, which the login entry and the boot task keep. */
|
|
29
|
+
const SUPERVISE_LOOP = join(CONFIG_DIR, "bnDaemon.js");
|
|
30
|
+
/** The Stop the panel writes. */
|
|
31
|
+
const STOP_FILE = join(CONFIG_DIR, "daemon-stop.json");
|
|
32
|
+
/** Run by the boot supervisor (BullseyeShared workspace-mcp/originSupervisor.js, under the login starter every Bullseye extension installs), or on Windows by the login session's supervise loop in bnDaemon.js, each of which starts it again when it exits. On Windows that supervisor is this process's IPC parent: the channel is open only while it lives, so a dead supervisor, or a reused pid, never reads as supervised. */
|
|
33
|
+
function supervised() {
|
|
34
|
+
if (process.platform === "win32")
|
|
35
|
+
return process.connected === true;
|
|
36
|
+
if (process.platform === "darwin")
|
|
37
|
+
return process.env.XPC_SERVICE_NAME === ENTRY_LABEL;
|
|
38
|
+
if (process.platform !== "linux")
|
|
39
|
+
return false;
|
|
40
|
+
const cgroup = readFileSync("/proc/self/cgroup", "utf8");
|
|
41
|
+
return cgroup.includes(ENTRY_UNIT);
|
|
42
|
+
}
|
|
43
|
+
/** Who starts the installed build after this unsupervised process exits: on Windows the supervise loop the login entry and the boot task keep in the config dir, which owns every run after this one; elsewhere the same entry, started again. */
|
|
44
|
+
function successor() {
|
|
45
|
+
const self = fileURLToPath(import.meta.url);
|
|
46
|
+
if (process.platform !== "win32")
|
|
47
|
+
return spawn(process.execPath, [...process.execArgv, self], { detached: true, stdio: "ignore", windowsHide: true });
|
|
48
|
+
if (!existsSync(SUPERVISE_LOOP))
|
|
49
|
+
throw new Error(`the supervise loop is not in the config dir at ${SUPERVISE_LOOP} — the login entry and the boot task copy it there, so nothing can own the next run`);
|
|
50
|
+
return spawn(process.execPath, [SUPERVISE_LOOP, "supervise"], { detached: true, stdio: "ignore", windowsHide: true });
|
|
51
|
+
}
|
|
52
|
+
/** The installed build has replaced this one on disk: a supervised process only exits and its owner starts that build; an unsupervised one starts its successor and names it in the heartbeat before it exits, so no other owner starts a second build meanwhile, and on Windows the supervise loop reads that beat as the claim on its first run. */
|
|
53
|
+
function replaceWithInstalledBuild() {
|
|
54
|
+
clearInterval(beatTimer);
|
|
55
|
+
if (!supervised()) {
|
|
56
|
+
const next = successor();
|
|
57
|
+
next.unref();
|
|
58
|
+
if (next.pid !== undefined)
|
|
59
|
+
beat(next.pid);
|
|
60
|
+
}
|
|
61
|
+
process.exit(0);
|
|
62
|
+
}
|
|
63
|
+
function pressedIn(file) {
|
|
64
|
+
if (!existsSync(file))
|
|
65
|
+
return undefined;
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
throw new Error(`${file} is not readable JSON, so whether a Stop was pressed on this machine cannot be known — ${err.message}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** The Stop the panel pressed is this machine's own setting until a Start or the next boot (#3849 Q782), so a process a login entry started after it in this boot reads the same file and starts nothing. Absent, the machine has never been stopped and starts as it always has. */
|
|
74
|
+
function stoppedByHand() {
|
|
75
|
+
const pressed = pressedIn(STOP_FILE);
|
|
76
|
+
if (pressed === undefined)
|
|
77
|
+
return false;
|
|
78
|
+
if (pressed.desired !== "stopped")
|
|
79
|
+
return false;
|
|
80
|
+
if (typeof pressed.at !== "number")
|
|
81
|
+
throw new Error(`${STOP_FILE} names a Stop with no time it was pressed, so whether it was pressed in this boot cannot be known`);
|
|
82
|
+
return inThisBoot(pressed.at);
|
|
83
|
+
}
|
|
84
|
+
if (stoppedByHand()) {
|
|
85
|
+
console.log("[BOOT] BullseyeNotify daemon — a Stop was pressed on this machine; nothing started, and nothing beats until Start is pressed in the panel or the machine reboots.");
|
|
86
|
+
process.exit(0);
|
|
87
|
+
}
|
|
88
|
+
// The shared hand-over (src/shared/webhost/originHandover.js ensureResidentDoor) puts a later release on the chat door: the new build is started with --takeover over an IPC channel, says it waits, and binds once this build lets the door go.
|
|
89
|
+
const takeover = process.argv.includes("--takeover");
|
|
90
|
+
/** Whether this process writes the heartbeat: the next release only from the moment it holds the chat door, so a takeover that never lands leaves the serving build's beat alone; and a build that let the door go no longer, so the release that took it is the one beat. */
|
|
91
|
+
let beating = !takeover;
|
|
92
|
+
// The server's own timers are unref'd, so this beat and the door hold the process until it is stopped.
|
|
93
|
+
if (beating)
|
|
94
|
+
beat();
|
|
95
|
+
/** Each tick reads the Stop first, beating or not: a press in a window that may not end this process — the boot task's, in session 0, or one still draining its gateway after a hand-over — stops it all the same, within one tick. */
|
|
96
|
+
const beatTimer = setInterval(() => {
|
|
97
|
+
if (stoppedByHand())
|
|
98
|
+
process.exit(0);
|
|
99
|
+
if (beating)
|
|
100
|
+
beat();
|
|
101
|
+
}, HEARTBEAT_MS);
|
|
102
|
+
/** Settles once the chat door has closed after the next release's `POST /shutdown`; set only then, when that release is already running and waiting for the port, so this process starts no successor. */
|
|
103
|
+
let handedOver;
|
|
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
|
+
const tunnel = new TunnelRunner();
|
|
106
|
+
const daemonHost = {
|
|
107
|
+
clientId: DAEMON_TAG, tag: DAEMON_TAG,
|
|
108
|
+
onDoorOwned: (port) => {
|
|
109
|
+
tunnel.beat(port);
|
|
110
|
+
setInterval(() => tunnel.beat(port), HEARTBEAT_MS);
|
|
111
|
+
},
|
|
112
|
+
onSuperseded: () => (handedOver === undefined ? replaceWithInstalledBuild() : void handedOver.then(() => process.exit(0))),
|
|
113
|
+
};
|
|
114
|
+
startNotifyServer(daemonHost);
|
|
115
|
+
takePendingInbox();
|
|
116
|
+
startNotifyDoor(() => { beating = true; beat(); }, undefined, {
|
|
117
|
+
version: PACKAGE_VERSION,
|
|
118
|
+
takeover,
|
|
119
|
+
onShutdown: (closed) => {
|
|
120
|
+
beating = false;
|
|
121
|
+
handedOver = closed;
|
|
122
|
+
yieldGateway();
|
|
123
|
+
},
|
|
124
|
+
onTakeoverGaveUp: () => process.exit(1),
|
|
125
|
+
});
|
|
126
|
+
if (takeover)
|
|
127
|
+
announceTakeover();
|
|
128
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
129
|
+
process.on(signal, () => process.exit(0));
|
|
130
|
+
}
|
|
131
|
+
process.on("exit", () => tunnel.stop());
|