omni-notify-mcp 1.3.450 → 1.3.451

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 (69) hide show
  1. package/dist/agentGateway.js +555 -0
  2. package/dist/channelReading.cjs +18 -0
  3. package/dist/chunk.js +41 -0
  4. package/dist/daemon.js +131 -0
  5. package/dist/desk.js +268 -0
  6. package/dist/gateway/chatPage.js +944 -0
  7. package/dist/gateway/conversationOwner.js +141 -0
  8. package/dist/gateway/extensionModule.js +20 -0
  9. package/dist/gateway/gatewayInstall.js +83 -0
  10. package/dist/gateway/iconData.js +8 -0
  11. package/dist/gateway/iconDoor.js +23 -0
  12. package/dist/gateway/lanProbe.js +86 -0
  13. package/dist/gateway/mcpDoor.js +411 -0
  14. package/dist/gateway/mcpEvents.js +448 -0
  15. package/dist/gateway/mcpHosts.js +19 -0
  16. package/dist/gateway/notifyDoor.js +166 -0
  17. package/dist/gateway/oauthDoor.js +345 -0
  18. package/dist/gateway/panel.js +303 -0
  19. package/dist/gateway/panelPage.js +388 -0
  20. package/dist/gateway/passkeyClient.js +47 -0
  21. package/dist/gateway/passkeyDoor.js +974 -0
  22. package/dist/gateway/publicAccess.js +374 -0
  23. package/dist/gateway/restDoor.js +327 -0
  24. package/dist/gateway/terminalDoor.js +247 -0
  25. package/dist/gateway/terminalPage.js +619 -0
  26. package/dist/gateway/tunnel.js +166 -0
  27. package/dist/gatewayInstall.cjs +59 -0
  28. package/dist/mcpHosts.cjs +454 -0
  29. package/dist/messaging/chatInbound.js +405 -0
  30. package/dist/messaging/decisionDigit.js +84 -0
  31. package/dist/messaging/deliveryVerdict.js +52 -0
  32. package/dist/messaging/emailInbound.js +292 -0
  33. package/dist/messaging/inboundPayloads.js +41 -0
  34. package/dist/messaging/messenger.js +482 -0
  35. package/dist/messaging/notificationEngine.js +198 -0
  36. package/dist/messaging/telegramError.js +6 -0
  37. package/dist/messaging/telegramFormat.js +95 -0
  38. package/dist/notify.js +3122 -0
  39. package/dist/shared/agentSession.js +6808 -0
  40. package/dist/shared/conversation/claudeProvider.js +358 -0
  41. package/dist/shared/conversation/cliSession.js +452 -0
  42. package/dist/shared/conversation/codexArchive.js +67 -0
  43. package/dist/shared/conversation/codexProvider.js +193 -0
  44. package/dist/shared/conversation/conversationOwner.js +44 -0
  45. package/dist/shared/conversation/conversations.js +930 -0
  46. package/dist/shared/conversation/copilotProvider.js +151 -0
  47. package/dist/shared/conversation/nativeCliInvocation.js +70 -0
  48. package/dist/shared/conversation/nativeTerminal.js +529 -0
  49. package/dist/shared/conversation/nativeTerminalWorker.js +158 -0
  50. package/dist/shared/conversation/opencodeEvents/server.mjs +32 -0
  51. package/dist/shared/conversation/opencodeProvider.js +316 -0
  52. package/dist/shared/conversation/ownerContext.js +1 -0
  53. package/dist/shared/conversation/provider.js +38 -0
  54. package/dist/shared/conversation/providers.js +30 -0
  55. package/dist/shared/conversation/sessionDriver.js +1070 -0
  56. package/dist/shared/conversation/terminalTransport.js +126 -0
  57. package/dist/shared/providerOwnership.js +294 -0
  58. package/dist/shared/webhost/autoSwitch.cjs +2438 -0
  59. package/dist/shared/webhost/bullseyeWebHost.js +1443 -0
  60. package/dist/shared/webhost/homeRelative.js +19 -0
  61. package/dist/shared/webhost/originHandover.js +653 -0
  62. package/dist/shared/webhost/package.json +1 -0
  63. package/dist/shared/webhost/userSession.js +178 -0
  64. package/dist/shared/webhost/webviewShim.js +851 -0
  65. package/dist/shared/webhost/workspaceList.js +691 -0
  66. package/dist/shared/workspaceList.js +1 -0
  67. package/package.json +1 -1
  68. package/scripts/shared/ownerGuard.cs +665 -0
  69. package/scripts/shared/ownerGuard.ps1 +31 -0
@@ -0,0 +1,555 @@
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.
12
+ */
13
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "fs";
14
+ import { homedir } from "os";
15
+ import { join } from "path";
16
+ import { splitForNotify } from "./chunk.js";
17
+ import { choicesOf, StreamedReply } from "./messaging/messenger.js";
18
+ import { appendEvent, archiveConversation, conversationRefusal, openConversation, readConversation, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, rootFolder, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversationOwner.js";
19
+ import { conversationOwner } from "./gateway/conversationOwner.js";
20
+ import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
21
+ import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
22
+ export const AGENT_PREFIX = "!";
23
+ /** The thread's newest conversation is ended; the next message opens a fresh one. */
24
+ async function endNewest(key, _platform, end) {
25
+ const open = this.conversationOf(key);
26
+ // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
27
+ if (open !== undefined)
28
+ end(open.id);
29
+ const stay = this.allOf(key).length;
30
+ return stay === 0 ? "🆕 New conversation. Your next ! message starts it." : `🆕 Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`;
31
+ }
32
+ const stoppedOfMany = (stopped, others) => 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.`;
33
+ /** Each carried event of a turn sent as its parts. */
34
+ function partsRelay(reply, carriage) {
35
+ return {
36
+ async event(event) {
37
+ if (carriage.carries(event.kind))
38
+ for (const part of carriage.parts(event))
39
+ await reply(part);
40
+ },
41
+ close: () => { },
42
+ };
43
+ }
44
+ /** A chat: the newest conversation not stopped (`/new` and `/stop` end it), and every line of the turn, the answer split at 500. */
45
+ const CHAT = {
46
+ conversationOf: openConversationOf,
47
+ routeOf: routeAsk,
48
+ stopOf: stopTargetOf,
49
+ allOf: openConversationsOf,
50
+ carries: (kind) => kind !== "returned",
51
+ parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
52
+ stopped: stoppedOfMany,
53
+ renew: endNewest,
54
+ folderOf: (text) => resolveProject(undefined, text),
55
+ };
56
+ /** Meni's one private chat with the bot (#4453): its newest conversation not deleted — an idle archive keeps it bound, only /new replaces it. */
57
+ const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted");
58
+ /** The bound chat: ONE conversation at the workspace root, every message goes on with it, a stop pauses it, /new opens the next one at once. */
59
+ const ONE = {
60
+ conversationOf: boundOf,
61
+ routeOf: boundOf,
62
+ stopOf: boundOf,
63
+ allOf: (key) => [boundOf(key)].filter((c) => c !== undefined),
64
+ carries: CHAT.carries,
65
+ parts: CHAT.parts,
66
+ stopped: () => "⏹ Stopped. Your next message picks the conversation up where it stopped.",
67
+ folderOf: () => rootFolder(),
68
+ async renew(key, platform, end) {
69
+ const bound = boundOf(key);
70
+ // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
71
+ if (bound !== undefined) {
72
+ end(bound.id);
73
+ archiveConversation(bound.id);
74
+ }
75
+ const { notice } = await createdIn(rootFolder(), undefined, () => key, (on) => openConversation({ platform, chat: key, ...on }));
76
+ // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
77
+ return `🆕 Fresh conversation — your next message starts it.${notice === undefined ? "" : `\n${notice.text}`}`;
78
+ },
79
+ };
80
+ const MAILED_KINDS = new Set(["answer", "failed", "stopped"]);
81
+ /** An email thread: its one conversation, a stopped one resumed by the next reply; only what needs Meni is mailed, each whole. */
82
+ const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
83
+ const MAIL = {
84
+ conversationOf: THREADS_ONE,
85
+ routeOf: THREADS_ONE,
86
+ stopOf: THREADS_ONE,
87
+ allOf: (key) => listConversations().filter((c) => c.chat === key),
88
+ carries: (kind) => MAILED_KINDS.has(kind),
89
+ parts: (event) => [event.text],
90
+ stopped: stoppedOfMany,
91
+ renew: endNewest,
92
+ folderOf: (text) => resolveProject(undefined, text),
93
+ };
94
+ const CARRIAGE = { telegram: ONE, slack: CHAT, discord: CHAT, teams: CHAT, ntfy: CHAT, sms: CHAT, email: MAIL };
95
+ /** The key of Meni's direct-message chat with the bot on Slack (#4453): one conversation, as his Telegram chat is; a Slack channel thread keeps its own. */
96
+ export const SLACK_DM = "slack:dm:";
97
+ /** How a chat key's conversations are carried. */
98
+ function carriageOf(platform, key) {
99
+ return key.startsWith(SLACK_DM) ? ONE : CARRIAGE[platform];
100
+ }
101
+ const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
102
+ const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
103
+ export class AgentGateway {
104
+ driver;
105
+ static self;
106
+ static instance() {
107
+ return (AgentGateway.self ??= new AgentGateway(conversationOwner.driver));
108
+ }
109
+ /** The messages waiting on their answer, by conversation and user event. */
110
+ turns = new Map();
111
+ doors = new Map();
112
+ recovered = false;
113
+ constructor(driver) {
114
+ this.driver = driver;
115
+ driver.onEvent((event) => this.deliver(event));
116
+ driver.onEvent(turnEnded);
117
+ }
118
+ registerDoor(platform, door) {
119
+ this.doors.set(platform, door);
120
+ }
121
+ /** Starts the driver in the process that owns the pollers, then takes back every turn the last process owed its thread an answer for. */
122
+ boot() {
123
+ clearOpenCodeLogs();
124
+ this.driver.boot();
125
+ if (this.recovered)
126
+ return;
127
+ this.recovered = true;
128
+ resendUndelivered();
129
+ for (const c of listConversations())
130
+ this.recover(c);
131
+ }
132
+ /** 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. */
133
+ recover(c) {
134
+ const owed = Object.entries(c.owed ?? {});
135
+ if (owed.length === 0)
136
+ return;
137
+ if (c.state === "closed")
138
+ return editOwed(c.id, (o) => { for (const [turn] of owed)
139
+ delete o[turn]; });
140
+ const door = this.doors.get(c.platform);
141
+ if (door === undefined)
142
+ throw new Error(`conversation ${c.id} on ${c.platform} is owed an answer and no door of that platform is registered before boot`);
143
+ for (const [turn, sent] of owed) {
144
+ const pending = readEvents(c.id).filter((e) => e.turn === Number(turn) && e.n > sent && e.role !== "user").map((e) => ({ ...e, id: c.id }));
145
+ // OWNER: ITER/LOOP — a thread that cannot be reached is shown on its conversation and the next owed turn is still carried on.
146
+ void this.awaitTurn(c.id, Number(turn), partsRelay((part) => door(c, part), carriageOf(c.platform, c.chat ?? "")), 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)}` }));
147
+ }
148
+ }
149
+ /** 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. */
150
+ quiet() {
151
+ return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
152
+ }
153
+ /** Gives the store back when this process hands the gateway over. */
154
+ async shutdown() {
155
+ await this.driver.shutdown();
156
+ this.recovered = false;
157
+ }
158
+ /** What this message asks of the agent, or undefined when it is not addressed to it and belongs to the inbox. */
159
+ classify(key, raw) {
160
+ const text = raw.trim();
161
+ if (text.startsWith(AGENT_PREFIX)) {
162
+ const body = text.slice(AGENT_PREFIX.length).trim();
163
+ const cmd = body.match(COMMAND_RE);
164
+ if (cmd)
165
+ return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
166
+ return { kind: "say", text: body };
167
+ }
168
+ const cmd = text.match(COMMAND_RE);
169
+ if (cmd && openConversationOf(key) !== undefined)
170
+ return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
171
+ return undefined;
172
+ }
173
+ /**
174
+ * A message of the bound chat is all for its one conversation (#4453): `/new` and `/stop` act, anything else is said as it is — a leading `!`
175
+ * of the old door is taken off. A bare "new" or "stop" is a command only where `bare` says the chat cannot type a slash (Slack's own client
176
+ * takes "/new" as its slash command); in Telegram it is his answer — "new" to "a new or the existing branch?" — never the end of the conversation.
177
+ */
178
+ classifyChat(raw, bare) {
179
+ const said = raw.trim();
180
+ const text = said.replace(/^!\s*/, "");
181
+ const cmd = text.match(COMMAND_RE);
182
+ const commanded = cmd !== null && (bare || text.startsWith("/") || said.startsWith(AGENT_PREFIX));
183
+ return commanded ? { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" } : { kind: "say", text };
184
+ }
185
+ /** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
186
+ classifyInThread(key, raw) {
187
+ return this.classify(key, raw) ?? { kind: "say", text: raw.trim() };
188
+ }
189
+ /** Whether this email message was already taken as a turn of some conversation, so a BN restart never answers it twice. */
190
+ emailTaken(messageId) {
191
+ // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
192
+ return listConversations().some((c) => c.email !== undefined && c.email.messageIds.includes(messageId));
193
+ }
194
+ /** Shows on this chat key's conversation that its answer never reached the chat, so the web page tells what the chat could not. */
195
+ noteUndelivered(key, platform, text) {
196
+ const c = carriageOf(platform, key).conversationOf(key);
197
+ // NULL-OK: field c is OPTIONAL and therefore it is ok to check for NULL
198
+ if (c === undefined)
199
+ return;
200
+ appendEvent(c.id, { role: "system", kind: "status", text });
201
+ }
202
+ openSlackThreads() {
203
+ const newestOfThread = new Set();
204
+ return listConversations().filter((c) => {
205
+ if (c.platform !== "slack" || c.state === "closed" || c.slack === undefined || newestOfThread.has(c.chat ?? c.id))
206
+ return false;
207
+ newestOfThread.add(c.chat ?? c.id);
208
+ return true;
209
+ });
210
+ }
211
+ /** Records how far a Slack thread has been read. */
212
+ markSlackRead(key, readTs) {
213
+ for (const c of openConversationsOf(key))
214
+ updateConversation(c.id, { slack: { ...c.slack, readTs } });
215
+ }
216
+ /** Acts on one addressed message. Resolves when its answer (or its failure) has been sent back. */
217
+ async handle(key, platform, act, out, origin = {}) {
218
+ const arrived = monotonicMs();
219
+ const carriage = carriageOf(platform, key);
220
+ const reply = typeof out === "function" ? out : out.say;
221
+ const relayOf = (id, n, queued) => (typeof out === "function" ? partsRelay(out, carriage) : out.turn(id, n, queued));
222
+ const refusal = conversationRefusal();
223
+ if (refusal !== undefined)
224
+ return reply(refusal);
225
+ // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
226
+ for (let pending = creationPending(key); pending !== undefined; pending = creationPending(key))
227
+ await pending;
228
+ const open = carriage.conversationOf(key);
229
+ if (act.kind === "stop") {
230
+ const stopped = carriage.stopOf(key);
231
+ // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
232
+ if (stopped === undefined)
233
+ return reply("Nothing to stop here — no conversation is open.");
234
+ this.end(stopped.id);
235
+ return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => c.id !== stopped.id).length));
236
+ }
237
+ if (act.kind === "new")
238
+ return reply(await carriage.renew(key, platform, (id) => this.end(id)));
239
+ if (act.text === "")
240
+ return reply("Send `! <your message>` to talk to the agent.");
241
+ const target = carriage.routeOf(key, act.text);
242
+ // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
243
+ if (target === undefined) {
244
+ let project;
245
+ try {
246
+ project = carriage.folderOf(act.text);
247
+ }
248
+ catch (err) {
249
+ // 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
250
+ if (err instanceof GatewayError)
251
+ return reply(err.message);
252
+ throw err;
253
+ }
254
+ // A conversation opened in a thread the chat already reads starts reading after what was read, never from the thread's root again.
255
+ // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
256
+ const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
257
+ const turn = {};
258
+ const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
259
+ const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
260
+ // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
261
+ 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.`)];
262
+ turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false), told);
263
+ turn.id = created.id;
264
+ return created;
265
+ })]);
266
+ if (creation.status === "rejected") {
267
+ // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
268
+ if (turn.id === undefined)
269
+ throw creation.reason;
270
+ const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
271
+ 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`);
272
+ 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}`));
273
+ return turn.answered;
274
+ }
275
+ // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
276
+ if (creation.value.notice !== undefined)
277
+ this.deliver({ ...creation.value.notice, id: creation.value.made.id });
278
+ return turn.answered;
279
+ }
280
+ // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
281
+ if (origin.email !== undefined)
282
+ updateConversation(target.id, { email: { ...target.email, messageIds: [...target.email.messageIds, ...origin.email.messageIds] } });
283
+ const sent = sendToConversation(target.id, act.text, monotonicMs() - arrived);
284
+ // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
285
+ const notice = queueNoticeOf(target.id, sent.n);
286
+ // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
287
+ 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.`)] : [];
288
+ return this.awaitTurn(target.id, sent.n, relayOf(target.id, sent.n, notice !== undefined), [...told, ...(notice === undefined ? [] : [{ ...notice, id: target.id }])]);
289
+ }
290
+ /** 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. */
291
+ told(id, n, text) {
292
+ return { id, n, turn: n, role: "system", kind: "status", text, ts: new Date().toISOString() };
293
+ }
294
+ end(id) {
295
+ for (const turn of this.turns.get(id)?.values() ?? [])
296
+ turn.close();
297
+ this.turns.delete(id);
298
+ this.driver.stop(id);
299
+ editOwed(id, (o) => { for (const turn of Object.keys(o))
300
+ delete o[turn]; });
301
+ }
302
+ /** 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. */
303
+ awaitTurn(id, n, relay, pending = []) {
304
+ editOwed(id, (o) => { o[n] ??= n; });
305
+ let wake = () => { };
306
+ let closed = false;
307
+ const turns = this.turns.get(id) ?? new Map();
308
+ turns.set(n, { push: (event) => { pending.push(event); wake(); }, close: () => { closed = true; wake(); } });
309
+ this.turns.set(id, turns);
310
+ return (async () => {
311
+ for (;;) {
312
+ if (pending.length === 0) {
313
+ if (closed)
314
+ return relay.close();
315
+ await new Promise((resolve) => { wake = resolve; });
316
+ continue;
317
+ }
318
+ const event = pending.shift();
319
+ await relay.event(event).catch((err) => {
320
+ relay.close();
321
+ throw err;
322
+ });
323
+ const final = FINAL_KINDS.has(event.kind ?? "");
324
+ if (!closed)
325
+ editOwed(id, (o) => { if (final)
326
+ delete o[n];
327
+ else
328
+ o[n] = event.n; });
329
+ if (final) {
330
+ // NULL-OK: field turns is OPTIONAL and therefore it is ok to check for NULL
331
+ this.turns.get(id)?.delete(n);
332
+ return;
333
+ }
334
+ }
335
+ })();
336
+ }
337
+ deliver(event) {
338
+ const turns = this.turns.get(event.id);
339
+ // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
340
+ if (event.turn === undefined && turns !== undefined) {
341
+ for (const waiting of turns.values())
342
+ waiting.push(event);
343
+ this.turns.delete(event.id);
344
+ return;
345
+ }
346
+ // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
347
+ const turn = event.turn === undefined ? undefined : turns?.get(event.turn);
348
+ // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
349
+ if (turn === undefined)
350
+ return;
351
+ turn.push(event);
352
+ if (FINAL_KINDS.has(event.kind ?? ""))
353
+ turns.delete(event.turn);
354
+ }
355
+ }
356
+ /**
357
+ * What the bound chat's conversation is told before its first message (#4453), about 300 tokens: that it is BN's agent
358
+ * in Meni's one chat, how the work it hands off reports back (his words in notify's answers, #4123), how it labels a reply,
359
+ * what the chat can show, and how it asks him something there.
360
+ */
361
+ const chatBrief = (messenger) => `You are BN's agent in Meni's one ${messenger} chat with the BN bot: every message he sends the bot reaches you, and your reply streams back into that chat. Work exactly as the BN agent CLI does — answer a question directly; route a request to the project it belongs to, file it as a story on that project's board and let FleetView's queue run it, so this chat stays free for his next message; a story or lane you start reports back into this same chat — brief it with his own words, verbatim, to pass in the notify tool's answers when it tells him what he asked for, because notify refuses every other message.
362
+ Start every reply with a short bracketed label for the work it is about — the story id ([#4453]), the project ([AlphaWave]) or a few words — so he never has to pick a thread: you decide which work each message is about.
363
+ The chat shows bold, italic, code, links, bullets and emojis, never tables; keep replies short. Your reply already reaches the chat — never also send it with the notify tool.
364
+ Never use the AskUserQuestion tool here: its question stays on a screen he cannot see. To ask him, end the reply with the question and one line per choice starting with 🔘 — each becomes a choice he taps, and he may answer in his own words instead.`;
365
+ /** The text one message of the bound chat is sent as: the brief on the conversation's first turn, then what the chat knows around it, then his own words, last. */
366
+ export function chatTurnText(key, text, context) {
367
+ const bound = boundOf(key);
368
+ // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
369
+ const first = bound === undefined || !readEvents(bound.id).some((e) => e.role === "user");
370
+ return [...(first ? [chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram")] : []), ...context, text].join("\n\n");
371
+ }
372
+ /** The Claude CLI's own folder of session transcripts. */
373
+ function claudeProjects() {
374
+ return join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
375
+ }
376
+ /** Where the CLI keeps this session's transcript: found by its id across every folder, as the CLI itself finds it. */
377
+ function transcriptOf(sessionId) {
378
+ const projects = claudeProjects();
379
+ if (!existsSync(projects))
380
+ return undefined;
381
+ for (const dir of readdirSync(projects)) {
382
+ const file = join(projects, dir, `${sessionId}.jsonl`);
383
+ if (existsSync(file))
384
+ return file;
385
+ }
386
+ return undefined;
387
+ }
388
+ /** A file-system error Node names by its code (ENOENT, EBUSY, EPERM, …): the transcript moved, is locked or is gone. */
389
+ function fsFailure(err) {
390
+ return err instanceof Error && typeof err.code === "string";
391
+ }
392
+ /** A tool step as he reads it: the tool and what it is doing. */
393
+ function stepOf(block) {
394
+ const input = block.input ?? {};
395
+ const what = [input.description, input.command, input.file_path, input.pattern, input.url, input.prompt].find((v) => typeof v === "string" && v.trim() !== "");
396
+ // NULL-OK: field what is OPTIONAL and therefore it is ok to check for NULL
397
+ const shown = what === undefined ? "" : ` — ${what.replace(/\s+/g, " ").slice(0, 90)}`;
398
+ return `🔧 ${String(block.name ?? "tool")}${shown}`;
399
+ }
400
+ /**
401
+ * A conversation's Claude transcript read as it grows while a turn runs: each text block the agent writes and each tool
402
+ * it starts reach the chat's preview. The CLI writes one line per block, so the preview moves block by block.
403
+ */
404
+ class TranscriptTail {
405
+ sessionId;
406
+ reply;
407
+ log;
408
+ file;
409
+ offset = 0;
410
+ rest = "";
411
+ timer;
412
+ /** Why the transcript could not be read on the last tick, named once until a read succeeds again. */
413
+ unread;
414
+ static of(id, reply, log) {
415
+ const c = readConversation(id);
416
+ if (c.provider !== "claude")
417
+ return undefined;
418
+ try {
419
+ return new TranscriptTail(c.sessionId, reply, log);
420
+ }
421
+ catch (err) {
422
+ if (!fsFailure(err))
423
+ throw err;
424
+ // OWNER: the turn's answer comes from the CLI's own end-of-turn report, never from the tail — a transcript that cannot be read now leaves this turn without a text preview, named, and its answer still reaches the chat.
425
+ log(`transcript ${c.sessionId} could not be read (${err.message}) — this turn's preview shows its working state only`);
426
+ return undefined;
427
+ }
428
+ }
429
+ constructor(sessionId, reply, log) {
430
+ this.sessionId = sessionId;
431
+ this.reply = reply;
432
+ this.log = log;
433
+ this.file = transcriptOf(sessionId);
434
+ // NULL-OK: field file is OPTIONAL and therefore it is ok to check for NULL
435
+ this.offset = this.file === undefined ? 0 : statSync(this.file).size;
436
+ // GATE: how often a running turn's transcript is read for the chat's preview; the preview itself is paced by the messenger.
437
+ this.timer = setInterval(() => this.tick(), 400);
438
+ this.timer.unref();
439
+ }
440
+ stop() {
441
+ clearInterval(this.timer);
442
+ }
443
+ /** One read on the timer: a transcript moved, locked or gone is named once and read again on the next tick, never a crash of the daemon. */
444
+ tick() {
445
+ try {
446
+ this.read();
447
+ this.unread = undefined;
448
+ }
449
+ catch (err) {
450
+ if (!fsFailure(err))
451
+ throw err;
452
+ // OWNER: the timer is this read's own trigger root — the file system refused this read (ENOENT, EBUSY, EPERM, …), so it is named once, a file that is gone is looked for again, and the next tick reads again.
453
+ if (err.code === "ENOENT")
454
+ this.file = undefined;
455
+ if (this.unread !== err.message)
456
+ this.log(`transcript ${this.sessionId} could not be read (${err.message}) — the chat's preview waits for it; the answer still comes`);
457
+ this.unread = err.message;
458
+ }
459
+ }
460
+ read() {
461
+ this.file ??= transcriptOf(this.sessionId);
462
+ // NULL-OK: field file is OPTIONAL and therefore it is ok to check for NULL
463
+ if (this.file === undefined)
464
+ return;
465
+ const size = statSync(this.file).size;
466
+ if (size <= this.offset)
467
+ return;
468
+ const fd = openSync(this.file, "r");
469
+ const buf = Buffer.alloc(size - this.offset);
470
+ try {
471
+ readSync(fd, buf, 0, buf.length, this.offset);
472
+ }
473
+ finally {
474
+ closeSync(fd);
475
+ }
476
+ this.offset = size;
477
+ const lines = (this.rest + buf.toString("utf8")).split("\n");
478
+ this.rest = lines.pop();
479
+ for (const line of lines)
480
+ this.take(line);
481
+ }
482
+ take(line) {
483
+ if (line.trim() === "")
484
+ return;
485
+ let entry;
486
+ try {
487
+ entry = JSON.parse(line);
488
+ }
489
+ catch (err) {
490
+ if (!(err instanceof SyntaxError))
491
+ throw err;
492
+ // OWNER: ITER/LOOP — a transcript line that is not JSON is left out of the preview and named; the answer itself comes from the CLI's Stop, not from here.
493
+ this.log(`transcript ${this.sessionId}: a line is not JSON (${err.message}) — it is left out of the chat's preview`);
494
+ return;
495
+ }
496
+ if (entry.type !== "assistant" || !Array.isArray(entry.message?.content))
497
+ return;
498
+ for (const block of entry.message.content) {
499
+ if (block.type === "text" && typeof block.text === "string")
500
+ this.reply.wrote(block.text);
501
+ if (block.type === "tool_use")
502
+ this.reply.step(stepOf(block));
503
+ }
504
+ }
505
+ }
506
+ /** The draft of each streamed turn this process shows, one id per turn so no turn's preview lands on another's. */
507
+ let draftIds = 0;
508
+ /** The bound chat's turns as they happen (#4453): the working state at once, the agent's text and steps as a paced preview, the answer with its choices as buttons. */
509
+ export function streamedChat(messenger, log) {
510
+ return {
511
+ say: (text) => messenger.send(text),
512
+ turn(id, _n, queued) {
513
+ const reply = new StreamedReply(messenger, ++draftIds, log);
514
+ let tail;
515
+ if (!queued)
516
+ reply.begin();
517
+ const close = () => {
518
+ // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
519
+ tail?.stop();
520
+ reply.close();
521
+ };
522
+ return {
523
+ close,
524
+ async event(event) {
525
+ switch (event.kind) {
526
+ case "start":
527
+ reply.begin(event.text);
528
+ // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
529
+ tail ??= TranscriptTail.of(id, reply, log);
530
+ return;
531
+ case "answer": {
532
+ // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
533
+ tail?.stop();
534
+ const { text, choices } = choicesOf(event.text);
535
+ return reply.finish(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
536
+ }
537
+ case "failed":
538
+ case "stopped":
539
+ case "archived":
540
+ case "deleted":
541
+ // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
542
+ tail?.stop();
543
+ return reply.finish(event.text);
544
+ case "returned":
545
+ case "resumed":
546
+ case "restored":
547
+ return;
548
+ default:
549
+ return messenger.send(event.text);
550
+ }
551
+ },
552
+ };
553
+ },
554
+ };
555
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ const CHANNEL_KEYS = ["desktop", "telegram", "slack", "sms", "ntfy", "discord", "teams"];
4
+
5
+ function channelsOn(cfg) {
6
+ // NULL-OK: field cfg[key] is OPTIONAL and therefore it is ok to check for NULL
7
+ return CHANNEL_KEYS.filter((key) => cfg[key]?.enabled === true);
8
+ }
9
+
10
+ function masterMuted(cfg) {
11
+ return cfg.muteAll === true;
12
+ }
13
+
14
+ function firstRunNote(absent) {
15
+ return absent ? " (the file does not exist yet — open the panel and switch a channel on)" : "";
16
+ }
17
+
18
+ module.exports = { CHANNEL_KEYS, channelsOn, masterMuted, firstRunNote };
package/dist/chunk.js ADDED
@@ -0,0 +1,41 @@
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
+ const BLOCK_START = /^\s*(#{1,6}\s|>|[-*+]\s|\||```|\*\*\S)/;
21
+ export function withLead(lead, text) {
22
+ return `${lead}${BLOCK_START.test(text) ? "\n" : " "}${text}`;
23
+ }
24
+ export function splitForNotify(message, limit = NOTIFY_CHUNK_LIMIT) {
25
+ if (message.length <= limit)
26
+ return [message];
27
+ let parts = Math.ceil(message.length / limit);
28
+ for (;;) {
29
+ const reserve = `(${parts}/${parts}) `.length;
30
+ const needed = Math.ceil(message.length / Math.max(1, limit - reserve));
31
+ if (needed <= parts)
32
+ break;
33
+ parts = needed;
34
+ }
35
+ const body = Math.max(1, limit - `(${parts}/${parts}) `.length);
36
+ let chunks = packChunks(message, body, true);
37
+ if (chunks.length > parts)
38
+ chunks = packChunks(message, body, false);
39
+ const total = chunks.length;
40
+ return chunks.map((chunk, i) => withLead(`(${i + 1}/${total})`, chunk));
41
+ }