@kadaliao/dsh-bots 0.10.1 → 0.11.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/LICENSE +21 -0
- package/README.md +83 -48
- package/README.zh-CN.md +62 -34
- package/client.js +441 -100
- package/index.js +323 -50
- package/lib/channels/discord.mjs +1 -1
- package/lib/memory.mjs +39 -5
- package/lib/needs.mjs +400 -0
- package/lib/prompt.mjs +28 -8
- package/lib/settings.mjs +8 -5
- package/lib/watchdog.mjs +13 -0
- package/package.json +4 -4
package/index.js
CHANGED
|
@@ -6,19 +6,15 @@
|
|
|
6
6
|
* open-computer-use) and scheduled tasks. One bot is the dispatcher that
|
|
7
7
|
* delegates work and schedules tasks.
|
|
8
8
|
*
|
|
9
|
-
* How bots hand work to each other
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* home inbox, which wakes it; the reply travels back the same way.
|
|
19
|
-
*
|
|
20
|
-
* A ticket Session works the same way in both modes: reports go to whoever
|
|
21
|
-
* asked, and asking another bot opens a sub-ticket.
|
|
9
|
+
* How bots hand work to each other: `bot_send_message` from a bot's home opens
|
|
10
|
+
* a ticket (lib/tickets.mjs) for the other bot, which works on it in a Session
|
|
11
|
+
* of its own (`ticket-<id>`) and reports back with a status; the dispatcher's
|
|
12
|
+
* home only understands, hands out and reports (its tools are limited and it
|
|
13
|
+
* may not wait), once it has a teammate. At most `tickets.maxWorking` ticket
|
|
14
|
+
* Sessions run at once; the rest queue. A ticket Session's reports go to
|
|
15
|
+
* whoever asked, and asking another bot from it opens a sub-ticket. (The 0.7
|
|
16
|
+
* `hands-on` mode, where messages went into the other bot's home, is gone
|
|
17
|
+
* since 0.11; a message from outside any bot still goes into the bot's home.)
|
|
22
18
|
*
|
|
23
19
|
* Everything a bot is made of is applied to its Agent's own scope when that
|
|
24
20
|
* Agent comes up (and re-applied when the bot changes): a persona prompt
|
|
@@ -50,15 +46,16 @@ import { createUnfurler } from './lib/unfurl.mjs';
|
|
|
50
46
|
import { isLogoName, withLogo } from './lib/logos.mjs';
|
|
51
47
|
import { askNoticeText, CHANNEL_LABELS, channelEntry, channelIssue, createChannels, credentialsOf, maskBot, threadNote, unmaskApps } from './lib/channels.mjs';
|
|
52
48
|
import { createActivity } from './lib/activity.mjs';
|
|
53
|
-
import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
|
|
49
|
+
import { describeTiming, dmBody, dmHeader, isNoReply, NO_REPLY, noWaitReason, personaText, reportsGoDirect, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
|
|
54
50
|
import { createSettings } from './lib/settings.mjs';
|
|
55
51
|
import { createPriceCatalog, priceOf } from './lib/prices.mjs';
|
|
56
52
|
import { createLedger, promptTokens, report, ticketUsage, todayByBot, usageRow } from './lib/usage.mjs';
|
|
57
53
|
import { createSlots, createTickets, parkedOf, REPORT_STATUSES, sessionIdOf, stageOf } from './lib/tickets.mjs';
|
|
54
|
+
import { clampNeedTitle, createNeeds, NEED_ID_RE, needStatus } from './lib/needs.mjs';
|
|
58
55
|
import { assignmentText, clip, discussionNoteText, failedNoticeText, followUpNoticeText, NEWS_MESSAGES, nudgeText, panelHeaderText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, shownNoticeText, stalledNoticeText, threadNewsText } from './lib/cards.mjs';
|
|
59
|
-
import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
|
|
56
|
+
import { checkTickets, isEmptyResponse, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
|
|
60
57
|
import { isLiveSubscriber, isPanelThread, isTopicThread, panelThreadKey, panelTopicOf, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
|
|
61
|
-
import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
|
|
58
|
+
import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, languageOf, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
|
|
62
59
|
import { createTopics, rotationReason } from './lib/topics.mjs';
|
|
63
60
|
import { chatMessageRef, createDiscussions, forkPoint, messageRef, seqByTime } from './lib/discussions.mjs';
|
|
64
61
|
import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
|
|
@@ -118,7 +115,7 @@ const AVATAR_ATTEMPTS = 3;
|
|
|
118
115
|
/** Errors from a gateway or the network rather than from the request itself. */
|
|
119
116
|
export const TRANSIENT = /\b(408|409|429|500|502|503|504|520|522|524)\b|connection (lost|reset|closed)|ECONNRESET|ETIMEDOUT|EPIPE|socket hang up|fetch failed|could not reach|did not answer within|overloaded|temporarily/i;
|
|
120
117
|
|
|
121
|
-
export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_reply', 'bot_recall', 'bot_ticket', 'bot_schedule', 'memory_save', 'memory_forget', 'memory_search'];
|
|
118
|
+
export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_reply', 'bot_recall', 'bot_ticket', 'bot_need', 'bot_schedule', 'memory_save', 'memory_forget', 'memory_search'];
|
|
122
119
|
/** Message ids of the plugin's own deliveries start with this, so a retry can tell it already delivered one. */
|
|
123
120
|
const MESSAGE_PREFIX = 'bots:';
|
|
124
121
|
/**
|
|
@@ -240,6 +237,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
240
237
|
const memory = createMemory(join(dir, 'memory'));
|
|
241
238
|
const topics = createTopics(dir);
|
|
242
239
|
const tickets = createTickets(dir, { now: nowMs });
|
|
240
|
+
// What the person asked for, above the tasks that do it (Bots 0.11).
|
|
241
|
+
const needs = createNeeds(dir, { now: nowMs });
|
|
243
242
|
// Replies to one message talked over in a forked Session of their own (Bots 0.10).
|
|
244
243
|
const discussions = createDiscussions(dir, { now: nowMs });
|
|
245
244
|
// A tasks file that is there but cannot be read stops the plugin now, before anything writes over it.
|
|
@@ -326,18 +325,16 @@ export function apply(ctx, config, deps = {}) {
|
|
|
326
325
|
}
|
|
327
326
|
/** Whether `sessionId` is `bot`'s home, or a discussion forked from its conversation (it talks to the person like the home). */
|
|
328
327
|
const isHomeOf = (bot, sessionId) => Boolean(bot && sessionId) && (bot.sessionId === sessionId || discussions.bySession(sessionId)?.botId === bot.id);
|
|
329
|
-
const dispatcherMode = () => settings.get().dispatcher;
|
|
330
328
|
/**
|
|
331
|
-
* Router mode is in effect: the
|
|
332
|
-
*
|
|
333
|
-
*
|
|
329
|
+
* Router mode is in effect: the dispatcher has someone to hand work to. A dispatcher that is the
|
|
330
|
+
* only bot does the work itself (a router alone would have no hands); adding a second bot makes it
|
|
331
|
+
* a router, removing the last teammate makes it work alone again. Since 0.11 there is no other
|
|
332
|
+
* mode: the 0.7 hands-on dispatcher is gone.
|
|
334
333
|
*/
|
|
335
|
-
const routerActive = () =>
|
|
334
|
+
const routerActive = () => store.list().length > 1;
|
|
336
335
|
/** The dispatcher works as a router (in its home; its ticket Sessions are ordinary workers). */
|
|
337
336
|
const isRouter = (bot) => Boolean(bot) && bot.role === 'primary' && routerActive();
|
|
338
337
|
const isRouterHome = (bot, sessionId) => isRouter(bot) && isHomeOf(bot, sessionId) && !ticketOf(sessionId);
|
|
339
|
-
/** Bot-to-bot work opens tickets (router mode), or goes to the other bot's home as in 0.7 (hands-on). */
|
|
340
|
-
const ticketsOn = () => dispatcherMode() === 'router';
|
|
341
338
|
|
|
342
339
|
/**
|
|
343
340
|
* Questions a bot's home or ticket Session put to the person with `ask_user_question`, by id, while
|
|
@@ -497,7 +494,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
497
494
|
const roster = store.list();
|
|
498
495
|
const ticket = ticketId ? tickets.get(ticketId) : undefined;
|
|
499
496
|
return now
|
|
500
|
-
? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets:
|
|
497
|
+
? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets: true, ...(ticket ? { ticket } : {}) })
|
|
501
498
|
: '';
|
|
502
499
|
},
|
|
503
500
|
}),
|
|
@@ -882,6 +879,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
882
879
|
: task.trigger === 'chat'
|
|
883
880
|
? `a ${task.via ?? 'chat'} message from the user`
|
|
884
881
|
: 'a message from the user';
|
|
882
|
+
/**
|
|
883
|
+
* The language the person writes to the bots in (`zh` | `en`), for memory written without them
|
|
884
|
+
* in view: their last messages (panel and chat apps), else `material` (the memory itself), else
|
|
885
|
+
* this machine's language.
|
|
886
|
+
*/
|
|
887
|
+
function userLanguage(material = []) {
|
|
888
|
+
const said = store.messages({ limit: 2000, roots: false }).filter((m) => m.from === 'user').slice(-40).map((m) => m.text);
|
|
889
|
+
return languageOf(said) || languageOf(material) || (zh ? 'zh' : 'en');
|
|
890
|
+
}
|
|
885
891
|
async function reflect(bot, task) {
|
|
886
892
|
// A bot deleted while its summary waited keeps nothing.
|
|
887
893
|
if (!store.get(bot.id)) return;
|
|
@@ -893,7 +899,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
893
899
|
let summary = '';
|
|
894
900
|
if (sel) {
|
|
895
901
|
try {
|
|
896
|
-
const p = reflectionPrompt({ bot, notes: memory.notes(bot.id), team: memory.notes('team'), transcript, trigger: triggerWords(task) });
|
|
902
|
+
const p = reflectionPrompt({ bot, notes: memory.notes(bot.id), team: memory.notes('team'), transcript, trigger: triggerWords(task), language: userLanguage([transcript]) });
|
|
897
903
|
const r = await complete(sel, p.system, p.user, { purpose: 'bots-memory', sessionId: task.s });
|
|
898
904
|
ledger.record(usageRow({ botId: bot.id, sessionId: task.s, taskId: task.id, ticketId: task.ticket, kind: 'memory', provider: sel.provider, model: sel.model, usage: r.usage }));
|
|
899
905
|
const parsed = parseJsonReply(r.text) ?? {};
|
|
@@ -911,6 +917,12 @@ export function apply(ctx, config, deps = {}) {
|
|
|
911
917
|
}
|
|
912
918
|
|
|
913
919
|
let dreaming = null;
|
|
920
|
+
/**
|
|
921
|
+
* Output budget of a consolidation call. A thinking model spends most of it reasoning (DeepSeek
|
|
922
|
+
* Flash: ~2–3K tokens on a 5-bot team), and rewriting notes left in another language adds to the
|
|
923
|
+
* answer; 4000 came back empty now and then.
|
|
924
|
+
*/
|
|
925
|
+
const DREAM_TOKENS = 16_000;
|
|
914
926
|
/** Consolidate every bot's notes and write the team digest (the daily "dream"). */
|
|
915
927
|
function dream({ reason = 'schedule' } = {}) {
|
|
916
928
|
if (dreaming) return dreaming;
|
|
@@ -921,6 +933,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
921
933
|
const since = Number(before.lastAt) || now - DAY_MS;
|
|
922
934
|
const bots = store.list();
|
|
923
935
|
const result = { at: now, reason, bots: [], digest: null, errors: [] };
|
|
936
|
+
const language = userLanguage(memory.journal({ since: now - 7 * DAY_MS, limit: 300 }).map((j) => j.summary || j.title));
|
|
924
937
|
for (const bot of bots) {
|
|
925
938
|
const journal = memory.journal({ bot: bot.id, since: now - 7 * DAY_MS, limit: 300 });
|
|
926
939
|
const fresh = journal.some((j) => j.at >= since);
|
|
@@ -929,8 +942,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
929
942
|
const sel = memoryModelOf(bot);
|
|
930
943
|
if (!sel) continue;
|
|
931
944
|
try {
|
|
932
|
-
const p = dreamBotPrompt({ bot, notes, journal, tz });
|
|
933
|
-
const r = await complete(sel, p.system, p.user, { purpose: 'bots-dream', maxTokens:
|
|
945
|
+
const p = dreamBotPrompt({ bot, notes, journal, tz, language });
|
|
946
|
+
const r = await complete(sel, p.system, p.user, { purpose: 'bots-dream', maxTokens: DREAM_TOKENS, timeoutMs: 180_000 });
|
|
934
947
|
ledger.record(usageRow({ botId: bot.id, kind: 'dream', provider: sel.provider, model: sel.model, usage: r.usage }));
|
|
935
948
|
const parsed = parseJsonReply(r.text);
|
|
936
949
|
if (!parsed) throw new Error('the model did not answer with JSON');
|
|
@@ -946,8 +959,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
946
959
|
const date = memory.dayOf(journal[journal.length - 1].at, tz);
|
|
947
960
|
if (sel) {
|
|
948
961
|
try {
|
|
949
|
-
const p = dreamTeamPrompt({ bots, team: memory.notes('team'), journal, date, tz });
|
|
950
|
-
const r = await complete(sel, p.system, p.user, { purpose: 'bots-dream', maxTokens:
|
|
962
|
+
const p = dreamTeamPrompt({ bots, team: memory.notes('team'), journal, date, tz, language });
|
|
963
|
+
const r = await complete(sel, p.system, p.user, { purpose: 'bots-dream', maxTokens: DREAM_TOKENS, timeoutMs: 180_000 });
|
|
951
964
|
ledger.record(usageRow({ botId: lead?.id ?? 'team', kind: 'dream', provider: sel.provider, model: sel.model, usage: r.usage }));
|
|
952
965
|
const parsed = parseJsonReply(r.text);
|
|
953
966
|
if (!parsed) throw new Error('the model did not answer with JSON');
|
|
@@ -1504,7 +1517,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1504
1517
|
store.log({ id, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, thread: panelThreadKey(sid), sid });
|
|
1505
1518
|
// The panel shows thread replies in the chat: what the person read there since, the main conversation hears first.
|
|
1506
1519
|
const news = threadNewsFor(bot, sid);
|
|
1507
|
-
|
|
1520
|
+
// The router reads which tasks a message may continue, and the person's open requests (Bots 0.11).
|
|
1521
|
+
const header = isRouterHome(bot, sid) ? [panelHeaderText({ open: openTasksOf(bot) }, cardCtx()), openNeedsLine(bot)].filter(Boolean).join('\n') : '';
|
|
1508
1522
|
try {
|
|
1509
1523
|
await sendTo(agent, { content: [news.text, header, body].filter(Boolean).map((text) => ({ type: 'text', text })), source: { kind: 'user' }, mode: homeMode(bot), key: `panel:${id}` });
|
|
1510
1524
|
} catch (error) {
|
|
@@ -1702,6 +1716,131 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1702
1716
|
};
|
|
1703
1717
|
}
|
|
1704
1718
|
|
|
1719
|
+
// --- needs: what the person asked for, one level above its tasks (Bots 0.11, lib/needs.mjs) ---
|
|
1720
|
+
/** The top-level ticket a ticket works under (itself for one that is no sub-task). */
|
|
1721
|
+
function rootTicketOf(t) {
|
|
1722
|
+
let cur = t;
|
|
1723
|
+
for (let hops = 0; cur?.parentId && hops < 16; hops += 1) cur = tickets.get(cur.parentId) ?? null;
|
|
1724
|
+
return cur ?? t;
|
|
1725
|
+
}
|
|
1726
|
+
/** The need a ticket (or the task that opened it) counts toward, if any. */
|
|
1727
|
+
const needOfTicket = (t) => (t ? needs.byTicket(rootTicketOf(t).id) : undefined);
|
|
1728
|
+
const needTasks = (n) => n.tickets.map((id) => tickets.get(id)).filter(Boolean);
|
|
1729
|
+
const needStatusOf = (n) => needStatus(n, needTasks(n), stageOf);
|
|
1730
|
+
/** Keep a need's latest status (for when its tasks are pruned). */
|
|
1731
|
+
const refreshNeed = (n) => (n ? needs.snapshot(n.id, needStatusOf(n)) : undefined);
|
|
1732
|
+
// Every change of a task may move its need.
|
|
1733
|
+
tickets.onChange((t) => {
|
|
1734
|
+
try {
|
|
1735
|
+
if (t) refreshNeed(needOfTicket(t));
|
|
1736
|
+
} catch (error) {
|
|
1737
|
+
ctx.logger?.debug?.(`bots: a need's status: ${error?.message ?? error}`);
|
|
1738
|
+
}
|
|
1739
|
+
});
|
|
1740
|
+
/** Needs the dispatcher may add to: open ones, and ones that settled in the last day (a change to a result). */
|
|
1741
|
+
function openNeedsOf(bot) {
|
|
1742
|
+
const since = nowMs() - 24 * 3600_000;
|
|
1743
|
+
return needs.list().filter((n) => (!bot || n.botId === bot.id) && (['waiting', 'working'].includes(needStatusOf(n).status) || n.updatedAt >= since));
|
|
1744
|
+
}
|
|
1745
|
+
/** How the dispatcher reads open needs: `n… "title" (working, 1/3 done)`. */
|
|
1746
|
+
const needPhrase = (n) => {
|
|
1747
|
+
const s = needStatusOf(n);
|
|
1748
|
+
return `${n.id} "${n.title}" (${s.status}${s.total > 1 ? `, ${s.done}/${s.total} done` : ''})`;
|
|
1749
|
+
};
|
|
1750
|
+
/** The line a message to the dispatcher lists its needs in, or ''. */
|
|
1751
|
+
const openNeedsLine = (bot) => {
|
|
1752
|
+
const list = openNeedsOf(bot).slice(0, 8);
|
|
1753
|
+
return list.length ? `Open needs: ${list.map(needPhrase).join('; ')}` : '';
|
|
1754
|
+
};
|
|
1755
|
+
/** A chat message as the person sent it: without the open-needs block the router reads before it. */
|
|
1756
|
+
const withoutNeedsLine = (text) => String(text ?? '').replace(/^Open needs: [^\n]*\n/, '');
|
|
1757
|
+
/** That line as a text block before a chat message, for the router's own conversations only. */
|
|
1758
|
+
const needsNoteFor = (target, sessionId) => {
|
|
1759
|
+
const bot = store.get(target?.id) ?? target;
|
|
1760
|
+
const line = bot && isRouterHome(bot, sessionId) ? openNeedsLine(bot) : '';
|
|
1761
|
+
return line ? [{ type: 'text', text: line }] : [];
|
|
1762
|
+
};
|
|
1763
|
+
/** One need as the panel's board lists it. */
|
|
1764
|
+
function needRow(n) {
|
|
1765
|
+
const s = needStatusOf(n);
|
|
1766
|
+
const list = needTasks(n);
|
|
1767
|
+
// The latest word from its tasks: a question waiting for the person first.
|
|
1768
|
+
const reports = list.flatMap((t) => t.reports.map((r) => ({ ...r, botId: t.botId, ticket: t.id }))).sort((a, b) => a.at - b.at);
|
|
1769
|
+
const asked = s.waiting.length ? reports.filter((r) => s.waiting.includes(r.ticket) && (r.status === 'question' || r.status === 'blocked')).at(-1) : undefined;
|
|
1770
|
+
const latest = asked ?? reports.at(-1);
|
|
1771
|
+
const first = n.asks[0];
|
|
1772
|
+
return {
|
|
1773
|
+
id: n.id,
|
|
1774
|
+
title: n.title,
|
|
1775
|
+
...(n.auto ? { auto: true } : {}),
|
|
1776
|
+
status: s.status,
|
|
1777
|
+
done: s.done,
|
|
1778
|
+
total: s.total,
|
|
1779
|
+
...(s.failed ? { failed: s.failed } : {}),
|
|
1780
|
+
...(s.stalled ? { stalled: s.stalled } : {}),
|
|
1781
|
+
...(s.waiting.length ? { waiting: s.waiting } : {}),
|
|
1782
|
+
bots: [...new Set(list.map((t) => t.botId))],
|
|
1783
|
+
...(n.origin?.via ? { via: n.origin.via } : {}),
|
|
1784
|
+
...(n.origin?.who && n.origin.who !== 'the user' ? { who: n.origin.who } : {}),
|
|
1785
|
+
...(n.origin?.threadKey ? { threadKey: n.origin.threadKey } : {}),
|
|
1786
|
+
...(first ? { asked: clip(first.text, 200).text } : {}),
|
|
1787
|
+
...(latest ? { latest: { status: latest.status, at: latest.at, botId: latest.botId, ticket: latest.ticket, preview: clip(String(latest.text ?? '').trim(), PREVIEW_CHARS).text } } : {}),
|
|
1788
|
+
createdAt: n.createdAt,
|
|
1789
|
+
updatedAt: Math.max(n.updatedAt, ...list.map((t) => t.updatedAt)),
|
|
1790
|
+
...(s.endedAt ? { endedAt: s.endedAt } : {}),
|
|
1791
|
+
...(n.closed ? { closed: n.closed } : {}),
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
/** One need in full: the row, the person's words, its tasks and what they delivered. */
|
|
1795
|
+
function needView(n) {
|
|
1796
|
+
const list = needTasks(n);
|
|
1797
|
+
const results = list
|
|
1798
|
+
.flatMap((t) => t.reports.filter((r) => r.status === 'done').map((r) => ({ at: r.at, botId: t.botId, ticket: t.id, text: clip(String(r.text ?? ''), 4000).text })))
|
|
1799
|
+
.sort((a, b) => a.at - b.at);
|
|
1800
|
+
return { ...needRow(n), asks: n.asks, tickets: list.map(ticketRow), results };
|
|
1801
|
+
}
|
|
1802
|
+
const needOr404 = (id) => {
|
|
1803
|
+
const n = needs.get(String(id ?? ''));
|
|
1804
|
+
if (!n) throw new Error('no such need');
|
|
1805
|
+
return n;
|
|
1806
|
+
};
|
|
1807
|
+
/** Drop a need: its open tasks stop, and it shows as dropped. */
|
|
1808
|
+
function dropNeed(n, by) {
|
|
1809
|
+
for (const t of needTasks(n)) if (!t.ended) endTicket(t, { by: by === 'user' ? 'user' : 'requester', outcome: 'stopped' });
|
|
1810
|
+
return needs.close(n.id, { by });
|
|
1811
|
+
}
|
|
1812
|
+
/** Where a need was asked, from the task that serves it. */
|
|
1813
|
+
const needOrigin = (t) => ({ ...(t?.origin?.threadKey ? { threadKey: t.origin.threadKey } : {}), via: t?.origin?.via || 'panel', ...(t?.origin?.who ? { who: t.origin.who } : {}) });
|
|
1814
|
+
/**
|
|
1815
|
+
* The need a task the dispatcher opens or adds to counts toward: the one `given` names by id; the
|
|
1816
|
+
* need the task already counts toward (a follow-up: the person's words join it); one this turn made
|
|
1817
|
+
* under the same words (parallel calls); a new one when `given` restates a request; with nothing
|
|
1818
|
+
* given in a turn the person spoke in, one under their own words (marked `auto`). Work nobody asked
|
|
1819
|
+
* for (a teammate's request, a schedule) counts toward none. Undefined then.
|
|
1820
|
+
*/
|
|
1821
|
+
function needFor(bot, sessionId, given, t) {
|
|
1822
|
+
const n = needOfTurn(bot, sessionId, given, t);
|
|
1823
|
+
if (n) refreshNeed(n);
|
|
1824
|
+
return n ? needs.get(n.id) : undefined;
|
|
1825
|
+
}
|
|
1826
|
+
function needOfTurn(bot, sessionId, given, t) {
|
|
1827
|
+
const st = turnState.get(sessionId);
|
|
1828
|
+
const asks = st?.asks ?? [];
|
|
1829
|
+
const root = rootTicketOf(t);
|
|
1830
|
+
if (given && NEED_ID_RE.test(given)) return needs.addTicket(needs.get(given).id, root.id, asks);
|
|
1831
|
+
const current = needs.byTicket(root.id);
|
|
1832
|
+
if (current) return needs.addAsks(current.id, asks) ?? current;
|
|
1833
|
+
if (!given && asks.length === 0) return undefined;
|
|
1834
|
+
const title = given ? clampNeedTitle(given) : clampNeedTitle(asks[0].text, 60);
|
|
1835
|
+
const made = st ? (st.needs ??= new Map()) : new Map();
|
|
1836
|
+
const key = given ? title.toLowerCase() : '';
|
|
1837
|
+
const same = made.get(key);
|
|
1838
|
+
if (same && needs.get(same)) return needs.addTicket(same, root.id, asks);
|
|
1839
|
+
const n = needs.create({ title, botId: bot.id, origin: needOrigin(t), asks, tickets: [root.id], ...(given ? {} : { auto: true }) });
|
|
1840
|
+
made.set(key, n.id);
|
|
1841
|
+
return n;
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1705
1844
|
/** A Thread as a ticket subscribes to it: its key and label (`Slack · Acme #general · thread`). */
|
|
1706
1845
|
const threadRecordOf = (o) => ({ key: o.threadKey, label: threadLabel(o) });
|
|
1707
1846
|
/** A ticket's `origin` from one of the turn's Threads; `replyTo`: the chat message that started it, which its answer quotes. */
|
|
@@ -2013,6 +2152,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2013
2152
|
cur = back ?? cur;
|
|
2014
2153
|
}
|
|
2015
2154
|
cur = tickets.touch(cur.id, human ? { human: true } : { requester: true }) ?? cur;
|
|
2155
|
+
// The person's own words to a task (a chat follow-up, the panel's task box) join its need (Bots 0.11).
|
|
2156
|
+
if (human && !sender) {
|
|
2157
|
+
try {
|
|
2158
|
+
const n = needOfTicket(cur);
|
|
2159
|
+
if (n) needs.addAsks(n.id, [{ ...(key ? { id: key } : {}), at: nowMs(), text: body, ...(chat?.kind ? { via: chat.kind } : {}), ...(chat?.who ? { who: chat.who } : {}) }]);
|
|
2160
|
+
} catch {
|
|
2161
|
+
// The need is a view; the message goes on.
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2016
2164
|
const who = sender ? `@${sender.handle} (${sender.name})` : 'the user';
|
|
2017
2165
|
if (!cur.startedAt) {
|
|
2018
2166
|
cur = tickets.patch(cur.id, { text: `${cur.text}\n\n--- Added by ${who} ---\n${body}` }) ?? cur;
|
|
@@ -2310,6 +2458,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2310
2458
|
function ticketError(t, error) {
|
|
2311
2459
|
if (!t || t.ended || retryTimers.has(t.id)) return;
|
|
2312
2460
|
if (error?.name === 'AbortError') return; // stopped on purpose (Harness reports no cancellation here anyway)
|
|
2461
|
+
// Nothing to say, even after Harness's retries (some models end a turn with an empty answer after
|
|
2462
|
+
// a report): the turn ended quietly. The watchdog still asks a task that never reports.
|
|
2463
|
+
if (isEmptyResponse(error)) return;
|
|
2313
2464
|
// A model failure is an `LlmError` whose `failure` holds the facts (`status`, `message`, `code`).
|
|
2314
2465
|
const facts = error?.failure && typeof error.failure === 'object' ? error.failure : error;
|
|
2315
2466
|
const reason = String(facts?.message ?? error?.message ?? error?.error?.message ?? (typeof error === 'string' ? error : '') ?? '').trim() || 'the model call failed';
|
|
@@ -2445,6 +2596,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2445
2596
|
await watch(now);
|
|
2446
2597
|
tickets.flush();
|
|
2447
2598
|
tickets.prune();
|
|
2599
|
+
needs.prune();
|
|
2448
2600
|
await pump();
|
|
2449
2601
|
}
|
|
2450
2602
|
|
|
@@ -2550,6 +2702,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2550
2702
|
const note = first ? `${discussionNoteText({})}\n` : '';
|
|
2551
2703
|
const sent = await sendTo(into.agent, {
|
|
2552
2704
|
content: [
|
|
2705
|
+
...needsNoteFor(target, into.agent.session.id),
|
|
2553
2706
|
{ type: 'text', text: `${note}${header}${threadNote(meta.threadKey)}` },
|
|
2554
2707
|
{ type: 'text', text: body },
|
|
2555
2708
|
],
|
|
@@ -2564,6 +2717,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2564
2717
|
const agent = await agentOf(store.get(target.id) ?? target);
|
|
2565
2718
|
const sent = await sendTo(agent, {
|
|
2566
2719
|
content: [
|
|
2720
|
+
...needsNoteFor(target, agent.session.id),
|
|
2567
2721
|
{ type: 'text', text: `${header}${threadNote(meta.threadKey)}` },
|
|
2568
2722
|
{ type: 'text', text: body },
|
|
2569
2723
|
],
|
|
@@ -2707,7 +2861,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2707
2861
|
st.answers = new Set();
|
|
2708
2862
|
st.acted = false;
|
|
2709
2863
|
turnState.set(session.id, st);
|
|
2710
|
-
|
|
2864
|
+
// The router's list of open needs before a chat message is context, not what the person said.
|
|
2865
|
+
let said = kind === 'user' ? withoutNeedsLine(textOf(event.data.content)) : textOf(event.data.content);
|
|
2711
2866
|
// A message typed in the panel (Bots 0.9) is logged already; its topic joins the turn's Threads.
|
|
2712
2867
|
const panelId = kind === 'user' ? /^bots:panel:(p[a-z0-9]{8})$/.exec(id)?.[1] : undefined;
|
|
2713
2868
|
const typed = panelId ? store.message(panelId) : undefined;
|
|
@@ -2735,11 +2890,17 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2735
2890
|
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 });
|
|
2736
2891
|
}
|
|
2737
2892
|
const thread = via ? via.threadKey : homeThreadOf(session.id);
|
|
2893
|
+
// The person's words in the dispatcher's turn: a need it names now keeps them (Bots 0.11).
|
|
2894
|
+
const asked = (m) => {
|
|
2895
|
+
if (isRouterHome(bot, session.id) && m?.text) st.asks = [...(st.asks ?? []), { id: m.id, at: m.at ?? nowMs(), text: m.text, ...(m.via ? { via: m.via } : {}), ...(m.who ? { who: m.who } : {}) }];
|
|
2896
|
+
};
|
|
2738
2897
|
if (kind === 'user' && typed) {
|
|
2739
2898
|
// Logged when it was sent.
|
|
2899
|
+
asked(typed);
|
|
2740
2900
|
} else if (kind === 'user') {
|
|
2741
2901
|
const topic = !via && isPanelThread(thread) ? panelTopicOf(thread) : '';
|
|
2742
2902
|
const logged = store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who, ...(thread ? { thread } : {}) } : { from: 'user', to: bot.id, text: said, kind: 'user', ...(thread ? { thread } : {}), ...(topic ? { topic } : {}) });
|
|
2903
|
+
asked(logged);
|
|
2743
2904
|
if (home) {
|
|
2744
2905
|
const refs = [messageRef(logged.id)];
|
|
2745
2906
|
// A chat message: by its id in the chat app, and its Thread's latest exchange with the home.
|
|
@@ -2762,7 +2923,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2762
2923
|
if (id && st.reports.has(id)) st.answers.add(id);
|
|
2763
2924
|
else st.acted = true;
|
|
2764
2925
|
}
|
|
2765
|
-
|
|
2926
|
+
// NO_REPLY: the bot had nothing to say (an empty answer is an error in Harness), so nothing is shown or sent.
|
|
2927
|
+
const text = calls.length > 0 || isNoReply(textOf(content)) ? '' : textOf(content);
|
|
2766
2928
|
const why = trigger.get(session.id);
|
|
2767
2929
|
// Shown in the bot's chat: what it says to the user. Hidden: acknowledging a schedule notice,
|
|
2768
2930
|
// the closing words of a turn that answered a bot by DM, and those of a turn whose only inputs
|
|
@@ -2816,7 +2978,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2816
2978
|
const task = openTasks.get(sid);
|
|
2817
2979
|
if (!task) return;
|
|
2818
2980
|
for (const b of Array.isArray(msg.content) ? msg.content : []) {
|
|
2819
|
-
if (b?.type === 'text' && b.text?.trim()) logLine(task, `[assistant] ${b.text.trim()}`);
|
|
2981
|
+
if (b?.type === 'text' && b.text?.trim() && !isNoReply(b.text)) logLine(task, `[assistant] ${b.text.trim()}`);
|
|
2820
2982
|
else if (b?.type === 'tool-call') {
|
|
2821
2983
|
let args = '';
|
|
2822
2984
|
try {
|
|
@@ -2837,7 +2999,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2837
2999
|
} else if (event.type === 'turn/end') {
|
|
2838
3000
|
const task = openTasks.get(sid);
|
|
2839
3001
|
const reason = event.data?.reason?.kind;
|
|
2840
|
-
|
|
3002
|
+
// A model that answered with nothing, even after Harness's retries, ended its turn quietly: no error.
|
|
3003
|
+
if (task && reason && reason !== 'completed' && !(reason === 'error' && isEmptyResponse(event.data?.reason?.error ?? event.data?.reason?.failure))) {
|
|
3004
|
+
task.status = reason === 'error' ? 'error' : reason === 'aborted' ? 'stopped' : task.status;
|
|
3005
|
+
}
|
|
2841
3006
|
settleSoon(sid);
|
|
2842
3007
|
}
|
|
2843
3008
|
} catch (error) {
|
|
@@ -3455,7 +3620,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3455
3620
|
if (e?.type === 'assistant/message') {
|
|
3456
3621
|
const parts = [];
|
|
3457
3622
|
for (const b of Array.isArray(d.message?.content) ? d.message.content : []) {
|
|
3458
|
-
if (b?.type === 'text' && b.text?.trim()) parts.push(`[assistant] ${b.text.trim()}`);
|
|
3623
|
+
if (b?.type === 'text' && b.text?.trim() && !isNoReply(b.text)) parts.push(`[assistant] ${b.text.trim()}`);
|
|
3459
3624
|
else if (b?.type === 'tool-call') {
|
|
3460
3625
|
let args = '';
|
|
3461
3626
|
try {
|
|
@@ -3617,12 +3782,13 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3617
3782
|
name: 'bot_send_message',
|
|
3618
3783
|
description: [
|
|
3619
3784
|
'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.',
|
|
3620
|
-
"- To delegate: `to` (the bot's @handle) and `text`.
|
|
3785
|
+
"- To delegate: `to` (the bot's @handle) and `text`. From a bot's own conversation or a task this opens a task (ticket) that the bot works on in a conversation of its own; from elsewhere it 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.",
|
|
3621
3786
|
'- 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.',
|
|
3622
3787
|
'- When the dispatcher only routes, a message to it opens no task: it goes into its own conversation, and it passes on to the person what they should know. Work goes to the teammate who does it.',
|
|
3623
3788
|
'- 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).',
|
|
3624
3789
|
'- 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`.',
|
|
3625
3790
|
'- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
|
|
3791
|
+
'- The dispatcher names the person\'s request a task serves with `need`: a short restatement for a new request, or the id of a need already open.',
|
|
3626
3792
|
].join('\n'),
|
|
3627
3793
|
parameters: {
|
|
3628
3794
|
to: { type: 'string', description: '@handle (or id / name) of the bot. Leave it out to report on your own task.' },
|
|
@@ -3632,6 +3798,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3632
3798
|
title: { type: 'string', description: 'A short title for a new task; taken from the first line of text when left out.' },
|
|
3633
3799
|
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.' },
|
|
3634
3800
|
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.' },
|
|
3801
|
+
need: { type: 'string', description: 'Dispatcher only: the person\'s request this task serves. For a new request, restate it for the person in one short line in their language, saying what they get (not who does it); tasks for the same request pass the same line or the need id the first call returned. For more work on an open need ("Open needs: …"), its id (n…).' },
|
|
3635
3802
|
},
|
|
3636
3803
|
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => lossless({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
|
|
3637
3804
|
isConcurrencySafe: () => true,
|
|
@@ -3655,16 +3822,24 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3655
3822
|
status === 'progress'
|
|
3656
3823
|
? `Recorded on task ${ticket.id}; progress does not interrupt whoever asked. Go on with the work.`
|
|
3657
3824
|
: shown
|
|
3658
|
-
? `Shown to the person as it is, in ${shown.where}${to ? `; @${to.handle} is told` : ''}.${status === 'done' ?
|
|
3825
|
+
? `Shown to the person as it is, in ${shown.where}${to ? `; @${to.handle} is told` : ''}.${status === 'done' ? ` The task is done: end your turn with only ${NO_REPLY}.` : ` Their answer will arrive here by itself; end your turn now with only ${NO_REPLY}.`}`
|
|
3659
3826
|
: unread
|
|
3660
|
-
? `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.`
|
|
3661
|
-
: `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' ?
|
|
3827
|
+
? `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 with only ${NO_REPLY}.`
|
|
3828
|
+
: `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 with only ${NO_REPLY}.` : ` An answer will arrive here by itself; end your turn now with only ${NO_REPLY}.`}`;
|
|
3662
3829
|
return { ok: true, text: said, ticket: row(ticket), to: face(to), from: face(sender) };
|
|
3663
3830
|
}
|
|
3664
3831
|
}
|
|
3665
3832
|
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');
|
|
3666
3833
|
|
|
3667
3834
|
const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? threadRef(args.thread, sessionId) : '';
|
|
3835
|
+
// The person's request it serves (Bots 0.11): only the dispatcher's own conversation names one.
|
|
3836
|
+
const routing = Boolean(sender) && !mine && isRouterHome(sender, sessionId);
|
|
3837
|
+
const needArg = routing ? String(args.need ?? '').trim().replace(/^need\//, '') : '';
|
|
3838
|
+
if (needArg && NEED_ID_RE.test(needArg) && !needs.get(needArg)) {
|
|
3839
|
+
const open = openNeedsOf(sender).map((n) => n.id);
|
|
3840
|
+
throw new Error(`no need ${needArg}${open.length ? `; open needs: ${open.join(', ')}` : ''}. For a new request, pass a short line restating it instead`);
|
|
3841
|
+
}
|
|
3842
|
+
const needText = (n) => (n ? ` It counts toward need ${n.id} ("${n.title}")${n.auto ? '; pass `need` with a short restatement to name it for the person' : ''}.` : '');
|
|
3668
3843
|
// Adding to an existing ticket.
|
|
3669
3844
|
if (wantTicket) {
|
|
3670
3845
|
const t = tickets.get(wantTicket);
|
|
@@ -3681,7 +3856,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3681
3856
|
const target = store.get(next.botId);
|
|
3682
3857
|
const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
|
|
3683
3858
|
const after = reportsGoDirect(next) ? `${handleOf(next.botId)} answers the person ${isPanelThread(next.showIn ?? next.origin?.threadKey) ? 'in the panel' : 'in the chat'} itself` : `${handleOf(next.botId)}'s report will arrive here by itself`;
|
|
3684
|
-
|
|
3859
|
+
const need = routing ? needFor(sender, sessionId, needArg, next) : undefined;
|
|
3860
|
+
return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${after}; do not wait for it.${needText(need)}`, ticket: row(next), ...(need ? { need: { id: need.id, title: need.title } } : {}), to: face(target), from: face(sender) };
|
|
3685
3861
|
}
|
|
3686
3862
|
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`');
|
|
3687
3863
|
|
|
@@ -3698,9 +3874,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3698
3874
|
}
|
|
3699
3875
|
|
|
3700
3876
|
// A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
|
|
3701
|
-
if (sender && sessionId && (mine ||
|
|
3877
|
+
if (sender && sessionId && (mine || isHomeOf(sender, sessionId))) {
|
|
3702
3878
|
const relay = String(args.report_to ?? '').trim().toLowerCase() === 'me';
|
|
3703
3879
|
const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen, relay });
|
|
3880
|
+
const need = routing ? needFor(sender, sessionId, needArg, t) : undefined;
|
|
3704
3881
|
const stage = stageOf(t);
|
|
3705
3882
|
const who = named.id === sender.id ? 'yourself' : `@${named.handle}`;
|
|
3706
3883
|
const answer = reportsGoDirect(t)
|
|
@@ -3709,10 +3886,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3709
3886
|
const said =
|
|
3710
3887
|
stage === 'failed'
|
|
3711
3888
|
? `Task ${t.id} for ${who} could not start: ${t.error ?? 'unknown error'}.`
|
|
3712
|
-
: `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}`;
|
|
3713
|
-
return { ok: stage !== 'failed', text: said, ticket: row(t), stage, to: face(named), from: face(sender) };
|
|
3889
|
+
: `Opened task ${t.id} for ${who} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). ${answer}${needText(need)}`;
|
|
3890
|
+
return { ok: stage !== 'failed', text: said, ticket: row(t), stage, ...(need ? { need: { id: need.id, title: need.title } } : {}), to: face(named), from: face(sender) };
|
|
3714
3891
|
}
|
|
3715
|
-
//
|
|
3892
|
+
// Into the other bot's home: the user, from a conversation that belongs to no bot.
|
|
3716
3893
|
if (chosen) throw new Error('`thread` is for opening a task; this message goes to the bot\'s own conversation, so leave it out');
|
|
3717
3894
|
await deliver(sender ?? null, named, args.text, sessionId);
|
|
3718
3895
|
return { ok: true, text: `Delivered to @${named.handle}. Its answer will arrive as a new message; continue with other work or end your turn.`, to: face(named), from: face(sender) };
|
|
@@ -3776,12 +3953,24 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3776
3953
|
description:
|
|
3777
3954
|
'Read tasks (tickets) and chat threads by reference instead of guessing: `tickets` (a page of them, open ones first), `ticket/<id>` (its card), `ticket/<id>/text` (what was asked), `ticket/<id>/reports`, `ticket/<id>/transcript` (its conversation), `thread/<key>` (a chat thread: its tasks and latest messages), `bot/<handle>` (that bot\'s tasks). Every id on a card can be read this way; long text comes in pages (`offset`). From a task conversation you can read that task, its parent and sub-tasks, and its threads.',
|
|
3778
3955
|
parameters: {
|
|
3779
|
-
ref: { type: 'string', required: true, description: 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key
|
|
3956
|
+
ref: { type: 'string', required: true, description: 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key>, bot/<handle>, needs or need/<id>.' },
|
|
3780
3957
|
offset: { type: 'number', description: 'Where the next page starts: the `next_offset` of the last one.' },
|
|
3781
3958
|
},
|
|
3782
3959
|
output: { schema: anyValue, render: (_a, v) => text(v.text) },
|
|
3783
3960
|
isConcurrencySafe: () => true,
|
|
3784
3961
|
execute: async (args, exec) => {
|
|
3962
|
+
const ref = String(args.ref ?? '').trim();
|
|
3963
|
+
// The person's requests (Bots 0.11): what each asked for and how far it got.
|
|
3964
|
+
if (ref === 'needs' || /^need\/n[a-z0-9]{8}$/.test(ref)) {
|
|
3965
|
+
if (ref === 'needs') {
|
|
3966
|
+
const items = needs.list().slice(0, 30).map((n) => ({ id: n.id, title: n.title, ...needStatusOf(n), tasks: n.tickets }));
|
|
3967
|
+
return { ok: true, items, text: JSON.stringify({ needs: items }, null, 1) };
|
|
3968
|
+
}
|
|
3969
|
+
const n = needs.get(ref.slice(5));
|
|
3970
|
+
if (!n) throw new Error(`no ${ref}`);
|
|
3971
|
+
const v = { ...needRow(n), asks: n.asks.map((a) => ({ at: a.at, text: a.text })), tasks: n.tickets };
|
|
3972
|
+
return { ok: true, ...v, text: JSON.stringify(v, null, 1) };
|
|
3973
|
+
}
|
|
3785
3974
|
const result = await readResource(String(args.ref ?? ''), {
|
|
3786
3975
|
viewer: viewerOf(actorOf(exec)),
|
|
3787
3976
|
tickets,
|
|
@@ -3848,6 +4037,43 @@ export function apply(ctx, config, deps = {}) {
|
|
|
3848
4037
|
return { ok: true, text: said, ticket: ticketRow(tickets.get(next.id) ?? next) };
|
|
3849
4038
|
},
|
|
3850
4039
|
}),
|
|
4040
|
+
defineTool({
|
|
4041
|
+
name: 'bot_need',
|
|
4042
|
+
description:
|
|
4043
|
+
'Keep the person\'s requests (needs) as they mean them; the panel shows each with how far its tasks got. `rename` one when they change what they want (`title`: the new short line), `merge` one into another when two turn out to be the same request (`into`: the need that stays), `drop` one when they no longer want it (its open tasks stop). `bot_recall` with `needs` lists them.',
|
|
4044
|
+
parameters: {
|
|
4045
|
+
need: { type: 'string', required: true, description: 'The need id (n…).' },
|
|
4046
|
+
action: { type: 'string', required: true, enum: ['rename', 'merge', 'drop'] },
|
|
4047
|
+
title: { type: 'string', description: 'For rename: the request restated in one short line, in the person\'s language.' },
|
|
4048
|
+
into: { type: 'string', description: 'For merge: the id of the need that takes this one\'s tasks.' },
|
|
4049
|
+
},
|
|
4050
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text) },
|
|
4051
|
+
execute: async (args, exec) => {
|
|
4052
|
+
const { sessionId, bot: sender } = actor(exec);
|
|
4053
|
+
if (sender && !isRouterHome(sender, sessionId)) throw new Error('only the dispatcher keeps the person\'s needs; report on your task instead');
|
|
4054
|
+
const n = needs.get(String(args.need ?? '').trim());
|
|
4055
|
+
if (!n) throw new Error(`no need ${String(args.need ?? '').trim()}. bot_recall {"ref":"needs"} lists them.`);
|
|
4056
|
+
const action = String(args.action ?? '').trim().toLowerCase();
|
|
4057
|
+
let next;
|
|
4058
|
+
let said;
|
|
4059
|
+
if (action === 'rename') {
|
|
4060
|
+
if (!String(args.title ?? '').trim()) throw new Error('rename needs a `title`');
|
|
4061
|
+
next = needs.rename(n.id, args.title);
|
|
4062
|
+
said = `Need ${n.id} is now "${next.title}".`;
|
|
4063
|
+
} else if (action === 'merge') {
|
|
4064
|
+
const into = needs.get(String(args.into ?? '').trim());
|
|
4065
|
+
if (!into) throw new Error('merge needs `into`: the id of the need that stays');
|
|
4066
|
+
if (into.id === n.id) throw new Error('a need cannot be merged into itself');
|
|
4067
|
+
next = needs.merge(n.id, into.id);
|
|
4068
|
+
said = `Merged need ${n.id} into ${next.id} ("${next.title}"): its tasks count toward that one now.`;
|
|
4069
|
+
} else if (action === 'drop') {
|
|
4070
|
+
const open = needTasks(n).filter((t) => !t.ended).length;
|
|
4071
|
+
next = dropNeed(n, sender ? 'dispatcher' : 'user');
|
|
4072
|
+
said = `Dropped need ${n.id} ("${n.title}")${open ? `; stopped its ${open} open task${open > 1 ? 's' : ''}` : ''}.`;
|
|
4073
|
+
} else throw new Error('action is one of rename, merge, drop');
|
|
4074
|
+
return { ok: true, text: said, need: needRow(next) };
|
|
4075
|
+
},
|
|
4076
|
+
}),
|
|
3851
4077
|
defineTool({
|
|
3852
4078
|
name: 'bot_schedule',
|
|
3853
4079
|
description:
|
|
@@ -4409,8 +4635,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4409
4635
|
limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
|
|
4410
4636
|
teamNotes: memory.notes('team').length,
|
|
4411
4637
|
dispatcher: s.dispatcher,
|
|
4412
|
-
// The
|
|
4638
|
+
// The dispatcher has a teammate to hand work to: it routes now.
|
|
4413
4639
|
routerActive: routerActive(),
|
|
4640
|
+
// The person's requests (Bots 0.11): how many wait for them, and how many are being worked on.
|
|
4641
|
+
needs: needCounts(),
|
|
4414
4642
|
routerNoticePending: s.routerNotice === 'pending',
|
|
4415
4643
|
// A task whose conversation waits for an answer to its question needs you too (its row says `asking`).
|
|
4416
4644
|
attention: live.filter((t) => needsPerson(t) || askingIn(t.sessionId)).sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 50).map(ticketRow),
|
|
@@ -4794,8 +5022,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4794
5022
|
const patch = body.patch && typeof body.patch === 'object' ? { ...body.patch } : {};
|
|
4795
5023
|
delete patch.codex;
|
|
4796
5024
|
delete patch.prices;
|
|
4797
|
-
//
|
|
4798
|
-
|
|
5025
|
+
// The dispatcher always routes (0.11): there is no mode to pick.
|
|
5026
|
+
delete patch.dispatcher;
|
|
4799
5027
|
const saved = settings.save(patch);
|
|
4800
5028
|
settingsChanged();
|
|
4801
5029
|
return { ok: true, settings: saved };
|
|
@@ -4805,6 +5033,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4805
5033
|
'router-notice/dismiss': { post: () => (settings.save({ routerNotice: 'dismissed' }), { ok: true, routerNoticePending: false }) },
|
|
4806
5034
|
// Tasks (tickets), PLAN-0.8 §6.3. `tickets/:id…` and `threads/:key` are under `paramRoutes`.
|
|
4807
5035
|
tickets: { get: (url) => ticketList(url) },
|
|
5036
|
+
// The person's requests (Bots 0.11). `needs/:id…` is under `paramRoutes`.
|
|
5037
|
+
needs: { get: (url) => needList(url) },
|
|
4808
5038
|
memory: { get: (url) => memoryView(url.searchParams.get('bot') ?? 'team') },
|
|
4809
5039
|
'memory/put': {
|
|
4810
5040
|
post: (body) => {
|
|
@@ -4953,8 +5183,51 @@ export function apply(ctx, config, deps = {}) {
|
|
|
4953
5183
|
if (!t) throw new Error('no such task');
|
|
4954
5184
|
return t;
|
|
4955
5185
|
};
|
|
4956
|
-
/**
|
|
5186
|
+
/** GET /needs: the person's requests, newest first (`status` filters: waiting,working,…). */
|
|
5187
|
+
function needList(url) {
|
|
5188
|
+
const want = (url.searchParams.get('status') ?? '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
5189
|
+
const limit = Math.min(300, Math.max(1, Math.floor(Number(url.searchParams.get('limit')) || 100)));
|
|
5190
|
+
const offset = Math.max(0, Math.floor(Number(url.searchParams.get('offset')) || 0));
|
|
5191
|
+
const rows = needs.list().map(needRow).filter((r) => !want.length || want.includes(r.status)).sort((a, b) => b.updatedAt - a.updatedAt);
|
|
5192
|
+
return { items: rows.slice(offset, offset + limit), next_offset: offset + limit < rows.length ? offset + limit : null };
|
|
5193
|
+
}
|
|
5194
|
+
/** How many of the person's requests wait for them (a question, or not done: the board's first group), and how many are being worked on. */
|
|
5195
|
+
function needCounts() {
|
|
5196
|
+
const out = { waiting: 0, working: 0 };
|
|
5197
|
+
try {
|
|
5198
|
+
for (const n of needs.list()) {
|
|
5199
|
+
const st = needStatusOf(n).status;
|
|
5200
|
+
if (st === 'waiting' || st === 'failed') out.waiting += 1;
|
|
5201
|
+
else if (st === 'working') out.working += 1;
|
|
5202
|
+
}
|
|
5203
|
+
} catch {
|
|
5204
|
+
// The rail does without.
|
|
5205
|
+
}
|
|
5206
|
+
return out;
|
|
5207
|
+
}
|
|
5208
|
+
/** Routes with a path parameter: `tickets/<id>[/<action>]`, `needs/<id>[/<action>]`, `threads/<key>` (the key URI-encoded). */
|
|
4957
5209
|
const paramRoutes = {
|
|
5210
|
+
needs: {
|
|
5211
|
+
get: (rest) => {
|
|
5212
|
+
if (rest.length !== 1) throw new Error('no such route');
|
|
5213
|
+
return needView(needOr404(rest[0]));
|
|
5214
|
+
},
|
|
5215
|
+
post: (rest, body) => {
|
|
5216
|
+
const [id, action] = rest;
|
|
5217
|
+
const n = needOr404(id);
|
|
5218
|
+
switch (action) {
|
|
5219
|
+
case 'rename': {
|
|
5220
|
+
const next = needs.rename(n.id, body.title);
|
|
5221
|
+
if (!next) throw new Error('a need needs a title');
|
|
5222
|
+
return { ok: true, ...needView(next) };
|
|
5223
|
+
}
|
|
5224
|
+
case 'drop':
|
|
5225
|
+
return { ok: true, ...needView(dropNeed(n, 'user')) };
|
|
5226
|
+
default:
|
|
5227
|
+
throw new Error('no such route');
|
|
5228
|
+
}
|
|
5229
|
+
},
|
|
5230
|
+
},
|
|
4958
5231
|
tickets: {
|
|
4959
5232
|
get: (rest) => {
|
|
4960
5233
|
if (rest.length !== 1) throw new Error('no such route');
|