omni-notify-mcp 1.3.487 → 1.3.489

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 (46) hide show
  1. package/dist/agentGateway.js +328 -433
  2. package/dist/daemon.js +6 -6
  3. package/dist/gateway/chatPage.js +0 -536
  4. package/dist/gateway/gatewayInstall.js +1 -2
  5. package/dist/gateway/oauthDoor.js +1 -2
  6. package/dist/gateway/panel.js +14 -17
  7. package/dist/gateway/passkeyDoor.js +1 -2
  8. package/dist/gateway/publicAccess.js +1 -2
  9. package/dist/gateway/restDoor.js +322 -161
  10. package/dist/messaging/chatInbound.js +3 -1
  11. package/dist/messaging/emailInbound.js +3 -7
  12. package/dist/notify.js +244 -87
  13. package/dist/shared/webhost/originHandover.js +4 -3
  14. package/dist/shared/webhost/workspaceList.js +56 -8
  15. package/package.json +2 -9
  16. package/dist/gateway/conversationOwner.js +0 -139
  17. package/dist/gateway/mcpDoor.js +0 -411
  18. package/dist/gateway/mcpEvents.js +0 -448
  19. package/dist/gateway/terminalDoor.js +0 -243
  20. package/dist/gateway/terminalPage.js +0 -613
  21. package/dist/shared/agentSession.js +0 -8375
  22. package/dist/shared/conversation/agentReaper.js +0 -218
  23. package/dist/shared/conversation/claudeProvider.js +0 -585
  24. package/dist/shared/conversation/cliSession.js +0 -481
  25. package/dist/shared/conversation/codexArchive.js +0 -67
  26. package/dist/shared/conversation/codexProvider.js +0 -240
  27. package/dist/shared/conversation/conversationOwner.js +0 -43
  28. package/dist/shared/conversation/conversations.js +0 -1037
  29. package/dist/shared/conversation/copilotProvider.js +0 -229
  30. package/dist/shared/conversation/nativeCliInvocation.js +0 -70
  31. package/dist/shared/conversation/nativeTerminal.js +0 -529
  32. package/dist/shared/conversation/nativeTerminalWorker.js +0 -158
  33. package/dist/shared/conversation/opencodeEvents/server.mjs +0 -36
  34. package/dist/shared/conversation/opencodeProvider.js +0 -375
  35. package/dist/shared/conversation/ownerContext.js +0 -1
  36. package/dist/shared/conversation/provider.js +0 -44
  37. package/dist/shared/conversation/providerProof.js +0 -75
  38. package/dist/shared/conversation/providers.js +0 -30
  39. package/dist/shared/conversation/sessionDriver.js +0 -1182
  40. package/dist/shared/conversation/terminalTransport.js +0 -126
  41. package/dist/shared/providerOwnership.js +0 -294
  42. package/dist/shared/webhost/autoSwitch.cjs +0 -2558
  43. package/dist/shared/workspaceList.js +0 -1
  44. package/scripts/shared/ownerGuard.cjs +0 -135
  45. package/scripts/shared/ownerGuard.sh +0 -64
  46. /package/dist/shared/{conversation/toolLine.js → toolLine.js} +0 -0
@@ -1,467 +1,358 @@
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. Meni's one chat (#4453) is streamed: AB relays each event
8
+ * of its turn whole to BN's relay door (`POST /v1/chat/relay`), and the chat shows it as it happens — the working state,
9
+ * the agent's text and steps read from its own transcript, the answer with its choices as buttons.
12
10
  */
11
+ import { randomUUID } from "crypto";
13
12
  import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "fs";
14
13
  import { homedir } from "os";
15
14
  import { join } from "path";
16
- import { splitForNotify } from "./chunk.js";
15
+ import { setTimeout as delay } from "node:timers/promises";
17
16
  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, turnInFlight, updateConversation, } from "./gateway/conversationOwner.js";
19
- import { conversationOwner } from "./gateway/conversationOwner.js";
20
- import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
21
- import { toolLine } from "./shared/conversation/provider.js";
22
- import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
17
+ import { GatewayError, readGatewaySettings } from "./notify.js";
18
+ import { toolLine } from "./shared/toolLine.js";
23
19
  export const AGENT_PREFIX = "!";
24
- /** The thread's newest conversation is ended; the next message opens a fresh one. */
25
- async function endNewest(key, _platform, end) {
26
- const open = this.conversationOf(key);
27
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
28
- if (open !== undefined)
29
- end(open.id);
30
- const stay = this.allOf(key).length;
31
- return stay === 0 ? "🆕 New conversation. Your next ! message starts it." : `🆕 Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`;
20
+ /** 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. */
21
+ export const SLACK_DM = "slack:dm:";
22
+ const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
23
+ /** The kinds that end a turn: a relay that carried one is done. */
24
+ const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
25
+ // 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.
26
+ const CLUSTER_URL = "http://127.0.0.1:7481";
27
+ // GATE: a refused connection to AB is tried five times, waiting 0.5, 1, 2 and 4 s — the bound AB's own call into BN takes (AgenticBullseye wire.ts BN_CALL_TRIES) — then AB is unreachable.
28
+ const CLUSTER_CALL_TRIES = 5;
29
+ const CLUSTER_FIRST_WAIT_MS = 500;
30
+ /** AgenticBullseye's base URL: the one this machine runs, or the stand-in a suite names under the test gate. */
31
+ export function clusterBase() {
32
+ return process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" && process.env.NOTIFY_AGENT_CLUSTER_URL ? process.env.NOTIFY_AGENT_CLUSTER_URL.replace(/\/+$/, "") : CLUSTER_URL;
32
33
  }
33
- 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.`;
34
- /** The pieces of a turn shown while they happen and never stored: a tool step started or ended. */
35
- const LIVE_KINDS = new Set(["step", "stepDone", "stepFailed"]);
36
- /** Each carried event of a turn sent as its parts. */
37
- function partsRelay(reply, carriage) {
38
- return {
39
- async event(event) {
40
- if (carriage.carries(event.kind))
41
- for (const part of carriage.parts(event))
42
- await reply(part);
43
- },
44
- close: () => { },
45
- };
34
+ /** The gateway bearer every call to AB carries; with no `agentGateway.token` in config.json BN has no way into AB and says so. */
35
+ export function clusterToken() {
36
+ const settings = readGatewaySettings();
37
+ // NULL-OK: field settings is OPTIONAL and therefore it is ok to check for NULL
38
+ if (settings === undefined)
39
+ 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");
40
+ return settings.token;
41
+ }
42
+ /** The refusal BN answers when AB cannot be reached at all: a 503 naming the cluster and the cause, never a local stand-in. */
43
+ export function clusterUnreachable(err) {
44
+ // NULL-OK: field cause is OPTIONAL and therefore it is ok to check for NULL
45
+ const cause = err.cause?.code ?? err.code ?? err.message;
46
+ return new GatewayError(503, `AgenticBullseye at ${clusterBase()} could not be reached (${cause}); the agent conversations run there`);
46
47
  }
47
- /** A chat: the newest conversation not stopped (`/new` and `/stop` end it), and every line of the turn, the answer split at 500. */
48
- const CHAT = {
49
- conversationOf: openConversationOf,
50
- routeOf: routeAsk,
51
- stopOf: (key) => [stopTargetOf(key)].filter((c) => c !== undefined),
52
- allOf: openConversationsOf,
53
- carries: (kind) => kind !== "returned" && !LIVE_KINDS.has(kind),
54
- parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
55
- stopped: stoppedOfMany,
56
- renew: endNewest,
57
- folderOf: (text) => resolveProject(undefined, text),
58
- forkOf: () => undefined,
59
- };
60
- /** Meni's one private chat with the bot (#4453): its main conversation, the newest not deleted and not forked beside another — an idle archive keeps it bound, only /new replaces it. */
61
- const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted" && c.forkOf === undefined);
62
- /** The conversations forked beside the bound chat's main one while it was busy (#4584), newest first; a stopped or put-away one is done. */
63
- const sidesOf = (key) => listConversations().filter((c) => c.chat === key && c.forkOf !== undefined && c.state !== "closed" && c.shelf === undefined);
64
- /** A conversation in the middle of a turn, or holding a message stored for its next one. */
65
- const busy = (c) => turnInFlight(readEvents(c.id), c) !== undefined;
66
- /** The busy main conversation a message forks beside (#4584): an OpenCode one never forks, since each fork is a new OpenCode process left behind it, so its message queues on it instead. */
67
- const forkedFrom = (key) => {
68
- const main = boundOf(key);
69
- // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
70
- return main !== undefined && main.provider !== "opencode" && busy(main) ? main : undefined;
71
- };
72
- /** The bound chat's main conversation, unless it is busy and forks (#4584): then undefined, so the message runs at once in a new conversation forked from it and never waits behind the reply under way. */
73
- const freeBound = (key) => (forkedFrom(key) === undefined ? boundOf(key) : undefined);
74
- /** The bound chat: ONE main conversation at the workspace root, every message goes on with it, or beside it in a fork while it is busy (#4584); a stop pauses the one at work, /new opens the next one at once. */
75
- const ONE = {
76
- conversationOf: boundOf,
77
- routeOf: freeBound,
78
- stopOf: (key) => {
79
- const working = ONE.allOf(key).filter(busy);
80
- return working.length > 0 ? working : [boundOf(key)].filter((c) => c !== undefined);
81
- },
82
- allOf: (key) => [boundOf(key), ...sidesOf(key)].filter((c) => c !== undefined),
83
- carries: CHAT.carries,
84
- parts: CHAT.parts,
85
- stopped: (stopped) => {
86
- const forks = stopped.filter((c) => c.forkOf !== undefined).length;
87
- const parallel = `${forks} parallel conversation${forks === 1 ? "" : "s"}`;
88
- if (forks === stopped.length)
89
- return `⏹ Stopped ${parallel}.`;
90
- return `⏹ Stopped${forks === 0 ? "" : `, with ${parallel}`}. Your next message picks the conversation up where it stopped.`;
91
- },
92
- folderOf: () => rootFolder(),
93
- forkOf: (key) => forkedFrom(key)?.sessionId,
94
- async renew(key, platform, end, provider) {
95
- for (const c of ONE.allOf(key)) {
96
- end(c.id);
97
- archiveConversation(c.id);
48
+ /** One call to AB under the gateway bearer: AB's JSON answer, or AB's own refusal as a GatewayError carrying its status and words. */
49
+ export async function clusterCall(method, path, body, signal) {
50
+ let answer;
51
+ for (let attempt = 1;; attempt++) {
52
+ try {
53
+ answer = await fetch(`${clusterBase()}${path}`, { method, headers: { authorization: `Bearer ${clusterToken()}`, ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body), signal });
54
+ break;
98
55
  }
99
- const { notice } = await createdIn(rootFolder(), provider, () => key, (on) => openConversation({ platform, chat: key, ...on }));
100
- // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
101
- return `🆕 Fresh conversation — your next message starts it.${notice === undefined ? "" : `\n${notice.text}`}`;
102
- },
103
- };
104
- const MAILED_KINDS = new Set(["answer", "failed", "stopped", "asking"]);
105
- /** An email thread: its one conversation, a stopped one resumed by the next reply; only what needs Meni is mailed, each whole. */
106
- const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
107
- const MAIL = {
108
- conversationOf: THREADS_ONE,
109
- routeOf: THREADS_ONE,
110
- stopOf: (key) => [THREADS_ONE(key)].filter((c) => c !== undefined),
111
- allOf: (key) => listConversations().filter((c) => c.chat === key),
112
- carries: (kind) => MAILED_KINDS.has(kind),
113
- parts: (event) => [event.text],
114
- stopped: stoppedOfMany,
115
- renew: endNewest,
116
- folderOf: (text) => resolveProject(undefined, text),
117
- forkOf: () => undefined,
118
- };
119
- const CARRIAGE = { telegram: ONE, slack: CHAT, discord: CHAT, teams: CHAT, ntfy: CHAT, sms: CHAT, email: MAIL };
120
- /** 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. */
121
- export const SLACK_DM = "slack:dm:";
122
- /** How a chat key's conversations are carried. */
123
- function carriageOf(platform, key) {
124
- return key.startsWith(SLACK_DM) ? ONE : CARRIAGE[platform];
56
+ catch (err) {
57
+ if (!(err instanceof TypeError))
58
+ throw err;
59
+ // NULL-OK: field cause is OPTIONAL and therefore it is ok to check for NULL
60
+ const refused = err.cause?.code === "ECONNREFUSED";
61
+ // OWNER: ITER/LOOP — a refused connection never reached AB (it is restarting), so it is tried again after a pause; any other failure, or the last try, is AB unreachable, thrown as the 503 naming it.
62
+ if (!refused || attempt === CLUSTER_CALL_TRIES)
63
+ throw clusterUnreachable(err);
64
+ await delay(CLUSTER_FIRST_WAIT_MS << (attempt - 1), undefined, { signal });
65
+ }
66
+ }
67
+ let text;
68
+ try {
69
+ text = await answer.text();
70
+ }
71
+ catch (err) {
72
+ if (!(err instanceof TypeError))
73
+ throw err;
74
+ throw clusterUnreachable(err);
75
+ }
76
+ let parsed;
77
+ try {
78
+ parsed = JSON.parse(text);
79
+ }
80
+ catch (err) {
81
+ if (!(err instanceof SyntaxError))
82
+ throw err;
83
+ throw new GatewayError(502, `AgenticBullseye answered ${method} ${path} with HTTP ${answer.status} and a body that is not JSON: ${text.slice(0, 200)}`);
84
+ }
85
+ if (!answer.ok) {
86
+ // NULL-OK: field error is OPTIONAL and therefore it is ok to check for NULL
87
+ const said = parsed?.error;
88
+ throw new GatewayError(answer.status, typeof said === "string" ? said : `AgenticBullseye answered ${method} ${path} with HTTP ${answer.status}: ${text.slice(0, 200)}`);
89
+ }
90
+ return parsed;
125
91
  }
126
- /** The turns a conversation hands the one replacing it on another provider: his messages and its answers, newest last, each cut to fit. */
127
- const CARRIED_TURNS = 8;
128
- const CARRIED_CHARS = 1500;
129
- function carriedOver(from, to) {
130
- const said = readEvents(from.id).filter((e) => e.role === "user" || e.kind === "answer").slice(-CARRIED_TURNS);
131
- if (said.length === 0)
132
- return undefined;
133
- // A stored message of his ends with his own words (the brief and context ride before them), so the end of each turn is what is kept.
134
- const lines = said.map((e) => `${e.role === "user" ? "He said" : `${from.provider} answered`}: ${e.text.length > CARRIED_CHARS ? `(cut)… ${e.text.slice(-CARRIED_CHARS)}` : e.text}`);
135
- return `(BN: he switched this chat from ${from.provider} to ${to}. This conversation goes on from the one ${from.provider} held — its latest turns, read them as this chat's history:\n${lines.join("\n\n")})`;
92
+ /** One chat carriage operation, `POST <AB>/v1/chat/<op>`. */
93
+ function carriage(op, body) {
94
+ return clusterCall("POST", `/v1/chat/${op}`, body);
95
+ }
96
+ async function chatCallWithDeadline(op, body) {
97
+ const signal = AbortSignal.timeout(2000);
98
+ try {
99
+ return await clusterCall("POST", `/v1/chat/${op}`, body, signal);
100
+ }
101
+ catch (err) {
102
+ if (!signal.aborted)
103
+ throw err;
104
+ throw new GatewayError(504, "AgenticBullseye did not answer in time.");
105
+ }
136
106
  }
137
- const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
138
- const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
139
107
  export class AgentGateway {
140
- driver;
141
108
  static self;
142
109
  static instance() {
143
- return (AgentGateway.self ??= new AgentGateway(conversationOwner.driver));
110
+ return (AgentGateway.self ??= new AgentGateway());
144
111
  }
145
- /** The messages waiting on their answer, by conversation and user event. */
146
- turns = new Map();
112
+ /** The messages whose turn is still sending, by the reply id handed to AB with them. */
113
+ held = new Map();
147
114
  doors = new Map();
148
- recovered = false;
149
- constructor(driver) {
150
- this.driver = driver;
151
- driver.onEvent((event) => this.deliver(event));
152
- driver.onEvent(turnEnded);
153
- }
154
115
  registerDoor(platform, door) {
155
116
  this.doors.set(platform, door);
156
117
  }
157
- /** Starts the driver in the process that owns the pollers, then takes back every turn the last process owed its thread an answer for. */
158
- boot() {
159
- clearOpenCodeLogs();
160
- this.driver.boot();
161
- if (this.recovered)
162
- return;
163
- this.recovered = true;
164
- resendUndelivered();
165
- for (const c of listConversations())
166
- this.recover(c);
167
- }
168
- /** 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. */
169
- recover(c) {
170
- const owed = Object.entries(c.owed ?? {});
171
- if (owed.length === 0)
172
- return;
173
- if (c.state === "closed")
174
- return editOwed(c.id, (o) => { for (const [turn] of owed)
175
- delete o[turn]; });
176
- const door = this.doors.get(c.platform);
177
- if (door === undefined)
178
- throw new Error(`conversation ${c.id} on ${c.platform} is owed an answer and no door of that platform is registered before boot`);
179
- for (const [turn, sent] of owed) {
180
- const pending = readEvents(c.id).filter((e) => e.turn === Number(turn) && e.n > sent && e.role !== "user").map((e) => ({ ...e, id: c.id }));
181
- // OWNER: ITER/LOOP — a thread that cannot be reached is shown on its conversation and the next owed turn is still carried on.
182
- const answered = this.awaitTurn(c.id, Number(turn), partsRelay((part) => door(c, part), carriageOf(c.platform, c.chat ?? "")), pending);
183
- // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
184
- void (c.forkOf === undefined ? answered : answered.finally(() => this.end(c.id))).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)}` }));
185
- }
118
+ /**
119
+ * No message's turn is still sending through this process, so the gateway can pass to another one without losing a reply's
120
+ * own thread. A hold whose message AB took while AB answers that no turn of its own is in flight waits on nothing — AB
121
+ * restarted mid-turn, or its release never reached BN — and is let go here; AB unreachable is thrown, as nothing proves then
122
+ * whether its turns still run.
123
+ */
124
+ async quiesce() {
125
+ if (this.held.size === 0)
126
+ return true;
127
+ if (![...this.held.values()].some((held) => held.taken))
128
+ return false;
129
+ if (!(await carriage("quiet", {})).quiet)
130
+ return false;
131
+ for (const [replyId, held] of [...this.held])
132
+ if (held.taken)
133
+ this.release(replyId);
134
+ return this.held.size === 0;
186
135
  }
187
- /** No chat message waiting on its conversation's creation and no CLI running a background subagent or shell: the gateway can pass to another process without losing either. A turn under way never holds it — the next build takes a cut turn up again on its session and sends its answer to its chat (#2116, #4584); background work cannot be taken up again, so its CLI is kept until that work ends (#4814). */
188
- quiet() {
189
- return !creationsPending() && this.driver.backgroundHolders().length === 0;
136
+ /**
137
+ * What this message asks of the agent, or undefined when it is not addressed to it and belongs to the inbox. Only a
138
+ * message that can be addressed to the agent at all — a `!` message, or a bare `/new` or `/stop` — is asked of AB, so
139
+ * the inbox never waits on the cluster.
140
+ */
141
+ async classify(key, raw) {
142
+ const text = raw.trim();
143
+ if (!text.startsWith(AGENT_PREFIX) && !COMMAND_RE.test(text))
144
+ return undefined;
145
+ // NULL-OK: field act is OPTIONAL and therefore it is ok to check for NULL
146
+ return (await chatCallWithDeadline("classify", { key, raw })).act ?? undefined;
190
147
  }
191
- /** Gives the store back when this process hands the gateway over. */
192
- async shutdown() {
193
- await this.driver.shutdown();
194
- this.recovered = false;
148
+ /** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
149
+ async classifyInThread(key, raw) {
150
+ return (await chatCallWithDeadline("classifyInThread", { key, raw })).act;
195
151
  }
196
- /** What this message asks of the agent, or undefined when it is not addressed to it and belongs to the inbox. */
197
- classify(key, raw) {
198
- const text = raw.trim();
199
- if (text.startsWith(AGENT_PREFIX)) {
200
- const body = text.slice(AGENT_PREFIX.length).trim();
201
- const cmd = body.match(COMMAND_RE);
202
- if (cmd)
203
- return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
204
- return { kind: "say", text: body };
152
+ /** A message of Meni's one chat is all for its one conversation (#4453); `bare` says the chat cannot type a slash, so a bare "new" or "stop" is a command there. */
153
+ async classifyChat(raw, bare) {
154
+ return (await chatCallWithDeadline("classifyChat", { raw, bare })).act;
155
+ }
156
+ /** The text one message of Meni's one chat is sent as: the bound conversation's brief on its first turn, then what the chat knows around it, then his own words. */
157
+ async turnText(key, text, context) {
158
+ return (await chatCallWithDeadline("turnText", { key, text, context })).text;
159
+ }
160
+ async workingStatus(key, platform) {
161
+ try {
162
+ const { text } = await chatCallWithDeadline("workingStatus", { key, platform });
163
+ return text;
164
+ }
165
+ catch (err) {
166
+ // OWNER: the status read answers its originating chat even when the cluster cannot report the turn.
167
+ if (!(err instanceof GatewayError))
168
+ throw err;
169
+ return err.status === 504 ? "BN received your message. The agent did not report its status in time." : "BN received your message. The agent's status is unavailable.";
205
170
  }
206
- const cmd = text.match(COMMAND_RE);
207
- if (cmd && openConversationOf(key) !== undefined)
208
- return { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" };
209
- return undefined;
210
171
  }
211
172
  /**
212
- * 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 `!`
213
- * 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
214
- * 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.
173
+ * A message's act as AB classifies it; one AB could not classify (unreachable, or refused with its reason) has that
174
+ * reason answered to its chat and reads as "answered", so the poll reads on and the message is never taken for the inbox.
215
175
  */
216
- classifyChat(raw, bare) {
217
- const said = raw.trim();
218
- const text = said.replace(/^!\s*/, "");
219
- const cmd = text.match(COMMAND_RE);
220
- const commanded = cmd !== null && (bare || text.startsWith("/") || said.startsWith(AGENT_PREFIX) || cmd[1].toLowerCase() === "stop");
221
- return commanded ? { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" } : { kind: "say", text };
222
- }
223
- /** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
224
- classifyInThread(key, raw) {
225
- return this.classify(key, raw) ?? { kind: "say", text: raw.trim() };
176
+ async classified(classify, reply) {
177
+ try {
178
+ return await classify();
179
+ }
180
+ catch (err) {
181
+ if (!(err instanceof GatewayError))
182
+ throw err;
183
+ // 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
184
+ await reply(`❌ ${err.message}`);
185
+ return "answered";
186
+ }
226
187
  }
227
188
  /** Whether this email message was already taken as a turn of some conversation, so a BN restart never answers it twice. */
228
- emailTaken(messageId) {
229
- // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
230
- return listConversations().some((c) => c.email !== undefined && c.email.messageIds.includes(messageId));
231
- }
232
- /** Shows on this chat key's conversation that its answer never reached the chat, so the web page tells what the chat could not. */
233
- noteUndelivered(key, platform, text) {
234
- const c = carriageOf(platform, key).conversationOf(key);
235
- // NULL-OK: field c is OPTIONAL and therefore it is ok to check for NULL
236
- if (c === undefined)
237
- return;
238
- appendEvent(c.id, { role: "system", kind: "status", text });
239
- }
240
- openSlackThreads() {
241
- const newestOfThread = new Set();
242
- return listConversations().filter((c) => {
243
- if (c.platform !== "slack" || c.state === "closed" || c.slack === undefined || newestOfThread.has(c.chat ?? c.id))
244
- return false;
245
- newestOfThread.add(c.chat ?? c.id);
246
- return true;
247
- });
189
+ async emailTaken(messageId) {
190
+ return (await carriage("emailTaken", { messageId })).taken;
191
+ }
192
+ async openSlackThreads() {
193
+ return (await chatCallWithDeadline("openSlackThreads", {})).conversations;
194
+ }
195
+ /** Every conversation AB holds, each marked `working` while a turn of it is under way: the Slack Home tab and the Slack thread reader list them. */
196
+ async conversations() {
197
+ return (await chatCallWithDeadline("conversations", {})).conversations;
248
198
  }
249
199
  /** Records how far a Slack thread has been read. */
250
- markSlackRead(key, readTs) {
251
- for (const c of openConversationsOf(key))
252
- updateConversation(c.id, { slack: { ...c.slack, readTs } });
200
+ async markSlackRead(key, readTs) {
201
+ await chatCallWithDeadline("markSlackRead", { key, readTs });
253
202
  }
254
- /** Acts on one addressed message. Resolves when its answer (or its failure) has been sent back. */
203
+ /**
204
+ * Hands one addressed message to AB with its own way back held under a fresh reply id. A plain reply resolves once the
205
+ * turn's final part went out or AB released it; a streamed chat (#4453) is told `streamed`, so AB relays each event of
206
+ * its turns whole, and resolves on AB's release alone. It rejects when a part the thread refused is the reason — AB has
207
+ * already shown that on the conversation. An act AB did not take is answered to the chat with AB's reason.
208
+ */
255
209
  async handle(key, platform, act, out, origin = {}) {
256
- const arrived = monotonicMs();
257
- const carriage = carriageOf(platform, key);
258
- const reply = typeof out === "function" ? out : out.say;
259
- const relayOf = (id, n, queued, parallel = false) => (typeof out === "function" ? partsRelay(out, carriage) : out.turn(id, n, queued, parallel));
260
- const refusal = conversationRefusal();
261
- if (refusal !== undefined)
262
- return reply(refusal);
263
- // NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
264
- for (let pending = creationPending(key); pending !== undefined; pending = creationPending(key))
265
- await pending;
266
- const open = carriage.conversationOf(key);
267
- if (act.kind === "stop") {
268
- const stopped = carriage.stopOf(key);
269
- if (stopped.length === 0)
270
- return reply("Nothing to stop here — no conversation is open.");
271
- for (const c of stopped)
272
- this.end(c.id);
273
- return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => !stopped.includes(c)).length));
210
+ const replyId = randomUUID();
211
+ const say = typeof out === "function" ? out : out.say;
212
+ const answered = new Promise((resolve, reject) => {
213
+ const held = {
214
+ out,
215
+ relays: new Map(),
216
+ taken: false,
217
+ settle: () => {
218
+ this.held.delete(replyId);
219
+ for (const relay of held.relays.values())
220
+ relay.close();
221
+ held.relays.clear();
222
+ // NULL-OK: field failed is OPTIONAL and therefore it is ok to check for NULL
223
+ if (held.failed === undefined)
224
+ resolve();
225
+ else
226
+ reject(held.failed);
227
+ },
228
+ };
229
+ this.held.set(replyId, held);
230
+ });
231
+ try {
232
+ await carriage("handle", { key, platform, act, origin, replyId, streamed: typeof out !== "function" });
233
+ const taken = this.held.get(replyId);
234
+ // NULL-OK: field taken is OPTIONAL and therefore it is ok to check for NULL
235
+ if (taken !== undefined)
236
+ taken.taken = true;
274
237
  }
275
- if (act.kind === "new") {
276
- try {
277
- return reply(await carriage.renew(key, platform, (id) => this.end(id), act.provider));
278
- }
279
- catch (err) {
280
- if (!(err instanceof GatewayError))
281
- throw err;
282
- // OWNER: the message is the trigger root — a fresh conversation the gateway refused (its CLI does not answer, no subscription has room) is answered to the chat with the reason, never silence.
283
- return reply(`❌ NOT STARTED — ${err.message}`);
284
- }
238
+ catch (err) {
239
+ this.release(replyId);
240
+ if (!(err instanceof GatewayError))
241
+ throw err;
242
+ // 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
243
+ return say(`❌ ${err.message}`);
244
+ }
245
+ return answered;
246
+ }
247
+ /**
248
+ * AB's reply door: one part of a turn, sent through the reply its message is held with, or — none held (BN restarted, or
249
+ * AB recovered an owed turn with no reply id) — through the platform's registered door, from the conversation's record.
250
+ * A part with no conversation (a line that belongs to none, such as a switch refusal) has only its held reply. A part the
251
+ * thread refuses is thrown as a 502 naming why, which AB records on the conversation. A streamed chat's part is one of
252
+ * its plain lines, and its hold is let go only on AB's release.
253
+ */
254
+ async carry(replyId, platform, conversation, part, final) {
255
+ // NULL-OK: field replyId is OPTIONAL and therefore it is ok to check for NULL
256
+ const held = replyId === null ? undefined : this.held.get(replyId);
257
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
258
+ if (held === undefined) {
259
+ // NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
260
+ if (conversation === null)
261
+ 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`);
262
+ const door = this.doors.get(platform);
263
+ // NULL-OK: field door is OPTIONAL and therefore it is ok to check for NULL
264
+ if (door === undefined)
265
+ throw new GatewayError(404, `no ${platform} door is registered in this BN process, so the part has no way to its thread`);
266
+ return sent(platform, () => door(conversation, part));
285
267
  }
286
- if (act.text === "")
287
- return reply("Send `! <your message>` to talk to the agent.");
288
- const replaced = open !== undefined && act.provider !== undefined && open.provider !== act.provider;
289
- // #4671 — a provider switch keeps the thread: the conversation it replaces hands its latest turns to the new one, so nothing said is lost.
290
- const carried = replaced ? carriedOver(open, act.provider) : undefined;
291
- // The conversations it replaces end only once the new one is made: a provider that refuses leaves the chat on the one it had, every turn kept.
292
- const retire = () => {
293
- if (!replaced)
294
- return;
295
- for (const c of carriage.allOf(key)) {
296
- this.end(c.id);
297
- archiveConversation(c.id);
298
- }
299
- };
300
- // The one chat's brief rides the first turn of a conversation; the replacing one has had none, so it is given it with the turns carried over.
301
- // NULL-OK: field carried is OPTIONAL and therefore it is ok to check for NULL
302
- const said = carried === undefined ? act.text : [...(carriage === ONE ? [chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram")] : []), carried, act.text].join("\n\n");
303
- const switched = (id) => (replaced ? [this.told(id, 1, `🔀 Switched from ${open.provider} to ${act.provider} — the conversation goes on there, its last turns carried over.`)] : []);
304
- const target = replaced ? undefined : carriage.routeOf(key, act.text);
305
- const forkOf = replaced ? undefined : carriage.forkOf(key);
306
- // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
307
- if (target === undefined) {
308
- let project;
309
- try {
310
- project = carriage.folderOf(act.text);
311
- }
312
- catch (err) {
313
- // 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
314
- if (err instanceof GatewayError)
315
- return reply(err.message);
268
+ const out = held.out;
269
+ const streamed = typeof out !== "function";
270
+ try {
271
+ await sent(platform, () => (streamed ? out.say(part) : out(part)));
272
+ }
273
+ catch (err) {
274
+ if (!(err instanceof GatewayError))
316
275
  throw err;
317
- }
318
- // A conversation opened in a thread the chat already reads starts reading after what was read, never from the thread's root again.
319
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
320
- const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
321
- const turn = {};
322
- // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
323
- const provider = forkOf !== undefined ? open.provider : act.kind === "say" ? act.provider : undefined;
324
- const [creation] = await Promise.allSettled([createdIn(project, provider, () => key, (on) => {
325
- retire();
326
- const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: said, receivedMs: monotonicMs() - arrived });
327
- const answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false, forkOf !== undefined), switched(created.id));
328
- // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
329
- turn.answered = forkOf === undefined ? answered : answered.finally(() => this.end(created.id));
330
- turn.id = created.id;
331
- return created;
332
- })]);
333
- if (creation.status === "rejected") {
334
- // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
335
- if (turn.id === undefined) {
336
- if (!(creation.reason instanceof GatewayError))
337
- throw creation.reason;
338
- // OWNER: the message is the trigger root — a conversation the gateway refused to start (the named CLI does not answer, no subscription has room, the other owner holds it) is answered to the chat with the reason, never thrown past the poll loop into silence.
339
- return reply(replaced ? `❌ NOT SWITCHED to ${act.provider} — ${creation.reason.message}\nThis chat stays on ${open.provider}, everything said in it kept, until ${act.provider} answers or another provider is chosen. This message was not sent: send it again then.` : `❌ NOT STARTED — ${creation.reason.message}\nThis message was not sent: send it again once a provider answers.`);
340
- }
341
- const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
342
- 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`);
343
- 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}`));
344
- return turn.answered;
345
- }
346
- // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
347
- if (creation.value.notice !== undefined)
348
- this.deliver({ ...creation.value.notice, id: creation.value.made.id });
349
- return turn.answered;
276
+ held.failed = err;
277
+ throw err;
350
278
  }
351
- // NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
352
- if (origin.email !== undefined)
353
- updateConversation(target.id, { email: { ...target.email, messageIds: [...target.email.messageIds, ...origin.email.messageIds] } });
354
- const sent = sendToConversation(target.id, act.text, monotonicMs() - arrived);
355
- // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
356
- const notice = queueNoticeOf(target.id, sent.n);
357
- // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
358
- 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.`)] : [];
359
- return this.awaitTurn(target.id, sent.n, relayOf(target.id, sent.n, notice !== undefined), [...told, ...(notice === undefined ? [] : [{ ...notice, id: target.id }])]);
360
- }
361
- /** 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. */
362
- told(id, n, text) {
363
- return { id, n, turn: n, role: "system", kind: "status", text, ts: new Date().toISOString() };
364
- }
365
- end(id) {
366
- for (const turn of this.turns.get(id)?.values() ?? [])
367
- turn.close();
368
- this.turns.delete(id);
369
- this.driver.stop(id);
370
- editOwed(id, (o) => { for (const turn of Object.keys(o))
371
- delete o[turn]; });
372
- }
373
- /** 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. */
374
- awaitTurn(id, n, relay, pending = []) {
375
- editOwed(id, (o) => { o[n] ??= n; });
376
- let wake = () => { };
377
- let closed = false;
378
- const turns = this.turns.get(id) ?? new Map();
379
- turns.set(n, { push: (event) => { pending.push(event); wake(); }, close: () => { closed = true; wake(); } });
380
- this.turns.set(id, turns);
381
- return (async () => {
382
- for (;;) {
383
- if (pending.length === 0) {
384
- if (closed)
385
- return relay.close();
386
- await new Promise((resolve) => { wake = resolve; });
387
- continue;
388
- }
389
- const event = pending.shift();
390
- await relay.event(event).catch((err) => {
391
- relay.close();
392
- throw err;
393
- });
394
- if (LIVE_KINDS.has(event.kind))
395
- continue;
396
- const final = FINAL_KINDS.has(event.kind ?? "");
397
- if (!closed)
398
- editOwed(id, (o) => { if (final)
399
- delete o[n];
400
- else
401
- o[n] = event.n; });
402
- if (final) {
403
- // NULL-OK: field turns is OPTIONAL and therefore it is ok to check for NULL
404
- this.turns.get(id)?.delete(n);
405
- return;
406
- }
407
- }
408
- })();
409
- }
410
- deliver(event) {
411
- const turns = this.turns.get(event.id);
412
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
413
- if (event.turn === undefined && turns !== undefined) {
414
- for (const waiting of turns.values())
415
- waiting.push(event);
416
- this.turns.delete(event.id);
417
- return;
279
+ finally {
280
+ if (final && !streamed)
281
+ held.settle();
418
282
  }
419
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
420
- const turn = event.turn === undefined ? undefined : turns?.get(event.turn);
421
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
422
- if (turn === undefined)
283
+ }
284
+ /**
285
+ * AB's relay door (#4453): one event of a streamed turn shown on the chat its message is held with, through that turn's
286
+ * relay (made on its first event), or `close` — the turn ended without a last event of its own. An event the chat
287
+ * refuses is thrown as a 502 naming why; a relay that carried the turn's last event is done.
288
+ */
289
+ async relay(replyId, turn, event, close) {
290
+ const held = this.held.get(replyId);
291
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
292
+ if (held === undefined)
293
+ throw new GatewayError(404, `no streamed chat is held under ${replyId} (its turn was released, or BN restarted since), so turn ${turn.id} #${turn.n} has no chat to show it`);
294
+ const out = held.out;
295
+ if (typeof out === "function")
296
+ throw new GatewayError(409, `the reply held under ${replyId} is not a streamed chat; its parts go to /v1/chat/reply`);
297
+ const name = `${turn.id}:${turn.n}`;
298
+ if (close) {
299
+ // NULL-OK: field relay is OPTIONAL and therefore it is ok to check for NULL
300
+ held.relays.get(name)?.close();
301
+ held.relays.delete(name);
423
302
  return;
424
- turn.push(event);
425
- if (FINAL_KINDS.has(event.kind ?? ""))
426
- turns.delete(event.turn);
303
+ }
304
+ // NULL-OK: field event is OPTIONAL and therefore it is ok to check for NULL
305
+ if (event === undefined)
306
+ throw new GatewayError(400, "a relay carries an event of the turn, or close: true");
307
+ const relay = held.relays.get(name) ?? out.turn(turn);
308
+ held.relays.set(name, relay);
309
+ try {
310
+ await relay.event(event, turn);
311
+ }
312
+ catch (err) {
313
+ if (!deliveryFailure(err))
314
+ throw err;
315
+ held.failed = new GatewayError(502, `the chat did not take the ${event.kind ?? "status"} line of turn ${turn.id} #${turn.n}: ${err.message}`);
316
+ throw held.failed;
317
+ }
318
+ finally {
319
+ if (FINAL_KINDS.has(event.kind))
320
+ held.relays.delete(name);
321
+ }
322
+ }
323
+ /** 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. */
324
+ release(replyId) {
325
+ // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
326
+ this.held.get(replyId)?.settle();
327
+ }
328
+ /** Asks AB to re-drive every turn it still owes a thread, once this process holds the doors those turns go out through. */
329
+ async recover() {
330
+ await carriage("recover", {});
331
+ }
332
+ }
333
+ /** One part handed to its thread; a refusal of the thread's own platform is thrown as the 502 the reply door answers. */
334
+ async function sent(platform, send) {
335
+ try {
336
+ await send();
337
+ }
338
+ catch (err) {
339
+ if (!deliveryFailure(err))
340
+ throw err;
341
+ throw new GatewayError(502, `the ${platform} thread did not take the part: ${err.message}`);
427
342
  }
428
343
  }
429
- /** What each chat can show (#4585): Telegram's phone chat takes inline marks only; Slack renders the reply as Block Kit, and each of its threads is one piece of work. */
430
- const SHOWS = {
431
- Telegram: "The chat shows bold, italic, code, links, bullets and emojis, never tables; keep replies short.",
432
- Slack: "The chat shows # headings as headers, --- as dividers, code blocks, > quotes, bold, italic, links, bullets and emojis, and a markdown table as a card per row, its columns in two-column fields; each Slack thread is one piece of work, so answer the work of the thread you are in. Keep replies short.",
433
- };
434
344
  /**
435
- * What the bound chat's conversation is told before its first message (#4453), about 300 tokens: that it is BN's agent
436
- * 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,
437
- * what the chat can show, and how it asks him something there.
345
+ * Whether a send failed in the world — the platform refused it, could not be reached, timed out, or its channel is off —
346
+ * rather than in our own code: a reference, range or syntax fault, or a TypeError the runtime raised with no cause (a call
347
+ * on something that is not a function), is a bug and is thrown as itself, never recorded on the conversation as a refusal.
348
+ * A network TypeError from fetch always carries its cause.
438
349
  */
439
- 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.
440
- 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.
441
- ${SHOWS[messenger] ?? SHOWS.Telegram} Your reply already reaches the chat — never also send it with the notify tool.
442
- 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.`;
443
- /** What a message forked beside the busy main conversation is told (#4584), about 70 tokens. */
444
- const BESIDE = "(BN: the main conversation of this chat is still busy on an earlier message of his, so this one runs at once beside it, in a parallel conversation. Answer this message only, under its own label, and leave the work under way to the main conversation.)";
445
- /** The answers his chat got from the forked conversations since the main one last heard from him (#4584): the main one, and each new fork of it, reads them as part of the chat. */
446
- function answeredBeside(key, main) {
447
- const heard = readEvents(main.id).filter((e) => e.role === "user").at(-1)?.ts ?? main.createdAt;
448
- const answers = listConversations()
449
- .filter((c) => c.chat === key && c.forkOf !== undefined && c.shelf !== "deleted")
450
- .flatMap((c) => readEvents(c.id).filter((e) => e.kind === "answer" && e.ts > heard))
451
- .sort((x, y) => x.ts.localeCompare(y.ts));
452
- return answers.length === 0 ? [] : [`(BN: while the main conversation worked, these answers reached his chat from conversations running beside it — read them as part of this chat:\n${answers.map((e) => `• «${e.text}»`).join("\n")})`];
453
- }
454
- /** The text one message of the bound chat is sent as: the brief on the conversation's first turn, what the chat was answered beside it and whether this one runs beside it, then what the chat knows around it, then his own words, last. */
455
- export function chatTurnText(key, text, context) {
456
- const brief = chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram");
457
- const bound = boundOf(key);
458
- // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
459
- if (bound === undefined)
460
- return [brief, ...context, text].join("\n\n");
461
- // A message beside a main conversation whose session is not written yet runs in a session of its own, which has not had the brief.
462
- const beside = forkedFrom(key) !== undefined;
463
- const first = !readEvents(bound.id).some((e) => e.role === "user") || (beside && !bound.started);
464
- return [...(first ? [brief] : []), ...answeredBeside(key, bound), ...(beside ? [BESIDE] : []), ...context, text].join("\n\n");
350
+ function deliveryFailure(err) {
351
+ if (!(err instanceof Error))
352
+ return false;
353
+ if (err instanceof ReferenceError || err instanceof RangeError || err instanceof SyntaxError)
354
+ return false;
355
+ return !(err instanceof TypeError) || err.cause !== undefined;
465
356
  }
466
357
  /** The Claude CLI's own folder of session transcripts. */
467
358
  function claudeProjects() {
@@ -497,18 +388,18 @@ class TranscriptTail {
497
388
  timer;
498
389
  /** Why the transcript could not be read on the last tick, named once until a read succeeds again. */
499
390
  unread;
500
- static of(id, reply, log) {
501
- const c = readConversation(id);
502
- if (c.provider !== "claude")
391
+ /** The tail of the relayed turn's own CLI session: a Claude turn's transcript, read from where it stands now; any other CLI writes none here. */
392
+ static of(turn, reply, log) {
393
+ if (turn.provider !== "claude")
503
394
  return undefined;
504
395
  try {
505
- return new TranscriptTail(c.sessionId, reply, log);
396
+ return new TranscriptTail(turn.sessionId, reply, log);
506
397
  }
507
398
  catch (err) {
508
399
  if (!fsFailure(err))
509
400
  throw err;
510
401
  // 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.
511
- log(`transcript ${c.sessionId} could not be read (${err.message}) — this turn's preview shows its working state only`);
402
+ log(`transcript ${turn.sessionId} could not be read (${err.message}) — this turn's preview shows its working state only`);
512
403
  return undefined;
513
404
  }
514
405
  }
@@ -598,14 +489,16 @@ function tookLine(event) {
598
489
  if (ms === undefined)
599
490
  return "";
600
491
  const seconds = Math.max(1, Math.round(ms / 1000));
601
- return `\n\n⏱ ${seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min ${seconds % 60} s`}`;
492
+ return `
493
+
494
+ ⏱ ${seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min ${seconds % 60} s`}`;
602
495
  }
603
496
  /** The bound chat's turns as they happen (#4453): the start line at once, each text the agent finishes as a message of its own, the answer with its choices as buttons. */
604
497
  export function streamedChat(messenger, log) {
605
498
  return {
606
499
  say: async (text) => { await messenger.send(text); },
607
- turn(id, _n, _queued, parallel) {
608
- const chat = parallel ? messenger.alongside() : messenger;
500
+ turn(turn) {
501
+ const chat = turn.parallel === true ? messenger.alongside() : messenger;
609
502
  const reply = new StreamedReply(chat, log);
610
503
  let tail;
611
504
  const ended = () => {
@@ -618,12 +511,14 @@ export function streamedChat(messenger, log) {
618
511
  };
619
512
  return {
620
513
  close,
621
- async event(event) {
514
+ async event(event, now) {
622
515
  switch (event.kind) {
623
516
  case "start":
624
517
  // The start line stays in the store for the web page; the chat gets no message before the first real output, so nothing sits between his message and his next one.
625
518
  // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
626
- tail ??= TranscriptTail.of(id, reply, log);
519
+ // The session the turn runs on is read off the event that starts it: a warm spare or a rotated session gives the record its id only then.
520
+ // NULL-OK: field now is OPTIONAL and therefore it is ok to check for NULL
521
+ tail ??= TranscriptTail.of(now ?? turn, reply, log);
627
522
  return;
628
523
  case "said":
629
524
  reply.said(event.text);
@@ -639,13 +534,13 @@ export function streamedChat(messenger, log) {
639
534
  return;
640
535
  case "asking": {
641
536
  const { text, choices } = choicesOf(event.text);
642
- reply.ask(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
537
+ reply.ask(text, choices.map((label, i) => ({ label, data: `b|${turn.id.slice(0, 8)}|${i}` })));
643
538
  return;
644
539
  }
645
540
  case "answer": {
646
541
  ended();
647
542
  const { text, choices } = choicesOf(event.text);
648
- return reply.finish(`${text}${tookLine(event)}`, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
543
+ return reply.finish(`${text}${tookLine(event)}`, choices.map((label, i) => ({ label, data: `b|${turn.id.slice(0, 8)}|${i}` })));
649
544
  }
650
545
  case "failed":
651
546
  ended();