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.
- package/dist/agentGateway.js +328 -433
- package/dist/daemon.js +6 -6
- package/dist/gateway/chatPage.js +0 -536
- package/dist/gateway/gatewayInstall.js +1 -2
- package/dist/gateway/oauthDoor.js +1 -2
- package/dist/gateway/panel.js +14 -17
- package/dist/gateway/passkeyDoor.js +1 -2
- package/dist/gateway/publicAccess.js +1 -2
- package/dist/gateway/restDoor.js +322 -161
- package/dist/messaging/chatInbound.js +3 -1
- package/dist/messaging/emailInbound.js +3 -7
- package/dist/notify.js +244 -87
- package/dist/shared/webhost/originHandover.js +4 -3
- package/dist/shared/webhost/workspaceList.js +56 -8
- package/package.json +2 -9
- package/dist/gateway/conversationOwner.js +0 -139
- package/dist/gateway/mcpDoor.js +0 -411
- package/dist/gateway/mcpEvents.js +0 -448
- package/dist/gateway/terminalDoor.js +0 -243
- package/dist/gateway/terminalPage.js +0 -613
- package/dist/shared/agentSession.js +0 -8375
- package/dist/shared/conversation/agentReaper.js +0 -218
- package/dist/shared/conversation/claudeProvider.js +0 -585
- package/dist/shared/conversation/cliSession.js +0 -481
- package/dist/shared/conversation/codexArchive.js +0 -67
- package/dist/shared/conversation/codexProvider.js +0 -240
- package/dist/shared/conversation/conversationOwner.js +0 -43
- package/dist/shared/conversation/conversations.js +0 -1037
- package/dist/shared/conversation/copilotProvider.js +0 -229
- package/dist/shared/conversation/nativeCliInvocation.js +0 -70
- package/dist/shared/conversation/nativeTerminal.js +0 -529
- package/dist/shared/conversation/nativeTerminalWorker.js +0 -158
- package/dist/shared/conversation/opencodeEvents/server.mjs +0 -36
- package/dist/shared/conversation/opencodeProvider.js +0 -375
- package/dist/shared/conversation/ownerContext.js +0 -1
- package/dist/shared/conversation/provider.js +0 -44
- package/dist/shared/conversation/providerProof.js +0 -75
- package/dist/shared/conversation/providers.js +0 -30
- package/dist/shared/conversation/sessionDriver.js +0 -1182
- package/dist/shared/conversation/terminalTransport.js +0 -126
- package/dist/shared/providerOwnership.js +0 -294
- package/dist/shared/webhost/autoSwitch.cjs +0 -2558
- package/dist/shared/workspaceList.js +0 -1
- package/scripts/shared/ownerGuard.cjs +0 -135
- package/scripts/shared/ownerGuard.sh +0 -64
- /package/dist/shared/{conversation/toolLine.js → toolLine.js} +0 -0
package/dist/agentGateway.js
CHANGED
|
@@ -1,467 +1,358 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The agent gateway's chat side (#2052): a Telegram, Slack, Discord
|
|
3
|
-
* the agent
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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 {
|
|
15
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
17
16
|
import { choicesOf, StreamedReply } from "./messaging/messenger.js";
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
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
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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
|
-
/**
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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
|
-
/**
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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(
|
|
110
|
+
return (AgentGateway.self ??= new AgentGateway());
|
|
144
111
|
}
|
|
145
|
-
/** The messages
|
|
146
|
-
|
|
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
|
-
/**
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
/**
|
|
188
|
-
|
|
189
|
-
|
|
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
|
-
/**
|
|
192
|
-
async
|
|
193
|
-
await
|
|
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
|
-
/**
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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
|
|
213
|
-
*
|
|
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
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
-
|
|
252
|
-
updateConversation(c.id, { slack: { ...c.slack, readTs } });
|
|
200
|
+
async markSlackRead(key, readTs) {
|
|
201
|
+
await chatCallWithDeadline("markSlackRead", { key, readTs });
|
|
253
202
|
}
|
|
254
|
-
/**
|
|
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
|
|
257
|
-
const
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
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
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
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
|
-
|
|
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
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
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
|
-
|
|
425
|
-
|
|
426
|
-
|
|
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
|
-
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
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
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
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
|
-
|
|
501
|
-
|
|
502
|
-
if (
|
|
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(
|
|
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 ${
|
|
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
|
|
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(
|
|
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
|
-
|
|
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();
|