omni-notify-mcp 1.3.475 β 1.3.477
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 +55 -30
- package/dist/gateway/mcpDoor.js +5 -5
- package/dist/gateway/restDoor.js +2 -2
- package/dist/gateway/terminalDoor.js +1 -1
- package/dist/messaging/messenger.js +124 -124
- package/dist/notify.js +59 -40
- package/dist/shared/agentSession.js +276 -39
- package/dist/shared/conversation/cliSession.js +19 -0
- package/dist/shared/conversation/conversations.js +32 -10
- package/dist/shared/conversation/opencodeEvents/server.mjs +4 -0
- package/dist/shared/conversation/opencodeProvider.js +42 -5
- package/dist/shared/conversation/provider.js +9 -0
- package/dist/shared/conversation/sessionDriver.js +27 -7
- package/dist/shared/webhost/bullseyeWebHost.js +2 -38
- package/dist/shared/webhost/webviewShim.js +1 -44
- package/package.json +1 -1
package/dist/agentGateway.js
CHANGED
|
@@ -18,6 +18,7 @@ import { choicesOf, StreamedReply } from "./messaging/messenger.js";
|
|
|
18
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
19
|
import { conversationOwner } from "./gateway/conversationOwner.js";
|
|
20
20
|
import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
|
|
21
|
+
import { toolLine } from "./shared/conversation/provider.js";
|
|
21
22
|
import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
|
|
22
23
|
export const AGENT_PREFIX = "!";
|
|
23
24
|
/** The thread's newest conversation is ended; the next message opens a fresh one. */
|
|
@@ -30,6 +31,8 @@ async function endNewest(key, _platform, end) {
|
|
|
30
31
|
return stay === 0 ? "π New conversation. Your next ! message starts it." : `π Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`;
|
|
31
32
|
}
|
|
32
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"]);
|
|
33
36
|
/** Each carried event of a turn sent as its parts. */
|
|
34
37
|
function partsRelay(reply, carriage) {
|
|
35
38
|
return {
|
|
@@ -47,7 +50,7 @@ const CHAT = {
|
|
|
47
50
|
routeOf: routeAsk,
|
|
48
51
|
stopOf: (key) => [stopTargetOf(key)].filter((c) => c !== undefined),
|
|
49
52
|
allOf: openConversationsOf,
|
|
50
|
-
carries: (kind) => kind !== "returned",
|
|
53
|
+
carries: (kind) => kind !== "returned" && !LIVE_KINDS.has(kind),
|
|
51
54
|
parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
|
|
52
55
|
stopped: stoppedOfMany,
|
|
53
56
|
renew: endNewest,
|
|
@@ -100,7 +103,7 @@ const ONE = {
|
|
|
100
103
|
return `π Fresh conversation β your next message starts it.${notice === undefined ? "" : `\n${notice.text}`}`;
|
|
101
104
|
},
|
|
102
105
|
};
|
|
103
|
-
const MAILED_KINDS = new Set(["answer", "failed", "stopped"]);
|
|
106
|
+
const MAILED_KINDS = new Set(["answer", "failed", "stopped", "asking"]);
|
|
104
107
|
/** An email thread: its one conversation, a stopped one resumed by the next reply; only what needs Meni is mailed, each whole. */
|
|
105
108
|
const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
|
|
106
109
|
const MAIL = {
|
|
@@ -203,7 +206,7 @@ export class AgentGateway {
|
|
|
203
206
|
const said = raw.trim();
|
|
204
207
|
const text = said.replace(/^!\s*/, "");
|
|
205
208
|
const cmd = text.match(COMMAND_RE);
|
|
206
|
-
const commanded = cmd !== null && (bare || text.startsWith("/") || said.startsWith(AGENT_PREFIX));
|
|
209
|
+
const commanded = cmd !== null && (bare || text.startsWith("/") || said.startsWith(AGENT_PREFIX) || cmd[1].toLowerCase() === "stop");
|
|
207
210
|
return commanded ? { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" } : { kind: "say", text };
|
|
208
211
|
}
|
|
209
212
|
/** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
|
|
@@ -242,7 +245,7 @@ export class AgentGateway {
|
|
|
242
245
|
const arrived = monotonicMs();
|
|
243
246
|
const carriage = carriageOf(platform, key);
|
|
244
247
|
const reply = typeof out === "function" ? out : out.say;
|
|
245
|
-
const relayOf = (id, n, queued) => (typeof out === "function" ? partsRelay(out, carriage) : out.turn(id, n, queued));
|
|
248
|
+
const relayOf = (id, n, queued, parallel = false) => (typeof out === "function" ? partsRelay(out, carriage) : out.turn(id, n, queued, parallel));
|
|
246
249
|
const refusal = conversationRefusal();
|
|
247
250
|
if (refusal !== undefined)
|
|
248
251
|
return reply(refusal);
|
|
@@ -289,7 +292,7 @@ export class AgentGateway {
|
|
|
289
292
|
const turn = {};
|
|
290
293
|
const [creation] = await Promise.allSettled([createdIn(project, act.kind === "say" ? act.provider : undefined, () => key, (on) => {
|
|
291
294
|
const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: act.text, receivedMs: monotonicMs() - arrived });
|
|
292
|
-
turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false));
|
|
295
|
+
turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false, forkOf !== undefined));
|
|
293
296
|
turn.id = created.id;
|
|
294
297
|
return created;
|
|
295
298
|
})]);
|
|
@@ -350,6 +353,8 @@ export class AgentGateway {
|
|
|
350
353
|
relay.close();
|
|
351
354
|
throw err;
|
|
352
355
|
});
|
|
356
|
+
if (LIVE_KINDS.has(event.kind))
|
|
357
|
+
continue;
|
|
353
358
|
const final = FINAL_KINDS.has(event.kind ?? "");
|
|
354
359
|
if (!closed)
|
|
355
360
|
editOwed(id, (o) => { if (final)
|
|
@@ -439,17 +444,9 @@ function transcriptOf(sessionId) {
|
|
|
439
444
|
function fsFailure(err) {
|
|
440
445
|
return err instanceof Error && typeof err.code === "string";
|
|
441
446
|
}
|
|
442
|
-
/** A tool step as he reads it: the tool and what it is doing. */
|
|
443
|
-
function stepOf(block) {
|
|
444
|
-
const input = block.input ?? {};
|
|
445
|
-
const what = [input.description, input.command, input.file_path, input.pattern, input.url, input.prompt].find((v) => typeof v === "string" && v.trim() !== "");
|
|
446
|
-
// NULL-OK: field what is OPTIONAL and therefore it is ok to check for NULL
|
|
447
|
-
const shown = what === undefined ? "" : ` β ${what.replace(/\s+/g, " ").slice(0, 90)}`;
|
|
448
|
-
return `π§ ${String(block.name ?? "tool")}${shown}`;
|
|
449
|
-
}
|
|
450
447
|
/**
|
|
451
|
-
* A conversation's Claude transcript read as it grows while a turn runs: each text block the agent writes
|
|
452
|
-
*
|
|
448
|
+
* A conversation's Claude transcript read as it grows while a turn runs: each text block the agent writes reaches the
|
|
449
|
+
* chat as a message once the agent has gone on to a tool or a next text. The CLI writes one line per block.
|
|
453
450
|
*/
|
|
454
451
|
class TranscriptTail {
|
|
455
452
|
sessionId;
|
|
@@ -543,27 +540,35 @@ class TranscriptTail {
|
|
|
543
540
|
this.log(`transcript ${this.sessionId}: a line is not JSON (${err.message}) β it is left out of the chat's preview`);
|
|
544
541
|
return;
|
|
545
542
|
}
|
|
546
|
-
if (
|
|
543
|
+
if (!Array.isArray(entry.message?.content))
|
|
547
544
|
return;
|
|
548
545
|
for (const block of entry.message.content) {
|
|
549
|
-
if (block.type === "text" && typeof block.text === "string")
|
|
546
|
+
if (entry.type === "assistant" && block.type === "text" && typeof block.text === "string")
|
|
550
547
|
this.reply.wrote(block.text);
|
|
551
|
-
if (block.type === "tool_use")
|
|
552
|
-
this.reply.step(
|
|
548
|
+
if (entry.type === "assistant" && block.type === "tool_use")
|
|
549
|
+
this.reply.step(String(block.id), toolLine(String(block.name ?? "tool"), block.input));
|
|
550
|
+
if (entry.type === "user" && block.type === "tool_result")
|
|
551
|
+
this.reply.stepDone(String(block.tool_use_id), block.is_error !== true);
|
|
553
552
|
}
|
|
554
553
|
}
|
|
555
554
|
}
|
|
556
|
-
/**
|
|
557
|
-
|
|
558
|
-
|
|
555
|
+
/** How long a turn took, in one short line a CLI prints when it ends; empty when the turn was not timed. */
|
|
556
|
+
function tookLine(event) {
|
|
557
|
+
const ms = event.timing?.agentMs ?? event.timing?.totalMs;
|
|
558
|
+
// NULL-OK: field ms is OPTIONAL and therefore it is ok to check for NULL
|
|
559
|
+
if (ms === undefined)
|
|
560
|
+
return "";
|
|
561
|
+
const seconds = Math.max(1, Math.round(ms / 1000));
|
|
562
|
+
return `\n\nβ± ${seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min ${seconds % 60} s`}`;
|
|
563
|
+
}
|
|
564
|
+
/** 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. */
|
|
559
565
|
export function streamedChat(messenger, log) {
|
|
560
566
|
return {
|
|
561
|
-
say: (text) => messenger.send(text),
|
|
562
|
-
turn(id, _n,
|
|
563
|
-
const
|
|
567
|
+
say: async (text) => { await messenger.send(text); },
|
|
568
|
+
turn(id, _n, _queued, parallel) {
|
|
569
|
+
const chat = parallel ? messenger.alongside() : messenger;
|
|
570
|
+
const reply = new StreamedReply(chat, log);
|
|
564
571
|
let tail;
|
|
565
|
-
if (!queued)
|
|
566
|
-
reply.begin();
|
|
567
572
|
const ended = () => {
|
|
568
573
|
// NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
|
|
569
574
|
tail?.stop();
|
|
@@ -577,16 +582,35 @@ export function streamedChat(messenger, log) {
|
|
|
577
582
|
async event(event) {
|
|
578
583
|
switch (event.kind) {
|
|
579
584
|
case "start":
|
|
580
|
-
|
|
585
|
+
// 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.
|
|
581
586
|
// NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
|
|
582
587
|
tail ??= TranscriptTail.of(id, reply, log);
|
|
583
588
|
return;
|
|
589
|
+
case "said":
|
|
590
|
+
reply.said(event.text);
|
|
591
|
+
return;
|
|
592
|
+
case "step":
|
|
593
|
+
// NULL-OK: field uid is OPTIONAL and therefore it is ok to check for NULL
|
|
594
|
+
reply.step(event.uid ?? event.text, event.text);
|
|
595
|
+
return;
|
|
596
|
+
case "stepDone":
|
|
597
|
+
case "stepFailed":
|
|
598
|
+
// NULL-OK: field uid is OPTIONAL and therefore it is ok to check for NULL
|
|
599
|
+
reply.stepDone(event.uid ?? "", event.kind === "stepDone", event.text);
|
|
600
|
+
return;
|
|
601
|
+
case "asking": {
|
|
602
|
+
const { text, choices } = choicesOf(event.text);
|
|
603
|
+
reply.ask(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
584
606
|
case "answer": {
|
|
585
607
|
ended();
|
|
586
608
|
const { text, choices } = choicesOf(event.text);
|
|
587
|
-
return reply.finish(text
|
|
609
|
+
return reply.finish(`${text}${tookLine(event)}`, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
|
|
588
610
|
}
|
|
589
611
|
case "failed":
|
|
612
|
+
ended();
|
|
613
|
+
return reply.finish(`${event.text}${tookLine(event)}`);
|
|
590
614
|
case "stopped":
|
|
591
615
|
case "archived":
|
|
592
616
|
case "deleted":
|
|
@@ -597,7 +621,8 @@ export function streamedChat(messenger, log) {
|
|
|
597
621
|
case "restored":
|
|
598
622
|
return;
|
|
599
623
|
default:
|
|
600
|
-
|
|
624
|
+
await chat.send(event.text);
|
|
625
|
+
return;
|
|
601
626
|
}
|
|
602
627
|
},
|
|
603
628
|
};
|
package/dist/gateway/mcpDoor.js
CHANGED
|
@@ -232,8 +232,8 @@ function buildServer(caller, base, offer) {
|
|
|
232
232
|
const target = conversation !== undefined ? seen(conversation) : (routes ? routeAsk(caller, text)?.id : undefined);
|
|
233
233
|
// NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
|
|
234
234
|
const sent = target === undefined
|
|
235
|
-
? { id: (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, text, receivedMs: Math.round(performance.now() - arrived), arrival }), model)).made.id, turn: 1 }
|
|
236
|
-
: { id: seen(target), turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival).n };
|
|
235
|
+
? { id: (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, text, receivedMs: Math.round(performance.now() - arrived), arrival }), model, viewerNow()?.folder)).made.id, turn: 1 }
|
|
236
|
+
: { id: seen(target), turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival, viewerNow()?.folder).n };
|
|
237
237
|
const { events, ended, turn } = await waitForTurn(sent.id, sent.turn, MAX_WAIT_SECONDS);
|
|
238
238
|
const meta = readConversation(sent.id);
|
|
239
239
|
const reply = events.filter((e) => e.turn === turn && REPLY_FIELD[e.kind] !== undefined).at(-1);
|
|
@@ -263,16 +263,16 @@ function buildServer(caller, base, offer) {
|
|
|
263
263
|
server.tool("agent_start", `Creates a new conversation AND submits text as its first task (turn 1) in one call, and returns {id, state} at once without waiting for the agent. The way to run a long or autonomous task: read its progress and answer with agent_wait {id, after:1, wait:${MAX_WAIT_SECONDS}}, again with the after each reply returned, until an event of kind answer or failed with turn 1, or of kind stopped, arrives. The task is already submitted, so do not also agent_send the same text, and do not call agent_start again for it β each call starts another agent on the task. agent_prompt sends and waits in one blocking call instead.`, { project: projectField(offer).optional().describe(`The workspace this conversation runs in: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never resolved from the text`), text: z.string().min(1).describe("The first task, submitted by this call itself"), provider: z.string().min(1).optional().describe(`The agent CLI this conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Use auto or omit it for the shared subscription-first choice. A permitted funded key is considered once eligible subscriptions are exhausted`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(async () => {
|
|
264
264
|
const arrived = performance.now();
|
|
265
265
|
const arrival = arrivalOf(requestIdOf(), randomUUID().slice(0, 8));
|
|
266
|
-
const meta = (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, text, receivedMs: Math.round(performance.now() - arrived), arrival }), model)).made;
|
|
266
|
+
const meta = (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, text, receivedMs: Math.round(performance.now() - arrived), arrival }), model, viewerNow()?.folder)).made;
|
|
267
267
|
return { id: meta.id, state: meta.state };
|
|
268
268
|
}));
|
|
269
269
|
server.tool("agent_open", `Opens a new conversation with no message and starts no agent: no text, no process started and nothing spent. It returns {id, state} at once. It names the workspace and the agent CLI the conversation opens on β project and provider are both optional: a conversation with no project runs at the workspace root, whose rules route each request to its project, and one with no provider runs on the agent CLI whose subscription has room. Ask it with agent_send and read it with agent_wait; the folder can be switched afterwards with agent_project, and the conversation keeps its id and its whole transcript.`, { project: projectField(offer).optional().describe(`Exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out for the workspace root (${offer.under}), where the rules of every project route the request; it is never resolved from anything else`), provider: z.string().min(1).optional().describe(`The agent CLI the conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Use auto or omit it for the shared subscription-first choice. A permitted funded key is considered once eligible subscriptions are exhausted`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(async () => {
|
|
270
|
-
const meta = (await createdOn(project, provider, () => caller, (on) => openConversation({ platform: "mcp", technical: true, chat: caller, ...on }), model)).made;
|
|
270
|
+
const meta = (await createdOn(project, provider, () => caller, (on) => openConversation({ platform: "mcp", technical: true, chat: caller, ...on }), model, viewerNow()?.folder)).made;
|
|
271
271
|
return { id: meta.id, state: meta.state };
|
|
272
272
|
}));
|
|
273
273
|
server.tool("agent_send", `Sends a message to a conversation that already exists (agent_start or agent_prompt made it) and returns {n} at once without waiting for the agent. n is the message's position in the log and the number of the turn it starts: read its answer with agent_wait {id, after:n, wait:${MAX_WAIT_SECONDS}}. A message sent while a turn runs is queued behind that turn, not an interrupt β also while a conversation's agent waits on a question on its own CLI screen, which the user answers there by opening the conversation in BN, never by a message to it. A stopped or archived conversation resumes. Each call submits its text once more, so do not repeat a send that returned.`, { id: z.string().min(1).describe("The conversation id agent_start returned, or the 'conversation' agent_prompt returned"), text: z.string().min(1).describe("The follow-up message; the first task belongs in agent_start") }, ({ id, text }) => act(() => {
|
|
274
274
|
const arrived = performance.now();
|
|
275
|
-
return { n: sendToConversation(seen(id), text, Math.round(performance.now() - arrived), arrivalOf(requestIdOf(), randomUUID().slice(0, 8))).n };
|
|
275
|
+
return { n: sendToConversation(seen(id), text, Math.round(performance.now() - arrived), arrivalOf(requestIdOf(), randomUUID().slice(0, 8)), viewerNow()?.folder).n };
|
|
276
276
|
}));
|
|
277
277
|
server.tool("agent_wait", `Reads a conversation's events past position 'after' β a long-poll read the caller repeats, not a notification BN pushes. With wait=0 (the default) it returns at once with whatever is there; with wait above 0 it holds the call until a new event arrives or the wait (at most ${MAX_WAIT_SECONDS} seconds) runs out, and an empty events list means nothing new yet. Repeat the call with the reply's after value (the position it leaves you at, a line it wrote itself included) until the turn you wait on ends: an event of kind answer or failed whose turn is that turn's number (1 after agent_start, the n agent_send returned), or an event of kind stopped. A question the agent asks does not end the turn: a status event says it waits on its own CLI screen, and the turn goes on once the user answers there. after=0 reads the log from the start, earlier turns' answers included. The state is not the end of the turn, because a conversation stays running until its idle process is freed. Reading sends nothing, so it is always safe to call again. Each answer or failed event carries its timing, in which a reply's time is three separate figures rather than one number: bnMs, the end-to-end elapsed time from the request arriving at BN's door to the answer being stored; queuedMs (beside queued, whether it stood in line at all β false is the store's own statement that it never stood in line, absent is unmeasured), the part of it the message waited for a free slot or the turn ahead; and agentMs, the part the agent itself worked. totalMs is BN's own total from the message being stored to the answer being stored, never the agent's time, and rows carries the turn layer by layer.`, { id: z.string().min(1), after: z.number().int().min(0).default(0).describe("The last event position n already read; events past it are returned. 1 right after agent_start, the n agent_send returned after a send"), wait: z.number().min(0).default(0).describe(`Seconds to hold the call for a new event, capped at ${MAX_WAIT_SECONDS}; 0 returns at once`) }, ({ id, after, wait }) => {
|
|
278
278
|
const arrived = performance.now();
|
package/dist/gateway/restDoor.js
CHANGED
|
@@ -175,7 +175,7 @@ async function route(req, url, arrivedAt) {
|
|
|
175
175
|
receivedMs = monotonicMs() - arrivedAt;
|
|
176
176
|
const chat = creatorOf(viewer, on.project);
|
|
177
177
|
return text === undefined ? openConversation({ platform: "rest", chat, ...on }) : startConversation({ platform: "rest", chat, ...on, text, receivedMs });
|
|
178
|
-
}, model);
|
|
178
|
+
}, model, viewer?.folder);
|
|
179
179
|
return { status: 201, body: { id: meta.id, state: meta.state, receivedMs } };
|
|
180
180
|
}
|
|
181
181
|
}
|
|
@@ -201,7 +201,7 @@ async function route(req, url, arrivedAt) {
|
|
|
201
201
|
else if (sub === "messages" && method === "POST") {
|
|
202
202
|
const text = requiredText(await readJson(req), "text");
|
|
203
203
|
const receivedMs = monotonicMs() - arrivedAt;
|
|
204
|
-
const event = sendToConversation(id, text, receivedMs);
|
|
204
|
+
const event = sendToConversation(id, text, receivedMs, undefined, viewer?.folder);
|
|
205
205
|
return { status: 202, body: { n: event.n, receivedMs } };
|
|
206
206
|
}
|
|
207
207
|
else if (sub === "events" && method === "GET") {
|
|
@@ -183,7 +183,7 @@ async function newAgent(body, viewer) {
|
|
|
183
183
|
const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined;
|
|
184
184
|
if (model !== undefined && !/^[a-zA-Z0-9._:/-]+$/.test(model))
|
|
185
185
|
throw new GatewayError(400, "Model must be its CLI name, without spaces or shell characters.");
|
|
186
|
-
return (await createdOn(body.project, body.provider, (folder) => creatorOf(viewer, folder), (on) => openConversation({ platform: "rest", chat: creatorOf(viewer, on.project), ...on }), model)).made.id;
|
|
186
|
+
return (await createdOn(body.project, body.provider, (folder) => creatorOf(viewer, folder), (on) => openConversation({ platform: "rest", chat: creatorOf(viewer, on.project), ...on }), model, viewer?.folder)).made.id;
|
|
187
187
|
}
|
|
188
188
|
/** The conversation's own CLI, opened by the session driver β never a second one β once it is running, or the reason this machine could not start it. */
|
|
189
189
|
async function opened(id) {
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
* One private chat as one BN conversation (#4453): the messenger interface the conversation's turn is relayed through,
|
|
3
3
|
* the streamed reply that paces its updates, and the Telegram messenger with every Bot API call classified.
|
|
4
4
|
*
|
|
5
|
-
* A turn
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* (
|
|
9
|
-
* "one message per second per chat".
|
|
5
|
+
* A turn says so in a real message the moment it starts, sends each text the agent finishes as a message of its own while
|
|
6
|
+
* the turn goes on β no faster than the platform allows β and ends in the answer, split at the platform's message limit,
|
|
7
|
+
* its π lines turned into buttons. There is no preview and no typing state: the chat shows only messages. Built from
|
|
8
|
+
* https://core.telegram.org/bots/api (sendMessage, answerCallbackQuery, editMessageReplyMarkup, ResponseParameters) and
|
|
9
|
+
* the Bot FAQ's "one message per second per chat".
|
|
10
10
|
*/
|
|
11
11
|
import { markdownToTelegramHtml, stripTelegramMarks } from "./telegramFormat.js";
|
|
12
12
|
import { messageBlocks } from "./slackBlocks.js";
|
|
@@ -74,110 +74,122 @@ export function splitMessage(text, limit) {
|
|
|
74
74
|
close(part, undefined);
|
|
75
75
|
return parts.filter((p) => p !== "");
|
|
76
76
|
}
|
|
77
|
+
// GATE: how long tool lines are held to be sent as ONE message β a run of tool calls costs a message, never one per call.
|
|
78
|
+
const STEP_BATCH_MS = 2500;
|
|
77
79
|
/**
|
|
78
|
-
* One turn's
|
|
79
|
-
*
|
|
80
|
-
*
|
|
80
|
+
* One turn's messages in a chat, slim and in order: each text the agent finishes is one message when it finishes, a run
|
|
81
|
+
* of tool calls is one short message of CLI-style lines, and the answer is one message at the end. Every message keeps the
|
|
82
|
+
* messenger's pace and its order; the turn's last text β its answer β is never also sent as a finished text. There is no
|
|
83
|
+
* streaming, no edit and no typing state: only messages.
|
|
81
84
|
*/
|
|
82
85
|
export class StreamedReply {
|
|
83
86
|
messenger;
|
|
84
|
-
id;
|
|
85
87
|
log;
|
|
86
|
-
|
|
87
|
-
doing = "";
|
|
88
|
-
shown;
|
|
88
|
+
held = "";
|
|
89
89
|
lastAt = 0;
|
|
90
|
-
timer;
|
|
91
|
-
/** The timer only re-sends an unchanged preview before it lapses, so a new update may take its place. */
|
|
92
|
-
holding = false;
|
|
93
90
|
inFlight = Promise.resolve();
|
|
94
91
|
ended = false;
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
constructor(messenger,
|
|
92
|
+
steps = [];
|
|
93
|
+
stepTimer;
|
|
94
|
+
constructor(messenger, log) {
|
|
98
95
|
this.messenger = messenger;
|
|
99
|
-
this.id = id;
|
|
100
96
|
this.log = log;
|
|
101
97
|
}
|
|
102
|
-
/**
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
if (this.began)
|
|
109
|
-
return this.schedule();
|
|
110
|
-
this.began = true;
|
|
111
|
-
this.flush();
|
|
112
|
-
}
|
|
113
|
-
/** A block of text the agent wrote during the turn. */
|
|
98
|
+
/** A text the agent finished writing: the tool lines before it go out first, then it is sent at once. */
|
|
99
|
+
said(text) {
|
|
100
|
+
this.flushSteps();
|
|
101
|
+
this.post(text);
|
|
102
|
+
}
|
|
103
|
+
/** A block of text the agent wrote, for a CLI that reports only finished blocks: the one before it is complete and goes out now, this one may be the answer and waits. */
|
|
114
104
|
wrote(block) {
|
|
115
105
|
const text = block.trim();
|
|
116
106
|
if (text === "")
|
|
117
107
|
return;
|
|
118
|
-
this.
|
|
119
|
-
this.
|
|
108
|
+
this.release();
|
|
109
|
+
this.held = text;
|
|
110
|
+
}
|
|
111
|
+
/** The agent started a tool: the text it wrote before is complete, and the tool is a line of the next steps message. */
|
|
112
|
+
step(id, line) {
|
|
113
|
+
if (this.ended)
|
|
114
|
+
return;
|
|
115
|
+
this.release();
|
|
116
|
+
this.steps.push({ id, text: line, mark: "" });
|
|
117
|
+
// NULL-OK: field stepTimer is OPTIONAL and therefore it is ok to check for NULL
|
|
118
|
+
this.stepTimer ??= setTimeout(() => this.flushSteps(), STEP_BATCH_MS);
|
|
119
|
+
this.stepTimer.unref();
|
|
120
|
+
}
|
|
121
|
+
/** A tool ended: its line shows how, if its message has not gone out yet; a run of tools that has all ended goes out at once. */
|
|
122
|
+
stepDone(id, ok, why) {
|
|
123
|
+
const line = this.steps.find((s) => s.id === id);
|
|
124
|
+
// NULL-OK: field line is OPTIONAL and therefore it is ok to check for NULL
|
|
125
|
+
if (line === undefined)
|
|
126
|
+
return;
|
|
127
|
+
line.mark = ok ? " β
" : ` β${why === undefined || why === "" ? "" : ` ${why}`}`;
|
|
128
|
+
if (this.steps.every((s) => s.mark !== ""))
|
|
129
|
+
this.flushSteps();
|
|
130
|
+
}
|
|
131
|
+
/** The tool lines waiting go out as one message. */
|
|
132
|
+
flushSteps() {
|
|
133
|
+
clearTimeout(this.stepTimer);
|
|
134
|
+
this.stepTimer = undefined;
|
|
135
|
+
if (this.steps.length === 0)
|
|
136
|
+
return;
|
|
137
|
+
const text = this.steps.map((s) => `${s.text}${s.mark}`).join("\n");
|
|
138
|
+
this.steps = [];
|
|
139
|
+
this.post(text);
|
|
120
140
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
this.
|
|
141
|
+
release() {
|
|
142
|
+
if (this.held === "")
|
|
143
|
+
return;
|
|
144
|
+
const text = this.held;
|
|
145
|
+
this.held = "";
|
|
146
|
+
this.said(text);
|
|
125
147
|
}
|
|
126
|
-
/** Ends the
|
|
148
|
+
/** Ends the reply with nothing more to send: the turn was ended from the chat. */
|
|
127
149
|
close() {
|
|
128
150
|
this.ended = true;
|
|
129
|
-
|
|
151
|
+
this.held = "";
|
|
152
|
+
this.steps = [];
|
|
153
|
+
clearTimeout(this.stepTimer);
|
|
154
|
+
this.stepTimer = undefined;
|
|
130
155
|
}
|
|
131
|
-
/** Ends the
|
|
156
|
+
/** Ends the turn and sends the reply's final text, split at the limit, its choices as buttons on the last part. */
|
|
132
157
|
async finish(text, buttons = []) {
|
|
158
|
+
this.flushSteps();
|
|
133
159
|
this.ended = true;
|
|
134
|
-
|
|
160
|
+
this.held = "";
|
|
135
161
|
await this.inFlight;
|
|
136
|
-
const
|
|
137
|
-
const parts = splitMessage(body, this.messenger.limit);
|
|
162
|
+
const parts = splitMessage(text, this.messenger.limit);
|
|
138
163
|
for (const [i, part] of parts.entries()) {
|
|
139
|
-
|
|
140
|
-
await
|
|
164
|
+
await this.paced();
|
|
165
|
+
await this.messenger.send(part, i === parts.length - 1 ? buttons : [], i === 0);
|
|
141
166
|
this.lastAt = Date.now();
|
|
142
|
-
await this.messenger.send(part, i === parts.length - 1 ? buttons : [], i === 0 ? this.id : undefined);
|
|
143
167
|
}
|
|
144
168
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const room = this.messenger.limit - 2;
|
|
149
|
-
return whole.length <= room ? whole : `β¦${whole.slice(whole.length - room)}`;
|
|
150
|
-
}
|
|
151
|
-
/** The next update at the messenger's pace; one already paced is left to go, a hold waiting to re-send the preview gives way to it. */
|
|
152
|
-
schedule() {
|
|
153
|
-
if (this.ended || this.previewOff !== undefined || (this.timer !== undefined && !this.holding))
|
|
154
|
-
return;
|
|
155
|
-
this.wait(Math.max(0, this.lastAt + this.messenger.paceMs - Date.now()), false);
|
|
169
|
+
/** Waits until the platform's pace allows the next message: its gap is counted from the end of the last one. */
|
|
170
|
+
paced() {
|
|
171
|
+
return sleep(Math.max(0, this.lastAt + this.messenger.paceMs - Date.now()));
|
|
156
172
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
this.
|
|
160
|
-
this.
|
|
161
|
-
this.timer.unref();
|
|
173
|
+
/** A question the agent asks mid-turn: one message with its choices as buttons, and the turn goes on after it. */
|
|
174
|
+
ask(text, buttons) {
|
|
175
|
+
this.flushSteps();
|
|
176
|
+
this.post(text, buttons, true);
|
|
162
177
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
if (this.ended ||
|
|
178
|
+
post(text, buttons = [], answer = false) {
|
|
179
|
+
const body = text.trim();
|
|
180
|
+
if (this.ended || body === "")
|
|
166
181
|
return;
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
this.previewOff = why;
|
|
178
|
-
this.log(`preview ${this.id} not shown: ${why}${this.previewOff === undefined ? " β the next update sends it again" : " β no more previews this turn"}`);
|
|
182
|
+
this.inFlight = this.inFlight.then(async () => {
|
|
183
|
+
const parts = splitMessage(body, this.messenger.limit);
|
|
184
|
+
for (const [i, part] of parts.entries()) {
|
|
185
|
+
await this.paced();
|
|
186
|
+
await this.messenger.send(part, i === parts.length - 1 ? buttons : [], answer && i === 0);
|
|
187
|
+
this.lastAt = Date.now();
|
|
188
|
+
}
|
|
189
|
+
}).catch((err) => {
|
|
190
|
+
// OWNER: a text of a turn is sent from the turn's own event trigger β one that cannot be sent is named in the log and the answer, sent whole at the end, still carries the turn.
|
|
191
|
+
this.log(`a text of the turn was not sent: ${err instanceof Error ? err.message : String(err)}`);
|
|
179
192
|
});
|
|
180
|
-
this.wait(this.messenger.holdMs, true);
|
|
181
193
|
}
|
|
182
194
|
}
|
|
183
195
|
// ββ Telegram βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -267,7 +279,7 @@ export async function telegramCall(url, method, body, tries = TELEGRAM_TRIES, ti
|
|
|
267
279
|
}
|
|
268
280
|
}
|
|
269
281
|
const unparsable = (err) => err instanceof TelegramRefused && err.status === 400 && /can't parse entities/i.test(err.description);
|
|
270
|
-
/** The bound private chat: messages in Telegram's rich text,
|
|
282
|
+
/** The bound private chat: messages in Telegram's rich text, choices as inline buttons. */
|
|
271
283
|
export class TelegramMessenger {
|
|
272
284
|
api;
|
|
273
285
|
file;
|
|
@@ -276,13 +288,13 @@ export class TelegramMessenger {
|
|
|
276
288
|
switchedOn;
|
|
277
289
|
log;
|
|
278
290
|
thread;
|
|
291
|
+
replyTo;
|
|
292
|
+
quoting;
|
|
279
293
|
// GATE: source characters per message β Telegram takes 4096 after entities are parsed, and the markdown source is never shorter than what it renders, so a part this size always fits.
|
|
280
294
|
limit = 3900;
|
|
281
|
-
// GATE: the Bot FAQ's "avoid sending more than one message per second" in a chat β no
|
|
295
|
+
// GATE: the Bot FAQ's "avoid sending more than one message per second" in a chat β no two messages of a turn go out faster.
|
|
282
296
|
paceMs = 1000;
|
|
283
|
-
|
|
284
|
-
holdMs = 20_000;
|
|
285
|
-
constructor(api, file, chatId, mode, switchedOn, log, thread) {
|
|
297
|
+
constructor(api, file, chatId, mode, switchedOn, log, thread, replyTo, quoting = false) {
|
|
286
298
|
this.api = api;
|
|
287
299
|
this.file = file;
|
|
288
300
|
this.chatId = chatId;
|
|
@@ -290,16 +302,22 @@ export class TelegramMessenger {
|
|
|
290
302
|
this.switchedOn = switchedOn;
|
|
291
303
|
this.log = log;
|
|
292
304
|
this.thread = thread;
|
|
305
|
+
this.replyTo = replyTo;
|
|
306
|
+
this.quoting = quoting;
|
|
293
307
|
}
|
|
294
308
|
/** #4586: every message of this messenger lands in its story's topic when it has one. */
|
|
295
309
|
get topic() { return this.thread === undefined ? {} : { message_thread_id: this.thread }; }
|
|
296
310
|
async send(text, buttons = []) {
|
|
297
|
-
|
|
298
|
-
await this.formatted("sendMessage", { chat_id: this.chatId, reply_markup, ...this.topic }, text);
|
|
311
|
+
await this.formatted("sendMessage", { chat_id: this.chatId, reply_markup: this.markup(buttons), ...this.topic, ...this.quote }, text);
|
|
299
312
|
}
|
|
300
|
-
|
|
301
|
-
|
|
313
|
+
alongside() {
|
|
314
|
+
return this.replyTo === undefined ? this : new TelegramMessenger(this.api, this.file, this.chatId, this.mode, this.switchedOn, this.log, this.thread, this.replyTo, true);
|
|
302
315
|
}
|
|
316
|
+
markup(buttons) {
|
|
317
|
+
return buttons.length === 0 ? undefined : { inline_keyboard: buttons.map((b) => [{ text: b.label, callback_data: b.data }]) };
|
|
318
|
+
}
|
|
319
|
+
/** The message every one of this messenger's quotes, when it runs beside another conversation's. */
|
|
320
|
+
get quote() { return this.quoting && this.replyTo !== undefined ? { reply_parameters: { message_id: this.replyTo, allow_sending_without_reply: true } } : {}; }
|
|
303
321
|
/** The bytes of a photo or file he sent, by getFile and its download link; Telegram's own refusal (a file over 20 MB) is thrown as it said it. */
|
|
304
322
|
async received(fileId) {
|
|
305
323
|
const { file_path } = await telegramCall(this.api("getFile"), "getFile", { file_id: fileId });
|
|
@@ -504,11 +522,8 @@ export class SlackMessenger {
|
|
|
504
522
|
tappable;
|
|
505
523
|
// GATE: source characters per message β chat.update refuses a text over 4,000 characters (msg_too_long), and mrkdwn's escapes (& as &) can lengthen the source, so a part leaves room for them.
|
|
506
524
|
limit = 3500;
|
|
507
|
-
// GATE: chat.
|
|
525
|
+
// GATE: chat.postMessage is Tier 4 and Slack asks for about one message per second per channel β no two messages of a turn go out faster than this.
|
|
508
526
|
paceMs = 1200;
|
|
509
|
-
// GATE: a Slack message stays until it is edited, so an unchanged preview is sent again only after ten minutes.
|
|
510
|
-
holdMs = 600_000;
|
|
511
|
-
previews = new Map();
|
|
512
527
|
constructor(base, token, channel, switchedOn,
|
|
513
528
|
/** The thread every message of this view lands in; undefined posts at the top of the chat. */
|
|
514
529
|
threadTs, state = { choices: [] }, log = () => undefined,
|
|
@@ -527,57 +542,42 @@ export class SlackMessenger {
|
|
|
527
542
|
inThread(ts) {
|
|
528
543
|
return new SlackMessenger(this.base, this.token, this.channel, this.switchedOn, ts, { choices: [] }, this.log, this.tappable);
|
|
529
544
|
}
|
|
530
|
-
async send(text, buttons = [],
|
|
545
|
+
async send(text, buttons = [], answer = false) {
|
|
546
|
+
const { fallback, blocks } = this.shown(text, buttons, answer);
|
|
547
|
+
await this.post(fallback, blocks);
|
|
548
|
+
}
|
|
549
|
+
/** Slack threads its own replies; a parallel conversation's answers are labelled by the thread they are in. */
|
|
550
|
+
alongside() {
|
|
551
|
+
return this;
|
|
552
|
+
}
|
|
553
|
+
shown(text, buttons, answer) {
|
|
531
554
|
const labels = buttons.map((b) => b.label);
|
|
532
555
|
const numbered = labels.map((label, i) => `${KEYCAPS[i] ?? `${i + 1}.`} ${label}`);
|
|
533
556
|
// The text is what a notification and a client without blocks show, so it carries the choices too.
|
|
534
557
|
const fallback = numbered.length === 0 ? text : `${text}\n\n${numbered.join("\n")}\n_Tap a choice, reply with its number, or answer in your own words._`;
|
|
535
558
|
// Each answer's own choices replace the last ones, so a number he answers a later question with is never taken as an older choice.
|
|
536
|
-
|
|
537
|
-
if (ends !== undefined)
|
|
559
|
+
if (answer)
|
|
538
560
|
this.state.choices = [];
|
|
539
561
|
if (labels.length > 0)
|
|
540
562
|
this.state.choices = labels;
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
this.previews.delete(ends);
|
|
546
|
-
const blocks = messageBlocks(text, labels, `bn_choices_${Date.now().toString(36)}`, this.tappable());
|
|
547
|
-
// NULL-OK: field preview is OPTIONAL and therefore it is ok to check for NULL
|
|
548
|
-
await this.post(preview, fallback, blocks);
|
|
549
|
-
}
|
|
550
|
-
async draft(id, text) {
|
|
551
|
-
const shown = text === "" ? "β³ _Workingβ¦_" : text;
|
|
552
|
-
const posted = await this.post(this.previews.get(id), shown, messageBlocks(shown, [], "bn_preview"));
|
|
553
|
-
// NULL-OK: field posted is OPTIONAL and therefore it is ok to check for NULL
|
|
554
|
-
if (posted !== undefined)
|
|
555
|
-
this.previews.set(id, posted);
|
|
556
|
-
}
|
|
557
|
-
/** Posts the message, or edits `ts` into it, as blocks; blocks Slack refuses go out once more as the plain mrkdwn text, logged. Answers the ts of a new message. */
|
|
558
|
-
async post(ts, text, blocks) {
|
|
563
|
+
return { fallback, blocks: messageBlocks(text, labels, `bn_choices_${Date.now().toString(36)}`, this.tappable()) };
|
|
564
|
+
}
|
|
565
|
+
/** Posts the message as blocks; blocks Slack refuses go out once more as the plain mrkdwn text, logged. */
|
|
566
|
+
async post(text, blocks) {
|
|
559
567
|
const where = { channel: this.channel };
|
|
560
568
|
// NULL-OK: field threadTs is OPTIONAL and therefore it is ok to check for NULL
|
|
561
|
-
if (
|
|
569
|
+
if (this.threadTs !== undefined)
|
|
562
570
|
where.thread_ts = this.threadTs;
|
|
563
|
-
// NULL-OK: field ts is OPTIONAL and therefore it is ok to check for NULL
|
|
564
|
-
const method = ts === undefined ? "chat.postMessage" : "chat.update";
|
|
565
|
-
// NULL-OK: field ts is OPTIONAL and therefore it is ok to check for NULL
|
|
566
|
-
if (ts !== undefined)
|
|
567
|
-
where.ts = ts;
|
|
568
571
|
const shown = markdownToSlackMrkdwn(text);
|
|
569
|
-
let answer;
|
|
570
572
|
try {
|
|
571
|
-
|
|
573
|
+
await this.call("chat.postMessage", { ...where, text: shown, blocks: JSON.stringify(blocks) });
|
|
572
574
|
}
|
|
573
575
|
catch (err) {
|
|
574
576
|
if (!(err instanceof SlackRefused) || err.error !== "invalid_blocks")
|
|
575
577
|
throw err;
|
|
576
|
-
this.log(
|
|
577
|
-
|
|
578
|
+
this.log(`chat.postMessage to ${this.channel} went out as plain text β Slack refused its blocks: ${err.message}`);
|
|
579
|
+
await this.call("chat.postMessage", { ...where, text: shown, blocks: "[]" });
|
|
578
580
|
}
|
|
579
|
-
// NULL-OK: field ts is OPTIONAL and therefore it is ok to check for NULL
|
|
580
|
-
return ts === undefined ? String(answer.ts) : undefined;
|
|
581
581
|
}
|
|
582
582
|
/** One post or edit in the chat, refused while Slack is switched off in BN settings. */
|
|
583
583
|
call(method, body) {
|