@kadaliao/dsh-bots 0.8.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 +115 -24
- package/README.zh-CN.md +81 -18
- package/client.js +783 -88
- package/index.js +789 -93
- package/lib/cards.mjs +89 -0
- 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 +61 -9
- package/lib/discussions.mjs +300 -0
- package/lib/prompt.mjs +50 -17
- package/lib/store.mjs +73 -5
- package/lib/threads.mjs +91 -26
- package/lib/tickets.mjs +7 -3
- package/package.json +1 -1
package/lib/prompt.mjs
CHANGED
|
@@ -20,6 +20,10 @@ const MANAGE_LINE = '- `bot_list` shows the team with each bot\'s skills and app
|
|
|
20
20
|
const SCHEDULE_NOTICE_LINE = '- Ignore "[SCHEDULE CHANGE]" notices: they need no reply.';
|
|
21
21
|
const SCHEDULE_LINE = 'Use `bot_schedule` to give any bot (yourself included) recurring or timed tasks: the instruction is delivered to that bot\'s conversation at each occurrence.';
|
|
22
22
|
|
|
23
|
+
/** A team's dispatcher has no Harness sub-agents (Bots 0.10): parallel help is a teammate's task, which the person can follow. The other bots keep theirs. */
|
|
24
|
+
const teamHelpersLine = (router) =>
|
|
25
|
+
`- Your helpers are your teammates: as the dispatcher you have no Harness sub-agents (\`subagent\`, \`wait_agent\`, workflows). When a skill says to start sub-agents or parallel researchers, hand those parts to teammates with \`bot_send_message\` instead${router ? '' : ', or do them yourself one after another'}.`;
|
|
26
|
+
|
|
23
27
|
/** "Working with other bots" as a hands-on bot reads it (0.7 text). */
|
|
24
28
|
const HANDS_ON_TEAM = [
|
|
25
29
|
'- Message another bot with `bot_send_message` (to: its @handle). It receives your text in its own conversation and works on it there; its answer comes back to you as a "Bot message from @…" message.',
|
|
@@ -31,10 +35,10 @@ const HANDS_ON_TEAM = [
|
|
|
31
35
|
MANAGE_LINE,
|
|
32
36
|
];
|
|
33
37
|
|
|
34
|
-
/** "Working with other bots" as a router dispatcher reads it. */
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
'- Keep messages self-contained: the
|
|
38
|
+
/** "Working with other bots" as a router dispatcher reads it (`self`: its own @handle). */
|
|
39
|
+
const routerTeam = (self) => [
|
|
40
|
+
`- Hand work to a teammate with \`bot_send_message\` (to: its @handle; never your own, @${self}: you do no work yourself, not even in a task). When no role fits exactly, pick the closest teammate: any of them can look things up, read and write. Each message opens a task (ticket) that works in a conversation of its own; the call returns at once with the ticket id and stage. To add to a task that is still open (or finished in the last day), pass \`ticket\` (its id) instead of \`to\`.`,
|
|
41
|
+
'- Keep messages self-contained: the bot (you too, in a task) cannot see this conversation.',
|
|
38
42
|
SCHEDULE_NOTICE_LINE,
|
|
39
43
|
LANGUAGE_LINE,
|
|
40
44
|
MANAGE_LINE,
|
|
@@ -42,7 +46,8 @@ const ROUTER_TEAM = [
|
|
|
42
46
|
|
|
43
47
|
/** "Working with other bots" as a bot's own home reads it when delegating opens tasks (router mode), the dispatcher aside. */
|
|
44
48
|
const HOME_TICKETS_TEAM = [
|
|
45
|
-
'- Message another bot with `bot_send_message` (to: its @handle). That opens a task (ticket) for it, which it works on in a conversation of its own; the call returns at once
|
|
49
|
+
'- Message another bot with `bot_send_message` (to: its @handle). That opens a task (ticket) for it, which it works on in a conversation of its own; the call returns at once. Never wait or poll for its answer. To add to a task you opened, pass `ticket` (its id) instead of `to`.',
|
|
50
|
+
'- When the request came from the person (the panel chat, a thread in it, or a chat app), that bot answers them there itself and you get a "[Shown]" note, which needs no reply. Pass `report_to: "me"` when you need the result back yourself; it then arrives as a "Report from @… on task …" message.',
|
|
46
51
|
'- A message that starts with "Report from @…" or "Bot message from @…" was sent by that bot, not by the user. Pass a report\'s result on to whoever asked; a `question` or `blocked` report needs an answer with `bot_send_message` (ticket: its id).',
|
|
47
52
|
'- Keep messages self-contained: the other bot cannot see your conversation.',
|
|
48
53
|
SCHEDULE_NOTICE_LINE,
|
|
@@ -71,6 +76,19 @@ function requesterPhrase(ticket, roster) {
|
|
|
71
76
|
return handle;
|
|
72
77
|
}
|
|
73
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Whether a ticket's `done`, `question` and `blocked` reports are posted as they are in the thread
|
|
81
|
+
* or chat its request came from (Bots 0.9), rather than handed to whoever asked to pass on: it has
|
|
82
|
+
* a Thread, it is no sub-task, and its requester did not ask for the reports (`relay`).
|
|
83
|
+
*/
|
|
84
|
+
export function reportsGoDirect(ticket) {
|
|
85
|
+
const t = ticket ?? {};
|
|
86
|
+
return !t.relay && Boolean(t.origin?.threadKey) && !t.parentId && !t.requester?.ticketId;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Where a ticket's direct reports are shown, as its worker reads it. */
|
|
90
|
+
const shownWhere = (ticket) => (String(ticket.showIn ?? ticket.origin?.threadKey ?? '').startsWith('panel:') ? 'in the panel, where the request came from' : `in the chat${ticket.origin?.via ? ` (${ticket.origin.via})` : ''} the request came from`);
|
|
91
|
+
|
|
74
92
|
/** `, for Kada on Slack` from a ticket's origin, or ''. */
|
|
75
93
|
function originPhrase(ticket) {
|
|
76
94
|
const { who, via } = ticket.origin ?? {};
|
|
@@ -100,14 +118,22 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
100
118
|
lines.push('', '## The bot team');
|
|
101
119
|
lines.push(roster.length > 1 ? 'These bots work for the same user and can message each other:' : 'You are the only bot so far.');
|
|
102
120
|
if (roster.length > 1) for (const b of roster) lines.push(rosterLine(b, bot.id));
|
|
103
|
-
lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ?
|
|
121
|
+
lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ? routerTeam(bot.handle) : homeTickets ? HOME_TICKETS_TEAM : HANDS_ON_TEAM));
|
|
122
|
+
if (others.length && bot.role === 'primary') lines.push(teamHelpersLine(router));
|
|
104
123
|
if (ticket) {
|
|
124
|
+
const direct = reportsGoDirect(ticket);
|
|
105
125
|
lines.push(
|
|
106
126
|
'',
|
|
107
127
|
'## This conversation is one task',
|
|
108
128
|
`It is task ${ticket.id}: "${String(ticket.title ?? '').trim()}", asked by ${requesterPhrase(ticket, roster)}${originPhrase(ticket)}. Its first message says what to do.`,
|
|
109
129
|
'- Report to whoever asked with `bot_send_message`: leave out `to` and give a `status`, which is required — `progress` for an update worth keeping, `done` with the result when you are finished, `blocked` when you cannot go on, `question` when you need an answer.',
|
|
110
|
-
|
|
130
|
+
...(direct
|
|
131
|
+
? [
|
|
132
|
+
`- Your \`done\`, \`question\` and \`blocked\` reports are shown to the person as they are, ${shownWhere(ticket)}, and whoever asked is told. Write them for the person: the whole answer, in their language, nothing addressed to a bot. Their replies come back here.`,
|
|
133
|
+
'- To the person a report reads as you talking to them in the chat, so write it the way you would answer there: start with the answer itself, not with its status ("done", "finished", "here is the report"), and leave out task ids and how the work was handed around.',
|
|
134
|
+
'- Your plain text reaches no one: only reports do. Put everything the person needs in the report (nobody sees this conversation); after a `done` report, end your turn without a summary.',
|
|
135
|
+
]
|
|
136
|
+
: ['- Your plain text reaches no one: only reports do. Put everything the requester needs in the report (it cannot see this conversation); after a `done` report, end your turn without a summary.']),
|
|
111
137
|
'- Asking another bot opens a sub-task; its report comes back here by itself.',
|
|
112
138
|
'- Messages from the person about this task may arrive here directly. Take them into account and answer them in a report.',
|
|
113
139
|
`- \`bot_recall\` reads this task (\`ticket/${ticket.id}\`), its parent and sub-tasks, and the threads it belongs to.`,
|
|
@@ -116,13 +142,17 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
116
142
|
lines.push(
|
|
117
143
|
'',
|
|
118
144
|
'## You are the dispatcher',
|
|
119
|
-
'The user treats you as the main bot, and you run the team. You do three things: understand what the person wants, hand the work out, and
|
|
120
|
-
'- Every
|
|
121
|
-
'-
|
|
122
|
-
'-
|
|
123
|
-
'-
|
|
145
|
+
'The user treats you as the main bot, and you run the team as its front desk. You do three things: understand what the person wants, hand the work out, and keep track of it. Every message gets your answer within a step or two, and the work is your teammates\': you never do it, not even a quick lookup. Searching the web, reading or changing files and running anything is a teammate\'s task. When no bot fits a recurring kind of work, propose creating one.',
|
|
146
|
+
'- Every message is its own request, unless it clearly continues one of the open tasks listed with it ("[Panel]" messages list them). When several messages arrive together, handle every one of them: never drop a request because another came after it.',
|
|
147
|
+
'- For each request do one of these, then end your turn: answer it yourself only from what you already know (a greeting, what the person means, the team, its tasks and what they already reported); hand it out with `bot_send_message` and tell the person in a sentence what happens next, as a colleague would in a chat ("@ledger is looking into it, back in a few minutes"); or, when it continues an open task, add it to that task with `bot_send_message` (ticket: its id).',
|
|
148
|
+
'- Talk to the person like a person in a chat, in their language. Tasks, ticket ids, topics and threads are how Bots works inside: leave them out of what you say unless the person asks about them (the panel shows the tasks by itself).',
|
|
149
|
+
'- A conversation that starts with "[Thread]" is a thread: the person replies to one earlier message, and you see the conversation up to it, not what came after. Stay on that message; tasks you open there answer in the thread.',
|
|
150
|
+
'- Every delegation with `bot_send_message` opens a task (ticket) for that bot and returns at once. Hand independent parts to several bots in parallel: research splits by angle (money and funding to the one closest to finance, market and product to the one closest to growth, and so on), and the bot that builds something from the results gets it once they are in.',
|
|
151
|
+
'- The bot doing a task answers the person itself, where the request came from (the panel chat, a thread, or a chat app), and the person\'s replies to its answer go straight to it. You get a "[Shown]" note: it needs no reply, so do not repeat the result. Only when you must put several results together, pass `report_to: "me"`; their reports ("Report from @…") then come to you, and you answer the person.',
|
|
152
|
+
'- Reports, notes ("[Shown]", "[follow_up]") and new messages arrive by themselves. Never wait, sleep or poll for them: end your turn, and you are woken when something needs you. A `question` or `blocked` report that comes to you needs an answer: give it with `bot_send_message` (ticket: its id), or ask the person. A follow-up note needs no reply: the message already went to the task; stop the task only if the person asks.',
|
|
153
|
+
'- When a turn involves more than one chat (the panel and a chat app, or two chat threads), answer each with `bot_reply` (thread: the key its header shows, or ticket: a task id) so every answer stays where it belongs; plain text then reaches none of them.',
|
|
124
154
|
'- Use `bot_recall` to look up tasks and threads (`tickets`, `ticket/<id>`, `thread/<key>`, `bot/<handle>`) instead of guessing.',
|
|
125
|
-
'- Keep
|
|
155
|
+
'- Keep your own replies short: 100 words at most, no tables.',
|
|
126
156
|
SCHEDULE_LINE,
|
|
127
157
|
);
|
|
128
158
|
} else if (bot.role === 'primary') {
|
|
@@ -153,7 +183,9 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
153
183
|
if (extra.channels?.length) {
|
|
154
184
|
const first = extra.channels[0];
|
|
155
185
|
const how = ticket
|
|
156
|
-
?
|
|
186
|
+
? reportsGoDirect(ticket)
|
|
187
|
+
? 'It is a follow-up about this task. Your plain text does not reach that chat: answer in a report, which is posted there.'
|
|
188
|
+
: 'It is a follow-up about this task. Your plain text does not reach that chat: answer in a report, and the requester passes it on.'
|
|
157
189
|
: 'Treat it like any request from the user: your reply is sent back to that chat as plain text, so keep it short, skip tables, and say plainly what you did or who is on it.';
|
|
158
190
|
lines.push(
|
|
159
191
|
'',
|
|
@@ -285,11 +317,12 @@ const OTHER_WORK_TOOLS = ['pwsh', 'terminal_open', 'terminal_send', 'terminal_re
|
|
|
285
317
|
* Tools a router dispatcher is denied by default: running commands (and the
|
|
286
318
|
* job tools that go with them; `pwsh` and the terminals too), writing and
|
|
287
319
|
* editing files (`apply_patch` and `str_replace_editor` too), sub-agents and
|
|
288
|
-
* workflows, image generation and Office tools.
|
|
289
|
-
*
|
|
320
|
+
* workflows, image generation and Office tools, and (0.9) the web: a search
|
|
321
|
+
* takes long enough to keep the person waiting, so it is a task too. It keeps
|
|
322
|
+
* `read`, `read_image`, `glob`, `grep` and `skill`.
|
|
290
323
|
*/
|
|
291
324
|
export const ROUTER_DENY = Object.freeze([
|
|
292
|
-
...new Set([...abilityTools('code'), 'write', 'edit', ...abilityTools('delegate'), ...abilityTools('images'), ...abilityTools('office'), ...OTHER_WORK_TOOLS]),
|
|
325
|
+
...new Set([...abilityTools('code'), 'write', 'edit', ...abilityTools('delegate'), ...abilityTools('images'), ...abilityTools('office'), ...abilityTools('web'), ...OTHER_WORK_TOOLS]),
|
|
293
326
|
]);
|
|
294
327
|
|
|
295
328
|
/** Longest `bash` / `pwsh` timeout a router may ask for, in ms. */
|
package/lib/store.mjs
CHANGED
|
@@ -276,12 +276,24 @@ export function createStore(dir) {
|
|
|
276
276
|
if (messages !== null && now === logSeen) return messages;
|
|
277
277
|
logSeen = now;
|
|
278
278
|
messages = [];
|
|
279
|
+
const index = new Map();
|
|
279
280
|
try {
|
|
280
281
|
for (const line of readFileSync(log, 'utf8').split('\n')) {
|
|
281
282
|
if (!line) continue;
|
|
282
283
|
try {
|
|
283
284
|
const m = JSON.parse(line);
|
|
284
|
-
if (m
|
|
285
|
+
if (!m || typeof m.id !== 'string') continue;
|
|
286
|
+
// A later line changing an earlier message (`patchMessage`): merged into it.
|
|
287
|
+
if (m.patch === true) {
|
|
288
|
+
const at = index.get(m.id);
|
|
289
|
+
if (at !== undefined) {
|
|
290
|
+
const { id: _id, patch: _patch, ...fields } = m;
|
|
291
|
+
Object.assign(messages[at], fields);
|
|
292
|
+
}
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
index.set(m.id, messages.length);
|
|
296
|
+
messages.push(m);
|
|
285
297
|
} catch {
|
|
286
298
|
// Skip a torn line.
|
|
287
299
|
}
|
|
@@ -406,11 +418,67 @@ export function createStore(dir) {
|
|
|
406
418
|
}
|
|
407
419
|
return m;
|
|
408
420
|
},
|
|
409
|
-
/**
|
|
410
|
-
|
|
421
|
+
/**
|
|
422
|
+
* Change fields of a logged message (`movedTo` when it was filed under another topic, …):
|
|
423
|
+
* an appended line, merged when the log is read. Returns the message as it is now, or null.
|
|
424
|
+
*/
|
|
425
|
+
patchMessage(id, fields = {}) {
|
|
411
426
|
const all = readLog();
|
|
412
|
-
const
|
|
413
|
-
|
|
427
|
+
const m = all.find((x) => x.id === id);
|
|
428
|
+
if (!m) return null;
|
|
429
|
+
const { id: _id, patch: _patch, ...rest } = fields;
|
|
430
|
+
Object.assign(m, rest);
|
|
431
|
+
try {
|
|
432
|
+
mkdirSync(dir, { recursive: true });
|
|
433
|
+
appendFileSync(log, JSON.stringify({ id, patch: true, ...rest }) + '\n', 'utf8');
|
|
434
|
+
logSeen = mtime(log);
|
|
435
|
+
} catch {
|
|
436
|
+
// The timeline is a convenience.
|
|
437
|
+
}
|
|
438
|
+
return { ...m };
|
|
439
|
+
},
|
|
440
|
+
/** One logged message by id, or undefined. */
|
|
441
|
+
message(id) {
|
|
442
|
+
const m = readLog().find((x) => x.id === id);
|
|
443
|
+
return m ? { ...m } : undefined;
|
|
444
|
+
},
|
|
445
|
+
/**
|
|
446
|
+
* Oldest first. `bot` limits to that bot's chat: messages that name it as their `chat`, and
|
|
447
|
+
* those with no `chat` sent from or to it. `topic` limits to one panel topic: its first
|
|
448
|
+
* message, the replies in it and the messages filed under it (`movedTo`). Without `topic`, a
|
|
449
|
+
* reply in the window whose topic began earlier brings that first message along, before the rest.
|
|
450
|
+
* `main` (Bots 0.10): only the main conversation, without what was said in discussions.
|
|
451
|
+
* `roots: false`: the window as it is, without bringing earlier first messages along.
|
|
452
|
+
*/
|
|
453
|
+
messages({ bot = '', limit = 200, topic = '', main = false, roots = true } = {}) {
|
|
454
|
+
const all = readLog();
|
|
455
|
+
// A message that was never handed over (`hidden`) is in no chat.
|
|
456
|
+
const mine = (m) => !m.hidden && (!bot || (m.chat ? m.chat === bot : m.from === bot || m.to === bot));
|
|
457
|
+
const cap = Math.max(1, Math.min(2000, Number(limit) || 200));
|
|
458
|
+
if (topic) return all.filter((m) => mine(m) && (m.id === topic || m.topic === topic || m.movedTo === topic)).slice(-cap);
|
|
459
|
+
// The main conversation (Bots 0.10): what is said in a discussion stays in it.
|
|
460
|
+
if (main) return all.filter((m) => mine(m) && !(m.topic && m.topic !== m.id) && !(m.movedTo && m.movedTo !== m.id)).slice(-cap);
|
|
461
|
+
const rows = all.filter(mine);
|
|
462
|
+
const window = rows.slice(-cap);
|
|
463
|
+
const have = new Set(window.map((m) => m.id));
|
|
464
|
+
const missing = new Set();
|
|
465
|
+
for (const m of window) for (const r of [m.topic, m.movedTo]) if (r && !have.has(r)) missing.add(r);
|
|
466
|
+
if (!roots || missing.size === 0) return window;
|
|
467
|
+
return [...rows.filter((m) => missing.has(m.id)), ...window];
|
|
468
|
+
},
|
|
469
|
+
/** The replies in the discussions under `roots` (ids) in `bot`'s chat, oldest first, per root. */
|
|
470
|
+
replies(bot, roots) {
|
|
471
|
+
const want = new Set([...(roots ?? [])].filter(Boolean));
|
|
472
|
+
const out = new Map();
|
|
473
|
+
if (want.size === 0) return out;
|
|
474
|
+
for (const m of readLog()) {
|
|
475
|
+
if (m.hidden || (bot && !(m.chat ? m.chat === bot : m.from === bot || m.to === bot))) continue;
|
|
476
|
+
const root = m.topic && m.topic !== m.id ? m.topic : m.movedTo && m.movedTo !== m.id ? m.movedTo : '';
|
|
477
|
+
if (!root || !want.has(root)) continue;
|
|
478
|
+
if (!out.has(root)) out.set(root, []);
|
|
479
|
+
out.get(root).push(m);
|
|
480
|
+
}
|
|
481
|
+
return out;
|
|
414
482
|
},
|
|
415
483
|
messageCount() {
|
|
416
484
|
return readLog().length;
|
package/lib/threads.mjs
CHANGED
|
@@ -6,8 +6,11 @@
|
|
|
6
6
|
* conversation in the panel. Its key is `kind:appKey:chatId[:rootId]`
|
|
7
7
|
* (`appKey` is the channel's record key in channels.mjs, `botId/appId`); a
|
|
8
8
|
* message with no thread id of its own belongs to the whole-chat thread
|
|
9
|
-
* `kind:appKey:chatId`. A panel conversation is `panel:<sessionId
|
|
10
|
-
*
|
|
9
|
+
* `kind:appKey:chatId`. A panel conversation is `panel:<sessionId>`, and a
|
|
10
|
+
* topic in it (a message in the panel and the replies under it, Bots 0.9) is
|
|
11
|
+
* `panel:<sessionId>:<rootId>`, `rootId` being the id of that first message.
|
|
12
|
+
* Inside a part, `%` and `:` are written `%25` and `%3A`, so any id survives
|
|
13
|
+
* the trip.
|
|
11
14
|
*
|
|
12
15
|
* This module decides, with no I/O:
|
|
13
16
|
*
|
|
@@ -17,10 +20,10 @@
|
|
|
17
20
|
* woken); otherwise the Router (the channel owner's home) does;
|
|
18
21
|
* - where a conversation's plain replies go (`createOrigins`): each turn
|
|
19
22
|
* collects the threads its inputs came from (user messages, and the origin
|
|
20
|
-
* threads of the tickets whose reports arrived). One chat thread
|
|
21
|
-
*
|
|
22
|
-
* panel
|
|
23
|
-
* `bot_reply` (`resolve`).
|
|
23
|
+
* threads of the tickets whose reports arrived). One thread (a chat thread or
|
|
24
|
+
* a panel topic): replies go there. Only the panel as a whole, or nothing:
|
|
25
|
+
* the panel. More than one, including the panel plus one chat: the panel
|
|
26
|
+
* only, and the bot names a target with `bot_reply` (`resolve`).
|
|
24
27
|
*
|
|
25
28
|
* @module @kadaliao/dsh-bots/lib/threads
|
|
26
29
|
*/
|
|
@@ -52,7 +55,7 @@ const unesc = (s) => s.replace(/%(25|3A)/gi, (_, c) => (c === '25' ? '%' : ':'))
|
|
|
52
55
|
*/
|
|
53
56
|
export function threadKey(kind, appKey, msg = {}) {
|
|
54
57
|
const k = part(kind);
|
|
55
|
-
if (k === PANEL) return panelThreadKey(msg?.sessionId ?? msg?.chatId);
|
|
58
|
+
if (k === PANEL) return panelThreadKey(msg?.sessionId ?? msg?.chatId, msg?.rootId ?? msg?.threadId);
|
|
56
59
|
if (!KIND_RE.test(k)) return null;
|
|
57
60
|
const app = part(appKey);
|
|
58
61
|
const chat = part(msg?.chatId);
|
|
@@ -61,15 +64,20 @@ export function threadKey(kind, appKey, msg = {}) {
|
|
|
61
64
|
return [k, esc(app), esc(chat), ...(root ? [esc(root)] : [])].join(':');
|
|
62
65
|
}
|
|
63
66
|
|
|
64
|
-
/**
|
|
65
|
-
|
|
67
|
+
/**
|
|
68
|
+
* The thread of a home conversation in the panel (replies to it stay in the
|
|
69
|
+
* panel), or with `rootId` one topic in it: a message and the replies under it.
|
|
70
|
+
*/
|
|
71
|
+
export function panelThreadKey(sessionId, rootId) {
|
|
66
72
|
const s = part(sessionId);
|
|
67
|
-
|
|
73
|
+
if (!s) return null;
|
|
74
|
+
const r = part(rootId);
|
|
75
|
+
return r ? `${PANEL}:${esc(s)}:${esc(r)}` : `${PANEL}:${esc(s)}`;
|
|
68
76
|
}
|
|
69
77
|
|
|
70
78
|
/**
|
|
71
79
|
* A thread key taken apart.
|
|
72
|
-
* @returns {{kind: string, appKey: string, chatId: string, rootId?: string} | {kind: 'panel', sessionId: string} | null}
|
|
80
|
+
* @returns {{kind: string, appKey: string, chatId: string, rootId?: string} | {kind: 'panel', sessionId: string, rootId?: string} | null}
|
|
73
81
|
*/
|
|
74
82
|
export function parseThreadKey(key) {
|
|
75
83
|
if (typeof key !== 'string' || key === '') return null;
|
|
@@ -77,8 +85,8 @@ export function parseThreadKey(key) {
|
|
|
77
85
|
const kind = parts[0];
|
|
78
86
|
if (!KIND_RE.test(kind)) return null;
|
|
79
87
|
if (kind === PANEL) {
|
|
80
|
-
if (parts.length
|
|
81
|
-
return { kind: PANEL, sessionId: unesc(parts[1]) };
|
|
88
|
+
if (parts.length < 2 || parts.length > 3 || parts.slice(1).some((p) => p === '')) return null;
|
|
89
|
+
return { kind: PANEL, sessionId: unesc(parts[1]), ...(parts.length === 3 ? { rootId: unesc(parts[2]) } : {}) };
|
|
82
90
|
}
|
|
83
91
|
if (parts.length < 3 || parts.length > 4 || parts.slice(1).some((p) => p === '')) return null;
|
|
84
92
|
const [, app, chat, root] = parts;
|
|
@@ -94,11 +102,11 @@ export function parseThreadKey(key) {
|
|
|
94
102
|
export function toThreadKey(ref) {
|
|
95
103
|
if (typeof ref === 'string') {
|
|
96
104
|
const p = parseThreadKey(ref);
|
|
97
|
-
return p ? (p.kind === PANEL ? panelThreadKey(p.sessionId) : threadKey(p.kind, p.appKey, p)) : null;
|
|
105
|
+
return p ? (p.kind === PANEL ? panelThreadKey(p.sessionId, p.rootId) : threadKey(p.kind, p.appKey, p)) : null;
|
|
98
106
|
}
|
|
99
107
|
if (!ref || typeof ref !== 'object') return null;
|
|
100
108
|
if (typeof ref.threadKey === 'string') return toThreadKey(ref.threadKey);
|
|
101
|
-
if (ref.kind === PANEL) return panelThreadKey(ref.sessionId ?? ref.chatId);
|
|
109
|
+
if (ref.kind === PANEL) return panelThreadKey(ref.sessionId ?? ref.chatId, ref.rootId);
|
|
102
110
|
if (ref.appKey == null && typeof ref.key === 'string' && parseThreadKey(ref.key)) return toThreadKey(ref.key);
|
|
103
111
|
return threadKey(ref.kind, ref.appKey ?? ref.key, ref);
|
|
104
112
|
}
|
|
@@ -109,12 +117,24 @@ export function sameThread(a, b) {
|
|
|
109
117
|
return ka !== null && ka === toThreadKey(b);
|
|
110
118
|
}
|
|
111
119
|
|
|
112
|
-
/** Whether a reference names a panel conversation. */
|
|
120
|
+
/** Whether a reference names a panel conversation (a whole one, or a topic in it). */
|
|
113
121
|
export function isPanelThread(ref) {
|
|
114
122
|
const k = toThreadKey(ref);
|
|
115
123
|
return k !== null && k.startsWith(`${PANEL}:`);
|
|
116
124
|
}
|
|
117
125
|
|
|
126
|
+
/** The root message id of a panel topic a reference names, or '' (a chat thread, the panel as a whole). */
|
|
127
|
+
export function panelTopicOf(ref) {
|
|
128
|
+
const p = parseThreadKey(toThreadKey(ref) ?? '');
|
|
129
|
+
return p?.kind === PANEL ? (p.rootId ?? '') : '';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Whether a reference is a thread replies can be aimed at: a chat thread, or a topic in the panel (not the panel as a whole). */
|
|
133
|
+
export const isTopicThread = (ref) => {
|
|
134
|
+
const k = toThreadKey(ref);
|
|
135
|
+
return k !== null && (!k.startsWith(`${PANEL}:`) || panelTopicOf(k) !== '');
|
|
136
|
+
};
|
|
137
|
+
|
|
118
138
|
const cleanName = (s, max = 60) =>
|
|
119
139
|
String(s ?? '')
|
|
120
140
|
.replace(/[[\]\r\n]+/g, ' ')
|
|
@@ -136,7 +156,8 @@ export function threadLabel(meta) {
|
|
|
136
156
|
const parts = [cleanName(m.source) || KIND_LABELS[kind] || cleanName(kind) || 'Chat'];
|
|
137
157
|
const chat = cleanName(m.chatTitle) || (kind === PANEL ? '' : cleanName(m.who) || cleanName(m.chatId));
|
|
138
158
|
if (chat) parts.push(chat);
|
|
139
|
-
if (kind
|
|
159
|
+
if (kind === PANEL && part(m.rootId)) parts.push(cleanName(m.threadTitle) ? `thread "${cleanName(m.threadTitle, 40)}"` : `thread ${part(m.rootId)}`);
|
|
160
|
+
else if (kind !== PANEL && part(m.rootId)) parts.push(cleanName(m.threadTitle) || (kind === 'telegram' ? 'topic' : 'thread'));
|
|
140
161
|
return parts.join(' · ');
|
|
141
162
|
}
|
|
142
163
|
|
|
@@ -253,7 +274,7 @@ function originOf(key, given) {
|
|
|
253
274
|
const { rootId: _root, key: _key, appKey: _app, chatId: _chat, ...extra } = rest;
|
|
254
275
|
if (p.kind === PANEL) {
|
|
255
276
|
const { replyTo: _replyTo, ...panelExtra } = extra;
|
|
256
|
-
return { ...panelExtra, threadKey: key, kind: PANEL, sessionId: p.sessionId };
|
|
277
|
+
return { ...panelExtra, threadKey: key, kind: PANEL, sessionId: p.sessionId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
|
|
257
278
|
}
|
|
258
279
|
return { ...extra, threadKey: key, kind: p.kind, key: p.appKey, appKey: p.appKey, chatId: p.chatId, ...(p.rootId !== undefined ? { rootId: p.rootId } : {}) };
|
|
259
280
|
}
|
|
@@ -280,8 +301,9 @@ function refOf(ref) {
|
|
|
280
301
|
* Per conversation, the threads this turn's inputs came from (plan §4.3).
|
|
281
302
|
*
|
|
282
303
|
* Rules for plain replies (`replyPlan`, `replyTarget`):
|
|
283
|
-
* - no input, or only panel
|
|
284
|
-
* - exactly one chat thread
|
|
304
|
+
* - no input, or only inputs from the panel as a whole: `panel` (the text stays in the panel);
|
|
305
|
+
* - exactly one thread (a chat thread, or a topic in the panel) and nothing
|
|
306
|
+
* else: `thread`, the text goes there (0.7's behaviour for a chat);
|
|
285
307
|
* - anything more, including the panel plus one chat: `choose` (the text stays
|
|
286
308
|
* in the panel; `bot_reply` names where it goes).
|
|
287
309
|
*
|
|
@@ -291,12 +313,24 @@ function refOf(ref) {
|
|
|
291
313
|
* by entry: losing one of two threads would turn "choose" into a wrong target.
|
|
292
314
|
*
|
|
293
315
|
* @param {{now?: () => number, ttlMs?: number, running?: (sessionId: string) => boolean,
|
|
294
|
-
* lookup?: (ref: {thread: string} | {ticket: string}) => object|string|null
|
|
316
|
+
* lookup?: (ref: {thread: string} | {ticket: string}) => object|string|null,
|
|
317
|
+
* homeKey?: (sessionId: string) => string|null|undefined}} [opts]
|
|
295
318
|
* `lookup`: for `resolve`, a known thread or a ticket's origin thread outside this turn
|
|
296
|
-
* (a key, an origin or a Thread record); without it `resolve` only knows this turn's threads
|
|
319
|
+
* (a key, an origin or a Thread record); without it `resolve` only knows this turn's threads.
|
|
320
|
+
* `homeKey`: the Thread an input without one belongs to (default the panel conversation
|
|
321
|
+
* `panel:<sessionId>`; a discussion's Session answers in its own Thread)
|
|
297
322
|
*/
|
|
298
323
|
export function createOrigins(opts = {}) {
|
|
299
324
|
const now = opts.now ?? Date.now;
|
|
325
|
+
// Where a Session's input with no Thread of its own belongs: the panel conversation, or for a
|
|
326
|
+
// discussion (Bots 0.10) the Thread it answers in.
|
|
327
|
+
const homeKey = (sid) => {
|
|
328
|
+
try {
|
|
329
|
+
return toThreadKey(opts.homeKey?.(sid)) ?? panelThreadKey(sid);
|
|
330
|
+
} catch {
|
|
331
|
+
return panelThreadKey(sid);
|
|
332
|
+
}
|
|
333
|
+
};
|
|
300
334
|
const ttlMs = opts.ttlMs ?? ORIGIN_TTL_MS;
|
|
301
335
|
/** sessionId → {at, items: Map<threadKey, origin>} */
|
|
302
336
|
const sessions = new Map();
|
|
@@ -322,9 +356,9 @@ export function createOrigins(opts = {}) {
|
|
|
322
356
|
|
|
323
357
|
function replyPlan(sessionId) {
|
|
324
358
|
const origins = list(sessionId);
|
|
325
|
-
const
|
|
326
|
-
const mode =
|
|
327
|
-
return { mode, target: mode === 'thread' ? copyOrigin(
|
|
359
|
+
const threads = origins.filter((o) => o.kind !== PANEL || o.rootId !== undefined);
|
|
360
|
+
const mode = threads.length === 0 ? 'panel' : threads.length === 1 && origins.length === 1 ? 'thread' : 'choose';
|
|
361
|
+
return { mode, target: mode === 'thread' ? copyOrigin(threads[0]) : null, origins: origins.map(copyOrigin) };
|
|
328
362
|
}
|
|
329
363
|
|
|
330
364
|
return {
|
|
@@ -344,7 +378,7 @@ export function createOrigins(opts = {}) {
|
|
|
344
378
|
const sid = part(sessionId);
|
|
345
379
|
if (!sid) return null;
|
|
346
380
|
for (const other of [...sessions.keys()]) setOf(other);
|
|
347
|
-
const key = toThreadKey(input.threadKey) ?? toThreadKey(input.origin) ??
|
|
381
|
+
const key = toThreadKey(input.threadKey) ?? toThreadKey(input.origin) ?? homeKey(sid);
|
|
348
382
|
const s = sessions.get(sid) ?? { at: now(), items: new Map() };
|
|
349
383
|
const prev = s.items.get(key);
|
|
350
384
|
const next = originOf(key, { ...(prev ?? {}), ...(input.origin ?? {}) });
|
|
@@ -397,6 +431,37 @@ export function createOrigins(opts = {}) {
|
|
|
397
431
|
return origin;
|
|
398
432
|
},
|
|
399
433
|
|
|
434
|
+
/**
|
|
435
|
+
* One of this turn's threads turned out to belong to another (a panel topic
|
|
436
|
+
* whose message was filed under an existing task's topic): it is replaced by
|
|
437
|
+
* `to` in its place, so plain replies go there. A `to` already in the turn
|
|
438
|
+
* keeps its place and the other is dropped. Returns the stored origin, or
|
|
439
|
+
* null when `from` is not one of this turn's threads.
|
|
440
|
+
* @param {string} sessionId
|
|
441
|
+
* @param {string} from - a thread key of this turn
|
|
442
|
+
* @param {string} to - the thread key replies go to instead
|
|
443
|
+
* @param {object} [origin] - details of `to` (as `noteInput` takes them)
|
|
444
|
+
*/
|
|
445
|
+
retarget(sessionId, from, to, origin = {}) {
|
|
446
|
+
const s = setOf(part(sessionId));
|
|
447
|
+
const fromKey = toThreadKey(from);
|
|
448
|
+
const toKey = toThreadKey(to);
|
|
449
|
+
if (!s || !fromKey || !toKey || !s.items.has(fromKey)) return null;
|
|
450
|
+
if (fromKey === toKey) return copyOrigin(s.items.get(fromKey));
|
|
451
|
+
const prev = s.items.get(fromKey);
|
|
452
|
+
const next = originOf(toKey, { ...(s.items.get(toKey) ?? {}), ...origin });
|
|
453
|
+
const tickets = [...new Set([...(s.items.get(toKey)?.tickets ?? []), ...(prev.tickets ?? [])])];
|
|
454
|
+
if (tickets.length) next.tickets = tickets;
|
|
455
|
+
const items = new Map();
|
|
456
|
+
for (const [k, v] of s.items) {
|
|
457
|
+
if (k === fromKey) {
|
|
458
|
+
if (!s.items.has(toKey)) items.set(toKey, next);
|
|
459
|
+
} else items.set(k, k === toKey ? next : v);
|
|
460
|
+
}
|
|
461
|
+
s.items = items;
|
|
462
|
+
return copyOrigin(next);
|
|
463
|
+
},
|
|
464
|
+
|
|
400
465
|
/** The turn ended: its threads are forgotten. Returns them. */
|
|
401
466
|
endTurn(sessionId) {
|
|
402
467
|
const out = list(part(sessionId)).map(copyOrigin);
|
package/lib/tickets.mjs
CHANGED
|
@@ -177,7 +177,8 @@ export function createSlots(max = DEFAULT_MAX_WORKING) {
|
|
|
177
177
|
/** Kind, app, chat and root from a Thread key (`kind:appKey:chatId[:rootId]`, `panel:<sessionId>`). */
|
|
178
178
|
function partsOfKey(key) {
|
|
179
179
|
const [kind = '', ...rest] = key.split(':');
|
|
180
|
-
|
|
180
|
+
// A panel conversation, or a topic in it (`panel:<sessionId>:<rootId>`).
|
|
181
|
+
if (kind === 'panel') return { kind, appKey: '', chatId: rest[0] ?? '', ...(rest.length > 1 && rest.slice(1).join(':') !== '' ? { rootId: rest.slice(1).join(':') } : {}) };
|
|
181
182
|
const [appKey = '', chatId = '', ...root] = rest;
|
|
182
183
|
return { kind, appKey, chatId, ...(root.length > 0 && root.join(':') !== '' ? { rootId: root.join(':') } : {}) };
|
|
183
184
|
}
|
|
@@ -408,9 +409,11 @@ export function createTickets(dir, { now = Date.now } = {}) {
|
|
|
408
409
|
* `parentId` defaults to the requesting ticket (`requester.ticketId`); the
|
|
409
410
|
* origin Thread is subscribed, as is each of `threads` (keys, or Thread
|
|
410
411
|
* metadata with a `key`).
|
|
411
|
-
*
|
|
412
|
+
* `relay`: its requester asked for the reports (`report_to: "me"`), so they go to it rather
|
|
413
|
+
* than to the person in the origin Thread (Bots 0.9).
|
|
414
|
+
* @param {{title?: string, text: string, botId: string, requester?: object, parentId?: string, origin?: {threadKey?: string, via?: string, who?: string}, threads?: Array<string|{key: string}>, relay?: boolean}} input
|
|
412
415
|
*/
|
|
413
|
-
create({ title, text, botId, requester, parentId, origin, threads = [] } = {}) {
|
|
416
|
+
create({ title, text, botId, requester, parentId, origin, threads = [], relay = false } = {}) {
|
|
414
417
|
load();
|
|
415
418
|
if (typeof botId !== 'string' || botId === '') throw new Error('a ticket needs the bot that does the work');
|
|
416
419
|
const body = str(text);
|
|
@@ -432,6 +435,7 @@ export function createTickets(dir, { now = Date.now } = {}) {
|
|
|
432
435
|
origin: normalizeOrigin(origin),
|
|
433
436
|
threads: [],
|
|
434
437
|
reports: [],
|
|
438
|
+
...(relay ? { relay: true } : {}),
|
|
435
439
|
createdAt: at,
|
|
436
440
|
updatedAt: at,
|
|
437
441
|
retries: 0,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kadaliao/dsh-bots",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Grok-style bots for DeepSeek Harness: create bots with their own avatar, persona, model, skills, apps, scheduled tasks and memory; they message each other, a dispatcher bot hands out the work, and a usage view counts tokens by bot, task and day.",
|
|
6
6
|
"exports": {
|