@kadaliao/dsh-bots 0.8.0 → 0.9.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 +60 -18
- package/README.zh-CN.md +45 -14
- package/client.js +713 -78
- package/index.js +359 -64
- package/lib/cards.mjs +43 -0
- package/lib/channels.mjs +36 -1
- package/lib/prompt.mjs +42 -17
- package/lib/store.mjs +55 -5
- package/lib/threads.mjs +76 -23
- package/lib/tickets.mjs +7 -3
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -50,14 +50,14 @@ import { createUnfurler } from './lib/unfurl.mjs';
|
|
|
50
50
|
import { isLogoName, withLogo } from './lib/logos.mjs';
|
|
51
51
|
import { askNoticeText, CHANNEL_LABELS, channelEntry, channelIssue, createChannels, credentialsOf, maskBot, threadNote, unmaskApps } from './lib/channels.mjs';
|
|
52
52
|
import { createActivity } from './lib/activity.mjs';
|
|
53
|
-
import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
|
|
53
|
+
import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
|
|
54
54
|
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, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, stalledNoticeText } from './lib/cards.mjs';
|
|
58
|
+
import { assignmentText, clip, failedNoticeText, followUpNoticeText, nudgeText, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, stalledNoticeText } from './lib/cards.mjs';
|
|
59
59
|
import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
|
|
60
|
-
import { isPanelThread, panelThreadKey, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
|
|
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
63
|
import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
|
|
@@ -715,9 +715,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
715
715
|
}
|
|
716
716
|
return firstLine(said);
|
|
717
717
|
}
|
|
718
|
-
function startTask(bot, sessionId, kind, event, via) {
|
|
718
|
+
function startTask(bot, sessionId, kind, event, via, typed) {
|
|
719
719
|
const content = event.data?.content;
|
|
720
|
-
const said = textOf(content);
|
|
720
|
+
const said = typed ?? textOf(content);
|
|
721
721
|
const sched = kind === 'schedule' ? (/schedule_id_json:\s*"([^"]+)"/.exec(said)?.[1] ?? /"schedule_id":\s*"([^"]+)"/.exec(said)?.[1] ?? '') : '';
|
|
722
722
|
const from = kind === 'agent-message' ? (botOfSession(event.data?.source?.senderSessionId)?.id ?? 'user') : '';
|
|
723
723
|
const ticket = ticketOf(sessionId);
|
|
@@ -1167,22 +1167,193 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1167
1167
|
return agent.session.id;
|
|
1168
1168
|
}
|
|
1169
1169
|
|
|
1170
|
+
// --- the panel chat: topics (Bots 0.9) -------------------------------------------------
|
|
1171
|
+
/** A new id for a message typed in the panel: `p` and 8 letters or digits, short enough for a model to copy. */
|
|
1172
|
+
const newPanelId = () => {
|
|
1173
|
+
for (;;) {
|
|
1174
|
+
const id = `p${randomUUID().replace(/-/g, '').slice(0, 8)}`;
|
|
1175
|
+
if (!store.message(id)) return id;
|
|
1176
|
+
}
|
|
1177
|
+
};
|
|
1178
|
+
/** Whether a timeline message belongs to `botId`'s panel chat (lib/store.mjs `messages`). */
|
|
1179
|
+
const inChat = (m, botId) => Boolean(m) && (m.chat ? m.chat === botId : m.from === botId || m.to === botId);
|
|
1180
|
+
/**
|
|
1181
|
+
* The key of the panel topic `root` from its first message: its `thread` when that is the topic's
|
|
1182
|
+
* key, else `panelThread` (a chat app's message, whose `thread` stays its chat Thread), else ''.
|
|
1183
|
+
*/
|
|
1184
|
+
const topicKeyOf = (first, root) => {
|
|
1185
|
+
if (first?.thread && panelTopicOf(first.thread) === root) return first.thread;
|
|
1186
|
+
if (first?.panelThread && panelTopicOf(first.panelThread) === root) return first.panelThread;
|
|
1187
|
+
return '';
|
|
1188
|
+
};
|
|
1189
|
+
/** Who wrote a timeline message, as a header names them. */
|
|
1190
|
+
const writerOf = (m) => (m.from === 'user' ? 'the user' : store.get(m.from) ? `@${store.get(m.from).handle}` : 'a bot');
|
|
1191
|
+
/** The tasks a dispatcher's panel message may continue: open, or ended within a day; the latest change first. */
|
|
1192
|
+
function openTasksOf(bot) {
|
|
1193
|
+
const since = nowMs() - 24 * 3600_000;
|
|
1194
|
+
return tickets
|
|
1195
|
+
.list({ archived: false })
|
|
1196
|
+
.filter((t) => t.requester?.botId === bot.id && !t.requester?.ticketId && (!t.ended || t.ended.at >= since))
|
|
1197
|
+
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* The topic a panel message goes into: a new one it starts, or for a reply the topic of the
|
|
1201
|
+
* message it answers (one filed under another topic counts as there). A message that was in no
|
|
1202
|
+
* topic becomes the first of one. `{root, key, quoted}`.
|
|
1203
|
+
*/
|
|
1204
|
+
function topicFor(bot, sessionId, id, replyTo) {
|
|
1205
|
+
if (!replyTo) return { root: id, key: panelThreadKey(sessionId, id), quoted: null };
|
|
1206
|
+
const quoted = store.message(replyTo);
|
|
1207
|
+
if (!quoted || !inChat(quoted, bot.id)) throw new Error('that message is not in this chat');
|
|
1208
|
+
const root = quoted.movedTo || quoted.topic || quoted.id;
|
|
1209
|
+
const first = root === quoted.id ? quoted : store.message(root);
|
|
1210
|
+
// Its first message names the key; one gone from the log leaves it on the message replied to (an older topic of the bot's).
|
|
1211
|
+
const key = topicKeyOf(first, root) || (panelTopicOf(quoted.thread) === root ? quoted.thread : '') || panelThreadKey(sessionId, root);
|
|
1212
|
+
if (first && first.topic !== root) {
|
|
1213
|
+
// A chat app's message keeps its chat Thread: the topic's key goes beside it.
|
|
1214
|
+
const chatThread = first.thread && !isPanelThread(first.thread);
|
|
1215
|
+
store.patchMessage(first.id, chatThread ? { topic: root, panelThread: key } : { topic: root, thread: key });
|
|
1216
|
+
}
|
|
1217
|
+
return { root, key, quoted };
|
|
1218
|
+
}
|
|
1219
|
+
/** A timeline message as the panel reads it: `pending` while no model has taken it yet; internal fields left out. */
|
|
1220
|
+
function messageView(m) {
|
|
1221
|
+
const { sid, ...rest } = m;
|
|
1222
|
+
if (m.from !== 'user' || m.kind !== 'user' || !/^p[a-z0-9]{8}$/.test(m.id)) return rest;
|
|
1223
|
+
const waiting = (sessionId, msgId) => pendingOf(agents()?.get?.(sessionId)).some((x) => x?.id === `${MESSAGE_PREFIX}${msgId}`);
|
|
1224
|
+
let pending = false;
|
|
1225
|
+
if (m.ticket && !sid) {
|
|
1226
|
+
const t = tickets.get(m.ticket);
|
|
1227
|
+
const key = `panel:${m.id}:${m.ticket}`;
|
|
1228
|
+
// Queued (its assignment carries the message), waiting for a worker slot, or not taken yet.
|
|
1229
|
+
pending = Boolean(t) && !t.ended && (!t.startedAt || parkedOf(t).some((x) => x.key === key) || (Boolean(t.sessionId) && waiting(t.sessionId, key)));
|
|
1230
|
+
} else if (sid) pending = waiting(sid, `panel:${m.id}`);
|
|
1231
|
+
return pending ? { ...rest, pending: true } : rest;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1170
1234
|
/**
|
|
1171
|
-
* The user writes to a bot from the panel
|
|
1172
|
-
*
|
|
1235
|
+
* The user writes to a bot from the panel. `/new` (or `/clear`, `/新话题`) first starts a new
|
|
1236
|
+
* 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) and is a topic of
|
|
1238
|
+
* its own, or with `replyTo` joins the topic of that message. A reply in a topic with live tasks
|
|
1239
|
+
* goes to them directly (the bot's home hears of it without waking); anything else goes to the
|
|
1240
|
+
* bot's home: a router steers it (a header names its topic and the tasks it may continue), other
|
|
1241
|
+
* homes take it as a turn of its own. Returns `{sessionId, message?}`.
|
|
1173
1242
|
*/
|
|
1174
|
-
async function userSend(target, text) {
|
|
1243
|
+
async function userSend(target, text, { replyTo = '' } = {}) {
|
|
1175
1244
|
let body = String(text ?? '').trim();
|
|
1176
1245
|
if (body === '') throw new Error('text must not be empty');
|
|
1177
1246
|
const cmd = TOPIC_COMMAND.exec(body);
|
|
1178
1247
|
if (cmd) {
|
|
1179
1248
|
const sessionId = await newTopic(target, 'manual');
|
|
1180
1249
|
body = body.slice(cmd[0].length).trim();
|
|
1181
|
-
if (!body) return sessionId;
|
|
1250
|
+
if (!body) return { sessionId };
|
|
1182
1251
|
} else await autoTopic(store.get(target.id) ?? target, 'user');
|
|
1183
|
-
const
|
|
1184
|
-
|
|
1185
|
-
|
|
1252
|
+
const bot = store.get(target.id) ?? target;
|
|
1253
|
+
const agent = await agentOf(bot);
|
|
1254
|
+
const sid = agent.session.id;
|
|
1255
|
+
const id = newPanelId();
|
|
1256
|
+
const { root, key, quoted } = topicFor(bot, sid, id, String(replyTo ?? '').trim());
|
|
1257
|
+
const live = quoted ? tickets.subscribers(key).filter(isLiveSubscriber) : [];
|
|
1258
|
+
const base = { id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: key, topic: root, ...(quoted ? { replyTo: quoted.id } : {}) };
|
|
1259
|
+
store.log(base);
|
|
1260
|
+
if (live.length) {
|
|
1261
|
+
try {
|
|
1262
|
+
const sessions = await toTopicTasks(bot, live, body, { key, root, id, quoted });
|
|
1263
|
+
return { sessionId: sessions[0] ?? sid, message: messageView(store.message(id)) };
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
// No task took it (one ended meanwhile, say): the bot's home does.
|
|
1266
|
+
ctx.logger?.warn?.(`bots: a panel reply did not reach its task (${error?.message ?? error}); @${bot.handle} takes it`);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
store.patchMessage(id, { sid });
|
|
1270
|
+
const router = isRouterHome(bot, sid);
|
|
1271
|
+
const header = router || quoted ? panelHeaderText({ topic: root, ...(quoted ? { replyTo: { who: writerOf(quoted), text: quoted.text } } : {}), open: router ? openTasksOf(bot) : [] }, cardCtx()) : '';
|
|
1272
|
+
try {
|
|
1273
|
+
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
|
+
} catch (error) {
|
|
1275
|
+
// Not handed over: it leaves the chat (the panel keeps its own copy to send again).
|
|
1276
|
+
store.patchMessage(id, { hidden: true });
|
|
1277
|
+
throw error;
|
|
1278
|
+
}
|
|
1279
|
+
return { sessionId: sid, message: messageView(store.message(id)) };
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* A reply in a panel topic whose tasks are live: into each task's Session as the person's
|
|
1284
|
+
* message (a done one opens again; it may take the extra slot), and the chat's bot hears of it
|
|
1285
|
+
* without waking. Returns the task Sessions; throws when no task took it.
|
|
1286
|
+
*/
|
|
1287
|
+
async function toTopicTasks(bot, list, body, { key, root, id, quoted }) {
|
|
1288
|
+
const reached = [];
|
|
1289
|
+
let lastError = null;
|
|
1290
|
+
const header = quoted && quoted.id !== root ? panelHeaderText({ replyTo: { who: writerOf(quoted), text: quoted.text } }) : '';
|
|
1291
|
+
for (const t of list) {
|
|
1292
|
+
const cur = tickets.get(t.id) ?? t;
|
|
1293
|
+
try {
|
|
1294
|
+
reached.push(await appendToTicket(cur, body, { human: true, logged: true, header, key: `panel:${id}:${cur.id}` }));
|
|
1295
|
+
} catch (error) {
|
|
1296
|
+
lastError = error;
|
|
1297
|
+
ctx.logger?.warn?.(`bots: a panel reply did not reach task ${cur.id}: ${error?.message ?? error}`);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
if (!reached.length) throw lastError ?? new Error('no task took the reply');
|
|
1301
|
+
store.patchMessage(id, { ticket: reached[0].id });
|
|
1302
|
+
if (bot.sessionId) {
|
|
1303
|
+
try {
|
|
1304
|
+
const found = await service(ctx, 'sessionController')?.resolveAgent?.(bot.sessionId);
|
|
1305
|
+
if (found?.agent) {
|
|
1306
|
+
const text = followUpNoticeText({ tickets: reached, thread: { key: root, label: threadLabel({ threadKey: key, threadTitle: store.message(root)?.text }) }, who: 'The user', text: body }, cardCtx());
|
|
1307
|
+
await sendTo(found.agent, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:panel:${id}` });
|
|
1308
|
+
}
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
ctx.logger?.warn?.(`bots: the follow-up notice for @${bot.handle}: ${error?.message ?? error}`);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
return reached.map((t) => t.sessionId).filter(Boolean);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
/**
|
|
1317
|
+
* A thread a tool call names, as a key: a key as is; a panel topic by the id its header shows
|
|
1318
|
+
* (`p…`), or by any message in it (one filed under another topic names that one). '' for none.
|
|
1319
|
+
*/
|
|
1320
|
+
function threadRef(ref, sessionId) {
|
|
1321
|
+
const r = String(ref ?? '').trim().replace(/^(?:thread|topic)\//, '');
|
|
1322
|
+
if (!r || parseThreadKey(r)) return r;
|
|
1323
|
+
const hit = channels.current(sessionId).find((o) => o.kind === 'panel' && o.rootId === r);
|
|
1324
|
+
if (hit) return hit.threadKey;
|
|
1325
|
+
const m = store.message(r);
|
|
1326
|
+
if (!m) return r;
|
|
1327
|
+
const root = m.movedTo || m.topic || '';
|
|
1328
|
+
const first = root ? store.message(root) : undefined;
|
|
1329
|
+
return topicKeyOf(first, root) || r;
|
|
1330
|
+
}
|
|
1331
|
+
/** The panel topics of a turn, and its chat Threads, as a tool error lists them. */
|
|
1332
|
+
const turnChoices = (sessionId) =>
|
|
1333
|
+
channels
|
|
1334
|
+
.current(sessionId)
|
|
1335
|
+
.filter((o) => o.kind !== 'panel' || o.rootId)
|
|
1336
|
+
.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;
|
|
1186
1357
|
}
|
|
1187
1358
|
|
|
1188
1359
|
// --- tickets: delegated work in Sessions of their own ---------------------------------
|
|
@@ -1277,6 +1448,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1277
1448
|
}
|
|
1278
1449
|
if (plan.mode === 'thread') return originFrom(plan.target);
|
|
1279
1450
|
if (plan.mode === 'choose') {
|
|
1451
|
+
// Several topics or chats a person is waiting in (Bots 0.9): the task must say which one is its own.
|
|
1452
|
+
const topics = plan.origins.filter((o) => isTopicThread(o.threadKey));
|
|
1453
|
+
if (topics.length > 1) throw new Error(`this turn involves several topics or chats: say which one this task is for with \`thread\`: ${turnChoices(sessionId).join('; ')}`);
|
|
1280
1454
|
// Several Threads and none named: the task belongs to none of them (its report reaches the requester only).
|
|
1281
1455
|
const people = [...new Set(plan.origins.map((o) => o.who).filter(Boolean))];
|
|
1282
1456
|
return { origin: { ...(people.length === 1 ? { who: people[0] } : { who: 'the user' }) } };
|
|
@@ -1499,6 +1673,17 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1499
1673
|
if (!(t.sessionId && openTasks.has(t.sessionId))) reflectTicket(t);
|
|
1500
1674
|
}
|
|
1501
1675
|
|
|
1676
|
+
/**
|
|
1677
|
+
* Where a ticket's own lines go in the panel (Bots 0.9): a ticket that came from a panel topic
|
|
1678
|
+
* logs its delegation, the messages added to it and its notices into that topic, in the chat of
|
|
1679
|
+
* the bot that asked. Others log as in 0.8 (`{}`).
|
|
1680
|
+
*/
|
|
1681
|
+
const topicFieldsOf = (t) => {
|
|
1682
|
+
const key = t?.origin?.threadKey;
|
|
1683
|
+
const topic = key ? panelTopicOf(key) : '';
|
|
1684
|
+
return topic ? { chat: t.requester?.botId ?? t.botId, thread: key, topic } : {};
|
|
1685
|
+
};
|
|
1686
|
+
|
|
1502
1687
|
/** Who may add to a ticket from `sessionId`: its requester (or the requesting bot from its current home), or the router. */
|
|
1503
1688
|
function mayAppend(t, sender, sessionId) {
|
|
1504
1689
|
const r = t.requester ?? {};
|
|
@@ -1516,7 +1701,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1516
1701
|
* take the extra one); until then it waits on the ticket. A message whose `key` was delivered (or
|
|
1517
1702
|
* parked) already changes nothing: a replay after a restart neither reopens nor wakes the ticket.
|
|
1518
1703
|
*/
|
|
1519
|
-
async function appendToTicket(t, text, { sender = null, senderSessionId = '', human = false, force = false, header = '', chat = null, key = '' } = {}) {
|
|
1704
|
+
async function appendToTicket(t, text, { sender = null, senderSessionId = '', human = false, force = false, header = '', chat = null, key = '', logged = false } = {}) {
|
|
1520
1705
|
const body = String(text ?? '').trim();
|
|
1521
1706
|
if (body === '') throw new Error('text must not be empty');
|
|
1522
1707
|
if (t.archivedAt) throw new Error(`task ${t.id} is archived; open a new task instead`);
|
|
@@ -1555,10 +1740,12 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1555
1740
|
: [{ type: 'text', text: body }];
|
|
1556
1741
|
// A person's follow-up may take the extra slot (new work cannot crowd it out); a bot's may not.
|
|
1557
1742
|
await toTicket(cur, { content, source: sender && senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' }, key: key || `msg:${cur.id}:${randomUUID()}`, human: human && !sender });
|
|
1743
|
+
// A panel message is in the timeline already (logged when it was sent).
|
|
1744
|
+
if (logged) return tickets.get(cur.id) ?? cur;
|
|
1558
1745
|
store.log(
|
|
1559
1746
|
chat
|
|
1560
1747
|
? { from: 'user', to: cur.botId, text: body, kind: 'user', via: chat.kind, ...(chat.who ? { who: chat.who } : {}), ...(chat.threadKey ? { thread: chat.threadKey } : {}), ticket: cur.id }
|
|
1561
|
-
: { from: sender ? sender.id : 'user', to: cur.botId, text: body, kind: 'dm', ticket: cur.id },
|
|
1748
|
+
: { from: sender ? sender.id : 'user', to: cur.botId, text: body, kind: 'dm', ticket: cur.id, ...topicFieldsOf(cur) },
|
|
1562
1749
|
);
|
|
1563
1750
|
return tickets.get(cur.id) ?? cur;
|
|
1564
1751
|
}
|
|
@@ -1567,10 +1754,11 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1567
1754
|
* Open a ticket for `target`, asked from `senderSessionId` (a bot's home or a ticket Session),
|
|
1568
1755
|
* and start it when a slot is free. Returns the ticket; a start that failed shows as stage `failed`.
|
|
1569
1756
|
*/
|
|
1570
|
-
async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen } = {}) {
|
|
1757
|
+
async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen, relay = false } = {}) {
|
|
1571
1758
|
const body = String(text ?? '').trim();
|
|
1572
1759
|
if (body === '') throw new Error('text must not be empty');
|
|
1573
|
-
|
|
1760
|
+
// The dispatcher may hand work to itself (Bots 0.9): it does it in a task of its own, with all its tools.
|
|
1761
|
+
if (sender.id === target.id && !isRouterHome(sender, senderSessionId)) throw new Error('a bot cannot message itself');
|
|
1574
1762
|
if (!service(ctx, 'sessionController')) throw new Error('tasks need the Web profile (no session controller here)');
|
|
1575
1763
|
const parent = ticketOf(senderSessionId);
|
|
1576
1764
|
const { origin, thread } = originOfTurn(senderSessionId, chosen);
|
|
@@ -1582,8 +1770,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1582
1770
|
requester: { kind: 'session', sessionId: senderSessionId, botId: sender.id, ...(parent ? { ticketId: parent.id } : {}) },
|
|
1583
1771
|
origin,
|
|
1584
1772
|
threads: thread ? [thread] : [],
|
|
1773
|
+
relay,
|
|
1585
1774
|
});
|
|
1586
|
-
store.log({ from: sender.id, to: target.id, text: body, kind: 'dm', ticket: t.id });
|
|
1775
|
+
store.log({ from: sender.id, to: target.id, text: body, kind: 'dm', ticket: t.id, ...topicFieldsOf(t) });
|
|
1587
1776
|
quietFailures.add(t.id);
|
|
1588
1777
|
try {
|
|
1589
1778
|
await pump();
|
|
@@ -1608,8 +1797,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1608
1797
|
// they are kept on the task (its reports) and the panel shows them.
|
|
1609
1798
|
const parent = next.requester?.ticketId ? tickets.get(next.requester.ticketId) : undefined;
|
|
1610
1799
|
const unread = !wasOpen ? 'ended' : next.requester?.ticketId && (!parent || parent.ended) ? 'parent' : '';
|
|
1611
|
-
|
|
1612
|
-
|
|
1800
|
+
// Bots 0.9: the person reads it as it is, where the task came from; whoever asked is told without waking.
|
|
1801
|
+
const shown = status !== 'progress' && !unread && reportsGoDirect(next) ? showReport(next, report) : null;
|
|
1802
|
+
if (shown) {
|
|
1803
|
+
relayed = true;
|
|
1804
|
+
if (next.requester?.kind === 'session') {
|
|
1805
|
+
await notifyRequester(next, shownNoticeText(next, report, { ...cardCtx(), where: shown.where }), { mode: 'inject', key: `shown:${next.id}:${index}:${report.at}` });
|
|
1806
|
+
}
|
|
1807
|
+
} else if (status !== 'progress' && !unread) {
|
|
1808
|
+
store.log({ from: next.botId, to: next.requester?.botId ?? 'user', text: body, kind: 'dm', ticket: next.id, status, ...topicFieldsOf(next) });
|
|
1613
1809
|
// A ticket the user asked for has no Session to tell: the panel shows it (attention).
|
|
1614
1810
|
if (next.requester?.kind === 'session') {
|
|
1615
1811
|
// The requester's turn takes this ticket's origin Thread as an input when the relay arrives in it
|
|
@@ -1618,7 +1814,38 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1618
1814
|
}
|
|
1619
1815
|
}
|
|
1620
1816
|
if (status === 'done' && wasOpen) ticketEnded(next);
|
|
1621
|
-
return { ticket: next, relayed, ...(unread ? { unread, ...(parent ? { parent: parent.id } : {}) } : {}) };
|
|
1817
|
+
return { ticket: next, relayed, ...(shown ? { shown } : {}), ...(unread ? { unread, ...(parent ? { parent: parent.id } : {}) } : {}) };
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/**
|
|
1821
|
+
* Post a worker's report where its task came from (Bots 0.9): a panel topic (or the panel as a
|
|
1822
|
+
* whole, for a task from before topics) shows it in the chat of the bot that asked; a chat Thread
|
|
1823
|
+
* gets it through that chat's app, signed with the worker's name when the worker is not the one
|
|
1824
|
+
* the chat belongs to. Returns `{where}` (how the place reads), or null when it cannot be reached
|
|
1825
|
+
* (the report then goes to whoever asked, as in 0.8).
|
|
1826
|
+
*/
|
|
1827
|
+
function showReport(t, report) {
|
|
1828
|
+
const key = t.origin?.threadKey;
|
|
1829
|
+
if (!key) return null;
|
|
1830
|
+
const worker = store.get(t.botId);
|
|
1831
|
+
const owner = t.requester?.botId ? store.get(t.requester.botId) : undefined;
|
|
1832
|
+
const chat = owner?.id ?? t.botId;
|
|
1833
|
+
const body = String(report.text ?? '').trim();
|
|
1834
|
+
if (isPanelThread(key)) {
|
|
1835
|
+
const topic = panelTopicOf(key);
|
|
1836
|
+
store.log({ from: t.botId, to: 'user', chat, text: body, kind: 'reply', thread: key, ...(topic ? { topic } : {}), ticket: t.id, status: report.status });
|
|
1837
|
+
return { where: threadLabel({ threadKey: key, ...(topic ? { threadTitle: store.message(topic)?.text } : {}) }) };
|
|
1838
|
+
}
|
|
1839
|
+
const signed = worker && owner && worker.id !== owner.id ? `【${worker.name}】\n${body}` : body;
|
|
1840
|
+
let sent = null;
|
|
1841
|
+
try {
|
|
1842
|
+
sent = channels.post({ thread: key }, signed, { replyTo: t.origin?.replyTo ?? '', typingOf: t.sessionId ?? '' });
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
ctx.logger?.warn?.(`bots: the report on task ${t.id} was not posted to its chat: ${error?.message ?? error}`);
|
|
1845
|
+
}
|
|
1846
|
+
if (!sent) return null;
|
|
1847
|
+
store.log({ from: t.botId, to: 'user', chat, text: body, kind: 'reply', via: sent.kind, thread: key, ticket: t.id, status: report.status });
|
|
1848
|
+
return { where: tickets.thread(key)?.label ?? threadLabel(sent) };
|
|
1622
1849
|
}
|
|
1623
1850
|
|
|
1624
1851
|
/** A person (the panel) or the requester ends a ticket (stop, or close as done); either cancels its running turn. */
|
|
@@ -1728,7 +1955,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1728
1955
|
await toTicket(t, { content: [{ type: 'text', text: nudgeText(t) }], source: sourceFrom(t.requester), key: `nudge:${t.id}:${now}` });
|
|
1729
1956
|
} else {
|
|
1730
1957
|
const stalled = tickets.patch(t.id, { stalledAt: now });
|
|
1731
|
-
store.log({ from: t.botId, to: t.requester?.botId ?? 'user', text: `Task ${t.id} stalled: no report after a status check.`, kind: 'dm', ticket: t.id, status: 'stalled' });
|
|
1958
|
+
store.log({ from: t.botId, to: t.requester?.botId ?? 'user', text: `Task ${t.id} stalled: no report after a status check.`, kind: 'dm', ticket: t.id, status: 'stalled', ...topicFieldsOf(t) });
|
|
1732
1959
|
if (slots.release(t.id)) void pump();
|
|
1733
1960
|
// A ticket the user asked for has no Session to tell: the panel shows it (attention).
|
|
1734
1961
|
if (stalled.requester?.kind === 'session') await notifyRequester(stalled, stalledNoticeText(stalled, cardCtx()), { key: `stalled:${t.id}:${now}` });
|
|
@@ -1749,7 +1976,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1749
1976
|
const reportedAt = asTicket ? Number(asTicket.reports.at(-1)?.at) || 0 : bot ? lastReplyAt(bot.id) : 0;
|
|
1750
1977
|
return { status: agents()?.get?.(sessionId) ? agentStatusOf(sessionId) : 'offline', reportedAt, remindedAt };
|
|
1751
1978
|
};
|
|
1752
|
-
|
|
1979
|
+
// A task that answers the person itself (Bots 0.9) leaves its requester nothing to pass on.
|
|
1980
|
+
const relayed = all.filter((t) => !reportsGoDirect(t));
|
|
1981
|
+
for (const r of requesterReminders(relayed.map((t) => ({ ticket: t, stage: stageOf(t) })), facts, now)) {
|
|
1753
1982
|
const list = r.ticketIds.map((id) => tickets.get(id)).filter(Boolean);
|
|
1754
1983
|
if (!list.length) continue;
|
|
1755
1984
|
try {
|
|
@@ -1801,7 +2030,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1801
2030
|
}
|
|
1802
2031
|
const failed = tickets.end(t.id, { by: 'system', outcome: 'failed', error: reason });
|
|
1803
2032
|
if (!failed) return;
|
|
1804
|
-
store.log({ from: failed.botId, to: failed.requester?.botId ?? 'user', text: `Task ${failed.id} failed: ${reason}`, kind: 'dm', ticket: failed.id, status: 'failed' });
|
|
2033
|
+
store.log({ from: failed.botId, to: failed.requester?.botId ?? 'user', text: `Task ${failed.id} failed: ${reason}`, kind: 'dm', ticket: failed.id, status: 'failed', ...topicFieldsOf(failed) });
|
|
1805
2034
|
ticketEnded(failed);
|
|
1806
2035
|
if (failed.requester?.kind === 'session') void notifyRequester(failed, failedNoticeText(failed, cardCtx()), { key: `failed:${failed.id}:${failed.ended.at}` });
|
|
1807
2036
|
}
|
|
@@ -2066,6 +2295,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2066
2295
|
let via = null;
|
|
2067
2296
|
let kind;
|
|
2068
2297
|
let ticket;
|
|
2298
|
+
// A panel message's own text, without the header it reached the model with.
|
|
2299
|
+
let typedText;
|
|
2069
2300
|
try {
|
|
2070
2301
|
bot = botOfSession(session?.id);
|
|
2071
2302
|
if (!bot || !event) return;
|
|
@@ -2088,8 +2319,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2088
2319
|
const id = String(event.data?.id ?? '');
|
|
2089
2320
|
// The Harness tells a session about task edits made elsewhere; that is not a delivery.
|
|
2090
2321
|
if (kind === 'schedule' && /^\[SCHEDULE CHANGE\]/.test(textOf(event.data.content))) kind = 'schedule-notice';
|
|
2091
|
-
if (/^bots:followup:/.test(id)) {
|
|
2092
|
-
// A follow-up went to its tasks directly
|
|
2322
|
+
if (/^bots:(?:followup|shown):/.test(id)) {
|
|
2323
|
+
// A follow-up went to its tasks directly, or a report went to the person (injected notes that
|
|
2324
|
+
// woke nothing): no input of the turn.
|
|
2093
2325
|
kind = 'followup-notice';
|
|
2094
2326
|
} else {
|
|
2095
2327
|
// A report (or notice) on a ticket this conversation asked for: answering it is speaking to the user.
|
|
@@ -2104,12 +2336,19 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2104
2336
|
st.answers = new Set();
|
|
2105
2337
|
st.acted = false;
|
|
2106
2338
|
turnState.set(session.id, st);
|
|
2107
|
-
|
|
2108
|
-
// A
|
|
2109
|
-
|
|
2339
|
+
let said = textOf(event.data.content);
|
|
2340
|
+
// A message typed in the panel (Bots 0.9) is logged already; its topic joins the turn's Threads.
|
|
2341
|
+
const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
|
|
2342
|
+
const typed = panelId ? store.message(panelId) : undefined;
|
|
2343
|
+
if (typed) said = typedText = typed.text;
|
|
2344
|
+
const topicTitle = typed?.thread ? store.message(panelTopicOf(typed.thread))?.text : undefined;
|
|
2345
|
+
// A chat message adds its Thread to the turn's; a panel message its topic, or the panel (lib/threads.mjs).
|
|
2346
|
+
via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport, ...(typed?.thread ? { threadKey: typed.thread, origin: topicTitle ? { threadTitle: clip(topicTitle, 60).text } : {} } : {}) });
|
|
2110
2347
|
// A drawing's note: the answer goes to the chats the person asked for it in.
|
|
2111
2348
|
for (const o of drawingOrigins.get(id) ?? []) channels.noteInput(session.id, { threadKey: o.threadKey, origin: o });
|
|
2112
2349
|
drawingOrigins.delete(id);
|
|
2350
|
+
// What arrives in a topic or chat since bot_reply answered it needs an answer again.
|
|
2351
|
+
if (st.replied) for (const k of [typed?.thread, via?.threadKey, ...about.map((t) => t.origin?.threadKey)]) if (k) st.replied.delete(k);
|
|
2113
2352
|
// A report's ticket came from a Thread: the answer to the person goes there (PLAN-0.8 §4.3).
|
|
2114
2353
|
for (const t of about) {
|
|
2115
2354
|
const key = t.origin?.threadKey;
|
|
@@ -2119,7 +2358,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2119
2358
|
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 });
|
|
2120
2359
|
}
|
|
2121
2360
|
const thread = via ? via.threadKey : panelThreadKey(session.id);
|
|
2122
|
-
if (kind === 'user'
|
|
2361
|
+
if (kind === 'user' && typed) {
|
|
2362
|
+
// Logged when it was sent.
|
|
2363
|
+
} else if (kind === 'user') 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 } : {}) });
|
|
2123
2364
|
else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
|
|
2124
2365
|
}
|
|
2125
2366
|
} else if (event.type === 'assistant/message') {
|
|
@@ -2140,15 +2381,20 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2140
2381
|
// were reports and that only answered those tasks (they reach no one). The dispatcher reporting
|
|
2141
2382
|
// back after its teammates answered is a message to the user, and so is any bot passing on a
|
|
2142
2383
|
// report from a task it asked for, also in a turn where it hands out more work.
|
|
2143
|
-
const
|
|
2384
|
+
const plan = channels.replyPlan(session.id);
|
|
2385
|
+
// Closing words after bot_reply answered every topic or chat of the turn (Bots 0.9): each has its answer already.
|
|
2386
|
+
const topicsOfTurn = plan.origins.filter((o) => isTopicThread(o.threadKey));
|
|
2387
|
+
const allAnswered = topicsOfTurn.length > 0 && topicsOfTurn.every((o) => st?.replied?.has(o.threadKey));
|
|
2388
|
+
const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id))) || (why === 'report' && closingOnly(session.id)) || allAnswered;
|
|
2144
2389
|
if (text && !hidden) {
|
|
2145
2390
|
// To the turn's one chat Thread; with several (or the panel and a chat) it stays in the panel,
|
|
2146
2391
|
// and bot_reply says where each answer goes.
|
|
2147
|
-
const plan = channels.replyPlan(session.id);
|
|
2148
2392
|
const sent = channels.noteReply(session.id, text);
|
|
2149
2393
|
const thread = sent ? sent.threadKey : panelThreadKey(session.id);
|
|
2394
|
+
// A topic in the panel (Bots 0.9): the reply is shown in it.
|
|
2395
|
+
const topic = sent?.kind === 'panel' ? panelTopicOf(sent.threadKey) : '';
|
|
2150
2396
|
const choices = plan.mode === 'choose' ? plan.origins.filter((o) => o.kind !== 'panel').map((o) => o.threadKey) : [];
|
|
2151
|
-
store.log({ from: bot.id, to: 'user', text, kind: 'reply', ...(sent ? { via: sent.kind } : {}), ...(thread ? { thread } : {}), ...(choices.length ? { notSent: true, choices } : {}) });
|
|
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 } : {}) });
|
|
2152
2398
|
}
|
|
2153
2399
|
} else if (event.type === 'turn/end') {
|
|
2154
2400
|
channels.noteTurnEnd(session.id);
|
|
@@ -2163,8 +2409,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2163
2409
|
const sid = session.id;
|
|
2164
2410
|
if (event.type === 'user/message') {
|
|
2165
2411
|
if (!TASK_KINDS.has(kind)) return;
|
|
2166
|
-
const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via);
|
|
2167
|
-
const said = textOf(event.data?.content);
|
|
2412
|
+
const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via, typedText);
|
|
2413
|
+
const said = typedText ?? textOf(event.data?.content);
|
|
2168
2414
|
const who = kind === 'schedule' ? 'scheduled' : kind === 'agent-message' ? (ticket ? 'task message' : 'bot message') : via ? `user via ${via.kind}` : 'user';
|
|
2169
2415
|
logLine(task, `[${who}] ${via ? via.body : said}`);
|
|
2170
2416
|
} else if (event.type === 'assistant/message') {
|
|
@@ -2960,8 +3206,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2960
3206
|
description: [
|
|
2961
3207
|
'Message another bot, or report on the task this conversation works on. Make the text self-contained: the other bot cannot see this conversation. Do not reply to acknowledgements.',
|
|
2962
3208
|
"- To delegate: `to` (the bot's @handle) and `text`. Depending on how the team works, this opens a task (ticket) that the bot works on in a conversation of its own, or drops the text into that bot's own conversation; the result says which. Either way the call returns at once and the answer (a report, or a bot message) arrives here by itself: never wait or poll for it.",
|
|
2963
|
-
'- When this turn involves several chats, name the one a new task is for with `thread` (its
|
|
2964
|
-
'-
|
|
3209
|
+
'- When this turn involves several topics or chats, name the one a new task is for with `thread` (as its message header shows it), so its answer goes there.',
|
|
3210
|
+
'- The dispatcher may name itself in `to`: it then does the work in a task conversation of its own, with all its tools.',
|
|
3211
|
+
'- A task from a topic or chat answers the person there itself; pass `report_to: "me"` to get its reports back instead (to combine several results).',
|
|
3212
|
+
'- To add to an open task you asked for (an answer to its question, a change, a message of the person\'s that continues it): `ticket` (its id) and `text`.',
|
|
2965
3213
|
'- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
|
|
2966
3214
|
].join('\n'),
|
|
2967
3215
|
parameters: {
|
|
@@ -2970,7 +3218,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2970
3218
|
ticket: { type: 'string', description: 'Id of an open task to add this message to.' },
|
|
2971
3219
|
status: { type: 'string', enum: REPORT_STATUSES, description: 'Required when reporting from a task conversation: progress (an update worth keeping), done (with the result), blocked, question.' },
|
|
2972
3220
|
title: { type: 'string', description: 'A short title for a new task; taken from the first line of text when left out.' },
|
|
2973
|
-
thread: { type: 'string', description: 'Only when this turn involves several chats: the
|
|
3221
|
+
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
|
+
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.' },
|
|
2974
3223
|
},
|
|
2975
3224
|
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
|
|
2976
3225
|
isConcurrencySafe: () => true,
|
|
@@ -2988,11 +3237,13 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2988
3237
|
const isReport = wantTicket ? wantTicket === mine.id : !named || (named.id === requesterBot && named.id !== sender.id);
|
|
2989
3238
|
if (isReport) {
|
|
2990
3239
|
if (!status) throw new Error(`a report on task ${mine.id} needs a status: progress (an update), done (with the result), blocked or question`);
|
|
2991
|
-
const { ticket, relayed, unread, parent } = await reportTicket(mine, status, args.text);
|
|
3240
|
+
const { ticket, relayed, unread, parent, shown } = await reportTicket(mine, status, args.text);
|
|
2992
3241
|
const to = requesterBot ? store.get(requesterBot) : null;
|
|
2993
3242
|
const said =
|
|
2994
3243
|
status === 'progress'
|
|
2995
3244
|
? `Recorded on task ${ticket.id}; progress does not interrupt whoever asked. Go on with the work.`
|
|
3245
|
+
: shown
|
|
3246
|
+
? `Shown to the person as it is, in ${shown.where}${to ? `; @${to.handle} is told` : ''}.${status === 'done' ? ' The task is done: end your turn without a summary.' : ' Their answer will arrive here by itself; end your turn now.'}`
|
|
2996
3247
|
: unread
|
|
2997
3248
|
? `Recorded "${status}" on task ${ticket.id}, but nobody is told: ${unread === 'ended' ? `the task has ended (${stageOf(ticket)})` : `the task that asked for it${parent ? `, ${parent},` : ''} has ended`}. The report is kept on the task; end your turn now.`
|
|
2998
3249
|
: `Reported "${status}" on task ${ticket.id} to ${to ? `@${to.handle}` : 'the user'}${relayed || !to ? '' : ' (it could not be reached just now; the report is kept on the task)'}.${status === 'done' ? ' The task is done: end your turn without a summary.' : ' An answer will arrive here by itself; end your turn now.'}`;
|
|
@@ -3001,6 +3252,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3001
3252
|
}
|
|
3002
3253
|
if (status) throw new Error(mine ? `\`status\` is for reports to whoever asked for task ${mine.id} (leave out "to"); to ask @${named?.handle ?? 'a bot'} for help, leave out \`status\`` : '`status` is only for reports from a task conversation; leave it out here');
|
|
3003
3254
|
|
|
3255
|
+
const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
|
|
3004
3256
|
// Adding to an existing ticket.
|
|
3005
3257
|
if (wantTicket) {
|
|
3006
3258
|
const t = tickets.get(wantTicket);
|
|
@@ -3010,19 +3262,26 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3010
3262
|
const next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
|
|
3011
3263
|
const target = store.get(next.botId);
|
|
3012
3264
|
const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
|
|
3013
|
-
|
|
3265
|
+
// The person's new message that continues this task joins the task's topic (Bots 0.9).
|
|
3266
|
+
const filed = !mine && sender ? fileUnder(next, sessionId, chosen) : '';
|
|
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) };
|
|
3014
3269
|
}
|
|
3015
3270
|
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`');
|
|
3016
3271
|
|
|
3017
3272
|
// A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
|
|
3018
|
-
const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : '';
|
|
3019
3273
|
if (sender && sessionId && (mine || (ticketsOn() && sender.sessionId === sessionId))) {
|
|
3020
|
-
const
|
|
3274
|
+
const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
|
|
3275
|
+
const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
|
|
3021
3276
|
const stage = stageOf(t);
|
|
3277
|
+
const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
|
|
3278
|
+
const answer = reportsGoDirect(t)
|
|
3279
|
+
? `${named.id === sender.id ? 'You answer' : `@${named.handle} answers`} the person in ${isPanelThread(t.origin?.threadKey) ? 'the topic' : '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
|
+
: 'Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.';
|
|
3022
3281
|
const said =
|
|
3023
3282
|
stage === 'failed'
|
|
3024
|
-
? `Task ${t.id} for
|
|
3025
|
-
: `Opened task ${t.id} for
|
|
3283
|
+
? `Task ${t.id} for ${who} could not start: ${t.error ?? 'unknown error'}.`
|
|
3284
|
+
: `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}`;
|
|
3026
3285
|
return { ok: stage !== 'failed', text: said, ticket: row(t), stage, to: face(named), from: face(sender) };
|
|
3027
3286
|
}
|
|
3028
3287
|
// 0.7: into the other bot's home (the user from any conversation; any home in hands-on mode).
|
|
@@ -3034,10 +3293,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3034
3293
|
defineTool({
|
|
3035
3294
|
name: 'bot_reply',
|
|
3036
3295
|
description:
|
|
3037
|
-
'
|
|
3296
|
+
'Answer in a topic or chat: the one a task came from (`ticket`: its id), or a thread (`thread`: as message headers "(thread …)" and task cards show it — a panel topic `p…`, or a chat thread key). Use it when this turn involves more than one topic or chat, so each answer stays in its own; your plain text then reaches none of them. With a single one in the turn, plain text goes there already.',
|
|
3038
3297
|
parameters: {
|
|
3039
|
-
ticket: { type: 'string', description: 'Id of a task (t…): the reply goes to the chat that task came from.' },
|
|
3040
|
-
thread: { type: 'string', description: '
|
|
3298
|
+
ticket: { type: 'string', description: 'Id of a task (t…): the reply goes to the topic or chat that task came from.' },
|
|
3299
|
+
thread: { type: 'string', description: 'A panel topic (p…) or chat thread key of this turn (or of a task you know of).' },
|
|
3041
3300
|
text: { type: 'string', required: true, description: 'The reply, as the person should read it.' },
|
|
3042
3301
|
},
|
|
3043
3302
|
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ via: v.via, thread: v.thread }) },
|
|
@@ -3047,23 +3306,38 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3047
3306
|
if (!bot) throw new Error("bot_reply answers from a bot's own conversation; this conversation has no chats");
|
|
3048
3307
|
const body = String(args.text ?? '').trim();
|
|
3049
3308
|
if (body === '') throw new Error('text must not be empty');
|
|
3050
|
-
const thread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread
|
|
3309
|
+
const thread = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
|
|
3051
3310
|
const ticketId = typeof args.ticket === 'string' && args.ticket.trim() !== '' ? args.ticket.trim().replace(/^(?:ticket|task)\//, '') : '';
|
|
3052
3311
|
const options = () => {
|
|
3053
|
-
const list =
|
|
3054
|
-
return list.length
|
|
3055
|
-
|
|
3056
|
-
|
|
3312
|
+
const list = turnChoices(sessionId);
|
|
3313
|
+
return list.length ? `This turn's topics and chats: ${list.join('; ')}.` : 'This turn has no topic or chat; a task id names the one it came from.';
|
|
3314
|
+
};
|
|
3315
|
+
if (!thread && !ticketId) throw new Error(`say where: \`ticket\` (a task id) or \`thread\` (a topic or thread). ${options()}`);
|
|
3316
|
+
// A topic in the panel (Bots 0.9): this turn's, one a task came from, or any the bot's chat has.
|
|
3317
|
+
const asked = ticketId ? tickets.get(ticketId) : undefined;
|
|
3318
|
+
const panelKey = thread ? (panelTopicOf(thread) ? thread : '') : panelTopicOf(asked?.origin?.threadKey) ? asked.origin.threadKey : '';
|
|
3319
|
+
// A panel topic of this bot's own chat only: one whose first message is there, or a task it asked for or does.
|
|
3320
|
+
if (panelKey) {
|
|
3321
|
+
const root = store.message(panelTopicOf(panelKey));
|
|
3322
|
+
const mine = thread ? Boolean(root) && inChat(root, bot.id) : Boolean(asked) && (asked.requester?.botId === bot.id || asked.botId === bot.id);
|
|
3323
|
+
if (!mine) throw new Error(`${thread ? `no topic "${args.thread}"` : `task ${ticketId} came from no topic`} in this bot's chat. ${options()}`);
|
|
3324
|
+
}
|
|
3325
|
+
const target = panelKey ? { kind: 'panel', threadKey: panelKey } : channels.resolveReply(sessionId, thread ? { thread } : { ticket: ticketId });
|
|
3326
|
+
if (!target) throw new Error(`${thread ? `no topic or chat thread "${thread}"` : `no topic or chat for task ${ticketId}`} can be reached from here. ${options()}`);
|
|
3327
|
+
const answeredHere = () => {
|
|
3328
|
+
const st = turnState.get(sessionId);
|
|
3329
|
+
if (st) (st.replied ??= new Set()).add(target.threadKey);
|
|
3057
3330
|
};
|
|
3058
|
-
if (!thread && !ticketId) throw new Error(`say where: \`ticket\` (a task id) or \`thread\` (a thread key). ${options()}`);
|
|
3059
|
-
const target = channels.resolveReply(sessionId, thread ? { thread } : { ticket: ticketId });
|
|
3060
|
-
if (!target) throw new Error(`${thread ? `no chat thread "${thread}"` : `no chat for task ${ticketId}`} can be reached from here. ${options()}`);
|
|
3061
3331
|
if (target.kind === 'panel') {
|
|
3062
|
-
|
|
3063
|
-
|
|
3332
|
+
const topic = panelTopicOf(target.threadKey);
|
|
3333
|
+
const chat = (topic && store.message(topic)?.chat) || bot.id;
|
|
3334
|
+
store.log({ from: bot.id, to: 'user', chat, text: body, kind: 'reply', thread: topic ? target.threadKey : panelThreadKey(sessionId), ...(topic ? { topic } : {}) });
|
|
3335
|
+
answeredHere();
|
|
3336
|
+
return { ok: true, text: topic ? `Shown in the panel, in topic ${topic}.` : 'That thread is the panel: the reply is shown there.', thread: target.threadKey };
|
|
3064
3337
|
}
|
|
3065
3338
|
channels.replyTo(sessionId, target, body);
|
|
3066
|
-
|
|
3339
|
+
answeredHere();
|
|
3340
|
+
store.log({ from: bot.id, to: 'user', chat: bot.id, text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
|
|
3067
3341
|
return { ok: true, text: `Sent to ${threadLabel(target)}.`, thread: target.threadKey, via: target.kind };
|
|
3068
3342
|
},
|
|
3069
3343
|
}),
|
|
@@ -3926,7 +4200,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3926
4200
|
const text = zhText
|
|
3927
4201
|
? `请为你自己写一个新技能:${ask}\n\n如果有 skill-creator 技能,先加载它并按它的方法写。写好后调用 bot_update(bot: @${bot.handle},add_skills)保存:name 用小写英文短横线,description 一句话写清楚何时使用,content 是完整的 Markdown 指南。最后用两三句话告诉我这个技能能做什么。`
|
|
3928
4202
|
: `Write a new skill for yourself: ${ask}\n\nIf the skill-creator skill is available, load it and follow it. Save the result with bot_update (bot: @${bot.handle}, add_skills): a lowercase-dashed name, a one-sentence description of when to use it, and the full Markdown instructions as content. Then tell me in two or three sentences what the skill does.`;
|
|
3929
|
-
return { ok: true, sessionId: await userSend(bot, text) };
|
|
4203
|
+
return { ok: true, sessionId: (await userSend(bot, text)).sessionId };
|
|
3930
4204
|
},
|
|
3931
4205
|
},
|
|
3932
4206
|
'apps/external': { get: () => ({ items: scanExternalMcp().map(maskedApp) }) },
|
|
@@ -3952,9 +4226,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3952
4226
|
catalog: { get: () => catalog() },
|
|
3953
4227
|
// A link preview card for the chat: YouTube, X posts, or any page's OpenGraph meta.
|
|
3954
4228
|
unfurl: { get: (url) => unfurlLink(url.searchParams.get('url') ?? '') },
|
|
3955
|
-
messages: {
|
|
3956
|
-
get: (url) => ({ items: store.messages({ bot: url.searchParams.get('bot') ?? '', limit: Number(url.searchParams.get('limit')) || 200 }) }),
|
|
3957
|
-
},
|
|
4229
|
+
messages: { get: (url) => messagesView(url) },
|
|
3958
4230
|
schedules: {
|
|
3959
4231
|
get: async (url) => {
|
|
3960
4232
|
const id = url.searchParams.get('bot');
|
|
@@ -3999,7 +4271,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3999
4271
|
post: async (body) => {
|
|
4000
4272
|
const bot = store.get(String(body.to ?? ''));
|
|
4001
4273
|
if (!bot) return { ok: false, reason: 'no such bot' };
|
|
4002
|
-
|
|
4274
|
+
const sent = await userSend(bot, body.text, { replyTo: String(body.replyTo ?? '') });
|
|
4275
|
+
return { ok: true, sessionId: sent.sessionId, ...(sent.message ? { message: sent.message } : {}) };
|
|
4003
4276
|
},
|
|
4004
4277
|
},
|
|
4005
4278
|
avatar: {
|
|
@@ -4140,6 +4413,26 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4140
4413
|
'channels/reconnect': { post: (body) => ({ ok: channels.reconnect(String(body.botId ?? ''), String(body.appId ?? '')) }) },
|
|
4141
4414
|
};
|
|
4142
4415
|
|
|
4416
|
+
/**
|
|
4417
|
+
* GET /messages?bot=&topic=&limit=: a bot's chat (or one topic of it, or everything), oldest first,
|
|
4418
|
+
* and per topic seen there its key and the tasks it has (PLAN-0.9 §7.3).
|
|
4419
|
+
*/
|
|
4420
|
+
function messagesView(url) {
|
|
4421
|
+
const bot = url.searchParams.get('bot') ?? '';
|
|
4422
|
+
const topic = url.searchParams.get('topic') ?? '';
|
|
4423
|
+
const limit = Number(url.searchParams.get('limit')) || (topic ? 500 : 200);
|
|
4424
|
+
const items = store.messages({ bot, limit, topic }).map(messageView);
|
|
4425
|
+
const roots = new Set(items.flatMap((m) => [m.topic, m.movedTo]).filter(Boolean));
|
|
4426
|
+
const topics = {};
|
|
4427
|
+
for (const root of roots) {
|
|
4428
|
+
const first = items.find((m) => m.id === root) ?? store.message(root);
|
|
4429
|
+
const key = topicKeyOf(first, root) || items.find((m) => m.topic === root && m.id !== root && panelTopicOf(m.thread) === root)?.thread;
|
|
4430
|
+
if (!key) continue;
|
|
4431
|
+
topics[root] = { key, tickets: tickets.subscribers(key).filter((t) => !t.archivedAt).map(ticketRow) };
|
|
4432
|
+
}
|
|
4433
|
+
return { items, topics };
|
|
4434
|
+
}
|
|
4435
|
+
|
|
4143
4436
|
/** GET /tickets?bot=&stage=&limit=&offset=: rows, the latest change first; `stage` may list several (a,b). */
|
|
4144
4437
|
function ticketList(url) {
|
|
4145
4438
|
const bot = url.searchParams.get('bot') || undefined;
|
|
@@ -4158,9 +4451,11 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4158
4451
|
const th = tickets.thread(key);
|
|
4159
4452
|
const parsed = parseThreadKey(key);
|
|
4160
4453
|
if (!th && !parsed) return { ok: false, reason: 'no such thread' };
|
|
4454
|
+
// The panel as a whole holds its topics (`panel:<sessionId>:<root>`).
|
|
4455
|
+
const whole = isPanelThread(key) && !panelTopicOf(key);
|
|
4161
4456
|
const recent = store
|
|
4162
4457
|
.messages({ limit: 2000 })
|
|
4163
|
-
.filter((m) => m.thread === key)
|
|
4458
|
+
.filter((m) => m.thread === key || (whole && String(m.thread ?? '').startsWith(`${key}:`)))
|
|
4164
4459
|
.slice(-10)
|
|
4165
4460
|
.map((m) => ({ at: m.at, from: m.from, to: m.to, ...(m.who ? { who: m.who } : {}), text: clip(String(m.text ?? ''), 300).text }));
|
|
4166
4461
|
return { key, label: th?.label ?? threadLabel(key), kind: th?.kind ?? parsed?.kind ?? '', tickets: tickets.subscribers(key).map(ticketRow), recent };
|
|
@@ -4267,7 +4562,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4267
4562
|
|
|
4268
4563
|
/** For tests: which per-Session records this process still keeps for `sessionId`. */
|
|
4269
4564
|
const tracked = (sessionId) => ({ trigger: trigger.has(sessionId), answered: answered.has(sessionId), turn: turnState.has(sessionId), delivered: deliveredIds.has(sessionId), history: historyRead.has(sessionId) });
|
|
4270
|
-
return { store, state, deliver, install, reconcile, installed, routes, channels, memory, ledger, topics, settings, newTopic, dream, sweep, userSend, openTasks, codexSync, finishTask, tickets, slots, pump, botOfSession, request, ticketView, ticketUpkeep, watch, startup, recoverTickets, tracked };
|
|
4565
|
+
return { store, state, deliver, install, reconcile, installed, routes, channels, memory, ledger, topics, settings, newTopic, dream, sweep, userSend: async (...a) => (await userSend(...a)).sessionId, panelSend: userSend, openTasks, codexSync, finishTask, tickets, slots, pump, botOfSession, request, ticketView, ticketUpkeep, watch, startup, recoverTickets, tracked };
|
|
4271
4566
|
}
|
|
4272
4567
|
|
|
4273
4568
|
function serveAvatar(dir, req, res) {
|