@kadaliao/dsh-bots 0.7.1 → 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/lib/memory.mjs CHANGED
@@ -251,6 +251,43 @@ export function reflectionPrompt({ bot, notes, team, transcript, trigger }) {
251
251
  };
252
252
  }
253
253
 
254
+ /**
255
+ * Tickets (tasks) whose title or one of whose reports contains every word of
256
+ * `query` (case-insensitive, as `search` matches notes), most recently changed
257
+ * first. A title hit wins over a report hit; a report hit carries the newest
258
+ * matching report's status and a short snippet around the first word.
259
+ * @param {string} query
260
+ * @param {object[]} tickets - tickets in the shape of docs/PLAN-0.8.md §10
261
+ * @param {{limit?: number}} [opts]
262
+ * @returns {Array<{ticket: object, where: 'title'|'report', status?: string, snippet?: string}>}
263
+ */
264
+ export function searchTickets(query, tickets, { limit = 10 } = {}) {
265
+ const words = String(query ?? '').toLowerCase().split(/\s+/).filter(Boolean);
266
+ if (words.length === 0) return [];
267
+ const hit = (text) => {
268
+ const s = String(text ?? '').toLowerCase();
269
+ return words.every((w) => s.includes(w));
270
+ };
271
+ const snippet = (text) => {
272
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
273
+ const at = Math.max(0, s.toLowerCase().indexOf(words[0]) - 60);
274
+ const cut = s.slice(at, at + 200);
275
+ return `${at > 0 ? '…' : ''}${cut}${at + 200 < s.length ? '…' : ''}`;
276
+ };
277
+ const out = [];
278
+ for (const t of [...(tickets ?? [])].sort((a, b) => (Number(b?.updatedAt) || 0) - (Number(a?.updatedAt) || 0))) {
279
+ if (!t?.id) continue;
280
+ if (hit(t.title)) {
281
+ out.push({ ticket: t, where: 'title' });
282
+ } else {
283
+ const report = [...(Array.isArray(t.reports) ? t.reports : [])].reverse().find((r) => hit(r?.text));
284
+ if (report) out.push({ ticket: t, where: 'report', status: report.status, snippet: snippet(report.text) });
285
+ }
286
+ if (out.length >= limit) break;
287
+ }
288
+ return out;
289
+ }
290
+
254
291
  /** Once a day per bot: tidy the notes with the last days of its journal. */
255
292
  export function dreamBotPrompt({ bot, notes, journal, tz = 0 }) {
256
293
  return {
package/lib/prompt.mjs CHANGED
@@ -1,24 +1,112 @@
1
1
  /**
2
- * What a bot's model reads: its persona section, the DM framing, and the
3
- * timing builder its schedule tool uses. Pure functions, no Harness.
2
+ * What a bot's model reads: its persona section (hands-on dispatcher, router
3
+ * dispatcher, or worker in a ticket session), the DM framing, the timing
4
+ * builder its schedule tool uses, and the router's tool limits. Pure
5
+ * functions, no Harness.
4
6
  *
5
7
  * @module @kadaliao/dsh-bots/lib/prompt
6
8
  */
7
9
 
10
+ import { ABILITIES } from './abilities.mjs';
11
+
8
12
  /** One roster line: `@handle — Name (dispatcher): bio`. */
9
13
  export function rosterLine(bot, selfId) {
10
14
  const tags = [bot.role === 'primary' ? 'dispatcher' : '', bot.id === selfId ? 'you' : ''].filter(Boolean);
11
15
  return `- @${bot.handle} — ${bot.name}${tags.length ? ` (${tags.join(', ')})` : ''}${bot.bio ? `: ${bot.bio}` : ''}`;
12
16
  }
13
17
 
18
+ const LANGUAGE_LINE = '- Write to the user in the language they use (Chinese or English). Between bots, use the language of the task you were given.';
19
+ const MANAGE_LINE = '- `bot_list` shows the team with each bot\'s skills and apps; `bot_create`, `bot_update` and `bot_delete` manage bots when the user asks for it or a new specialist is clearly needed.';
20
+ const SCHEDULE_NOTICE_LINE = '- Ignore "[SCHEDULE CHANGE]" notices: they need no reply.';
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
+
23
+ /** "Working with other bots" as a hands-on bot reads it (0.7 text). */
24
+ const HANDS_ON_TEAM = [
25
+ '- 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.',
26
+ '- A message that starts with "Bot message from @…" was sent by that bot, not by the user. Answer it with `bot_send_message` when it asks for something; do not answer pure acknowledgements or thanks, so conversations end.',
27
+ '- Keep messages self-contained: the other bot cannot see your conversation.',
28
+ '- When you are working on a bot message, your answer goes back through `bot_send_message`; after sending it, end your turn without a summary — nobody reads it.',
29
+ SCHEDULE_NOTICE_LINE,
30
+ LANGUAGE_LINE,
31
+ MANAGE_LINE,
32
+ ];
33
+
34
+ /** "Working with other bots" as a router dispatcher reads it (`self`: its own @handle). */
35
+ const routerTeam = (self) => [
36
+ `- Hand work to a bot with \`bot_send_message\` (to: its @handle, or your own, @${self}, when no teammate fits: you then do it yourself in a task conversation of your own, with all your tools). 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\`.`,
37
+ '- Keep messages self-contained: the bot (you too, in a task) cannot see this conversation.',
38
+ SCHEDULE_NOTICE_LINE,
39
+ LANGUAGE_LINE,
40
+ MANAGE_LINE,
41
+ ];
42
+
43
+ /** "Working with other bots" as a bot's own home reads it when delegating opens tasks (router mode), the dispatcher aside. */
44
+ 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. Never wait or poll for its answer. To add to a task you opened, pass `ticket` (its id) instead of `to`.',
46
+ '- When the request came from the person (a topic in the panel, or a chat), 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.',
47
+ '- 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).',
48
+ '- Keep messages self-contained: the other bot cannot see your conversation.',
49
+ SCHEDULE_NOTICE_LINE,
50
+ LANGUAGE_LINE,
51
+ MANAGE_LINE,
52
+ ];
53
+
54
+ /** "Working with other bots" as a worker in a ticket session reads it. */
55
+ const TICKET_TEAM = [
56
+ '- Ask another bot for help with `bot_send_message` (to: its @handle). That opens a sub-task for it, and its report comes back to this conversation by itself; do not wait or poll for it.',
57
+ '- Keep messages self-contained: the other bot cannot see your conversation.',
58
+ '- A message that starts with "Bot message from @…" or "Report from @…" was sent by that bot, not by the user.',
59
+ SCHEDULE_NOTICE_LINE,
60
+ LANGUAGE_LINE,
61
+ MANAGE_LINE,
62
+ ];
63
+
64
+ /** Who asked for a ticket, as a worker reads it: `@atlas`, `task t… (@coder)`, `the user`. */
65
+ function requesterPhrase(ticket, roster) {
66
+ const r = ticket.requester ?? {};
67
+ const bot = r.botId ? roster.find((b) => b.id === r.botId) : undefined;
68
+ const handle = bot ? `@${bot.handle}` : '';
69
+ const parent = ticket.parentId ?? r.ticketId;
70
+ if (parent) return `task ${parent}${handle ? ` (${handle})` : ''}`;
71
+ if (r.kind === 'user' || !handle) return 'the user';
72
+ return handle;
73
+ }
74
+
75
+ /**
76
+ * Whether a ticket's `done`, `question` and `blocked` reports are posted as they are in the topic
77
+ * or chat its request came from (Bots 0.9), rather than handed to whoever asked to pass on: it has
78
+ * a Thread, it is no sub-task, and its requester did not ask for the reports (`relay`).
79
+ */
80
+ export function reportsGoDirect(ticket) {
81
+ const t = ticket ?? {};
82
+ return !t.relay && Boolean(t.origin?.threadKey) && !t.parentId && !t.requester?.ticketId;
83
+ }
84
+
85
+ /** Where a ticket's direct reports are shown, as its worker reads it. */
86
+ const shownWhere = (ticket) => (String(ticket.origin?.threadKey ?? '').startsWith('panel:') ? 'in the panel, in the topic the request came from' : `in the chat${ticket.origin?.via ? ` (${ticket.origin.via})` : ''} the request came from`);
87
+
88
+ /** `, for Kada on Slack` from a ticket's origin, or ''. */
89
+ function originPhrase(ticket) {
90
+ const { who, via } = ticket.origin ?? {};
91
+ if (!who && !via) return '';
92
+ return `, for ${who || 'someone'}${via ? ` on ${via}` : ''}`;
93
+ }
94
+
14
95
  /**
15
96
  * The persona section of one bot. It replaces the deployment persona for that
16
97
  * bot's conversation only.
17
98
  * @param {object} bot
18
99
  * @param {object[]} roster - every bot, the bot itself included.
19
- * @param {{skillsInline?: boolean, apps?: string[], skillNames?: object, channels?: string[]}} [extra] - `channels`: chat apps the team is reachable from ('Telegram').
100
+ * @param {{skillsInline?: boolean, apps?: string[], skillNames?: object, channels?: string[], dispatcher?: 'router'|'hands-on', tickets?: boolean, ticket?: object}} [extra]
101
+ * `channels`: chat apps the team is reachable from ('Telegram').
102
+ * `dispatcher`: how the dispatcher (role 'primary') works in its home conversation; 'hands-on' (default) is the 0.7 text, 'router' only understands, hands out and reports. Ignored for other bots.
103
+ * `tickets`: delegating from a home opens a task whose answer arrives as a report (router mode); a non-dispatcher bot's home then says so. Without it (hands-on) the 0.7 text stands.
104
+ * `ticket`: the ticket (see PLAN-0.8 §10) when this conversation is that ticket's session; the text then frames the conversation as one task, whatever the bot's role.
20
105
  */
21
106
  export function personaText(bot, roster, extra = {}) {
107
+ const ticket = extra.ticket ?? null;
108
+ const router = !ticket && bot.role === 'primary' && extra.dispatcher === 'router';
109
+ const homeTickets = !ticket && !router && bot.role !== 'primary' && extra.tickets === true;
22
110
  const lines = [];
23
111
  lines.push(`You are ${bot.name} (@${bot.handle}), one of the user's bots in DeepSeek Harness.`);
24
112
  if (bot.persona.trim()) lines.push('', '## Your persona', bot.persona.trim());
@@ -26,26 +114,49 @@ export function personaText(bot, roster, extra = {}) {
26
114
  lines.push('', '## The bot team');
27
115
  lines.push(roster.length > 1 ? 'These bots work for the same user and can message each other:' : 'You are the only bot so far.');
28
116
  if (roster.length > 1) for (const b of roster) lines.push(rosterLine(b, bot.id));
29
- lines.push(
30
- '',
31
- '## Working with other bots',
32
- '- 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.',
33
- '- A message that starts with "Bot message from @…" was sent by that bot, not by the user. Answer it with `bot_send_message` when it asks for something; do not answer pure acknowledgements or thanks, so conversations end.',
34
- '- Keep messages self-contained: the other bot cannot see your conversation.',
35
- '- When you are working on a bot message, your answer goes back through `bot_send_message`; after sending it, end your turn without a summary — nobody reads it.',
36
- '- Ignore "[SCHEDULE CHANGE]" notices: they need no reply.',
37
- '- Write to the user in the language they use (Chinese or English). Between bots, use the language of the task you were given.',
38
- '- `bot_list` shows the team with each bot\'s skills and apps; `bot_create`, `bot_update` and `bot_delete` manage bots when the user asks for it or a new specialist is clearly needed.',
39
- );
40
- if (bot.role === 'primary') {
117
+ lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ? routerTeam(bot.handle) : homeTickets ? HOME_TICKETS_TEAM : HANDS_ON_TEAM));
118
+ if (ticket) {
119
+ const direct = reportsGoDirect(ticket);
120
+ lines.push(
121
+ '',
122
+ '## This conversation is one task',
123
+ `It is task ${ticket.id}: "${String(ticket.title ?? '').trim()}", asked by ${requesterPhrase(ticket, roster)}${originPhrase(ticket)}. Its first message says what to do.`,
124
+ '- 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.',
125
+ ...(direct
126
+ ? [
127
+ `- 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.`,
128
+ '- 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.',
129
+ ]
130
+ : ['- 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.']),
131
+ '- Asking another bot opens a sub-task; its report comes back here by itself.',
132
+ '- Messages from the person about this task may arrive here directly. Take them into account and answer them in a report.',
133
+ `- \`bot_recall\` reads this task (\`ticket/${ticket.id}\`), its parent and sub-tasks, and the threads it belongs to.`,
134
+ );
135
+ } else if (router) {
136
+ lines.push(
137
+ '',
138
+ '## You are the dispatcher',
139
+ '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, so you never do the work in this conversation, not even a quick lookup: searching the web, reading or changing files and running anything is a task (yours, when no teammate fits). When no bot fits a recurring kind of work, propose creating one.',
140
+ '- Every message is its own request, with its topic or chat in its header ("[Panel] (thread p…)", "[Telegram · Kada] (thread …)"), unless it clearly continues one of the open tasks listed with it. When several messages arrive together, handle every one of them: never drop a request because another came after it.',
141
+ '- For each request do one of these, then end your turn: answer it yourself when you can from what you already know (a greeting, a quick fact, a question about the team or its tasks); hand it out with `bot_send_message` and say in one line who is on it; or, when it continues an open task, add it to that task with `bot_send_message` (ticket: its id), which files the message under that task\'s topic.',
142
+ '- 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.',
143
+ '- The bot doing a task answers the person itself, in the topic or chat the request came from, and the person\'s replies there 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.',
144
+ '- 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.',
145
+ '- When a turn involves more than one topic or chat, answer each with `bot_reply` (thread: the id its header shows, or ticket: a task id) so every answer stays in its own topic; plain text then reaches none of them.',
146
+ '- Use `bot_recall` to look up tasks and threads (`tickets`, `ticket/<id>`, `thread/<key>`, `bot/<handle>`) instead of guessing.',
147
+ '- Keep your own replies short: 100 words at most, no tables.',
148
+ SCHEDULE_LINE,
149
+ );
150
+ } else if (bot.role === 'primary') {
41
151
  lines.push(
42
152
  '',
43
153
  '## You are the dispatcher',
44
154
  'The user treats you as the main bot. For a task that fits another bot\'s role, delegate it with `bot_send_message`, possibly to several bots in parallel, then combine their answers for the user. Do small or general tasks yourself. When no bot fits a recurring kind of work, propose creating one.',
45
155
  'While teammates are still answering, stay quiet: when a reply arrives and others are still outstanding, end your turn without writing to the user. Report once, when everything you asked for is in (or when something is blocked).',
46
- '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.',
156
+ SCHEDULE_LINE,
47
157
  );
48
- } else if (others.some((b) => b.role === 'primary')) {
158
+ }
159
+ if (bot.role !== 'primary' && others.some((b) => b.role === 'primary')) {
49
160
  const p = others.find((b) => b.role === 'primary');
50
161
  lines.push('', `@${p.handle} is the dispatcher. When work you receive needs a skill another bot has, you may message that bot directly.`);
51
162
  }
@@ -63,10 +174,15 @@ export function personaText(bot, roster, extra = {}) {
63
174
  if (extra.apps?.length) lines.push('', '## Your apps', `Tools from these connected apps are yours: ${extra.apps.join(', ')} (named \`mcp__<app>__<tool>\`).`);
64
175
  if (extra.channels?.length) {
65
176
  const first = extra.channels[0];
177
+ const how = ticket
178
+ ? reportsGoDirect(ticket)
179
+ ? 'It is a follow-up about this task. Your plain text does not reach that chat: answer in a report, which is posted there.'
180
+ : '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.'
181
+ : '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.';
66
182
  lines.push(
67
183
  '',
68
184
  '## Chat apps',
69
- `The user can also reach the team from ${extra.channels.join(' and ')}. A message that starts with "[${first} · Name]" was sent from that chat app by someone the user paired (usually the user). 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.`,
185
+ `The user can also reach the team from ${extra.channels.join(' and ')}. A message that starts with "[${first} · Name]" was sent from that chat app by someone the user paired (usually the user). ${how}`,
70
186
  );
71
187
  }
72
188
  return lines.join('\n');
@@ -176,7 +292,92 @@ export function textOf(content) {
176
292
  if (typeof content === 'string') return content;
177
293
  return (Array.isArray(content) ? content : [])
178
294
  .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
179
- .map((b) => b.text)
180
- .join('\n')
295
+ .map((b, i, all) => (i < all.length - 1 && !b.text.endsWith('\n') ? `${b.text}\n` : b.text))
296
+ .join('')
181
297
  .trim();
182
298
  }
299
+
300
+ const abilityTools = (id) => ABILITIES.find((a) => a.id === id)?.tools ?? [];
301
+
302
+ /**
303
+ * Harness tools that run commands or change files outside the abilities'
304
+ * lists: PowerShell, the persistent terminals, and the other file editors.
305
+ */
306
+ const OTHER_WORK_TOOLS = ['pwsh', 'terminal_open', 'terminal_send', 'terminal_read', 'terminal_signal', 'terminal_close', 'terminal_list', 'apply_patch', 'str_replace_editor'];
307
+
308
+ /**
309
+ * Tools a router dispatcher is denied by default: running commands (and the
310
+ * job tools that go with them; `pwsh` and the terminals too), writing and
311
+ * editing files (`apply_patch` and `str_replace_editor` too), sub-agents and
312
+ * workflows, image generation and Office tools, and (0.9) the web: a search
313
+ * takes long enough to keep the person waiting, so it is a task too. It keeps
314
+ * `read`, `read_image`, `glob`, `grep` and `skill`.
315
+ */
316
+ export const ROUTER_DENY = Object.freeze([
317
+ ...new Set([...abilityTools('code'), 'write', 'edit', ...abilityTools('delegate'), ...abilityTools('images'), ...abilityTools('office'), ...abilityTools('web'), ...OTHER_WORK_TOOLS]),
318
+ ]);
319
+
320
+ /** Longest `bash` / `pwsh` timeout a router may ask for, in ms. */
321
+ export const ROUTER_MAX_COMMAND_MS = 30_000;
322
+ /** The timeout Harness gives a command that names none (`dsh-bash-local`), in ms. */
323
+ export const DEFAULT_COMMAND_MS = 120_000;
324
+ /** Longest `job_output` wait a router may ask for, in ms (Harness waits 30 s when `wait` has no `timeout_ms`). */
325
+ export const ROUTER_MAX_JOB_WAIT_MS = 5_000;
326
+
327
+ const NO_WAIT = 'The dispatcher does not wait: reports and messages arrive by themselves. End your turn instead.';
328
+
329
+ /** Shell words that may stand before the command they run. */
330
+ const PREFIX_WORDS = new Set(['!', 'if', 'then', 'else', 'elif', 'do', 'while', 'until', 'time', 'command', 'builtin', 'exec', 'nohup', 'nice', 'sudo', 'xargs']);
331
+
332
+ /** Does a shell command run `sleep` at a command position (`sleep 5`, `x && sleep 1`, `do sleep 2; done`, `FOO=1 sleep 3`, `$(sleep 1)`)? */
333
+ export function runsSleep(command) {
334
+ const code = String(command ?? '')
335
+ .replace(/'[^']*'/g, "''")
336
+ .replace(/"(?:[^"\\$`]|\\.)*"/g, '""')
337
+ .replace(/(^|\s)#[^\n]*/g, '$1');
338
+ for (const segment of code.split(/\|\||&&|\$\(|[;&|\n(){}`]/)) {
339
+ const words = segment.trim().split(/\s+/).filter(Boolean);
340
+ let i = 0;
341
+ while (i < words.length) {
342
+ const w = words[i];
343
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) || PREFIX_WORDS.has(w)) i += 1;
344
+ else if (w === 'env' || w === 'timeout') {
345
+ i += 1;
346
+ while (i < words.length && (words[i].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || (w === 'timeout' && /^\d/.test(words[i])))) i += 1;
347
+ } else break;
348
+ }
349
+ const first = (words[i] ?? '').replace(/^\\/, '');
350
+ if (first.split('/').pop() === 'sleep') return true;
351
+ }
352
+ return false;
353
+ }
354
+
355
+ /**
356
+ * A guard for a router's tool calls (the shape of Harness `tools.guard`):
357
+ * the refusal reason for a call that would make the dispatcher wait, else
358
+ * undefined. Refused: `bash` or `pwsh` running `sleep`, or in the foreground
359
+ * without a `timeoutMs` of at most 30 s (none given means Harness's 120 s: the
360
+ * cap, not the shell text, is what bounds a wait such as `read -t` or
361
+ * `tail -f`); `run_in_background` returns at once and is allowed. And
362
+ * `job_output` waits above 5 s.
363
+ * @param {{name: string, arguments?: object}} call
364
+ * @returns {string|undefined}
365
+ */
366
+ export function noWaitReason(call) {
367
+ const name = call?.name;
368
+ const args = call?.arguments && typeof call.arguments === 'object' ? call.arguments : {};
369
+ if (name === 'bash' || name === 'pwsh') {
370
+ if (runsSleep(args.command)) return `Refused: no sleep. ${NO_WAIT}`;
371
+ if (args.run_in_background === true) return undefined;
372
+ const given = args.timeoutMs ?? args.timeout_ms;
373
+ const timeout = given === undefined || given === null || given === '' ? DEFAULT_COMMAND_MS : Number(given);
374
+ if (!(timeout > 0 && timeout <= ROUTER_MAX_COMMAND_MS)) {
375
+ return `Refused: a command here must finish within ${ROUTER_MAX_COMMAND_MS / 1000} s. Pass timeoutMs (at most ${ROUTER_MAX_COMMAND_MS}; left out it is ${DEFAULT_COMMAND_MS / 1000} s), hand long work to a bot with bot_send_message, or run it with run_in_background. ${NO_WAIT}`;
376
+ }
377
+ }
378
+ if (name === 'job_output' && args.wait === true) {
379
+ const timeout = args.timeout_ms === undefined ? Infinity : Number(args.timeout_ms);
380
+ if (!(timeout <= ROUTER_MAX_JOB_WAIT_MS)) return `Refused: job waits above ${ROUTER_MAX_JOB_WAIT_MS / 1000} s are not allowed here (pass timeout_ms up to ${ROUTER_MAX_JOB_WAIT_MS}, or read without wait). ${NO_WAIT}`;
381
+ }
382
+ return undefined;
383
+ }
package/lib/settings.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Team-wide settings of the bots plugin, kept in `settings.json` beside the
3
- * roster: when a bot starts a new topic by itself, how memory is written and
4
- * consolidated, and the prices the usage view counts with.
3
+ * roster: how the dispatcher works, how many tasks (tickets) run at once and
4
+ * when they are judged stalled or archived, when a bot starts a new topic by
5
+ * itself, how memory is written and consolidated, the prices the usage
6
+ * view counts with, and how the panel shows what bots say to each other.
5
7
  *
6
8
  * @module @kadaliao/dsh-bots/lib/settings
7
9
  */
@@ -10,6 +12,24 @@ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'no
10
12
  import { join } from 'node:path';
11
13
 
12
14
  export const DEFAULTS = Object.freeze({
15
+ /**
16
+ * How the dispatcher works in its home conversation: 'router' only understands, hands out
17
+ * (each delegation is a ticket with its own conversation) and reports; 'hands-on' is 0.7.
18
+ */
19
+ dispatcher: 'router',
20
+ tickets: Object.freeze({
21
+ /** Tickets whose conversations run at once; past this they queue (a person's follow-up may take one more). */
22
+ maxWorking: 4,
23
+ /** Minutes a working ticket may stay quiet before the watchdog asks for a report, and again before it is stalled. */
24
+ stallMinutes: 20,
25
+ /** Hours an ended ticket keeps its conversation before it is archived; 0 = at the next upkeep. */
26
+ archiveHours: 24,
27
+ }),
28
+ /**
29
+ * The one-time panel notice that an upgraded team now runs in router mode: 'pending' until the
30
+ * user dismisses it (or picks a mode), 'dismissed' after; null before the first run of 0.8 decided.
31
+ */
32
+ routerNotice: null,
13
33
  topics: Object.freeze({
14
34
  /** A conversation quiet for this many hours starts a new topic before its next task; 0 = never. */
15
35
  idleHours: 6,
@@ -30,8 +50,18 @@ export const DEFAULTS = Object.freeze({
30
50
  prices: Object.freeze({}),
31
51
  /** Keep a ChatGPT login borrowed from the Codex CLI in sync with ~/.codex/auth.json. */
32
52
  codex: Object.freeze({ sync: false, route: false }),
53
+ display: Object.freeze({
54
+ /**
55
+ * Messages between bots in a chat (delegations, reports, DMs): 'line' (who to whom, the task or
56
+ * first sentence, its stage and time), 'short' (that and two lines of the text), 'full' (all of it).
57
+ */
58
+ botMessages: 'line',
59
+ }),
33
60
  });
34
61
 
62
+ /** The levels of `display.botMessages`, least to most. */
63
+ export const BOT_MESSAGE_LEVELS = Object.freeze(['line', 'short', 'full']);
64
+
35
65
  const num = (v, d, min, max) => {
36
66
  const n = Number(v);
37
67
  return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : d;
@@ -67,6 +97,7 @@ export function normalizeSettings(input) {
67
97
  const s = input && typeof input === 'object' ? input : {};
68
98
  const t = s.topics ?? {};
69
99
  const m = s.memory ?? {};
100
+ const tk = s.tickets ?? {};
70
101
  const prices = {};
71
102
  if (s.prices && typeof s.prices === 'object') {
72
103
  for (const [k, v] of Object.entries(s.prices).slice(0, 300)) {
@@ -77,6 +108,13 @@ export function normalizeSettings(input) {
77
108
  }
78
109
  const model = m.model && typeof m.model === 'object' && typeof m.model.provider === 'string' && m.model.provider && typeof m.model.model === 'string' && m.model.model ? { provider: m.model.provider.slice(0, 200), model: m.model.model.slice(0, 200) } : null;
79
110
  return {
111
+ dispatcher: s.dispatcher === 'hands-on' ? 'hands-on' : 'router',
112
+ tickets: {
113
+ maxWorking: Math.round(num(tk.maxWorking, DEFAULTS.tickets.maxWorking, 1, 32)),
114
+ stallMinutes: Math.round(num(tk.stallMinutes, DEFAULTS.tickets.stallMinutes, 1, 24 * 60)),
115
+ archiveHours: num(tk.archiveHours, DEFAULTS.tickets.archiveHours, 0, 24 * 30),
116
+ },
117
+ routerNotice: s.routerNotice === 'pending' || s.routerNotice === 'dismissed' ? s.routerNotice : null,
80
118
  topics: {
81
119
  idleHours: num(t.idleHours, DEFAULTS.topics.idleHours, 0, 24 * 30),
82
120
  maxContextK: Math.round(num(t.maxContextK, DEFAULTS.topics.maxContextK, 0, 4096)),
@@ -89,6 +127,7 @@ export function normalizeSettings(input) {
89
127
  },
90
128
  prices,
91
129
  codex: { sync: s.codex?.sync === true, route: s.codex?.route === true },
130
+ display: { botMessages: BOT_MESSAGE_LEVELS.includes(s.display?.botMessages) ? s.display.botMessages : DEFAULTS.display.botMessages },
92
131
  };
93
132
  }
94
133
 
package/lib/store.mjs CHANGED
@@ -196,6 +196,10 @@ export function normalizeBot(input, prev, seed = 0) {
196
196
  const skills = capSkillsOn(dedupeSkills((Array.isArray(b.skills) ? b.skills : []).map(normalizeSkill).filter(Boolean)).slice(0, MAX_SKILLS), prev?.skills);
197
197
  const apps = (Array.isArray(b.apps) ? b.apps : []).map(normalizeApp).filter(Boolean).slice(0, 20);
198
198
  const deny = Array.isArray(b.tools?.deny) ? [...new Set(b.tools.deny.map(String).filter(Boolean))].slice(0, 200) : [];
199
+ // Tools a router dispatcher keeps although router mode denies them by default. An update whose
200
+ // `tools` leaves the list out (a panel that only edits `deny`) keeps the stored one.
201
+ const allowIn = Array.isArray(b.tools?.routerAllow) ? b.tools.routerAllow : input?.tools && typeof input.tools === 'object' && !('routerAllow' in input.tools) ? prev?.tools?.routerAllow : undefined;
202
+ const routerAllow = Array.isArray(allowIn) ? [...new Set(allowIn.map(String).filter(Boolean))].slice(0, 200) : [];
199
203
  const model =
200
204
  b.model && typeof b.model === 'object' && str(b.model.provider) && str(b.model.model)
201
205
  ? { provider: str(b.model.provider, 200), model: str(b.model.model, 200), ...(/^[a-z0-9_-]{1,32}$/.test(str(b.model.reasoningEffort)) ? { reasoningEffort: b.model.reasoningEffort } : {}) }
@@ -210,7 +214,7 @@ export function normalizeBot(input, prev, seed = 0) {
210
214
  persona: str(b.persona, 20_000),
211
215
  skills,
212
216
  apps,
213
- tools: { deny },
217
+ tools: { deny, ...(routerAllow.length ? { routerAllow } : {}) },
214
218
  model,
215
219
  sessionId: typeof b.sessionId === 'string' && b.sessionId !== '' ? b.sessionId : null,
216
220
  createdAt: prev?.createdAt ?? now,
@@ -272,12 +276,24 @@ export function createStore(dir) {
272
276
  if (messages !== null && now === logSeen) return messages;
273
277
  logSeen = now;
274
278
  messages = [];
279
+ const index = new Map();
275
280
  try {
276
281
  for (const line of readFileSync(log, 'utf8').split('\n')) {
277
282
  if (!line) continue;
278
283
  try {
279
284
  const m = JSON.parse(line);
280
- if (m && typeof m.id === 'string') messages.push(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);
281
297
  } catch {
282
298
  // Skip a torn line.
283
299
  }
@@ -402,11 +418,49 @@ export function createStore(dir) {
402
418
  }
403
419
  return m;
404
420
  },
405
- /** Oldest first; `bot` limits to messages from or to that bot. */
406
- messages({ bot = '', limit = 200 } = {}) {
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 = {}) {
407
426
  const all = readLog();
408
- const rows = bot ? all.filter((m) => m.from === bot || m.to === bot) : all;
409
- return rows.slice(-Math.max(1, Math.min(2000, limit)));
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
+ */
451
+ messages({ bot = '', limit = 200, topic = '' } = {}) {
452
+ const all = readLog();
453
+ // A message that was never handed over (`hidden`) is in no chat.
454
+ const mine = (m) => !m.hidden && (!bot || (m.chat ? m.chat === bot : m.from === bot || m.to === bot));
455
+ const cap = Math.max(1, Math.min(2000, Number(limit) || 200));
456
+ if (topic) return all.filter((m) => mine(m) && (m.id === topic || m.topic === topic || m.movedTo === topic)).slice(-cap);
457
+ const rows = all.filter(mine);
458
+ const window = rows.slice(-cap);
459
+ const have = new Set(window.map((m) => m.id));
460
+ const missing = new Set();
461
+ for (const m of window) for (const r of [m.topic, m.movedTo]) if (r && !have.has(r)) missing.add(r);
462
+ if (missing.size === 0) return window;
463
+ return [...rows.filter((m) => missing.has(m.id)), ...window];
410
464
  },
411
465
  messageCount() {
412
466
  return readLog().length;