@kadaliao/dsh-bots 0.9.0 → 0.10.0
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/README.md +91 -42
- package/README.zh-CN.md +63 -31
- package/client.js +437 -377
- package/index.js +518 -117
- package/lib/cards.mjs +53 -7
- package/lib/channels/discord.mjs +3 -0
- package/lib/channels/feishu.mjs +4 -1
- package/lib/channels/slack.mjs +8 -3
- package/lib/channels/telegram.mjs +7 -2
- package/lib/channels.mjs +27 -10
- package/lib/discussions.mjs +300 -0
- package/lib/prompt.mjs +18 -10
- package/lib/store.mjs +20 -2
- package/lib/threads.mjs +16 -4
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -55,11 +55,12 @@ import { createSettings } from './lib/settings.mjs';
|
|
|
55
55
|
import { createPriceCatalog, priceOf } from './lib/prices.mjs';
|
|
56
56
|
import { createLedger, promptTokens, report, ticketUsage, todayByBot, usageRow } from './lib/usage.mjs';
|
|
57
57
|
import { createSlots, createTickets, parkedOf, REPORT_STATUSES, sessionIdOf, stageOf } from './lib/tickets.mjs';
|
|
58
|
-
import { assignmentText, clip, failedNoticeText, followUpNoticeText, nudgeText, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, stalledNoticeText } from './lib/cards.mjs';
|
|
58
|
+
import { assignmentText, clip, discussionNoteText, failedNoticeText, followUpNoticeText, NEWS_MESSAGES, nudgeText, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, stalledNoticeText, threadNewsText } from './lib/cards.mjs';
|
|
59
59
|
import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
|
|
60
60
|
import { isLiveSubscriber, isPanelThread, isTopicThread, panelThreadKey, panelTopicOf, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
|
|
61
61
|
import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
|
|
62
62
|
import { createTopics, rotationReason } from './lib/topics.mjs';
|
|
63
|
+
import { chatMessageRef, createDiscussions, forkPoint, messageRef, seqByTime } from './lib/discussions.mjs';
|
|
63
64
|
import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
|
|
64
65
|
|
|
65
66
|
/**
|
|
@@ -239,6 +240,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
239
240
|
const memory = createMemory(join(dir, 'memory'));
|
|
240
241
|
const topics = createTopics(dir);
|
|
241
242
|
const tickets = createTickets(dir, { now: nowMs });
|
|
243
|
+
// Replies to one message talked over in a forked Session of their own (Bots 0.10).
|
|
244
|
+
const discussions = createDiscussions(dir, { now: nowMs });
|
|
242
245
|
// A tasks file that is there but cannot be read stops the plugin now, before anything writes over it.
|
|
243
246
|
try {
|
|
244
247
|
tickets.open();
|
|
@@ -311,14 +314,18 @@ export function apply(ctx, config, deps = {}) {
|
|
|
311
314
|
}
|
|
312
315
|
const activity = createActivity({ now: nowMs, secrets: channelSecrets, handleOf: (ref) => (store.find(String(ref)) ? `@${store.find(String(ref)).handle}` : '') });
|
|
313
316
|
|
|
314
|
-
/** The bot of a home Session or of a ticket Session (its executing bot). */
|
|
317
|
+
/** The bot of a home Session, of a discussion (forked from its conversation), or of a ticket Session (its executing bot). */
|
|
315
318
|
function botOfSession(sessionId) {
|
|
316
319
|
if (!sessionId) return undefined;
|
|
317
320
|
const home = store.bySession(sessionId);
|
|
318
321
|
if (home) return home;
|
|
322
|
+
const d = discussions.bySession(sessionId);
|
|
323
|
+
if (d) return store.get(d.botId);
|
|
319
324
|
const t = ticketOf(sessionId);
|
|
320
325
|
return t ? store.get(t.botId) : undefined;
|
|
321
326
|
}
|
|
327
|
+
/** Whether `sessionId` is `bot`'s home, or a discussion forked from its conversation (it talks to the person like the home). */
|
|
328
|
+
const isHomeOf = (bot, sessionId) => Boolean(bot && sessionId) && (bot.sessionId === sessionId || discussions.bySession(sessionId)?.botId === bot.id);
|
|
322
329
|
const dispatcherMode = () => settings.get().dispatcher;
|
|
323
330
|
/**
|
|
324
331
|
* Router mode is in effect: the setting says so and the dispatcher has someone to hand work to. A
|
|
@@ -328,7 +335,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
328
335
|
const routerActive = () => dispatcherMode() === 'router' && store.list().length > 1;
|
|
329
336
|
/** The dispatcher works as a router (in its home; its ticket Sessions are ordinary workers). */
|
|
330
337
|
const isRouter = (bot) => Boolean(bot) && bot.role === 'primary' && routerActive();
|
|
331
|
-
const isRouterHome = (bot, sessionId) => isRouter(bot) &&
|
|
338
|
+
const isRouterHome = (bot, sessionId) => isRouter(bot) && isHomeOf(bot, sessionId) && !ticketOf(sessionId);
|
|
332
339
|
/** Bot-to-bot work opens tickets (router mode), or goes to the other bot's home as in 0.7 (hands-on). */
|
|
333
340
|
const ticketsOn = () => dispatcherMode() === 'router';
|
|
334
341
|
|
|
@@ -344,7 +351,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
344
351
|
for (const a of asks.values()) {
|
|
345
352
|
if (!a.continued) continue;
|
|
346
353
|
const t = a.ticketId ? tickets.get(a.ticketId) : null;
|
|
347
|
-
if (a.ticketId ? !t || t.ended || t.archivedAt : store.get(a.botId)
|
|
354
|
+
if (a.ticketId ? !t || t.ended || t.archivedAt : !isHomeOf(store.get(a.botId), a.sessionId)) asks.delete(a.id);
|
|
348
355
|
}
|
|
349
356
|
return [...asks.values()];
|
|
350
357
|
}
|
|
@@ -357,8 +364,14 @@ export function apply(ctx, config, deps = {}) {
|
|
|
357
364
|
// Chat channels run outside the Agent; changing one does not restart the bot's MCP clients.
|
|
358
365
|
// A linked local skill counts by what its SKILL.md is now, so an edit there re-installs it.
|
|
359
366
|
// A router home also changes with the dispatcher mode and the role (its tool limits and guard).
|
|
367
|
+
/** What Harness keeps of a tool's result must be plain JSON: an `undefined` field (a panel reply has no `via`) fails the whole call. */
|
|
368
|
+
const lossless = (o) => JSON.parse(JSON.stringify(o ?? {}));
|
|
369
|
+
/** A team (more than one bot): the dispatcher's helpers are its teammates, so Harness's own sub-agents are off for it (the other bots keep theirs). */
|
|
370
|
+
const inTeam = () => store.list().length > 1;
|
|
371
|
+
const noSubagents = (bot) => bot?.role === 'primary' && inTeam();
|
|
372
|
+
const SUBAGENT_TOOLS = ABILITIES.find((a) => a.id === 'delegate')?.tools ?? [];
|
|
360
373
|
const signatureOf = (bot, sessionId) =>
|
|
361
|
-
JSON.stringify({ s: bot.skills, l: bot.skills.filter((s) => s.linked && s.enabled).map((s) => readLinkedSkill(s.dir)?.stamp ?? ''), a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle, r: isRouterHome(bot, sessionId) ? 1 : 0 });
|
|
374
|
+
JSON.stringify({ s: bot.skills, l: bot.skills.filter((s) => s.linked && s.enabled).map((s) => readLinkedSkill(s.dir)?.stamp ?? ''), a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle, r: isRouterHome(bot, sessionId) ? 1 : 0, m: noSubagents(bot) ? 1 : 0 });
|
|
362
375
|
/** The chat apps the team can be reached from ('Telegram'), for the persona. */
|
|
363
376
|
const channelNames = (bots) => {
|
|
364
377
|
const tpl = templates();
|
|
@@ -467,9 +480,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
467
480
|
ctx.logger?.warn?.(`bots: memory for @${bot.handle}: ${error?.message ?? error}`);
|
|
468
481
|
}
|
|
469
482
|
}
|
|
470
|
-
// A router home is also denied the tools that do the work, except those the user gave back.
|
|
483
|
+
// A router home is also denied the tools that do the work, except those the user gave back; a team's dispatcher starts no sub-agents.
|
|
471
484
|
const allowed = new Set(bot.tools.routerAllow ?? []);
|
|
472
|
-
const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : [])])];
|
|
485
|
+
const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : []), ...(noSubagents(bot) ? SUBAGENT_TOOLS : [])])];
|
|
473
486
|
if (wanted.length > 0) {
|
|
474
487
|
const tools = service(actx, 'tools');
|
|
475
488
|
try {
|
|
@@ -529,6 +542,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
529
542
|
);
|
|
530
543
|
ctx.effect(() => () => {
|
|
531
544
|
for (const id of [...installed.keys()]) uninstall(id);
|
|
545
|
+
discussions.flush();
|
|
532
546
|
}, 'bots: unwind bot scopes');
|
|
533
547
|
/** Apply every bot again to its live home and ticket Sessions (a bot, the roles or the dispatcher mode changed). */
|
|
534
548
|
function reapply() {
|
|
@@ -738,8 +752,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
738
752
|
replied: false,
|
|
739
753
|
};
|
|
740
754
|
openTasks.set(sessionId, task);
|
|
741
|
-
// A ticket Session is no topic of the bot's: rotation only ever looks at its home.
|
|
742
|
-
if (!ticket) topics.current(bot.id, sessionId);
|
|
755
|
+
// A ticket Session or a discussion is no topic of the bot's: rotation only ever looks at its home.
|
|
756
|
+
if (!ticket && !discussions.bySession(sessionId)) topics.current(bot.id, sessionId);
|
|
743
757
|
return task;
|
|
744
758
|
}
|
|
745
759
|
function logLine(task, line) {
|
|
@@ -755,7 +769,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
755
769
|
const task = openTasks.get(sessionId);
|
|
756
770
|
const ticketId = ticketOf(sessionId)?.id;
|
|
757
771
|
ledger.record(usageRow({ at, botId: bot.id, sessionId, taskId: kind === 'chat' || kind === 'compaction' ? task?.id : undefined, ticketId, kind, provider, model, usage }));
|
|
758
|
-
if (kind === 'chat' && !ticketId) topics.noteCall(bot.id, sessionId, promptTokens(usage));
|
|
772
|
+
if (kind === 'chat' && !ticketId && !discussions.bySession(sessionId)) topics.noteCall(bot.id, sessionId, promptTokens(usage));
|
|
759
773
|
}
|
|
760
774
|
/** The task of `sessionId` is over when its Agent is idle again. */
|
|
761
775
|
function settleSoon(sessionId, delay = 1200) {
|
|
@@ -784,7 +798,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
784
798
|
if (t?.ended) reflectTicket(t);
|
|
785
799
|
return;
|
|
786
800
|
}
|
|
787
|
-
topics.noteTask(task.b, task.s, task.title);
|
|
801
|
+
if (!discussions.bySession(task.s)) topics.noteTask(task.b, task.s, task.title);
|
|
788
802
|
if (bot) queueReflection(bot, { ...row, log });
|
|
789
803
|
}
|
|
790
804
|
/** ticketId → transcript lines of its finished runs, for the summary written when it ends. */
|
|
@@ -934,6 +948,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
934
948
|
|
|
935
949
|
// --- topics ------------------------------------------------------------------------------------
|
|
936
950
|
const rotating = new Map();
|
|
951
|
+
/** When a bot last started a new topic (ms; 0: not since this process started). */
|
|
952
|
+
let rotatedAt = 0;
|
|
937
953
|
/**
|
|
938
954
|
* Start `bot`'s next topic: a fresh conversation (the old one is archived, its
|
|
939
955
|
* scheduled tasks move to the new one). Refused while the bot is working.
|
|
@@ -991,6 +1007,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
991
1007
|
}
|
|
992
1008
|
uninstall(prev);
|
|
993
1009
|
forgetSession(prev);
|
|
1010
|
+
// Harness closes the panel when the conversation behind it is archived; the panel opens itself again.
|
|
1011
|
+
rotatedAt = nowMs();
|
|
994
1012
|
try {
|
|
995
1013
|
await service(ctx, 'workspaceRegistry')?.archiveSession?.(prev);
|
|
996
1014
|
} catch (error) {
|
|
@@ -998,6 +1016,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
998
1016
|
}
|
|
999
1017
|
}
|
|
1000
1018
|
topics.rotate(bot.id, next, reason);
|
|
1019
|
+
rotatedAt = nowMs();
|
|
1001
1020
|
store.log({ from: 'system', to: bot.id, kind: 'topic', text: reason });
|
|
1002
1021
|
return next;
|
|
1003
1022
|
})().finally(() => rotating.delete(bot.id));
|
|
@@ -1167,7 +1186,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1167
1186
|
return agent.session.id;
|
|
1168
1187
|
}
|
|
1169
1188
|
|
|
1170
|
-
// --- the panel chat
|
|
1189
|
+
// --- the panel chat (Bots 0.9; threads 0.10) ------------------------------------------
|
|
1171
1190
|
/** A new id for a message typed in the panel: `p` and 8 letters or digits, short enough for a model to copy. */
|
|
1172
1191
|
const newPanelId = () => {
|
|
1173
1192
|
for (;;) {
|
|
@@ -1188,6 +1207,59 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1188
1207
|
};
|
|
1189
1208
|
/** Who wrote a timeline message, as a header names them. */
|
|
1190
1209
|
const writerOf = (m) => (m.from === 'user' ? 'the user' : store.get(m.from) ? `@${store.get(m.from).handle}` : 'a bot');
|
|
1210
|
+
/** A message bots send each other (a DM or a report between two bots), not one said to the person. */
|
|
1211
|
+
const betweenBots = (m) => m.from !== 'user' && m.to !== 'user' && (m.kind === 'dm' || m.kind === 'report');
|
|
1212
|
+
/**
|
|
1213
|
+
* What was said in the threads of `bot`'s panel chat since its main conversation (Session `sid`)
|
|
1214
|
+
* last heard, as the note before the person's next message there (Bots 0.10): the panel shows those
|
|
1215
|
+
* replies in the chat, quoted. Since the later of the last note and the start of the current topic.
|
|
1216
|
+
* Returns `{text, upTo}` (`upTo`: the time of the latest message told; 0 for none).
|
|
1217
|
+
*/
|
|
1218
|
+
function threadNewsFor(bot, sid) {
|
|
1219
|
+
const cur = topics.peek(bot.id);
|
|
1220
|
+
const since = Math.max(discussions.toldAt(bot.id), cur?.sessionId === sid ? Number(cur.startedAt) || 0 : 0);
|
|
1221
|
+
const rows = store
|
|
1222
|
+
.messages({ bot: bot.id, limit: 400, roots: false })
|
|
1223
|
+
.filter((m) => Number(m.at) > since && !m.via && m.kind !== 'system' && m.kind !== 'topic' && !betweenBots(m) && rootIdOf(m) !== m.id && String(m.text ?? '').trim())
|
|
1224
|
+
.slice(-NEWS_MESSAGES);
|
|
1225
|
+
if (!rows.length) return { text: '', upTo: 0 };
|
|
1226
|
+
const byRoot = new Map();
|
|
1227
|
+
for (const m of rows) {
|
|
1228
|
+
const r = rootIdOf(m);
|
|
1229
|
+
if (!byRoot.has(r)) {
|
|
1230
|
+
const root = store.message(r);
|
|
1231
|
+
const whose = !root ? '' : root.from === bot.id ? 'your message' : root.from === 'user' ? "the user's message" : `${writerOf(root)}'s message`;
|
|
1232
|
+
byRoot.set(r, { who: whose, text: root?.text ?? '', said: [] });
|
|
1233
|
+
}
|
|
1234
|
+
byRoot.get(r).said.push({ who: m.from === 'user' ? 'The user' : m.from === bot.id ? 'You' : writerOf(m), text: m.text });
|
|
1235
|
+
}
|
|
1236
|
+
return { text: threadNewsText({ threads: [...byRoot.values()] }), upTo: Math.max(...rows.map((m) => Number(m.at) || 0)) };
|
|
1237
|
+
}
|
|
1238
|
+
/** Characters of the message a reply quotes, as the chat shows it. */
|
|
1239
|
+
const QUOTE_CHARS = 140;
|
|
1240
|
+
/**
|
|
1241
|
+
* The message a reply in a thread quotes, as the chat shows it (Bots 0.10): the person's, the one
|
|
1242
|
+
* they replied to (the thread's root unless they picked another of it); a bot's, the person's
|
|
1243
|
+
* latest message of the thread before it, else the root. Null for a message of the main chat.
|
|
1244
|
+
* @param {object} m
|
|
1245
|
+
* @param {Map<string, object[]>} replies - per root, the thread's messages in order
|
|
1246
|
+
* @param {(id: string) => object | undefined} lookup
|
|
1247
|
+
*/
|
|
1248
|
+
function quoteOf(m, replies, lookup) {
|
|
1249
|
+
const rootId = rootIdOf(m);
|
|
1250
|
+
if (!rootId || rootId === m.id) return null;
|
|
1251
|
+
let target = m.from === 'user' && m.replyTo ? lookup(m.replyTo) : null;
|
|
1252
|
+
if (!target && m.from !== 'user') {
|
|
1253
|
+
for (const x of replies.get(rootId) ?? []) {
|
|
1254
|
+
if (x.id === m.id) break;
|
|
1255
|
+
if (x.from === 'user' && x.kind === 'user') target = x;
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
target ??= lookup(rootId);
|
|
1259
|
+
if (!target) return null;
|
|
1260
|
+
const text = clip(String(target.text ?? '').replace(/\s+/g, ' ').trim(), QUOTE_CHARS).text;
|
|
1261
|
+
return { id: target.id, from: target.from, text, ...(target.who ? { who: target.who } : {}), ...(target.via ? { via: target.via } : {}) };
|
|
1262
|
+
}
|
|
1191
1263
|
/** The tasks a dispatcher's panel message may continue: open, or ended within a day; the latest change first. */
|
|
1192
1264
|
function openTasksOf(bot) {
|
|
1193
1265
|
const since = nowMs() - 24 * 3600_000;
|
|
@@ -1196,26 +1268,123 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1196
1268
|
.filter((t) => t.requester?.botId === bot.id && !t.requester?.ticketId && (!t.ended || t.ended.at >= since))
|
|
1197
1269
|
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
1198
1270
|
}
|
|
1271
|
+
// --- discussions: replies to one message, in a Session of their own (Bots 0.10) ----------
|
|
1272
|
+
/** The root of the discussion a timeline message is in; the message itself when it is in the main chat. */
|
|
1273
|
+
const rootIdOf = (m) => (m?.topic && m.topic !== m.id ? m.topic : m?.movedTo && m.movedTo !== m.id ? m.movedTo : m?.id ?? '');
|
|
1274
|
+
/** The Thread a Session's plain words go to when its turn named none: a discussion's own, else the panel. */
|
|
1275
|
+
const homeThreadOf = (sessionId) => discussions.bySession(sessionId)?.key ?? panelThreadKey(sessionId);
|
|
1199
1276
|
/**
|
|
1200
|
-
* The
|
|
1201
|
-
*
|
|
1202
|
-
* topic becomes the first of one. `{root, key, quoted}`.
|
|
1277
|
+
* The Session of `bot`'s that a timeline message was said in: noted on it, the panel conversation
|
|
1278
|
+
* its Thread names, the bot's own task it belongs to, or else the bot's home.
|
|
1203
1279
|
*/
|
|
1204
|
-
function
|
|
1205
|
-
if (
|
|
1206
|
-
const
|
|
1207
|
-
if (
|
|
1208
|
-
const
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1280
|
+
function sessionOfMessage(m, bot) {
|
|
1281
|
+
if (m?.sid) return m.sid;
|
|
1282
|
+
const p = parseThreadKey(m?.thread);
|
|
1283
|
+
if (p?.kind === 'panel' && p.sessionId) return p.sessionId;
|
|
1284
|
+
const t = m?.ticket ? tickets.get(m.ticket) : undefined;
|
|
1285
|
+
if (t?.sessionId && t.botId === bot.id) return t.sessionId;
|
|
1286
|
+
return bot.sessionId ?? '';
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Where `m` sits in a Session of `bot`'s: its anchor (kept since 0.10), else found in that
|
|
1290
|
+
* Session's log by time (an older message; a person's counts with the answer its turn gave).
|
|
1291
|
+
* Null when it cannot be told.
|
|
1292
|
+
*/
|
|
1293
|
+
async function positionOfMessage(m, bot) {
|
|
1294
|
+
const a = discussions.anchorOf(messageRef(m.id));
|
|
1295
|
+
if (a && isMine(bot, a.sessionId)) return a;
|
|
1296
|
+
const sessionId = sessionOfMessage(m, bot);
|
|
1297
|
+
if (!sessionId || !isMine(bot, sessionId)) return null;
|
|
1298
|
+
const seq = seqByTime(await readHistory(sessionId).catch(() => null), { at: Number(m.at), fromPerson: m.from === 'user' });
|
|
1299
|
+
return seq === undefined ? null : { sessionId, seq };
|
|
1300
|
+
}
|
|
1301
|
+
/** Whether a Session is `bot`'s: its home (now or an earlier topic), a discussion of it, or its task. */
|
|
1302
|
+
function isMine(bot, sessionId) {
|
|
1303
|
+
if (!sessionId) return false;
|
|
1304
|
+
const owner = botOfSession(sessionId);
|
|
1305
|
+
if (owner) return owner.id === bot.id;
|
|
1306
|
+
// An earlier topic of the bot's (archived): its conversations are still the bot's.
|
|
1307
|
+
return topics.peek(bot.id)?.sessionId === sessionId || topics.history(bot.id).some((x) => x.sessionId === sessionId);
|
|
1308
|
+
}
|
|
1309
|
+
/** Name a Session for its bot and give it the bot's model (a fork starts with Harness's default). */
|
|
1310
|
+
function decorate(agent, bot, title) {
|
|
1311
|
+
try {
|
|
1312
|
+
service(ctx, 'sessionTitle')?.rename?.(agent.session, title || bot.name);
|
|
1313
|
+
} catch {
|
|
1314
|
+
// A title is cosmetic.
|
|
1315
|
+
}
|
|
1316
|
+
const fresh = store.get(bot.id) ?? bot;
|
|
1317
|
+
if (fresh.model) {
|
|
1318
|
+
try {
|
|
1319
|
+
agent.model?.select?.(selectionOf(fresh.model));
|
|
1320
|
+
} catch {
|
|
1321
|
+
// The default model stays.
|
|
1322
|
+
}
|
|
1216
1323
|
}
|
|
1217
|
-
return { root, key, quoted };
|
|
1218
1324
|
}
|
|
1325
|
+
/** A discussion's Session again: taken out of the archive when it was put there. Null when it cannot come back. */
|
|
1326
|
+
async function reopenDiscussion(d) {
|
|
1327
|
+
const controller = service(ctx, 'sessionController');
|
|
1328
|
+
const reg = service(ctx, 'workspaceRegistry');
|
|
1329
|
+
if (d.archivedAt || (reg?.archivedSessionIds ?? []).includes(d.sessionId)) {
|
|
1330
|
+
try {
|
|
1331
|
+
await reg?.unarchiveSession?.(d.sessionId);
|
|
1332
|
+
} catch {
|
|
1333
|
+
return null;
|
|
1334
|
+
}
|
|
1335
|
+
if ((reg?.archivedSessionIds ?? []).includes(d.sessionId)) return null;
|
|
1336
|
+
discussions.patch(d.key, { archivedAt: null });
|
|
1337
|
+
}
|
|
1338
|
+
const found = await controller.resolveAgent(d.sessionId).catch((error) => ({ error }));
|
|
1339
|
+
if (!found || 'error' in found) return null;
|
|
1340
|
+
reconcile(found.agent);
|
|
1341
|
+
return found.agent;
|
|
1342
|
+
}
|
|
1343
|
+
const opening = new Map();
|
|
1344
|
+
/**
|
|
1345
|
+
* The discussion `key` is talked over in, opened the first time: `bot`'s conversation forked at
|
|
1346
|
+
* `point` (`{sessionId, seq?}`; no seq: its latest finished turn). One that cannot come back from
|
|
1347
|
+
* the archive continues from its own last turn. Returns `{discussion, agent}`.
|
|
1348
|
+
*/
|
|
1349
|
+
function discussionFor(bot, key, { point, rootId, title }) {
|
|
1350
|
+
if (opening.has(key)) return opening.get(key);
|
|
1351
|
+
const job = (async () => {
|
|
1352
|
+
const controller = service(ctx, 'sessionController');
|
|
1353
|
+
if (!controller) throw new Error('threads need the Web profile (no session controller here)');
|
|
1354
|
+
const known = discussions.get(key);
|
|
1355
|
+
if (known && known.botId === bot.id) {
|
|
1356
|
+
const agent = await reopenDiscussion(known);
|
|
1357
|
+
if (agent) return { discussion: discussions.get(key), agent };
|
|
1358
|
+
}
|
|
1359
|
+
if (typeof controller.fork !== 'function') throw new Error('this DeepSeek Harness cannot fork a conversation; update it to reply in a thread');
|
|
1360
|
+
const from = known?.botId === bot.id ? { sessionId: known.sessionId } : point;
|
|
1361
|
+
if (!from?.sessionId) throw new Error('the conversation that message was said in is gone; send it as a new message instead');
|
|
1362
|
+
let forked;
|
|
1363
|
+
// Forked at the replied message: the thread sees nothing said after it. Otherwise (the place is not
|
|
1364
|
+
// known, or cannot be forked) at the latest turn, and the note says the conversation may go on past it.
|
|
1365
|
+
let exact = from.seq !== undefined;
|
|
1366
|
+
try {
|
|
1367
|
+
forked = await controller.fork({ sessionId: from.sessionId, ...(from.seq !== undefined ? { atSeq: from.seq } : {}) });
|
|
1368
|
+
} catch (error) {
|
|
1369
|
+
if (from.seq === undefined) throw error;
|
|
1370
|
+
ctx.logger?.warn?.(`bots: forking at event ${from.seq} of ${from.sessionId}: ${error?.message ?? error}; forking at its latest turn`);
|
|
1371
|
+
forked = await controller.fork({ sessionId: from.sessionId });
|
|
1372
|
+
exact = false;
|
|
1373
|
+
}
|
|
1374
|
+
const d = discussions.add({ key, botId: bot.id, sessionId: forked.sessionId, rootId, source: from, title });
|
|
1375
|
+
if (known?.noted) discussions.patch(key, { noted: true });
|
|
1376
|
+
if (!known && !exact) discussions.patch(key, { exact: false });
|
|
1377
|
+
const found = await controller.resolveAgent(d.sessionId);
|
|
1378
|
+
if ('error' in found) throw found.error;
|
|
1379
|
+
reconcile(found.agent);
|
|
1380
|
+
decorate(found.agent, bot, title ? `${bot.name} · ${title}` : bot.name);
|
|
1381
|
+
return { discussion: discussions.get(key), agent: found.agent };
|
|
1382
|
+
})().finally(() => opening.delete(key));
|
|
1383
|
+
opening.set(key, job);
|
|
1384
|
+
return job;
|
|
1385
|
+
}
|
|
1386
|
+
/** One line of a message, for a discussion's title. */
|
|
1387
|
+
const titleOf = (text) => clip(String(text ?? '').replace(/\s+/g, ' ').trim(), 40).text;
|
|
1219
1388
|
/** A timeline message as the panel reads it: `pending` while no model has taken it yet; internal fields left out. */
|
|
1220
1389
|
function messageView(m) {
|
|
1221
1390
|
const { sid, ...rest } = m;
|
|
@@ -1234,15 +1403,16 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1234
1403
|
/**
|
|
1235
1404
|
* The user writes to a bot from the panel. `/new` (or `/clear`, `/新话题`) first starts a new
|
|
1236
1405
|
* topic of its conversation; text after it goes there. Every message is logged before it is
|
|
1237
|
-
* handed over (the panel shows it at once, `pending` until a model takes it)
|
|
1238
|
-
*
|
|
1239
|
-
*
|
|
1240
|
-
*
|
|
1241
|
-
* homes take it as a turn of its own. Returns `{sessionId, message?}`.
|
|
1406
|
+
* handed over (the panel shows it at once, `pending` until a model takes it). A message goes
|
|
1407
|
+
* to the main chat: the bot's home (a router steers it, with the tasks it may continue in a
|
|
1408
|
+
* header; other homes take it as a turn of its own). With `replyTo` it is a reply in the thread
|
|
1409
|
+
* of that message (Bots 0.10, `threadSend`). Returns `{sessionId, message?}`.
|
|
1242
1410
|
*/
|
|
1243
1411
|
async function userSend(target, text, { replyTo = '' } = {}) {
|
|
1244
1412
|
let body = String(text ?? '').trim();
|
|
1245
1413
|
if (body === '') throw new Error('text must not be empty');
|
|
1414
|
+
const ref = String(replyTo ?? '').trim();
|
|
1415
|
+
if (ref) return threadSend(store.get(target.id) ?? target, body, ref);
|
|
1246
1416
|
const cmd = TOPIC_COMMAND.exec(body);
|
|
1247
1417
|
if (cmd) {
|
|
1248
1418
|
const sessionId = await newTopic(target, 'manual');
|
|
@@ -1253,30 +1423,90 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1253
1423
|
const agent = await agentOf(bot);
|
|
1254
1424
|
const sid = agent.session.id;
|
|
1255
1425
|
const id = newPanelId();
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
const
|
|
1259
|
-
|
|
1426
|
+
store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: panelThreadKey(sid), sid });
|
|
1427
|
+
// The panel shows thread replies in the chat: what the person read there since, the main conversation hears first.
|
|
1428
|
+
const news = threadNewsFor(bot, sid);
|
|
1429
|
+
const header = isRouterHome(bot, sid) ? panelHeaderText({ open: openTasksOf(bot) }, cardCtx()) : '';
|
|
1430
|
+
try {
|
|
1431
|
+
await sendTo(agent, { content: [news.text, header, body].filter(Boolean).map((text) => ({ type: 'text', text })), source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
|
|
1432
|
+
} catch (error) {
|
|
1433
|
+
// Not handed over: it leaves the chat (the panel keeps its own copy to send again).
|
|
1434
|
+
store.patchMessage(id, { hidden: true });
|
|
1435
|
+
throw error;
|
|
1436
|
+
}
|
|
1437
|
+
if (news.upTo) discussions.markTold(bot.id, news.upTo);
|
|
1438
|
+
return { sessionId: sid, message: messageView(store.message(id)) };
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
/**
|
|
1442
|
+
* A reply in the thread of message `ref` in `bot`'s chat (Bots 0.10). A message in the main chat
|
|
1443
|
+
* opens its thread; one in a thread stays in that thread (it is quoted). The thread of a task's
|
|
1444
|
+
* message, or one a task follows, goes to the task (as in 0.9); any other is a discussion: the
|
|
1445
|
+
* bot's conversation forked at the replied message, so it sees what came before and nothing the
|
|
1446
|
+
* main chat said since. Returns `{sessionId, message}`.
|
|
1447
|
+
*/
|
|
1448
|
+
async function threadSend(bot, body, ref) {
|
|
1449
|
+
if (TOPIC_COMMAND.test(body)) throw new Error('a thread has no new topic: send /new in the main chat');
|
|
1450
|
+
const quoted = store.message(ref);
|
|
1451
|
+
if (!quoted || !inChat(quoted, bot.id)) throw new Error('that message is not in this chat');
|
|
1452
|
+
const rootId = rootIdOf(quoted);
|
|
1453
|
+
const root = rootId === quoted.id ? quoted : store.message(rootId);
|
|
1454
|
+
if (!root) throw new Error('the message this thread answers is gone');
|
|
1455
|
+
const homeSid = sessionOfMessage(root, bot);
|
|
1456
|
+
// The thread keeps the key it was opened with (the home may have a new topic since).
|
|
1457
|
+
const said = store.messages({ bot: bot.id, topic: rootId, limit: 50 }).find((m) => m.id !== rootId && panelTopicOf(m.thread) === rootId);
|
|
1458
|
+
const key = topicKeyOf(root, rootId) || discussions.byRoot(rootId)?.key || said?.thread || panelThreadKey(homeSid || bot.sessionId || 'panel', rootId);
|
|
1459
|
+
const id = newPanelId();
|
|
1460
|
+
const aside = quoted.id !== rootId ? quoted : null;
|
|
1461
|
+
store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: key, topic: rootId, ...(aside ? { replyTo: aside.id } : {}) });
|
|
1462
|
+
// A task's thread (opened on the task's own message, or a 0.9 topic it follows): the person's words go to the task.
|
|
1463
|
+
// In a discussion they go to its bot, who has the tasks it opened there report back into it.
|
|
1464
|
+
const talking = discussions.get(key);
|
|
1465
|
+
let live = talking ? [] : tickets.subscribers(key).filter(isLiveSubscriber);
|
|
1466
|
+
const own = root.ticket ? tickets.get(root.ticket) : undefined;
|
|
1467
|
+
if (!live.length && own && isLiveSubscriber(own)) {
|
|
1468
|
+
tickets.subscribe(own.id, key, { label: threadLabel({ threadKey: key, threadTitle: root.text }) });
|
|
1469
|
+
// Its later reports are shown in this thread.
|
|
1470
|
+
tickets.patch(own.id, { showIn: key });
|
|
1471
|
+
live = [tickets.get(own.id)];
|
|
1472
|
+
}
|
|
1260
1473
|
if (live.length) {
|
|
1261
1474
|
try {
|
|
1262
|
-
const sessions = await toTopicTasks(bot, live, body, { key, root, id, quoted });
|
|
1263
|
-
return { sessionId: sessions[0] ??
|
|
1475
|
+
const sessions = await toTopicTasks(bot, live, body, { key, root: rootId, id, quoted });
|
|
1476
|
+
return { sessionId: sessions[0] ?? bot.sessionId, message: messageView(store.message(id)) };
|
|
1264
1477
|
} catch (error) {
|
|
1265
|
-
// No task took it (one ended meanwhile, say):
|
|
1266
|
-
ctx.logger?.warn?.(`bots: a
|
|
1478
|
+
// No task took it (one ended meanwhile, say): a discussion does.
|
|
1479
|
+
ctx.logger?.warn?.(`bots: a reply did not reach its task (${error?.message ?? error}); @${bot.handle} takes it in a thread`);
|
|
1267
1480
|
}
|
|
1268
1481
|
}
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1482
|
+
let opened;
|
|
1483
|
+
try {
|
|
1484
|
+
const at = await positionOfMessage(root, bot);
|
|
1485
|
+
const point = forkPoint({ root: at, fallback: isMine(bot, homeSid) ? homeSid : bot.sessionId });
|
|
1486
|
+
opened = await discussionFor(bot, key, { point, rootId, title: titleOf(root.text) });
|
|
1487
|
+
} catch (error) {
|
|
1488
|
+
store.patchMessage(id, { hidden: true });
|
|
1489
|
+
throw error;
|
|
1490
|
+
}
|
|
1491
|
+
const { discussion, agent } = opened;
|
|
1492
|
+
// The first message of the thread carries the note; claimed now, so a second reply at once does not repeat it.
|
|
1493
|
+
const first = !discussions.get(key)?.noted;
|
|
1494
|
+
if (first) discussions.patch(key, { noted: true });
|
|
1495
|
+
const header = first
|
|
1496
|
+
? discussionNoteText({ who: writerOf(root), text: root.text, exact: discussion.exact !== false, ...(aside ? { quoted: { who: writerOf(aside), text: aside.text } } : {}) })
|
|
1497
|
+
: aside
|
|
1498
|
+
? panelHeaderText({ replyTo: { who: writerOf(aside), text: aside.text } })
|
|
1499
|
+
: '';
|
|
1500
|
+
store.patchMessage(id, { sid: agent.session.id });
|
|
1272
1501
|
try {
|
|
1273
1502
|
await sendTo(agent, { content: header ? [{ type: 'text', text: header }, { type: 'text', text: body }] : [{ type: 'text', text: body }], source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
|
|
1274
1503
|
} catch (error) {
|
|
1275
|
-
// Not handed over: it leaves the chat (the panel keeps its own copy to send again).
|
|
1276
1504
|
store.patchMessage(id, { hidden: true });
|
|
1505
|
+
if (first) discussions.patch(key, { noted: null });
|
|
1277
1506
|
throw error;
|
|
1278
1507
|
}
|
|
1279
|
-
|
|
1508
|
+
discussions.patch(key, { lastAt: nowMs() });
|
|
1509
|
+
return { sessionId: agent.session.id, message: messageView(store.message(id)) };
|
|
1280
1510
|
}
|
|
1281
1511
|
|
|
1282
1512
|
/**
|
|
@@ -1299,13 +1529,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1299
1529
|
}
|
|
1300
1530
|
if (!reached.length) throw lastError ?? new Error('no task took the reply');
|
|
1301
1531
|
store.patchMessage(id, { ticket: reached[0].id });
|
|
1302
|
-
|
|
1532
|
+
// Whoever asked for the tasks hears of it without waking: the bot's home, or the thread of it that opened them.
|
|
1533
|
+
const told = new Set();
|
|
1534
|
+
for (const t of reached) {
|
|
1303
1535
|
try {
|
|
1304
|
-
const
|
|
1305
|
-
if (
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
}
|
|
1536
|
+
const asked = t.requester?.kind === 'session' && t.requester.botId === bot.id && !t.requester.ticketId ? await requesterAgent(t) : await agentOf(bot);
|
|
1537
|
+
if (!asked || told.has(asked.session.id)) continue;
|
|
1538
|
+
told.add(asked.session.id);
|
|
1539
|
+
const text = followUpNoticeText({ tickets: reached, thread: { key: root, label: threadLabel({ threadKey: key, threadTitle: store.message(root)?.text }) }, who: 'The user', text: body }, cardCtx());
|
|
1540
|
+
await sendTo(asked, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:panel:${id}` });
|
|
1309
1541
|
} catch (error) {
|
|
1310
1542
|
ctx.logger?.warn?.(`bots: the follow-up notice for @${bot.handle}: ${error?.message ?? error}`);
|
|
1311
1543
|
}
|
|
@@ -1334,28 +1566,6 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1334
1566
|
.current(sessionId)
|
|
1335
1567
|
.filter((o) => o.kind !== 'panel' || o.rootId)
|
|
1336
1568
|
.map((o) => (o.kind === 'panel' ? `${o.rootId} (${threadLabel(o)})` : `${o.threadKey} (${threadLabel(o)}${o.tickets?.length ? `; task ${o.tickets.join(', ')}` : ''})`));
|
|
1337
|
-
/**
|
|
1338
|
-
* A home added a person's new message to an open task (`bot_send_message` with `ticket`): when
|
|
1339
|
-
* that task came from a panel topic and this turn has one other panel topic that is only that
|
|
1340
|
-
* message (or the one `chosen` names), the message is filed under the task's topic (`movedTo`),
|
|
1341
|
-
* and this turn's replies go there. Returns the task's topic root, or ''.
|
|
1342
|
-
*/
|
|
1343
|
-
function fileUnder(t, sessionId, chosen) {
|
|
1344
|
-
const target = t.origin?.threadKey;
|
|
1345
|
-
const toRoot = target ? panelTopicOf(target) : '';
|
|
1346
|
-
if (!toRoot) return '';
|
|
1347
|
-
const candidates = channels.current(sessionId).filter((o) => o.kind === 'panel' && o.rootId && o.threadKey !== target && tickets.subscribers(o.threadKey).length === 0);
|
|
1348
|
-
const pick = chosen ? candidates.find((o) => o.threadKey === chosen) : candidates.length === 1 ? candidates[0] : undefined;
|
|
1349
|
-
if (!pick) return '';
|
|
1350
|
-
const first = store.message(pick.rootId);
|
|
1351
|
-
if (!first || first.from !== 'user' || first.movedTo) return '';
|
|
1352
|
-
// Only a topic nobody answered in yet is filed away whole.
|
|
1353
|
-
if (store.messages({ topic: pick.rootId, limit: 5 }).some((m) => m.id !== pick.rootId)) return '';
|
|
1354
|
-
store.patchMessage(pick.rootId, { movedTo: toRoot });
|
|
1355
|
-
channels.retarget(sessionId, pick.threadKey, target, { threadTitle: clip(store.message(toRoot)?.text ?? '', 60).text });
|
|
1356
|
-
return toRoot;
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
1569
|
// --- tickets: delegated work in Sessions of their own ---------------------------------
|
|
1360
1570
|
/** What cards and relays read about the team and the tickets. */
|
|
1361
1571
|
const cardCtx = () => ({ bots: store.list(), threads: tickets, tickets, stageOf });
|
|
@@ -1643,6 +1853,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1643
1853
|
return resolveId(parent.sessionId ?? r.sessionId);
|
|
1644
1854
|
}
|
|
1645
1855
|
const bot = r.botId ? store.get(r.botId) : undefined;
|
|
1856
|
+
// Asked from a thread of the bot's (Bots 0.10): the thread hears of it, back from the archive if need be.
|
|
1857
|
+
const asked = discussions.bySession(r.sessionId);
|
|
1858
|
+
if (bot && asked?.botId === bot.id) return (await reopenDiscussion(asked)) ?? agentOf(bot);
|
|
1646
1859
|
// The asking bot may have started a new topic since: its report goes to the conversation it has now.
|
|
1647
1860
|
if (bot && bot.sessionId !== r.sessionId) return agentOf(bot);
|
|
1648
1861
|
return (await resolveId(r.sessionId)) ?? (bot ? agentOf(bot) : null);
|
|
@@ -1688,7 +1901,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1688
1901
|
function mayAppend(t, sender, sessionId) {
|
|
1689
1902
|
const r = t.requester ?? {};
|
|
1690
1903
|
if (r.sessionId === sessionId) return true;
|
|
1691
|
-
|
|
1904
|
+
// The asking bot's home, or a thread of it (Bots 0.10): the person may carry a task on there.
|
|
1905
|
+
if (sender && r.botId === sender.id && !r.ticketId && isHomeOf(sender, sessionId)) return true;
|
|
1692
1906
|
return Boolean(sender) && isRouterHome(sender, sessionId);
|
|
1693
1907
|
}
|
|
1694
1908
|
|
|
@@ -1757,8 +1971,14 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1757
1971
|
async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen, relay = false } = {}) {
|
|
1758
1972
|
const body = String(text ?? '').trim();
|
|
1759
1973
|
if (body === '') throw new Error('text must not be empty');
|
|
1760
|
-
// The dispatcher
|
|
1761
|
-
if (sender.id === target.id
|
|
1974
|
+
// The dispatcher only hands out (Bots 0.10; 0.9 let it hand work to itself): the work goes to a teammate.
|
|
1975
|
+
if (sender.id === target.id) {
|
|
1976
|
+
throw new Error(
|
|
1977
|
+
isRouterHome(sender, senderSessionId)
|
|
1978
|
+
? 'you are the dispatcher: hand the work to a teammate, the closest fit (any of them can look things up and write); answer yourself only from what you already know'
|
|
1979
|
+
: 'a bot cannot message itself',
|
|
1980
|
+
);
|
|
1981
|
+
}
|
|
1762
1982
|
if (!service(ctx, 'sessionController')) throw new Error('tasks need the Web profile (no session controller here)');
|
|
1763
1983
|
const parent = ticketOf(senderSessionId);
|
|
1764
1984
|
const { origin, thread } = originOfTurn(senderSessionId, chosen);
|
|
@@ -1825,7 +2045,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1825
2045
|
* (the report then goes to whoever asked, as in 0.8).
|
|
1826
2046
|
*/
|
|
1827
2047
|
function showReport(t, report) {
|
|
1828
|
-
|
|
2048
|
+
// Where the person carries the task on (a thread opened on it, Bots 0.10), else where it came from.
|
|
2049
|
+
const key = t.showIn || t.origin?.threadKey;
|
|
1829
2050
|
if (!key) return null;
|
|
1830
2051
|
const worker = store.get(t.botId);
|
|
1831
2052
|
const owner = t.requester?.botId ? store.get(t.requester.botId) : undefined;
|
|
@@ -2127,6 +2348,20 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2127
2348
|
tickets.archive(t.id);
|
|
2128
2349
|
slots.release(t.id);
|
|
2129
2350
|
}
|
|
2351
|
+
// Threads quiet for a day leave the sidebar; a new reply brings one back (Bots 0.10).
|
|
2352
|
+
for (const d of discussions.idle()) {
|
|
2353
|
+
if (openTasks.has(d.sessionId) || agents()?.get?.(d.sessionId)?.status === 'running') continue;
|
|
2354
|
+
uninstall(d.sessionId);
|
|
2355
|
+
forgetSession(d.sessionId);
|
|
2356
|
+
try {
|
|
2357
|
+
// The panel may be shown over this conversation: it opens itself again (see `rotatedAt`).
|
|
2358
|
+
rotatedAt = nowMs();
|
|
2359
|
+
await service(ctx, 'workspaceRegistry')?.archiveSession?.(d.sessionId);
|
|
2360
|
+
discussions.patch(d.key, { archivedAt: now });
|
|
2361
|
+
} catch (error) {
|
|
2362
|
+
ctx.logger?.warn?.(`bots: archiving a thread of @${store.get(d.botId)?.handle ?? '?'}: ${error?.message ?? error}`);
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2130
2365
|
await watch(now);
|
|
2131
2366
|
tickets.flush();
|
|
2132
2367
|
tickets.prune();
|
|
@@ -2193,6 +2428,26 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2193
2428
|
return sessions;
|
|
2194
2429
|
}
|
|
2195
2430
|
|
|
2431
|
+
/**
|
|
2432
|
+
* The discussion a chat message goes to (Bots 0.10), or null for the bot's home: a message in a
|
|
2433
|
+
* Thread (a reply chain, a group thread, a forum topic) whose conversation the bot had before in
|
|
2434
|
+
* its home, or that answers one of its messages, is talked over in the home forked there. The
|
|
2435
|
+
* Thread's first message, and one that arrives while the home is still on that Thread, go home.
|
|
2436
|
+
*/
|
|
2437
|
+
async function chatDiscussion(bot, meta) {
|
|
2438
|
+
const key = toThreadKey(meta?.threadKey);
|
|
2439
|
+
const p = key ? parseThreadKey(key) : null;
|
|
2440
|
+
if (!p || p.kind === 'panel' || p.rootId === undefined) return null;
|
|
2441
|
+
const known = discussions.get(key);
|
|
2442
|
+
let point = null;
|
|
2443
|
+
if (!known || known.botId !== bot.id) {
|
|
2444
|
+
if (known) return null;
|
|
2445
|
+
if (bot.sessionId && channels.current(bot.sessionId).some((o) => o.threadKey === key)) return null;
|
|
2446
|
+
point = forkPoint({ thread: discussions.anchorOf(key), root: discussions.anchorOf(chatMessageRef(p.appKey, p.chatId, p.rootId)) });
|
|
2447
|
+
if (!point || !isMine(bot, point.sessionId)) return null;
|
|
2448
|
+
}
|
|
2449
|
+
return discussionFor(bot, key, { point, rootId: p.rootId, title: titleOf(meta?.origin?.body ?? '') });
|
|
2450
|
+
}
|
|
2196
2451
|
const channels = createChannels({
|
|
2197
2452
|
file: join(dir, 'channels.json'),
|
|
2198
2453
|
bots: () => store.list(),
|
|
@@ -2201,6 +2456,30 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2201
2456
|
// and its Thread (so the bot can name it in bot_reply). Its id comes from the chat message's, so a
|
|
2202
2457
|
// message handed out again after a restart is not run twice.
|
|
2203
2458
|
deliver: async (target, { header, body }, meta = {}) => {
|
|
2459
|
+
// A reply in a chat Thread the bot spoke in before: its discussion (Bots 0.10).
|
|
2460
|
+
let into = null;
|
|
2461
|
+
try {
|
|
2462
|
+
into = await chatDiscussion(store.get(target.id) ?? target, meta);
|
|
2463
|
+
} catch (error) {
|
|
2464
|
+
ctx.logger?.warn?.(`bots: a chat thread could not get its own conversation (${error?.message ?? error}); @${target.handle} takes it`);
|
|
2465
|
+
}
|
|
2466
|
+
if (into) {
|
|
2467
|
+
// The thread's first message carries the note, claimed before the hand-over (two may arrive at once).
|
|
2468
|
+
const first = !discussions.get(into.discussion.key)?.noted;
|
|
2469
|
+
if (first) discussions.patch(into.discussion.key, { noted: true });
|
|
2470
|
+
const note = first ? `${discussionNoteText({})}\n` : '';
|
|
2471
|
+
const sent = await sendTo(into.agent, {
|
|
2472
|
+
content: [
|
|
2473
|
+
{ type: 'text', text: `${note}${header}${threadNote(meta.threadKey)}` },
|
|
2474
|
+
{ type: 'text', text: body },
|
|
2475
|
+
],
|
|
2476
|
+
source: { kind: 'user' },
|
|
2477
|
+
mode: homeMode(target),
|
|
2478
|
+
...(meta.key ? { key: meta.key } : {}),
|
|
2479
|
+
});
|
|
2480
|
+
discussions.patch(into.discussion.key, { lastAt: nowMs() });
|
|
2481
|
+
return { sessionId: into.agent.session.id, messageId: sent.message.id, ...(sent.skipped ? { skipped: true } : {}) };
|
|
2482
|
+
}
|
|
2204
2483
|
await autoTopic(store.get(target.id) ?? target, 'user');
|
|
2205
2484
|
const agent = await agentOf(store.get(target.id) ?? target);
|
|
2206
2485
|
const sent = await sendTo(agent, {
|
|
@@ -2220,6 +2499,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2220
2499
|
ticketThread: (id) => tickets.get(String(id ?? ''))?.origin?.threadKey,
|
|
2221
2500
|
running: (sessionId) => agents()?.get?.(sessionId)?.status === 'running',
|
|
2222
2501
|
newTopic: (bot) => newTopic(bot, 'manual'),
|
|
2502
|
+
homeKey: (sessionId) => discussions.bySession(sessionId)?.key,
|
|
2503
|
+
onSent: ({ tag, appKey, chatId, ids }) => {
|
|
2504
|
+
for (const id of ids) discussions.anchor(chatMessageRef(appKey, chatId, id), tag);
|
|
2505
|
+
},
|
|
2223
2506
|
...(deps.loadConnector ? { loadConnector: deps.loadConnector } : {}),
|
|
2224
2507
|
...(deps.typingEveryMs ? { typingEveryMs: deps.typingEveryMs } : {}),
|
|
2225
2508
|
log: (line) => ctx.logger?.info?.(`bots: ${line}`),
|
|
@@ -2267,6 +2550,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2267
2550
|
/** Drop what is kept per Session for one that is gone: an archived task's, a topic left behind, a removed bot's. */
|
|
2268
2551
|
function forgetSession(sessionId) {
|
|
2269
2552
|
if (!sessionId) return;
|
|
2553
|
+
lastSeq.delete(sessionId);
|
|
2270
2554
|
memoText.delete(sessionId);
|
|
2271
2555
|
memoStale.delete(sessionId);
|
|
2272
2556
|
deliveredIds.delete(sessionId);
|
|
@@ -2290,7 +2574,13 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2290
2574
|
}
|
|
2291
2575
|
/** Reminder message id → the tickets it names (their origin Threads join the requester's turn). */
|
|
2292
2576
|
const reminded = new Map();
|
|
2577
|
+
/** sessionId → the seq of its latest event: where a tool's chat message was said, as an anchor. */
|
|
2578
|
+
const lastSeq = new Map();
|
|
2293
2579
|
ctx.on('session/event', (session, event) => {
|
|
2580
|
+
if (Number.isSafeInteger(event?.seq) && session?.id) lastSeq.set(session.id, event.seq);
|
|
2581
|
+
// A thread's Session starts with its source's events; should Harness ever report them, they were logged already.
|
|
2582
|
+
const forkedFrom = session?.id ? discussions.bySession(session.id)?.source : undefined;
|
|
2583
|
+
if (forkedFrom?.seq !== undefined && Number.isSafeInteger(event?.seq) && event.seq <= forkedFrom.seq) return;
|
|
2294
2584
|
let bot;
|
|
2295
2585
|
let via = null;
|
|
2296
2586
|
let kind;
|
|
@@ -2341,6 +2631,12 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2341
2631
|
const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
|
|
2342
2632
|
const typed = panelId ? store.message(panelId) : undefined;
|
|
2343
2633
|
if (typed) said = typedText = typed.text;
|
|
2634
|
+
// Where it sits in the conversation, so a reply to it can fork there (Bots 0.10); again at the turn's end.
|
|
2635
|
+
const home = bot.sessionId === session.id;
|
|
2636
|
+
if (typed && home) {
|
|
2637
|
+
discussions.anchor(messageRef(typed.id), { sessionId: session.id, seq: event.seq });
|
|
2638
|
+
st.anchored = [...(st.anchored ?? []), messageRef(typed.id)];
|
|
2639
|
+
}
|
|
2344
2640
|
const topicTitle = typed?.thread ? store.message(panelTopicOf(typed.thread))?.text : undefined;
|
|
2345
2641
|
// A chat message adds its Thread to the turn's; a panel message its topic, or the panel (lib/threads.mjs).
|
|
2346
2642
|
via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport, ...(typed?.thread ? { threadKey: typed.thread, origin: topicTitle ? { threadTitle: clip(topicTitle, 60).text } : {} } : {}) });
|
|
@@ -2357,11 +2653,22 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2357
2653
|
// The answer quotes the message that started the task, not whatever was said there last.
|
|
2358
2654
|
channels.noteInput(session.id, { threadKey: key, origin: { ...(t.origin?.who ? { who: t.origin.who } : {}), ...(th?.label ? { label: th.label } : {}), ...(t.origin?.replyTo ? { replyTo: t.origin.replyTo } : {}) }, ticket: t.id });
|
|
2359
2655
|
}
|
|
2360
|
-
const thread = via ? via.threadKey :
|
|
2656
|
+
const thread = via ? via.threadKey : homeThreadOf(session.id);
|
|
2361
2657
|
if (kind === 'user' && typed) {
|
|
2362
2658
|
// Logged when it was sent.
|
|
2363
|
-
} else if (kind === 'user')
|
|
2364
|
-
|
|
2659
|
+
} else if (kind === 'user') {
|
|
2660
|
+
const topic = !via && isPanelThread(thread) ? panelTopicOf(thread) : '';
|
|
2661
|
+
const logged = store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who, ...(thread ? { thread } : {}) } : { from: 'user', to: bot.id, text: said, kind: 'user', ...(thread ? { thread } : {}), ...(topic ? { topic } : {}) });
|
|
2662
|
+
if (home) {
|
|
2663
|
+
const refs = [messageRef(logged.id)];
|
|
2664
|
+
// A chat message: by its id in the chat app, and its Thread's latest exchange with the home.
|
|
2665
|
+
const chatMsg = /^bots:chat:(.+):([^:]+):([^:]+)$/.exec(id);
|
|
2666
|
+
if (chatMsg) refs.push(chatMessageRef(chatMsg[1], chatMsg[2], chatMsg[3]));
|
|
2667
|
+
if (via?.threadKey) refs.push(via.threadKey);
|
|
2668
|
+
for (const r of refs) discussions.anchor(r, { sessionId: session.id, seq: event.seq });
|
|
2669
|
+
st.anchored = [...(st.anchored ?? []), ...refs];
|
|
2670
|
+
}
|
|
2671
|
+
} else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
|
|
2365
2672
|
}
|
|
2366
2673
|
} else if (event.type === 'assistant/message') {
|
|
2367
2674
|
const content = event.data?.message?.content ?? [];
|
|
@@ -2389,15 +2696,24 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2389
2696
|
if (text && !hidden) {
|
|
2390
2697
|
// To the turn's one chat Thread; with several (or the panel and a chat) it stays in the panel,
|
|
2391
2698
|
// and bot_reply says where each answer goes.
|
|
2392
|
-
const
|
|
2393
|
-
const
|
|
2394
|
-
//
|
|
2395
|
-
const
|
|
2699
|
+
const home = bot.sessionId === session.id;
|
|
2700
|
+
const at = { sessionId: session.id, seq: event.seq };
|
|
2701
|
+
// Sent to a chat: the ids it gets there are anchors too (a reply to one of them is a discussion).
|
|
2702
|
+
const sent = channels.noteReply(session.id, text, home ? at : undefined);
|
|
2703
|
+
const thread = sent ? sent.threadKey : homeThreadOf(session.id);
|
|
2704
|
+
// A thread in the panel (a discussion, or a 0.9 topic): the reply is shown in it.
|
|
2705
|
+
const topic = isPanelThread(thread) ? panelTopicOf(thread) : '';
|
|
2396
2706
|
const choices = plan.mode === 'choose' ? plan.origins.filter((o) => o.kind !== 'panel').map((o) => o.threadKey) : [];
|
|
2397
|
-
store.log({ from: bot.id, to: 'user', chat: bot.id, text, kind: 'reply', ...(sent && sent.kind !== 'panel' ? { via: sent.kind } : {}), ...(thread ? { thread } : {}), ...(topic ? { topic } : {}), ...(choices.length ? { notSent: true, choices } : {}) });
|
|
2707
|
+
const logged = store.log({ from: bot.id, to: 'user', chat: bot.id, text, kind: 'reply', ...(sent && sent.kind !== 'panel' ? { via: sent.kind } : {}), ...(thread ? { thread } : {}), ...(topic ? { topic } : {}), ...(choices.length ? { notSent: true, choices } : {}) });
|
|
2708
|
+
if (home) {
|
|
2709
|
+
discussions.anchor(messageRef(logged.id), at);
|
|
2710
|
+
if (sent && sent.kind !== 'panel') discussions.anchor(sent.threadKey, at);
|
|
2711
|
+
}
|
|
2398
2712
|
}
|
|
2399
2713
|
} else if (event.type === 'turn/end') {
|
|
2400
2714
|
channels.noteTurnEnd(session.id);
|
|
2715
|
+
// What the turn took in counts with the answer it gave: a reply to it forks after that answer.
|
|
2716
|
+
if (bot.sessionId === session.id) for (const r of turnState.get(session.id)?.anchored ?? []) discussions.anchor(r, { sessionId: session.id, seq: event.seq });
|
|
2401
2717
|
turnState.delete(session.id);
|
|
2402
2718
|
}
|
|
2403
2719
|
} catch {
|
|
@@ -2682,6 +2998,19 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2682
2998
|
// The conversation stays where it is.
|
|
2683
2999
|
}
|
|
2684
3000
|
}
|
|
3001
|
+
// Its threads go with it.
|
|
3002
|
+
for (const d of discussions.list({ botId: bot.id })) {
|
|
3003
|
+
uninstall(d.sessionId);
|
|
3004
|
+
forgetSession(d.sessionId);
|
|
3005
|
+
if (!d.archivedAt) {
|
|
3006
|
+
try {
|
|
3007
|
+
await service(ctx, 'workspaceRegistry')?.archiveSession?.(d.sessionId);
|
|
3008
|
+
} catch {
|
|
3009
|
+
// The conversation stays where it is.
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
discussions.remove(d.key);
|
|
3013
|
+
}
|
|
2685
3014
|
// Its tickets end with it; their conversations are archived now.
|
|
2686
3015
|
for (const t of tickets.list({ botId: bot.id, archived: false })) {
|
|
2687
3016
|
if (!t.ended) endTicket(t, { by: 'system', outcome: 'stopped' });
|
|
@@ -2715,7 +3044,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2715
3044
|
function applyModel(bot) {
|
|
2716
3045
|
if (!bot.model) return;
|
|
2717
3046
|
const live = agents();
|
|
2718
|
-
const ids = [bot.sessionId, ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
|
|
3047
|
+
const ids = [bot.sessionId, ...discussions.list({ botId: bot.id, archived: false }).map((d) => d.sessionId), ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
|
|
2719
3048
|
for (const id of ids) {
|
|
2720
3049
|
try {
|
|
2721
3050
|
live?.get?.(id)?.model?.select?.(selectionOf(bot.model));
|
|
@@ -3012,7 +3341,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3012
3341
|
const sessionId = caller?.sessionId;
|
|
3013
3342
|
const t = ticketOf(sessionId);
|
|
3014
3343
|
if (t) return { kind: 'ticket', ticketId: t.id };
|
|
3015
|
-
|
|
3344
|
+
// A home, or a thread of one (Bots 0.10).
|
|
3345
|
+
const bot = botOfSession(sessionId);
|
|
3016
3346
|
if (!bot) return undefined;
|
|
3017
3347
|
return isRouterHome(bot, sessionId) ? { kind: 'router' } : { kind: 'home' };
|
|
3018
3348
|
}
|
|
@@ -3100,7 +3430,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3100
3430
|
name: 'bot_list',
|
|
3101
3431
|
description: "List the user's bots: handle, name, role, status, bio, skills, apps and scheduled tasks. Use it before delegating to find the right bot.",
|
|
3102
3432
|
parameters: {},
|
|
3103
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bots: v.bots }) },
|
|
3433
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bots: v.bots }) },
|
|
3104
3434
|
isConcurrencySafe: () => true,
|
|
3105
3435
|
execute: async () => {
|
|
3106
3436
|
const bots = store.list();
|
|
@@ -3133,7 +3463,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3133
3463
|
...AVATAR_PARAMS,
|
|
3134
3464
|
skills: { ...skillInput, description: 'Skills to give it.' },
|
|
3135
3465
|
},
|
|
3136
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
|
|
3466
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
|
|
3137
3467
|
execute: async (args, exec) => {
|
|
3138
3468
|
const caller = actor(exec);
|
|
3139
3469
|
const by = caller.bot;
|
|
@@ -3169,7 +3499,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3169
3499
|
remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
|
|
3170
3500
|
make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
|
|
3171
3501
|
},
|
|
3172
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
|
|
3502
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
|
|
3173
3503
|
execute: async (args, exec) => {
|
|
3174
3504
|
// A helper whose line cannot be traced still changes bots, as before; it waits for a drawing.
|
|
3175
3505
|
const caller = actorOf(exec);
|
|
@@ -3192,7 +3522,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3192
3522
|
name: 'bot_delete',
|
|
3193
3523
|
description: 'Delete a bot, its scheduled tasks, and archive its conversation. Only when the user asked for it.',
|
|
3194
3524
|
parameters: { bot: { type: 'string', required: true, description: '@handle, id or name.' } },
|
|
3195
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
|
|
3525
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot }) },
|
|
3196
3526
|
execute: async (args, exec) => {
|
|
3197
3527
|
const bot = resolve(args.bot);
|
|
3198
3528
|
if (callerBot(exec)?.id === bot.id) throw new Error('a bot cannot delete itself; ask the dispatcher or the user');
|
|
@@ -3221,7 +3551,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3221
3551
|
thread: { type: 'string', description: 'Only when this turn involves several topics or chats: the thread (as the message header "(thread …)" shows it) the new task, or the message added to a task, is for. A new task then answers there, and follow-ups there reach it. Left out with several, a new task belongs to none of them.' },
|
|
3222
3552
|
report_to: { type: 'string', enum: ['thread', 'me'], description: 'For a new task: "thread" (default) — its bot answers the person in the topic or chat the request came from; "me" — its reports come back to you.' },
|
|
3223
3553
|
},
|
|
3224
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
|
|
3554
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
|
|
3225
3555
|
isConcurrencySafe: () => true,
|
|
3226
3556
|
execute: async (args, exec) => {
|
|
3227
3557
|
const { sessionId, bot: sender } = actor(exec);
|
|
@@ -3259,24 +3589,28 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3259
3589
|
if (!t) throw new Error(`no task ${wantTicket}`);
|
|
3260
3590
|
if (named && named.id !== t.botId) throw new Error(`task ${t.id} belongs to ${handleOf(t.botId)}, not @${named.handle}; leave out "to" or name its bot`);
|
|
3261
3591
|
if (!mayAppend(t, sender, sessionId)) throw new Error(`task ${t.id} was not asked for from this conversation; message its bot with a new task instead`);
|
|
3262
|
-
|
|
3592
|
+
let next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
|
|
3593
|
+
// Carried on from a thread (Bots 0.10): the task follows the thread, and its reports show there.
|
|
3594
|
+
const here = !mine ? discussions.bySession(sessionId) : undefined;
|
|
3595
|
+
if (here && reportsGoDirect(next) && (next.showIn ?? next.origin?.threadKey) !== here.key) {
|
|
3596
|
+
tickets.subscribe(next.id, here.key);
|
|
3597
|
+
next = tickets.patch(next.id, { showIn: here.key }) ?? next;
|
|
3598
|
+
}
|
|
3263
3599
|
const target = store.get(next.botId);
|
|
3264
3600
|
const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
const after = reportsGoDirect(next) ? `${handleOf(next.botId)} answers the person in the task's ${isPanelThread(next.origin?.threadKey) ? 'topic' : 'chat'} itself` : `${handleOf(next.botId)}'s report will arrive here by itself`;
|
|
3268
|
-
return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}).${filed ? " The person's message is filed under that task's topic." : ''} ${after}; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
|
|
3601
|
+
const after = reportsGoDirect(next) ? `${handleOf(next.botId)} answers the person ${isPanelThread(next.showIn ?? next.origin?.threadKey) ? 'in the panel' : 'in the chat'} itself` : `${handleOf(next.botId)}'s report will arrive here by itself`;
|
|
3602
|
+
return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${after}; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
|
|
3269
3603
|
}
|
|
3270
3604
|
if (!named) throw new Error(mine ? 'say which bot with `to`, or leave it out and give a `status` to report on your task' : 'say which bot with `to`');
|
|
3271
3605
|
|
|
3272
3606
|
// A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
|
|
3273
|
-
if (sender && sessionId && (mine || (ticketsOn() && sender
|
|
3607
|
+
if (sender && sessionId && (mine || (ticketsOn() && isHomeOf(sender, sessionId)))) {
|
|
3274
3608
|
const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
|
|
3275
3609
|
const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
|
|
3276
3610
|
const stage = stageOf(t);
|
|
3277
3611
|
const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
|
|
3278
3612
|
const answer = reportsGoDirect(t)
|
|
3279
|
-
? `${named.id === sender.id ? 'You answer' : `@${named.handle} answers`} the person in ${isPanelThread(t.origin?.threadKey) ? 'the
|
|
3613
|
+
? `${named.id === sender.id ? 'You answer' : `@${named.handle} answers`} the person in ${isPanelThread(t.origin?.threadKey) ? (panelTopicOf(t.origin.threadKey) ? 'the thread' : 'the panel chat') : 'the chat'} it came from, and you get a note; do not wait for it or repeat it — tell the person in one line who is on it and end your turn.`
|
|
3280
3614
|
: 'Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.';
|
|
3281
3615
|
const said =
|
|
3282
3616
|
stage === 'failed'
|
|
@@ -3299,7 +3633,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3299
3633
|
thread: { type: 'string', description: 'A panel topic (p…) or chat thread key of this turn (or of a task you know of).' },
|
|
3300
3634
|
text: { type: 'string', required: true, description: 'The reply, as the person should read it.' },
|
|
3301
3635
|
},
|
|
3302
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ via: v.via, thread: v.thread }) },
|
|
3636
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ via: v.via, thread: v.thread }) },
|
|
3303
3637
|
execute: async (args, exec) => {
|
|
3304
3638
|
const { sessionId, bot } = actor(exec);
|
|
3305
3639
|
if (ticketOf(sessionId)) throw new Error('a task conversation talks to no chat: report with bot_send_message (leave out "to"), and whoever asked passes it on');
|
|
@@ -3333,9 +3667,11 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3333
3667
|
const chat = (topic && store.message(topic)?.chat) || bot.id;
|
|
3334
3668
|
store.log({ from: bot.id, to: 'user', chat, text: body, kind: 'reply', thread: topic ? target.threadKey : panelThreadKey(sessionId), ...(topic ? { topic } : {}) });
|
|
3335
3669
|
answeredHere();
|
|
3336
|
-
return { ok: true, text: topic ? `Shown in the panel, in
|
|
3670
|
+
return { ok: true, text: topic ? `Shown in the panel, in thread ${topic}.` : 'That thread is the panel: the reply is shown there.', thread: target.threadKey };
|
|
3337
3671
|
}
|
|
3338
|
-
|
|
3672
|
+
// Said from the home: a reply to it in the chat is a thread that forks here (Bots 0.10).
|
|
3673
|
+
const at = bot.sessionId === sessionId && lastSeq.has(sessionId) ? { sessionId, seq: lastSeq.get(sessionId) } : undefined;
|
|
3674
|
+
channels.replyTo(sessionId, target, body, at);
|
|
3339
3675
|
answeredHere();
|
|
3340
3676
|
store.log({ from: bot.id, to: 'user', chat: bot.id, text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
|
|
3341
3677
|
return { ok: true, text: `Sent to ${threadLabel(target)}.`, thread: target.threadKey, via: target.kind };
|
|
@@ -3373,7 +3709,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3373
3709
|
id: { type: 'string', required: true, description: 'The task id (t…), as on its card.' },
|
|
3374
3710
|
action: { type: 'string', required: true, enum: ['stop', 'close', 'retry', 'status'] },
|
|
3375
3711
|
},
|
|
3376
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ ticket: v.ticket }) },
|
|
3712
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ ticket: v.ticket }) },
|
|
3377
3713
|
execute: async (args, exec) => {
|
|
3378
3714
|
const caller = actor(exec);
|
|
3379
3715
|
const sessionId = caller.sessionId;
|
|
@@ -3436,7 +3772,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3436
3772
|
cron: { type: 'string' },
|
|
3437
3773
|
time_zone: { type: 'string', description: `IANA zone, default ${zone}.` },
|
|
3438
3774
|
},
|
|
3439
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot, task: v.task }) },
|
|
3775
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ bot: v.bot, task: v.task }) },
|
|
3440
3776
|
execute: async (args, exec) => {
|
|
3441
3777
|
const actorId = exec?.agent?.session?.id;
|
|
3442
3778
|
const bot = args.bot ? resolve(args.bot) : callerBot(exec) ?? store.primary();
|
|
@@ -3478,7 +3814,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3478
3814
|
kind: { type: 'string', enum: MEMORY_KINDS },
|
|
3479
3815
|
replace_id: { type: 'string', description: 'Id of an existing note this one corrects or replaces.' },
|
|
3480
3816
|
},
|
|
3481
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ note: v.note, scope: v.scope }) },
|
|
3817
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ note: v.note, scope: v.scope }) },
|
|
3482
3818
|
execute: async (args, exec) => {
|
|
3483
3819
|
const me = callerBot(exec);
|
|
3484
3820
|
const scope = args.scope === 'team' ? 'team' : 'self';
|
|
@@ -3663,6 +3999,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3663
3999
|
mcp: Boolean(mcpClient),
|
|
3664
4000
|
// Off for a router dispatcher unless its bot lists them in `tools.routerAllow`.
|
|
3665
4001
|
routerDeny: [...ROUTER_DENY],
|
|
4002
|
+
// Off for the dispatcher while the team has more than one bot: its teammates help instead.
|
|
4003
|
+
teamDeny: inTeam() ? [...SUBAGENT_TOOLS] : [],
|
|
3666
4004
|
zone,
|
|
3667
4005
|
};
|
|
3668
4006
|
}
|
|
@@ -3970,6 +4308,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3970
4308
|
ticketMap,
|
|
3971
4309
|
messageCount: store.messageCount(),
|
|
3972
4310
|
version: store.version(),
|
|
4311
|
+
// The Bots this process loaded (the panel asks for a restart when it is newer), and the last new topic.
|
|
4312
|
+
botsVersion: VERSION,
|
|
4313
|
+
rotatedAt,
|
|
3973
4314
|
limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
|
|
3974
4315
|
teamNotes: memory.notes('team').length,
|
|
3975
4316
|
dispatcher: s.dispatcher,
|
|
@@ -4389,6 +4730,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4389
4730
|
},
|
|
4390
4731
|
},
|
|
4391
4732
|
'memory/dream': { post: async () => ({ ok: true, result: await dream({ reason: 'manual' }) }) },
|
|
4733
|
+
'threads/seen': {
|
|
4734
|
+
post: (body) => {
|
|
4735
|
+
const root = String(body.root ?? '');
|
|
4736
|
+
const m = root ? store.message(root) : undefined;
|
|
4737
|
+
if (!m || (body.bot && !inChat(m, String(body.bot)))) return { ok: false, reason: 'no such message' };
|
|
4738
|
+
discussions.markSeen(root, nowMs());
|
|
4739
|
+
return { ok: true, unread: 0 };
|
|
4740
|
+
},
|
|
4741
|
+
},
|
|
4392
4742
|
'topic/new': {
|
|
4393
4743
|
post: async (body) => {
|
|
4394
4744
|
const bot = store.get(String(body.id ?? ''));
|
|
@@ -4414,23 +4764,66 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4414
4764
|
};
|
|
4415
4765
|
|
|
4416
4766
|
/**
|
|
4417
|
-
* GET /messages?bot=&
|
|
4418
|
-
*
|
|
4767
|
+
* GET /messages?bot=&limit=: a bot's chat as it was said, oldest first (Bots 0.10): a reply in a
|
|
4768
|
+
* thread is in it too, with the message it quotes (`quote`, like a chat app's quoted reply); and a
|
|
4769
|
+
* summary of the thread under each of its messages that has one. With `topic=<rootId>`: that
|
|
4770
|
+
* thread alone, its root first. Without `bot`: everything.
|
|
4419
4771
|
*/
|
|
4420
4772
|
function messagesView(url) {
|
|
4421
4773
|
const bot = url.searchParams.get('bot') ?? '';
|
|
4422
4774
|
const topic = url.searchParams.get('topic') ?? '';
|
|
4423
4775
|
const limit = Number(url.searchParams.get('limit')) || (topic ? 500 : 200);
|
|
4424
|
-
|
|
4425
|
-
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
|
|
4430
|
-
|
|
4431
|
-
|
|
4776
|
+
if (topic) {
|
|
4777
|
+
const items = store.messages({ bot, limit, topic }).map(messageView);
|
|
4778
|
+
const replies = store.replies(bot, [topic]);
|
|
4779
|
+
const sum = threadSummary(topic, replies.get(topic) ?? [], items.find((m) => m.id === topic) ?? store.message(topic));
|
|
4780
|
+
return { items, threads: sum ? { [topic]: sum } : {} };
|
|
4781
|
+
}
|
|
4782
|
+
const rows = store.messages({ bot, limit, roots: false });
|
|
4783
|
+
const byId = new Map(rows.map((m) => [m.id, m]));
|
|
4784
|
+
const roots = new Set(rows.map(rootIdOf).filter(Boolean));
|
|
4785
|
+
const replies = store.replies(bot, roots);
|
|
4786
|
+
const lookup = (id) => byId.get(id) ?? store.message(id);
|
|
4787
|
+
const items = rows.map((m) => {
|
|
4788
|
+
const v = messageView(m);
|
|
4789
|
+
const q = quoteOf(m, replies, lookup);
|
|
4790
|
+
return q ? { ...v, quote: q } : v;
|
|
4791
|
+
});
|
|
4792
|
+
const threads = {};
|
|
4793
|
+
for (const m of rows) {
|
|
4794
|
+
if (rootIdOf(m) !== m.id) continue;
|
|
4795
|
+
const sum = threadSummary(m.id, replies.get(m.id) ?? [], m);
|
|
4796
|
+
if (sum) threads[m.id] = sum;
|
|
4432
4797
|
}
|
|
4433
|
-
return { items,
|
|
4798
|
+
return { items, threads };
|
|
4799
|
+
}
|
|
4800
|
+
/**
|
|
4801
|
+
* The thread under a panel message as the chat lists it (PLAN-0.10 §7.2): its key, how many
|
|
4802
|
+
* replies, the latest, how many of the bots' replies came since the person looked, whether a
|
|
4803
|
+
* bot is answering in it now, and the tasks it follows. Null when the message has no thread.
|
|
4804
|
+
*/
|
|
4805
|
+
function threadSummary(rootId, replies, root) {
|
|
4806
|
+
const d = discussions.byRoot(rootId);
|
|
4807
|
+
const key = d?.key || topicKeyOf(root, rootId) || replies.find((m) => panelTopicOf(m.thread) === rootId)?.thread || '';
|
|
4808
|
+
const list = key ? tickets.subscribers(key).filter((t) => !t.archivedAt) : [];
|
|
4809
|
+
const said = replies.filter((m) => m.kind !== 'system' && m.kind !== 'topic' && !betweenBots(m) && m.from !== m.to);
|
|
4810
|
+
if (!said.length && !d && !list.length) return null;
|
|
4811
|
+
const last = said.at(-1);
|
|
4812
|
+
const seen = discussions.seenAt(rootId);
|
|
4813
|
+
const unread = said.filter((m) => m.from !== 'user' && Number(m.at) > seen).length;
|
|
4814
|
+
// The thread's bot answering now (the chat shows it at work); `running` counts its working tasks too.
|
|
4815
|
+
const answering = Boolean(d) && agents()?.get?.(d.sessionId)?.status === 'running';
|
|
4816
|
+
const running = answering || list.some((t) => stageOf(t) === 'working');
|
|
4817
|
+
return {
|
|
4818
|
+
key,
|
|
4819
|
+
count: said.length,
|
|
4820
|
+
lastAt: last ? Number(last.at) || 0 : 0,
|
|
4821
|
+
last: last ? { from: last.from, text: clip(String(last.text ?? ''), PREVIEW_CHARS).text } : null,
|
|
4822
|
+
unread,
|
|
4823
|
+
running,
|
|
4824
|
+
answering,
|
|
4825
|
+
tickets: list.map(ticketRow),
|
|
4826
|
+
};
|
|
4434
4827
|
}
|
|
4435
4828
|
|
|
4436
4829
|
/** GET /tickets?bot=&stage=&limit=&offset=: rows, the latest change first; `stage` may list several (a,b). */
|
|
@@ -4589,6 +4982,14 @@ function serveAvatar(dir, req, res) {
|
|
|
4589
4982
|
}
|
|
4590
4983
|
|
|
4591
4984
|
const LOGO_DIR = fileURLToPath(new URL('./logos/', import.meta.url));
|
|
4985
|
+
/** The Bots version this process loaded: the panel compares it with its own, to say when Harness needs a restart. */
|
|
4986
|
+
const VERSION = (() => {
|
|
4987
|
+
try {
|
|
4988
|
+
return String(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '');
|
|
4989
|
+
} catch {
|
|
4990
|
+
return '';
|
|
4991
|
+
}
|
|
4992
|
+
})();
|
|
4592
4993
|
|
|
4593
4994
|
/** `${R}/logo/<name>.png`: an app logo shipped with the plugin. */
|
|
4594
4995
|
export function serveLogo(req, res) {
|