@kadaliao/dsh-bots 0.7.1 → 0.8.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 +213 -45
- package/README.zh-CN.md +151 -31
- package/client.js +1857 -116
- package/index.js +2154 -110
- package/lib/activity.mjs +221 -0
- package/lib/cards.mjs +539 -0
- package/lib/channels/discord.mjs +91 -11
- package/lib/channels/feishu.mjs +37 -9
- package/lib/channels/slack.mjs +26 -8
- package/lib/channels/telegram.mjs +37 -6
- package/lib/channels.mjs +364 -89
- package/lib/memory.mjs +37 -0
- package/lib/prompt.mjs +196 -20
- package/lib/settings.mjs +41 -2
- package/lib/store.mjs +5 -1
- package/lib/threads.mjs +407 -0
- package/lib/tickets.mjs +722 -0
- package/lib/usage.mjs +53 -7
- package/lib/watchdog.mjs +216 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,17 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Host half of the bots bundle: Grok-style bots inside DeepSeek Harness.
|
|
3
3
|
*
|
|
4
|
-
* A bot is a named persona with its own conversation (a DSH Session
|
|
5
|
-
* skills, tool access, apps (MCP servers, e.g.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* A bot is a named persona with its own conversation (a DSH Session, its
|
|
5
|
+
* "home"), avatar, skills, tool access, apps (MCP servers, e.g.
|
|
6
|
+
* open-computer-use) and scheduled tasks. One bot is the dispatcher that
|
|
7
|
+
* delegates work and schedules tasks.
|
|
8
|
+
*
|
|
9
|
+
* How bots hand work to each other depends on the team's `dispatcher` setting:
|
|
10
|
+
*
|
|
11
|
+
* - `router` (the default since 0.8): `bot_send_message` from a bot's home opens
|
|
12
|
+
* a ticket (lib/tickets.mjs) for the other bot, which works on it in a
|
|
13
|
+
* Session of its own (`ticket-<id>`) and reports back with a status; the
|
|
14
|
+
* dispatcher's home only understands, hands out and reports (its tools are
|
|
15
|
+
* limited and it may not wait). At most `tickets.maxWorking` ticket Sessions
|
|
16
|
+
* run at once; the rest queue.
|
|
17
|
+
* - `hands-on` (0.7): `bot_send_message` drops the text into the other bot's
|
|
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
22
|
*
|
|
10
23
|
* Everything a bot is made of is applied to its Agent's own scope when that
|
|
11
24
|
* Agent comes up (and re-applied when the bot changes): a persona prompt
|
|
12
|
-
* section, runtime skills, a tool restriction and agent-scoped MCP clients.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
25
|
+
* section, runtime skills, a tool restriction and agent-scoped MCP clients. A
|
|
26
|
+
* ticket Session is decorated as its executing bot the same way. Nothing
|
|
27
|
+
* touches other conversations, except the bot tools themselves, which every
|
|
28
|
+
* conversation gets so the user can manage bots from anywhere.
|
|
15
29
|
*
|
|
16
30
|
* Chat channel apps (Telegram, Discord, Feishu / Lark, Slack) are no MCP servers: lib/channels.mjs
|
|
17
31
|
* keeps a connector running for each, so paired people can message the team
|
|
@@ -22,7 +36,7 @@
|
|
|
22
36
|
|
|
23
37
|
import { createReadStream, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
24
38
|
import { homedir } from 'node:os';
|
|
25
|
-
import { join, sep } from 'node:path';
|
|
39
|
+
import { isAbsolute, join, sep } from 'node:path';
|
|
26
40
|
import { fileURLToPath } from 'node:url';
|
|
27
41
|
import { randomUUID } from 'node:crypto';
|
|
28
42
|
|
|
@@ -34,12 +48,17 @@ import { TEAMS, teamTiming, teamView } from './lib/teams.mjs';
|
|
|
34
48
|
import { maskedApp, scanExternalMcp } from './lib/mcp-import.mjs';
|
|
35
49
|
import { createUnfurler } from './lib/unfurl.mjs';
|
|
36
50
|
import { isLogoName, withLogo } from './lib/logos.mjs';
|
|
37
|
-
import { CHANNEL_LABELS, channelEntry, channelIssue, createChannels, maskBot, unmaskApps } from './lib/channels.mjs';
|
|
38
|
-
import {
|
|
51
|
+
import { askNoticeText, CHANNEL_LABELS, channelEntry, channelIssue, createChannels, credentialsOf, maskBot, threadNote, unmaskApps } from './lib/channels.mjs';
|
|
52
|
+
import { createActivity } from './lib/activity.mjs';
|
|
53
|
+
import { describeTiming, dmBody, dmHeader, noWaitReason, personaText, ROUTER_DENY, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
|
|
39
54
|
import { createSettings } from './lib/settings.mjs';
|
|
40
55
|
import { createPriceCatalog, priceOf } from './lib/prices.mjs';
|
|
41
|
-
import { createLedger, promptTokens, report, todayByBot, usageRow } from './lib/usage.mjs';
|
|
42
|
-
import {
|
|
56
|
+
import { createLedger, promptTokens, report, ticketUsage, todayByBot, usageRow } from './lib/usage.mjs';
|
|
57
|
+
import { createSlots, createTickets, parkedOf, REPORT_STATUSES, sessionIdOf, stageOf } from './lib/tickets.mjs';
|
|
58
|
+
import { assignmentText, clip, failedNoticeText, followUpNoticeText, nudgeText, PREVIEW_CHARS, readResource, recoveryNoteText, reminderText, reportRelayText, retryText, stalledNoticeText } from './lib/cards.mjs';
|
|
59
|
+
import { checkTickets, isTransient, requesterReminders, retryDelay } from './lib/watchdog.mjs';
|
|
60
|
+
import { isPanelThread, panelThreadKey, parseThreadKey, threadLabel, toThreadKey } from './lib/threads.mjs';
|
|
61
|
+
import { createMemory, dreamBotPrompt, dreamTeamPrompt, KINDS as MEMORY_KINDS, looksSecret, parseJsonReply, reflectionPrompt, searchTickets } from './lib/memory.mjs';
|
|
43
62
|
import { createTopics, rotationReason } from './lib/topics.mjs';
|
|
44
63
|
import { API_KINDS, CODEX_ROUTE, PI_SCOPE, ROUTE_PREFIX, codexAuthFile, createCodexSync, detectLogins, discoverModels, endpointView, keyRefFor, profileFor, readCodexAuth, codexCredential } from './lib/models.mjs';
|
|
45
64
|
|
|
@@ -79,6 +98,8 @@ const scopeOf = (await harnessModule('@deepseek-ai/dsh-scope'))?.scopeOf ?? (()
|
|
|
79
98
|
// The registry wants the compiled definition; outside a Harness the raw one stands in.
|
|
80
99
|
const defineTool = toolsModule?.defineTool ?? ((definition) => definition);
|
|
81
100
|
const createUserMessage = llmModule?.createUserMessage ?? ((input) => Object.freeze({ ...structuredClone(input), role: 'user', id: randomUUID() }));
|
|
101
|
+
/** A message whose id the caller chose (an idempotent delivery); detached and frozen like Harness's own. */
|
|
102
|
+
const freezeMessage = llmModule?.freezeMessage ?? ((message) => Object.freeze(structuredClone(message)));
|
|
82
103
|
|
|
83
104
|
export const inject = ['tools'];
|
|
84
105
|
export const name = 'bots';
|
|
@@ -96,7 +117,19 @@ const AVATAR_ATTEMPTS = 3;
|
|
|
96
117
|
/** Errors from a gateway or the network rather than from the request itself. */
|
|
97
118
|
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;
|
|
98
119
|
|
|
99
|
-
export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_schedule', 'memory_save', 'memory_forget', 'memory_search'];
|
|
120
|
+
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'];
|
|
121
|
+
/** Message ids of the plugin's own deliveries start with this, so a retry can tell it already delivered one. */
|
|
122
|
+
const MESSAGE_PREFIX = 'bots:';
|
|
123
|
+
/**
|
|
124
|
+
* Relays about a ticket, by the kind in their message id (`bots:<kind>:<ticketId>:…`). These are
|
|
125
|
+
* inputs of the requester's turn: the ticket's origin Thread joins it (replies to the person go there).
|
|
126
|
+
*/
|
|
127
|
+
const RELAY_KINDS = new Set(['report', 'failed', 'stalled']);
|
|
128
|
+
/** When queued tickets are first launched after the plugin starts (Harness services settle first); working ones get their recovery notes then. */
|
|
129
|
+
const STARTUP_PUMP_MS = 3000;
|
|
130
|
+
/** Events read from the end of a Session's stored log for its delivered message ids, and the largest log read at all. */
|
|
131
|
+
const HISTORY_TAIL = 4000;
|
|
132
|
+
const HISTORY_MAX_BYTES = 32 * 1024 * 1024;
|
|
100
133
|
const MEMORY_SECTION = 'bots:memory';
|
|
101
134
|
const MEMORY_ORDER = 60;
|
|
102
135
|
/** How often idle conversations are checked for a new topic, and the daily consolidation for being due. */
|
|
@@ -190,16 +223,30 @@ const service = (ctx, name) => {
|
|
|
190
223
|
/**
|
|
191
224
|
* @param {object} ctx
|
|
192
225
|
* @param {object} config
|
|
193
|
-
* @param {{loadConnector?: (kind: string) => Promise<object>, typingEveryMs?: number
|
|
226
|
+
* @param {{loadConnector?: (kind: string) => Promise<object>, typingEveryMs?: number, now?: () => number,
|
|
227
|
+
* setTimeout?: Function, clearTimeout?: Function}} [deps] - for tests: a stand-in chat connector; the clock and
|
|
228
|
+
* the timers the task watchdog (status checks, retries after temporary errors) runs on.
|
|
194
229
|
*/
|
|
195
230
|
export function apply(ctx, config, deps = {}) {
|
|
196
231
|
const cfg = config && typeof config === 'object' ? config : {};
|
|
197
232
|
const dir = join(homeDir(), 'cache', 'bots');
|
|
233
|
+
const nowMs = deps.now ?? Date.now;
|
|
234
|
+
const setTimer = deps.setTimeout ?? setTimeout;
|
|
235
|
+
const clearTimer = deps.clearTimeout ?? clearTimeout;
|
|
198
236
|
const store = createStore(dir);
|
|
199
237
|
const settings = createSettings(dir);
|
|
200
238
|
const ledger = createLedger(dir);
|
|
201
239
|
const memory = createMemory(join(dir, 'memory'));
|
|
202
240
|
const topics = createTopics(dir);
|
|
241
|
+
const tickets = createTickets(dir, { now: nowMs });
|
|
242
|
+
// A tasks file that is there but cannot be read stops the plugin now, before anything writes over it.
|
|
243
|
+
try {
|
|
244
|
+
tickets.open();
|
|
245
|
+
} catch (error) {
|
|
246
|
+
(ctx.logger?.error ?? ctx.logger?.warn)?.call(ctx.logger, `bots: not starting: ${error?.message ?? error}`);
|
|
247
|
+
throw error;
|
|
248
|
+
}
|
|
249
|
+
const slots = createSlots(settings.get().tickets.maxWorking);
|
|
203
250
|
const prices = createPriceCatalog(dir, { enabled: deps.prices !== false, ...(deps.fetch ? { fetch: deps.fetch } : {}) });
|
|
204
251
|
const home = deps.home ?? homedir();
|
|
205
252
|
const workdir = typeof cfg.workdir === 'string' && cfg.workdir.trim() ? cfg.workdir.trim() : join(homeDir(), 'bots', 'workspace');
|
|
@@ -212,6 +259,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
212
259
|
})();
|
|
213
260
|
|
|
214
261
|
// --- seeding: a dispatcher on the very first run ---------------------------------
|
|
262
|
+
/** Bots from an earlier version: this team was there before 0.8 made router mode the default. */
|
|
263
|
+
const hadBots = store.list().length > 0;
|
|
215
264
|
const seededFile = join(dir, 'seeded');
|
|
216
265
|
const zh = /^zh/i.test(String(cfg.language ?? '') || Intl.DateTimeFormat().resolvedOptions().locale || process.env.LANG || '');
|
|
217
266
|
if (store.list().length === 0 && !existsSync(seededFile)) {
|
|
@@ -233,6 +282,73 @@ export function apply(ctx, config, deps = {}) {
|
|
|
233
282
|
}
|
|
234
283
|
}
|
|
235
284
|
|
|
285
|
+
// The first run of 0.8 decides once whether the panel tells the user that the dispatcher now routes.
|
|
286
|
+
if (settings.get().routerNotice === null) {
|
|
287
|
+
try {
|
|
288
|
+
settings.save({ routerNotice: hadBots ? 'pending' : 'dismissed' });
|
|
289
|
+
} catch {
|
|
290
|
+
// Asked again at the next start.
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// --- which bot a conversation belongs to ---------------------------------------------
|
|
295
|
+
/** Ticket Sessions the controller named something other than `ticket-<id>`. */
|
|
296
|
+
const otherTicketSessions = new Set();
|
|
297
|
+
/** The ticket a Session runs, if it is a ticket Session. */
|
|
298
|
+
const ticketOf = (sessionId) => (typeof sessionId === 'string' && (sessionId.startsWith('ticket-') || otherTicketSessions.has(sessionId)) ? tickets.bySession(sessionId) : undefined);
|
|
299
|
+
// --- what each bot does right now (the panel's live status) -----------------------------
|
|
300
|
+
/** The tokens of every chat app, kept out of what the page is shown of a running tool. */
|
|
301
|
+
function channelSecrets() {
|
|
302
|
+
const tpl = templates();
|
|
303
|
+
const out = [];
|
|
304
|
+
for (const b of store.list()) {
|
|
305
|
+
for (const app of b.apps) {
|
|
306
|
+
const entry = channelEntry(app, tpl);
|
|
307
|
+
if (entry) out.push(...credentialsOf(app, entry).secrets);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
const activity = createActivity({ now: nowMs, secrets: channelSecrets, handleOf: (ref) => (store.find(String(ref)) ? `@${store.find(String(ref)).handle}` : '') });
|
|
313
|
+
|
|
314
|
+
/** The bot of a home Session or of a ticket Session (its executing bot). */
|
|
315
|
+
function botOfSession(sessionId) {
|
|
316
|
+
if (!sessionId) return undefined;
|
|
317
|
+
const home = store.bySession(sessionId);
|
|
318
|
+
if (home) return home;
|
|
319
|
+
const t = ticketOf(sessionId);
|
|
320
|
+
return t ? store.get(t.botId) : undefined;
|
|
321
|
+
}
|
|
322
|
+
const dispatcherMode = () => settings.get().dispatcher;
|
|
323
|
+
/**
|
|
324
|
+
* Router mode is in effect: the setting says so and the dispatcher has someone to hand work to. A
|
|
325
|
+
* dispatcher that is the only bot works hands-on (a router alone would have no hands); adding a
|
|
326
|
+
* second bot makes it a router, removing the last teammate makes it hands-on again.
|
|
327
|
+
*/
|
|
328
|
+
const routerActive = () => dispatcherMode() === 'router' && store.list().length > 1;
|
|
329
|
+
/** The dispatcher works as a router (in its home; its ticket Sessions are ordinary workers). */
|
|
330
|
+
const isRouter = (bot) => Boolean(bot) && bot.role === 'primary' && routerActive();
|
|
331
|
+
const isRouterHome = (bot, sessionId) => isRouter(bot) && Boolean(sessionId) && bot.sessionId === sessionId && !ticketOf(sessionId);
|
|
332
|
+
/** Bot-to-bot work opens tickets (router mode), or goes to the other bot's home as in 0.7 (hands-on). */
|
|
333
|
+
const ticketsOn = () => dispatcherMode() === 'router';
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Questions a bot's home or ticket Session put to the person with `ask_user_question`, by id, while
|
|
337
|
+
* they wait (see "questions a bot asks" below). In memory only: they die with the process, as the
|
|
338
|
+
* tool call does.
|
|
339
|
+
*/
|
|
340
|
+
const asks = new Map();
|
|
341
|
+
const askingIn = (sessionId) => Boolean(sessionId) && [...asks.values()].some((a) => a.sessionId === sessionId);
|
|
342
|
+
/** The questions still waiting. One past its timed wait (`continued`) goes with its task's end, or with its home (a new topic). */
|
|
343
|
+
function pendingAsks() {
|
|
344
|
+
for (const a of asks.values()) {
|
|
345
|
+
if (!a.continued) continue;
|
|
346
|
+
const t = a.ticketId ? tickets.get(a.ticketId) : null;
|
|
347
|
+
if (a.ticketId ? !t || t.ended || t.archivedAt : store.get(a.botId)?.sessionId !== a.sessionId) asks.delete(a.id);
|
|
348
|
+
}
|
|
349
|
+
return [...asks.values()];
|
|
350
|
+
}
|
|
351
|
+
|
|
236
352
|
// --- applying a bot to its Agent ----------------------------------------------------
|
|
237
353
|
/** sessionId → {agent, signature, disposers[]} */
|
|
238
354
|
const installed = new Map();
|
|
@@ -240,7 +356,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
240
356
|
const isChannel = (app) => Boolean(channelEntry(app, templates()));
|
|
241
357
|
// Chat channels run outside the Agent; changing one does not restart the bot's MCP clients.
|
|
242
358
|
// A linked local skill counts by what its SKILL.md is now, so an edit there re-installs it.
|
|
243
|
-
|
|
359
|
+
// A router home also changes with the dispatcher mode and the role (its tool limits and guard).
|
|
360
|
+
const signatureOf = (bot, sessionId) =>
|
|
361
|
+
JSON.stringify({ s: bot.skills, l: bot.skills.filter((s) => s.linked && s.enabled).map((s) => readLinkedSkill(s.dir)?.stamp ?? ''), a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle, r: isRouterHome(bot, sessionId) ? 1 : 0 });
|
|
244
362
|
/** The chat apps the team can be reached from ('Telegram'), for the persona. */
|
|
245
363
|
const channelNames = (bots) => {
|
|
246
364
|
const tpl = templates();
|
|
@@ -263,6 +381,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
263
381
|
|
|
264
382
|
function install(agent, bot) {
|
|
265
383
|
const actx = agent.ctx;
|
|
384
|
+
const sessionId = agent.session.id;
|
|
385
|
+
// A ticket Session is its executing bot working on one task; the persona says so.
|
|
386
|
+
const ticketId = ticketOf(sessionId)?.id ?? '';
|
|
387
|
+
const router = isRouterHome(bot, sessionId);
|
|
266
388
|
const disposers = [];
|
|
267
389
|
const skillNames = {};
|
|
268
390
|
const skills = service(actx, 'skills');
|
|
@@ -328,7 +450,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
328
450
|
text: () => {
|
|
329
451
|
const now = store.get(bot.id);
|
|
330
452
|
const roster = store.list();
|
|
331
|
-
|
|
453
|
+
const ticket = ticketId ? tickets.get(ticketId) : undefined;
|
|
454
|
+
return now
|
|
455
|
+
? personaText(now, roster, { skillsInline, skillNames, apps: appNames, channels: channelNames(roster), dispatcher: routerActive() ? 'router' : 'hands-on', tickets: ticketsOn(), ...(ticket ? { ticket } : {}) })
|
|
456
|
+
: '';
|
|
332
457
|
},
|
|
333
458
|
}),
|
|
334
459
|
);
|
|
@@ -342,30 +467,42 @@ export function apply(ctx, config, deps = {}) {
|
|
|
342
467
|
ctx.logger?.warn?.(`bots: memory for @${bot.handle}: ${error?.message ?? error}`);
|
|
343
468
|
}
|
|
344
469
|
}
|
|
345
|
-
|
|
470
|
+
// A router home is also denied the tools that do the work, except those the user gave back.
|
|
471
|
+
const allowed = new Set(bot.tools.routerAllow ?? []);
|
|
472
|
+
const wanted = [...new Set([...bot.tools.deny, ...(router ? ROUTER_DENY.filter((n) => !allowed.has(n)) : [])])];
|
|
473
|
+
if (wanted.length > 0) {
|
|
346
474
|
const tools = service(actx, 'tools');
|
|
347
475
|
try {
|
|
348
476
|
const view = ctx.tools?.view?.(scopeOf(actx));
|
|
349
477
|
const known = view?.restrictableNames instanceof Set ? view.restrictableNames : new Set((ctx.tools?.definitions?.() ?? []).map((d) => d.name));
|
|
350
|
-
const deny =
|
|
478
|
+
const deny = wanted.filter((n) => known.has(n) && n !== 'run_code');
|
|
351
479
|
if (deny.length > 0 && tools?.restrict) disposers.push(tools.restrict({ deny }));
|
|
352
480
|
} catch (error) {
|
|
353
481
|
ctx.logger?.warn?.(`bots: tool access for @${bot.handle}: ${error?.message ?? error}`);
|
|
354
482
|
}
|
|
355
483
|
}
|
|
356
|
-
|
|
484
|
+
if (router) {
|
|
485
|
+
// Even with `bash` given back, a router may not sleep or wait long: reports arrive by themselves.
|
|
486
|
+
const tools = service(actx, 'tools');
|
|
487
|
+
try {
|
|
488
|
+
if (typeof tools?.guard === 'function') disposers.push(tools.guard((execution) => noWaitReason(execution)));
|
|
489
|
+
} catch (error) {
|
|
490
|
+
ctx.logger?.warn?.(`bots: dispatcher guard for @${bot.handle}: ${error?.message ?? error}`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
installed.set(sessionId, { agent, signature: signatureOf(bot, sessionId), disposers });
|
|
357
494
|
}
|
|
358
495
|
|
|
359
496
|
function reconcile(agent) {
|
|
360
497
|
const sessionId = agent?.session?.id;
|
|
361
498
|
if (!sessionId) return;
|
|
362
|
-
const bot =
|
|
499
|
+
const bot = botOfSession(sessionId);
|
|
363
500
|
const rec = installed.get(sessionId);
|
|
364
501
|
if (!bot) {
|
|
365
502
|
if (rec) uninstall(sessionId);
|
|
366
503
|
return;
|
|
367
504
|
}
|
|
368
|
-
if (rec && rec.agent === agent && rec.signature === signatureOf(bot)) return;
|
|
505
|
+
if (rec && rec.agent === agent && rec.signature === signatureOf(bot, sessionId)) return;
|
|
369
506
|
if (rec) uninstall(sessionId);
|
|
370
507
|
install(agent, bot);
|
|
371
508
|
}
|
|
@@ -387,19 +524,24 @@ export function apply(ctx, config, deps = {}) {
|
|
|
387
524
|
});
|
|
388
525
|
ctx.effect(
|
|
389
526
|
() =>
|
|
390
|
-
store.onChange(() =>
|
|
391
|
-
const live = agents();
|
|
392
|
-
for (const bot of store.list()) {
|
|
393
|
-
const agent = bot.sessionId ? live?.get?.(bot.sessionId) : undefined;
|
|
394
|
-
if (agent) reconcile(agent);
|
|
395
|
-
}
|
|
396
|
-
for (const sessionId of [...installed.keys()]) if (!store.bySession(sessionId)) uninstall(sessionId);
|
|
397
|
-
}),
|
|
527
|
+
store.onChange(() => reapply()),
|
|
398
528
|
'bots: re-apply changed bots',
|
|
399
529
|
);
|
|
400
530
|
ctx.effect(() => () => {
|
|
401
531
|
for (const id of [...installed.keys()]) uninstall(id);
|
|
402
532
|
}, 'bots: unwind bot scopes');
|
|
533
|
+
/** Apply every bot again to its live home and ticket Sessions (a bot, the roles or the dispatcher mode changed). */
|
|
534
|
+
function reapply() {
|
|
535
|
+
const live = agents();
|
|
536
|
+
for (const bot of store.list()) {
|
|
537
|
+
const agent = bot.sessionId ? live?.get?.(bot.sessionId) : undefined;
|
|
538
|
+
if (agent) reconcile(agent);
|
|
539
|
+
}
|
|
540
|
+
for (const [sessionId, rec] of [...installed]) {
|
|
541
|
+
if (!botOfSession(sessionId)) uninstall(sessionId);
|
|
542
|
+
else reconcile(rec.agent);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
403
545
|
|
|
404
546
|
// --- sessions ---------------------------------------------------------------------
|
|
405
547
|
async function workspaceId() {
|
|
@@ -544,7 +686,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
544
686
|
function memoryTextFor(sessionId) {
|
|
545
687
|
let text = memoText.get(sessionId);
|
|
546
688
|
if (text === undefined) {
|
|
547
|
-
const bot =
|
|
689
|
+
const bot = botOfSession(sessionId);
|
|
548
690
|
try {
|
|
549
691
|
text = bot ? memory.promptFor(bot, { tz: tzMinutes() }) : '';
|
|
550
692
|
} catch {
|
|
@@ -577,11 +719,13 @@ export function apply(ctx, config, deps = {}) {
|
|
|
577
719
|
const content = event.data?.content;
|
|
578
720
|
const said = textOf(content);
|
|
579
721
|
const sched = kind === 'schedule' ? (/schedule_id_json:\s*"([^"]+)"/.exec(said)?.[1] ?? /"schedule_id":\s*"([^"]+)"/.exec(said)?.[1] ?? '') : '';
|
|
580
|
-
const from = kind === 'agent-message' ? (
|
|
722
|
+
const from = kind === 'agent-message' ? (botOfSession(event.data?.source?.senderSessionId)?.id ?? 'user') : '';
|
|
723
|
+
const ticket = ticketOf(sessionId);
|
|
581
724
|
const task = {
|
|
582
725
|
id: `task-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
|
|
583
726
|
b: bot.id,
|
|
584
727
|
s: sessionId,
|
|
728
|
+
...(ticket ? { t: ticket.id } : {}),
|
|
585
729
|
trigger: kind === 'schedule' ? 'schedule' : kind === 'agent-message' ? 'dm' : via ? 'chat' : 'user',
|
|
586
730
|
...(via ? { via: via.kind } : {}),
|
|
587
731
|
...(from ? { from } : {}),
|
|
@@ -594,7 +738,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
594
738
|
replied: false,
|
|
595
739
|
};
|
|
596
740
|
openTasks.set(sessionId, task);
|
|
597
|
-
|
|
741
|
+
// A ticket Session is no topic of the bot's: rotation only ever looks at its home.
|
|
742
|
+
if (!ticket) topics.current(bot.id, sessionId);
|
|
598
743
|
return task;
|
|
599
744
|
}
|
|
600
745
|
function logLine(task, line) {
|
|
@@ -608,8 +753,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
608
753
|
function recordUsage(bot, sessionId, { at, kind, provider, model, usage }) {
|
|
609
754
|
if (!usage) return;
|
|
610
755
|
const task = openTasks.get(sessionId);
|
|
611
|
-
|
|
612
|
-
|
|
756
|
+
const ticketId = ticketOf(sessionId)?.id;
|
|
757
|
+
ledger.record(usageRow({ at, botId: bot.id, sessionId, taskId: kind === 'chat' || kind === 'compaction' ? task?.id : undefined, ticketId, kind, provider, model, usage }));
|
|
758
|
+
if (kind === 'chat' && !ticketId) topics.noteCall(bot.id, sessionId, promptTokens(usage));
|
|
613
759
|
}
|
|
614
760
|
/** The task of `sessionId` is over when its Agent is idle again. */
|
|
615
761
|
function settleSoon(sessionId, delay = 1200) {
|
|
@@ -631,9 +777,38 @@ export function apply(ctx, config, deps = {}) {
|
|
|
631
777
|
row.end = Date.now();
|
|
632
778
|
row.status = status ?? (task.status === 'running' ? 'done' : task.status);
|
|
633
779
|
ledger.finishTask(row);
|
|
780
|
+
if (task.t) {
|
|
781
|
+
// A run of a ticket: its transcript waits for the ticket's end, which is summarized once.
|
|
782
|
+
keepTicketLog(task.t, log);
|
|
783
|
+
const t = tickets.get(task.t);
|
|
784
|
+
if (t?.ended) reflectTicket(t);
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
634
787
|
topics.noteTask(task.b, task.s, task.title);
|
|
635
788
|
if (bot) queueReflection(bot, { ...row, log });
|
|
636
789
|
}
|
|
790
|
+
/** ticketId → transcript lines of its finished runs, for the summary written when it ends. */
|
|
791
|
+
const ticketLogs = new Map();
|
|
792
|
+
function keepTicketLog(ticketId, lines) {
|
|
793
|
+
const rec = ticketLogs.get(ticketId) ?? { log: [], size: 0 };
|
|
794
|
+
for (const line of lines ?? []) logLine(rec, line);
|
|
795
|
+
ticketLogs.set(ticketId, rec);
|
|
796
|
+
}
|
|
797
|
+
/** ticketId → the transcript lines of an ended ticket, kept for bot_recall when Harness keeps no log (the latest 50). */
|
|
798
|
+
const doneLogs = new Map();
|
|
799
|
+
/** A ticket ended: its executing bot summarizes the work into its memory, as after any task. */
|
|
800
|
+
function reflectTicket(t) {
|
|
801
|
+
const rec = ticketLogs.get(t.id);
|
|
802
|
+
ticketLogs.delete(t.id);
|
|
803
|
+
if (rec?.log.length) {
|
|
804
|
+
doneLogs.delete(t.id);
|
|
805
|
+
doneLogs.set(t.id, [...rec.log]);
|
|
806
|
+
if (doneLogs.size > 50) doneLogs.delete(doneLogs.keys().next().value);
|
|
807
|
+
}
|
|
808
|
+
const bot = store.get(t.botId);
|
|
809
|
+
if (!bot || !rec?.log.length) return;
|
|
810
|
+
queueReflection(bot, { id: t.id, ticket: t.id, b: bot.id, s: t.sessionId, trigger: 'ticket', from: t.requester?.botId ?? 'user', title: t.title, log: rec.log });
|
|
811
|
+
}
|
|
637
812
|
|
|
638
813
|
// --- memory ----------------------------------------------------------------------------------
|
|
639
814
|
const reflecting = new Map();
|
|
@@ -650,7 +825,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
650
825
|
return next;
|
|
651
826
|
}
|
|
652
827
|
const triggerWords = (task) =>
|
|
653
|
-
task.trigger === '
|
|
828
|
+
task.trigger === 'ticket'
|
|
829
|
+
? `task ${task.ticket} from ${task.from === 'user' ? 'the user' : `@${store.get(task.from)?.handle ?? 'another bot'}`}`
|
|
830
|
+
: task.trigger === 'schedule'
|
|
831
|
+
? 'a scheduled task'
|
|
832
|
+
: task.trigger === 'dm'
|
|
833
|
+
? `a message from ${task.from === 'user' ? 'the user' : `@${store.get(task.from)?.handle ?? 'another bot'}`}`
|
|
834
|
+
: task.trigger === 'chat'
|
|
835
|
+
? `a ${task.via ?? 'chat'} message from the user`
|
|
836
|
+
: 'a message from the user';
|
|
654
837
|
async function reflect(bot, task) {
|
|
655
838
|
// A bot deleted while its summary waited keeps nothing.
|
|
656
839
|
if (!store.get(bot.id)) return;
|
|
@@ -664,7 +847,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
664
847
|
try {
|
|
665
848
|
const p = reflectionPrompt({ bot, notes: memory.notes(bot.id), team: memory.notes('team'), transcript, trigger: triggerWords(task) });
|
|
666
849
|
const r = await complete(sel, p.system, p.user, { purpose: 'bots-memory', sessionId: task.s });
|
|
667
|
-
ledger.record(usageRow({ botId: bot.id, sessionId: task.s, taskId: task.id, kind: 'memory', provider: sel.provider, model: sel.model, usage: r.usage }));
|
|
850
|
+
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 }));
|
|
668
851
|
const parsed = parseJsonReply(r.text) ?? {};
|
|
669
852
|
summary = String(parsed.summary ?? '').trim();
|
|
670
853
|
if (Array.isArray(parsed.notes) && parsed.notes.length) memory.edit(bot.id, parsed.notes, { source: 'auto' });
|
|
@@ -673,7 +856,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
673
856
|
ctx.logger?.warn?.(`bots: summarizing a task of @${bot.handle} failed: ${error?.message ?? error}`);
|
|
674
857
|
}
|
|
675
858
|
}
|
|
676
|
-
if (worth || summary) memory.addJournal({ bot: bot.id, task: task.id, trigger: task.trigger, title: task.title, summary: summary || task.title });
|
|
859
|
+
if (worth || summary) memory.addJournal({ bot: bot.id, task: task.id, trigger: task.trigger, ...(task.ticket ? { ticket: task.ticket } : {}), title: task.title, summary: summary || task.title });
|
|
677
860
|
// The bot started a new topic before this summary was written: that topic reads its memory again.
|
|
678
861
|
const now = store.get(bot.id)?.sessionId;
|
|
679
862
|
if (now && now !== task.s) staleMemory(now);
|
|
@@ -807,8 +990,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
807
990
|
throw new Error(`could not move the scheduled tasks of @${bot.handle} to a new topic (${failed?.message ?? failed}); it stays in the current one`);
|
|
808
991
|
}
|
|
809
992
|
uninstall(prev);
|
|
810
|
-
|
|
811
|
-
memoStale.delete(prev);
|
|
993
|
+
forgetSession(prev);
|
|
812
994
|
try {
|
|
813
995
|
await service(ctx, 'workspaceRegistry')?.archiveSession?.(prev);
|
|
814
996
|
} catch (error) {
|
|
@@ -856,24 +1038,131 @@ export function apply(ctx, config, deps = {}) {
|
|
|
856
1038
|
return true;
|
|
857
1039
|
}
|
|
858
1040
|
|
|
859
|
-
|
|
1041
|
+
const pairRefusal = (sender, target) => new Error(`@${sender.handle} and @${target.handle} exchanged ${PAIR_LIMIT} messages in the last 10 minutes; stop and report to the user instead of continuing.`);
|
|
1042
|
+
|
|
1043
|
+
/**
|
|
1044
|
+
* Deliveries the plugin made with an id of its own, per Session: what this process handed over
|
|
1045
|
+
* or saw arrive, and (read once per Session, see `loadHistory`) what its stored log says arrived
|
|
1046
|
+
* before a restart. With the Agent's pending inbox (durable too) it tells a retry the message is
|
|
1047
|
+
* there already.
|
|
1048
|
+
*/
|
|
1049
|
+
const deliveredIds = new Map();
|
|
1050
|
+
/**
|
|
1051
|
+
* The tail of a Session's stored log (Harness `sessionPersistence`, a read handle beside the live
|
|
1052
|
+
* writer), or null when there is no such service, no such Session, the log is too large to read
|
|
1053
|
+
* cheaply, or the read comes back in a shape not known here. `deps.history(sessionId)` stands in for tests.
|
|
1054
|
+
* @returns {Promise<object[]|null>}
|
|
1055
|
+
*/
|
|
1056
|
+
async function readHistory(sessionId) {
|
|
1057
|
+
if (!sessionId) return null;
|
|
1058
|
+
if (typeof deps.history === 'function') return (await deps.history(sessionId)) ?? null;
|
|
1059
|
+
const persistence = service(ctx, 'sessionPersistence');
|
|
1060
|
+
if (typeof persistence?.open !== 'function') return null;
|
|
1061
|
+
let snap;
|
|
1062
|
+
try {
|
|
1063
|
+
snap = await persistence.stat?.(sessionId);
|
|
1064
|
+
} catch {
|
|
1065
|
+
snap = undefined;
|
|
1066
|
+
}
|
|
1067
|
+
if (persistence.stat && snap === undefined) return null;
|
|
1068
|
+
if (Number(snap?.sizeBytes) > HISTORY_MAX_BYTES) return null;
|
|
1069
|
+
let handle;
|
|
1070
|
+
try {
|
|
1071
|
+
handle = await persistence.open(sessionId, 'read');
|
|
1072
|
+
const count = Number(snap?.eventCount);
|
|
1073
|
+
const offset = Number.isSafeInteger(count) && count > HISTORY_TAIL ? count - HISTORY_TAIL : 0;
|
|
1074
|
+
let read = await handle.read(offset, HISTORY_TAIL);
|
|
1075
|
+
if (offset > 0 && !(read?.events?.length > 0)) read = await handle.read(0);
|
|
1076
|
+
// A read in a shape not known here tells nothing (null), rather than an empty log.
|
|
1077
|
+
return Array.isArray(read?.events) ? read.events : null;
|
|
1078
|
+
} catch {
|
|
1079
|
+
return null;
|
|
1080
|
+
} finally {
|
|
1081
|
+
try {
|
|
1082
|
+
await handle?.close?.();
|
|
1083
|
+
} catch {
|
|
1084
|
+
// Closed with the process.
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
/** Sessions whose stored log was read for delivered ids in this process. */
|
|
1089
|
+
const historyRead = new Map();
|
|
1090
|
+
/** Read the delivered ids of `sessionId`'s stored log once per process (cheap: its tail; nothing without the service). */
|
|
1091
|
+
function loadHistory(sessionId) {
|
|
1092
|
+
if (!sessionId) return Promise.resolve();
|
|
1093
|
+
if (!historyRead.has(sessionId)) {
|
|
1094
|
+
historyRead.set(
|
|
1095
|
+
sessionId,
|
|
1096
|
+
readHistory(sessionId)
|
|
1097
|
+
.then((events) => {
|
|
1098
|
+
for (const e of events ?? []) if (e?.type === 'user/message') noteDelivered(sessionId, e.data?.id);
|
|
1099
|
+
})
|
|
1100
|
+
.catch(() => {}),
|
|
1101
|
+
);
|
|
1102
|
+
}
|
|
1103
|
+
return historyRead.get(sessionId);
|
|
1104
|
+
}
|
|
1105
|
+
const noteDelivered = (sessionId, id) => {
|
|
1106
|
+
if (!sessionId || typeof id !== 'string' || !id.startsWith(MESSAGE_PREFIX)) return;
|
|
1107
|
+
const set = deliveredIds.get(sessionId) ?? new Set();
|
|
1108
|
+
set.add(id);
|
|
1109
|
+
// Bounded: ids are only needed while a retry of the same request may come.
|
|
1110
|
+
if (set.size > 2000) set.delete(set.values().next().value);
|
|
1111
|
+
deliveredIds.set(sessionId, set);
|
|
1112
|
+
};
|
|
1113
|
+
/** An Agent's pending messages: Harness's `{nextTurn, nextStep}` (or a plain list). */
|
|
1114
|
+
const pendingOf = (agent) => {
|
|
1115
|
+
const inbox = agent?.inbox;
|
|
1116
|
+
if (Array.isArray(inbox)) return inbox;
|
|
1117
|
+
return [...(Array.isArray(inbox?.nextTurn) ? inbox.nextTurn : []), ...(Array.isArray(inbox?.nextStep) ? inbox.nextStep : [])];
|
|
1118
|
+
};
|
|
1119
|
+
const holds = (agent, id) => Boolean(deliveredIds.get(agent?.session?.id)?.has(id)) || pendingOf(agent).some((m) => m?.id === id);
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* Hand one message to an Agent.
|
|
1123
|
+
* - `mode`: 'steer' (the current turn's next step, or a new turn when idle: messages that arrive
|
|
1124
|
+
* while it works are taken together), 'followup' (a turn of its own; 0.7's only way) or 'inject'
|
|
1125
|
+
* (into the conversation without waking it). A Harness without `steer` gets a followup; one
|
|
1126
|
+
* without `inject` gets nothing for an 'inject' (`dropped`): such a note never wakes a turn.
|
|
1127
|
+
* - `key`: makes the message id `bots:<key>`; a message with that id already pending or delivered
|
|
1128
|
+
* is not delivered again, so a retried request is harmless.
|
|
1129
|
+
* @returns {{message: object, mode: string, skipped: boolean, dropped?: true}}
|
|
1130
|
+
*/
|
|
1131
|
+
async function sendTo(agent, { content: blocks, source, mode = 'followup', key }) {
|
|
1132
|
+
// Providers that take a message as one string join its blocks with nothing in between:
|
|
1133
|
+
// a header block ends its line itself, so the text under it starts on a new one.
|
|
1134
|
+
const content = blocks.map((b, i) => (i < blocks.length - 1 && b?.type === 'text' && !b.text.endsWith('\n') ? { ...b, text: `${b.text}\n` } : b));
|
|
1135
|
+
const message = key ? freezeMessage({ id: `${MESSAGE_PREFIX}${key}`, role: 'user', content, source }) : createUserMessage({ content, source });
|
|
1136
|
+
// A note that must not wake anyone is dropped where Harness cannot inject: it is "good to know", never worth a turn.
|
|
1137
|
+
if (mode === 'inject' && typeof agent.inject !== 'function') return { message, mode, skipped: true, dropped: true };
|
|
1138
|
+
if (key) await loadHistory(agent.session?.id);
|
|
1139
|
+
if (key && holds(agent, message.id)) return { message, mode, skipped: true };
|
|
1140
|
+
const how = mode === 'inject' ? 'inject' : mode !== 'followup' && typeof agent.steer === 'function' ? 'steer' : 'followup';
|
|
1141
|
+
agent[how](message);
|
|
1142
|
+
if (key) noteDelivered(agent.session?.id, message.id);
|
|
1143
|
+
await flush(agent);
|
|
1144
|
+
return { message, mode: how, skipped: false };
|
|
1145
|
+
}
|
|
1146
|
+
/** How a bot's home takes new input: a router steers (backlog is handled together), every other home as in 0.7. */
|
|
1147
|
+
const homeMode = (bot) => (isRouter(store.get(bot.id) ?? bot) ? 'steer' : 'followup');
|
|
1148
|
+
|
|
1149
|
+
/** A DM from `sender` (a bot, or null for the user) to `target`'s home: 0.7's bot-to-bot message. */
|
|
860
1150
|
async function deliver(sender, target, text, senderSessionId) {
|
|
861
1151
|
const body = String(text ?? '').trim();
|
|
862
1152
|
if (body === '') throw new Error('text must not be empty');
|
|
863
1153
|
if (sender && sender.id === target.id) throw new Error('a bot cannot message itself');
|
|
864
|
-
if (sender && !admitPair(sender.id, target.id)) throw
|
|
1154
|
+
if (sender && !admitPair(sender.id, target.id)) throw pairRefusal(sender, target);
|
|
865
1155
|
// A teammate's message may answer this bot's own question: only a long quiet starts a new topic here.
|
|
866
1156
|
await autoTopic(store.get(target.id) ?? target, sender ? 'dm' : 'user');
|
|
867
1157
|
const agent = await agentOf(store.get(target.id) ?? target);
|
|
868
|
-
|
|
1158
|
+
await sendTo(agent, {
|
|
869
1159
|
content: [
|
|
870
1160
|
{ type: 'text', text: dmHeader(sender) },
|
|
871
1161
|
{ type: 'text', text: dmBody(body, sender) },
|
|
872
1162
|
],
|
|
873
1163
|
source: senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' },
|
|
1164
|
+
mode: homeMode(target),
|
|
874
1165
|
});
|
|
875
|
-
agent.followup(message);
|
|
876
|
-
await flush(agent);
|
|
877
1166
|
store.log({ from: sender ? sender.id : 'user', to: target.id, text: body, kind: 'dm' });
|
|
878
1167
|
return agent.session.id;
|
|
879
1168
|
}
|
|
@@ -892,24 +1181,814 @@ export function apply(ctx, config, deps = {}) {
|
|
|
892
1181
|
if (!body) return sessionId;
|
|
893
1182
|
} else await autoTopic(store.get(target.id) ?? target, 'user');
|
|
894
1183
|
const agent = await agentOf(store.get(target.id) ?? target);
|
|
895
|
-
agent
|
|
896
|
-
await flush(agent);
|
|
1184
|
+
await sendTo(agent, { content: [{ type: 'text', text: body }], source: { kind: 'user' }, mode: homeMode(target) });
|
|
897
1185
|
return agent.session.id;
|
|
898
1186
|
}
|
|
899
1187
|
|
|
1188
|
+
// --- tickets: delegated work in Sessions of their own ---------------------------------
|
|
1189
|
+
/** What cards and relays read about the team and the tickets. */
|
|
1190
|
+
const cardCtx = () => ({ bots: store.list(), threads: tickets, tickets, stageOf });
|
|
1191
|
+
const handleOf = (botId) => (store.get(botId) ? `@${store.get(botId).handle}` : 'a removed bot');
|
|
1192
|
+
|
|
1193
|
+
/** A ticket as the panel lists it (PLAN-0.8 §6.3 `TicketRow`). */
|
|
1194
|
+
function ticketRow(t) {
|
|
1195
|
+
const last = t.reports.at(-1);
|
|
1196
|
+
return {
|
|
1197
|
+
id: t.id,
|
|
1198
|
+
title: t.title,
|
|
1199
|
+
botId: t.botId,
|
|
1200
|
+
stage: stageOf(t),
|
|
1201
|
+
requester: t.requester?.kind === 'session' && t.requester.botId ? { kind: 'bot', botId: t.requester.botId } : { kind: 'user' },
|
|
1202
|
+
...(t.origin?.via ? { via: t.origin.via } : {}),
|
|
1203
|
+
// Its conversation waits for the person's answer to a question (state `asks`): it needs you.
|
|
1204
|
+
...(askingIn(t.sessionId) ? { asking: true } : {}),
|
|
1205
|
+
// What its conversation does right now (lib/activity.mjs), while it runs.
|
|
1206
|
+
...(!t.ended && activity.get(t.sessionId) ? { activity: activity.get(t.sessionId) } : {}),
|
|
1207
|
+
createdAt: t.createdAt,
|
|
1208
|
+
updatedAt: t.updatedAt,
|
|
1209
|
+
...(last ? { lastReport: { status: last.status, preview: clip(String(last.text ?? '').trim(), PREVIEW_CHARS).text } } : {}),
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
const threadView = (key) => {
|
|
1213
|
+
const th = tickets.thread(key);
|
|
1214
|
+
const parsed = parseThreadKey(key);
|
|
1215
|
+
return { key, kind: th?.kind ?? parsed?.kind ?? '', label: th?.label ?? threadLabel(key) };
|
|
1216
|
+
};
|
|
1217
|
+
/** One ticket in full for the panel (`TicketView`): the row, the text, reports, Threads, runs with their cost. */
|
|
1218
|
+
function ticketView(t) {
|
|
1219
|
+
const overrides = settings.get().prices;
|
|
1220
|
+
const catalog = prices.peek();
|
|
1221
|
+
const running = [...openTasks.values()].map(({ log, size, replied, ...x }) => x);
|
|
1222
|
+
const use = ticketUsage({ calls: ledger.calls(), tasks: ledger.tasks(), running }, t.id, (m) => priceOf(m, overrides, catalog));
|
|
1223
|
+
return {
|
|
1224
|
+
...ticketRow(t),
|
|
1225
|
+
text: t.text,
|
|
1226
|
+
...(t.parentId ? { parentId: t.parentId } : {}),
|
|
1227
|
+
children: tickets.children(t.id).map((c) => c.id),
|
|
1228
|
+
requesterSessionId: t.requester?.sessionId ?? null,
|
|
1229
|
+
origin: t.origin ?? {},
|
|
1230
|
+
...(t.startedAt ? { startedAt: t.startedAt } : {}),
|
|
1231
|
+
...(t.ended ? { ended: t.ended } : {}),
|
|
1232
|
+
...(t.error ? { error: t.error } : {}),
|
|
1233
|
+
...(t.archivedAt ? { archivedAt: t.archivedAt } : {}),
|
|
1234
|
+
...(t.nudgedAt ? { nudgedAt: t.nudgedAt } : {}),
|
|
1235
|
+
...(t.stalledAt ? { stalledAt: t.stalledAt } : {}),
|
|
1236
|
+
...(t.retries ? { retries: t.retries } : {}),
|
|
1237
|
+
reports: t.reports.map((r) => ({ at: r.at, status: r.status, text: r.text })),
|
|
1238
|
+
threads: t.threads.map(threadView),
|
|
1239
|
+
runs: use.runs,
|
|
1240
|
+
usage: { tokens: use.tokens, calls: use.calls, cost: use.cost },
|
|
1241
|
+
sessionId: t.sessionId,
|
|
1242
|
+
running: Boolean(t.sessionId && agents()?.get?.(t.sessionId)?.status === 'running'),
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/** A Thread as a ticket subscribes to it: its key and label (`Slack · Acme #general · thread`). */
|
|
1247
|
+
const threadRecordOf = (o) => ({ key: o.threadKey, label: threadLabel(o) });
|
|
1248
|
+
/** A ticket's `origin` from one of the turn's Threads; `replyTo`: the chat message that started it, which its answer quotes. */
|
|
1249
|
+
const originFrom = (o) =>
|
|
1250
|
+
o.kind === 'panel'
|
|
1251
|
+
? { origin: { threadKey: o.threadKey, who: 'the user' }, thread: threadRecordOf(o) }
|
|
1252
|
+
: { origin: { threadKey: o.threadKey, via: o.kind, ...(o.who ? { who: o.who } : {}), ...(o.replyTo ? { replyTo: String(o.replyTo) } : {}) }, thread: threadRecordOf(o) };
|
|
1253
|
+
/** The choices a delegating call may name with `thread`, for an error. */
|
|
1254
|
+
const threadChoices = (list) => list.map((o) => `${o.threadKey} (${threadLabel(o)})`).join(', ');
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* Where the turn that is delegating now came from (PLAN-0.8 §4.3, §10 `origin`): its one chat
|
|
1258
|
+
* Thread (which the ticket then subscribes to); the Thread the call names with `thread` when the
|
|
1259
|
+
* turn has several; the panel conversation when only the panel spoke; no Thread at all for a
|
|
1260
|
+
* scheduled run without a chat, or several Threads and none named. A sub-ticket tells who it is
|
|
1261
|
+
* for but takes no Thread: follow-ups on it reach the parent.
|
|
1262
|
+
* @param {string} sessionId
|
|
1263
|
+
* @param {string} [chosen] - a Thread key of this turn the delegating call named
|
|
1264
|
+
*/
|
|
1265
|
+
function originOfTurn(sessionId, chosen) {
|
|
1266
|
+
const parent = ticketOf(sessionId);
|
|
1267
|
+
if (parent) {
|
|
1268
|
+
if (chosen) throw new Error('a sub-task takes no thread: follow-ups reach the task that asked for it; leave out `thread`');
|
|
1269
|
+
return { origin: { ...(parent.origin?.via ? { via: parent.origin.via } : {}), ...(parent.origin?.who ? { who: parent.origin.who } : {}) } };
|
|
1270
|
+
}
|
|
1271
|
+
const plan = channels.replyPlan(sessionId);
|
|
1272
|
+
if (chosen) {
|
|
1273
|
+
const key = toThreadKey(String(chosen).trim().replace(/^thread\//, ''));
|
|
1274
|
+
const hit = key ? plan.origins.find((o) => o.threadKey === key) : undefined;
|
|
1275
|
+
if (!hit) throw new Error(`\`thread\` must be one of this turn's threads: ${threadChoices(plan.origins) || 'none (this turn has no thread); leave it out'}`);
|
|
1276
|
+
return originFrom(hit);
|
|
1277
|
+
}
|
|
1278
|
+
if (plan.mode === 'thread') return originFrom(plan.target);
|
|
1279
|
+
if (plan.mode === 'choose') {
|
|
1280
|
+
// Several Threads and none named: the task belongs to none of them (its report reaches the requester only).
|
|
1281
|
+
const people = [...new Set(plan.origins.map((o) => o.who).filter(Boolean))];
|
|
1282
|
+
return { origin: { ...(people.length === 1 ? { who: people[0] } : { who: 'the user' }) } };
|
|
1283
|
+
}
|
|
1284
|
+
if (trigger.get(sessionId) === 'schedule') return { origin: { who: 'the user', via: 'schedule' } };
|
|
1285
|
+
return originFrom({ threadKey: panelThreadKey(sessionId), kind: 'panel' });
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* The Session a ticket works in: resolved when it exists, else made in the Bots workspace and
|
|
1290
|
+
* decorated as its bot. `info.created` says it had to be made.
|
|
1291
|
+
*/
|
|
1292
|
+
async function ticketAgent(t, info = {}) {
|
|
1293
|
+
const controller = service(ctx, 'sessionController');
|
|
1294
|
+
if (!controller) throw new Error('tasks need the Web profile (no session controller here)');
|
|
1295
|
+
const bot = store.get(t.botId);
|
|
1296
|
+
if (!bot) throw new Error('the bot of this task was removed');
|
|
1297
|
+
const wanted = t.sessionId ?? sessionIdOf(t.id);
|
|
1298
|
+
const archived = service(ctx, 'workspaceRegistry')?.archivedSessionIds ?? [];
|
|
1299
|
+
// Also when nothing is stored yet: a crash may have come between making the Session and recording it.
|
|
1300
|
+
if (!archived.includes(wanted)) {
|
|
1301
|
+
const found = await controller.resolveAgent(wanted).catch((error) => ({ error }));
|
|
1302
|
+
if (found && !('error' in found) && found.agent) {
|
|
1303
|
+
reconcile(found.agent);
|
|
1304
|
+
return found.agent;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
const wsId = await workspaceId().catch(() => undefined);
|
|
1308
|
+
// The Agent's creation already finds the ticket by the `ticket-<id>` name and installs the bot.
|
|
1309
|
+
const created = await controller.create({ sessionId: wanted, ...(wsId ? { workspaceId: wsId } : { cwd: workdir }) });
|
|
1310
|
+
info.created = true;
|
|
1311
|
+
const id = created?.sessionId ?? wanted;
|
|
1312
|
+
if (id !== wanted) {
|
|
1313
|
+
otherTicketSessions.add(id);
|
|
1314
|
+
tickets.patch(t.id, { sessionId: id });
|
|
1315
|
+
}
|
|
1316
|
+
let agent = agents()?.get?.(id);
|
|
1317
|
+
if (!agent) {
|
|
1318
|
+
const found = await controller.resolveAgent(id).catch((error) => ({ error }));
|
|
1319
|
+
if (!found || 'error' in found) throw found?.error ?? new Error('the task conversation did not start');
|
|
1320
|
+
agent = found.agent;
|
|
1321
|
+
}
|
|
1322
|
+
reconcile(agent);
|
|
1323
|
+
const title = t.title;
|
|
1324
|
+
try {
|
|
1325
|
+
const titles = service(ctx, 'sessionTitle');
|
|
1326
|
+
if (typeof titles?.rename === 'function') titles.rename(agent.session, title);
|
|
1327
|
+
else await controller.rename?.({ sessionId: id, title });
|
|
1328
|
+
} catch {
|
|
1329
|
+
// A title is cosmetic.
|
|
1330
|
+
}
|
|
1331
|
+
if (bot.model) {
|
|
1332
|
+
try {
|
|
1333
|
+
agent.model?.select?.(selectionOf(bot.model));
|
|
1334
|
+
} catch {
|
|
1335
|
+
// The default model stays.
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
return agent;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
/** How a ticket's requester appears as a message source in the worker's Session. */
|
|
1342
|
+
const sourceFrom = (requester) => (requester?.kind === 'session' && requester.sessionId ? { kind: 'agent-message', form: 'relay', senderSessionId: requester.sessionId } : { kind: 'user' });
|
|
1343
|
+
|
|
1344
|
+
/** Failures of tickets the caller is opening right now: its tool result says so, no notice is sent. */
|
|
1345
|
+
const quietFailures = new Set();
|
|
1346
|
+
|
|
1347
|
+
/**
|
|
1348
|
+
* Start a queued ticket that holds a slot: its Session, then the assignment as the first message.
|
|
1349
|
+
* One ended while its Session was being made (a person stopped it) does not start, and frees the slot.
|
|
1350
|
+
*/
|
|
1351
|
+
async function launch(t) {
|
|
1352
|
+
try {
|
|
1353
|
+
const agent = await ticketAgent(t);
|
|
1354
|
+
const now = tickets.get(t.id);
|
|
1355
|
+
if (!now || now.ended || now.startedAt) {
|
|
1356
|
+
// Its Session stays known to it, so upkeep archives it with the ticket.
|
|
1357
|
+
if (now && !now.startedAt && !now.sessionId) tickets.patch(now.id, { sessionId: agent.session.id });
|
|
1358
|
+
if (!now?.startedAt) slots.release(t.id);
|
|
1359
|
+
return false;
|
|
1360
|
+
}
|
|
1361
|
+
const started = tickets.start(t.id, { sessionId: agent.session.id });
|
|
1362
|
+
await sendTo(agent, { content: [{ type: 'text', text: assignmentText(started, cardCtx()) }], source: sourceFrom(started.requester), mode: 'steer', key: `assign:${t.id}` });
|
|
1363
|
+
return true;
|
|
1364
|
+
} catch (error) {
|
|
1365
|
+
const reason = String(error?.message ?? error);
|
|
1366
|
+
ctx.logger?.warn?.(`bots: task ${t.id} for ${handleOf(t.botId)} did not start: ${reason}`);
|
|
1367
|
+
slots.release(t.id);
|
|
1368
|
+
// Stopped while it was starting: it stays as the person left it.
|
|
1369
|
+
if (tickets.get(t.id)?.ended) return false;
|
|
1370
|
+
const failed = tickets.end(t.id, { by: 'system', outcome: 'failed', error: `did not start: ${reason}` });
|
|
1371
|
+
if (failed && !quietFailures.has(t.id)) void notifyRequester(failed, `[Failed] Task ${t.id} (${handleOf(t.botId)}: ${t.title}) could not start: ${reason}`, { key: `failed:${t.id}:${failed.ended.at}` });
|
|
1372
|
+
return false;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
/**
|
|
1377
|
+
* Hand a message to a started ticket's Session once it holds a worker slot: at once when it has one
|
|
1378
|
+
* or one is free (`human`: a person's message may take the extra slot), else parked on the ticket
|
|
1379
|
+
* (`parked`, kept in tickets.json, so it outlasts a restart) for the pump to deliver in order when a
|
|
1380
|
+
* slot frees. Messages already parked go first. Returns `{parked}`.
|
|
1381
|
+
*/
|
|
1382
|
+
async function toTicket(t, { content, source, key, human = false }) {
|
|
1383
|
+
const waiting = parkedOf(tickets.get(t.id) ?? t);
|
|
1384
|
+
if (waiting.some((m) => m.key === key)) return { parked: true };
|
|
1385
|
+
if (waiting.length === 0 && slots.acquire(t.id, { human })) {
|
|
1386
|
+
const agent = await ticketAgent(t);
|
|
1387
|
+
await sendTo(agent, { content, source, mode: 'steer', key });
|
|
1388
|
+
return { parked: false };
|
|
1389
|
+
}
|
|
1390
|
+
tickets.patch(t.id, { parked: [...waiting, { key, content, source, at: nowMs(), ...(human ? { human: true } : {}) }] });
|
|
1391
|
+
void pump();
|
|
1392
|
+
return { parked: true };
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/** Deliver the messages parked on a ticket that now holds a slot, oldest first; stops if it ends meanwhile. */
|
|
1396
|
+
async function deliverParked(t) {
|
|
1397
|
+
try {
|
|
1398
|
+
const agent = await ticketAgent(t);
|
|
1399
|
+
for (;;) {
|
|
1400
|
+
const cur = tickets.get(t.id);
|
|
1401
|
+
const [next, ...rest] = parkedOf(cur);
|
|
1402
|
+
if (!cur || cur.ended || !next) break;
|
|
1403
|
+
await sendTo(agent, { content: next.content, source: next.source, mode: 'steer', key: next.key });
|
|
1404
|
+
tickets.patch(cur.id, { parked: rest.length ? rest : undefined });
|
|
1405
|
+
}
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
ctx.logger?.warn?.(`bots: messages for task ${t.id} wait for the next try: ${error?.message ?? error}`);
|
|
1408
|
+
slots.release(t.id);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
let pumping = null;
|
|
1413
|
+
let pumpAgain = false;
|
|
1414
|
+
/**
|
|
1415
|
+
* While slots are free, oldest first: launch queued tickets, and hand started ones the messages parked
|
|
1416
|
+
* for them. A full pass still lets a person's parked message take the extra slot.
|
|
1417
|
+
*/
|
|
1418
|
+
function pump() {
|
|
1419
|
+
if (pumping) {
|
|
1420
|
+
pumpAgain = true;
|
|
1421
|
+
return pumping;
|
|
1422
|
+
}
|
|
1423
|
+
pumping = (async () => {
|
|
1424
|
+
do {
|
|
1425
|
+
pumpAgain = false;
|
|
1426
|
+
// No Session controller (yet, or in this profile): queued tickets wait for the next pump.
|
|
1427
|
+
if (!service(ctx, 'sessionController')) break;
|
|
1428
|
+
let full = false;
|
|
1429
|
+
for (const listed of tickets.open()) {
|
|
1430
|
+
// Read again: an earlier launch awaited, and a person may have stopped this one meanwhile.
|
|
1431
|
+
const t = tickets.get(listed.id);
|
|
1432
|
+
if (!t || t.ended) continue;
|
|
1433
|
+
const waiting = parkedOf(t);
|
|
1434
|
+
if (t.startedAt && waiting.length === 0) continue;
|
|
1435
|
+
if (!t.startedAt && !store.get(t.botId)) {
|
|
1436
|
+
tickets.end(t.id, { by: 'system', outcome: 'stopped', error: 'the bot was removed' });
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
const human = waiting.some((m) => m.human);
|
|
1440
|
+
if (full && !human) continue;
|
|
1441
|
+
if (!slots.acquire(t.id, { human })) {
|
|
1442
|
+
if (!human) full = true;
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
if (t.startedAt) await deliverParked(t);
|
|
1446
|
+
else await launch(t);
|
|
1447
|
+
}
|
|
1448
|
+
} while (pumpAgain);
|
|
1449
|
+
})().finally(() => {
|
|
1450
|
+
pumping = null;
|
|
1451
|
+
});
|
|
1452
|
+
return pumping;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
/** The Agent of whoever asked for a ticket: a parent ticket's Session, or a bot's current home. */
|
|
1456
|
+
async function requesterAgent(t) {
|
|
1457
|
+
const r = t.requester ?? {};
|
|
1458
|
+
if (r.kind !== 'session' || !r.sessionId) return null;
|
|
1459
|
+
const controller = service(ctx, 'sessionController');
|
|
1460
|
+
// An archived conversation (a removed bot's, an old topic's) is nobody's to wake.
|
|
1461
|
+
const archived = service(ctx, 'workspaceRegistry')?.archivedSessionIds ?? [];
|
|
1462
|
+
const resolveId = async (id) => {
|
|
1463
|
+
const found = id && !archived.includes(id) ? await controller?.resolveAgent?.(id).catch((error) => ({ error })) : null;
|
|
1464
|
+
return found && !('error' in found) ? found.agent : null;
|
|
1465
|
+
};
|
|
1466
|
+
if (r.ticketId) {
|
|
1467
|
+
const parent = tickets.get(r.ticketId);
|
|
1468
|
+
if (!parent || parent.archivedAt) return null;
|
|
1469
|
+
return resolveId(parent.sessionId ?? r.sessionId);
|
|
1470
|
+
}
|
|
1471
|
+
const bot = r.botId ? store.get(r.botId) : undefined;
|
|
1472
|
+
// The asking bot may have started a new topic since: its report goes to the conversation it has now.
|
|
1473
|
+
if (bot && bot.sessionId !== r.sessionId) return agentOf(bot);
|
|
1474
|
+
return (await resolveId(r.sessionId)) ?? (bot ? agentOf(bot) : null);
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
/** A notice for the requester's Session (steered; `inject` for one that need not wake it). */
|
|
1478
|
+
async function notifyRequester(t, text, { key, mode = 'steer' } = {}) {
|
|
1479
|
+
try {
|
|
1480
|
+
const agent = await requesterAgent(t);
|
|
1481
|
+
if (!agent) return false;
|
|
1482
|
+
await sendTo(agent, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay', ...(t.sessionId ? { senderSessionId: t.sessionId } : {}) }, mode, key });
|
|
1483
|
+
return true;
|
|
1484
|
+
} catch (error) {
|
|
1485
|
+
ctx.logger?.warn?.(`bots: a notice about task ${t.id} did not reach its requester: ${error?.message ?? error}`);
|
|
1486
|
+
return false;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* A ticket ended (done, stopped, failed; by anyone): its slot frees for the next queued one, and
|
|
1492
|
+
* its bot's memory summary runs now, or after the run still being recorded in its Session.
|
|
1493
|
+
*/
|
|
1494
|
+
function ticketEnded(t) {
|
|
1495
|
+
slots.release(t.id);
|
|
1496
|
+
// Messages still waiting for a slot were for work that is over now.
|
|
1497
|
+
if (parkedOf(t).length) tickets.patch(t.id, { parked: undefined });
|
|
1498
|
+
void pump();
|
|
1499
|
+
if (!(t.sessionId && openTasks.has(t.sessionId))) reflectTicket(t);
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
/** Who may add to a ticket from `sessionId`: its requester (or the requesting bot from its current home), or the router. */
|
|
1503
|
+
function mayAppend(t, sender, sessionId) {
|
|
1504
|
+
const r = t.requester ?? {};
|
|
1505
|
+
if (r.sessionId === sessionId) return true;
|
|
1506
|
+
if (sender && r.botId === sender.id && !r.ticketId && sender.sessionId === sessionId) return true;
|
|
1507
|
+
return Boolean(sender) && isRouterHome(sender, sessionId);
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/**
|
|
1511
|
+
* Add a message to a ticket: from its requester (a bot), or from a person (`human`: the panel, or a
|
|
1512
|
+
* follow-up on one of its chat Threads, which brings its `header` line and `chat` details for the
|
|
1513
|
+
* timeline, and a delivery `key`). An ended ticket is opened again unless it is archived, or a
|
|
1514
|
+
* person stopped it and this is not a person asking (`force`). A ticket still queued keeps the
|
|
1515
|
+
* text for its assignment. A started one gets it once it holds a worker slot (a person's message may
|
|
1516
|
+
* take the extra one); until then it waits on the ticket. A message whose `key` was delivered (or
|
|
1517
|
+
* parked) already changes nothing: a replay after a restart neither reopens nor wakes the ticket.
|
|
1518
|
+
*/
|
|
1519
|
+
async function appendToTicket(t, text, { sender = null, senderSessionId = '', human = false, force = false, header = '', chat = null, key = '' } = {}) {
|
|
1520
|
+
const body = String(text ?? '').trim();
|
|
1521
|
+
if (body === '') throw new Error('text must not be empty');
|
|
1522
|
+
if (t.archivedAt) throw new Error(`task ${t.id} is archived; open a new task instead`);
|
|
1523
|
+
if (key && t.sessionId) {
|
|
1524
|
+
await loadHistory(t.sessionId);
|
|
1525
|
+
const live = agents()?.get?.(t.sessionId) ?? { session: { id: t.sessionId } };
|
|
1526
|
+
if (holds(live, `${MESSAGE_PREFIX}${key}`) || parkedOf(tickets.get(t.id) ?? t).some((m) => m.key === key)) return tickets.get(t.id) ?? t;
|
|
1527
|
+
}
|
|
1528
|
+
if (sender && t.botId !== sender.id) {
|
|
1529
|
+
const target = store.get(t.botId);
|
|
1530
|
+
if (target && !admitPair(sender.id, target.id)) throw pairRefusal(sender, target);
|
|
1531
|
+
}
|
|
1532
|
+
let cur = t;
|
|
1533
|
+
if (cur.ended) {
|
|
1534
|
+
const back = tickets.resume(cur.id, { force });
|
|
1535
|
+
if (back === null) throw new Error(`task ${t.id} was stopped by the user; it stays stopped (open a new task if the work is still wanted)`);
|
|
1536
|
+
cur = back ?? cur;
|
|
1537
|
+
}
|
|
1538
|
+
cur = tickets.touch(cur.id, human ? { human: true } : { requester: true }) ?? cur;
|
|
1539
|
+
const who = sender ? `@${sender.handle} (${sender.name})` : 'the user';
|
|
1540
|
+
if (!cur.startedAt) {
|
|
1541
|
+
cur = tickets.patch(cur.id, { text: `${cur.text}\n\n--- Added by ${who} ---\n${body}` }) ?? cur;
|
|
1542
|
+
void pump();
|
|
1543
|
+
return cur;
|
|
1544
|
+
}
|
|
1545
|
+
const content = sender
|
|
1546
|
+
? [
|
|
1547
|
+
{ type: 'text', text: `Bot message from ${who} about task ${cur.id}:` },
|
|
1548
|
+
{ type: 'text', text: `${body}\n\n(Answer in a report: bot_send_message with a status, without "to".)` },
|
|
1549
|
+
]
|
|
1550
|
+
: header
|
|
1551
|
+
? [
|
|
1552
|
+
{ type: 'text', text: header },
|
|
1553
|
+
{ type: 'text', text: body },
|
|
1554
|
+
]
|
|
1555
|
+
: [{ type: 'text', text: body }];
|
|
1556
|
+
// A person's follow-up may take the extra slot (new work cannot crowd it out); a bot's may not.
|
|
1557
|
+
await toTicket(cur, { content, source: sender && senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' }, key: key || `msg:${cur.id}:${randomUUID()}`, human: human && !sender });
|
|
1558
|
+
store.log(
|
|
1559
|
+
chat
|
|
1560
|
+
? { from: 'user', to: cur.botId, text: body, kind: 'user', via: chat.kind, ...(chat.who ? { who: chat.who } : {}), ...(chat.threadKey ? { thread: chat.threadKey } : {}), ticket: cur.id }
|
|
1561
|
+
: { from: sender ? sender.id : 'user', to: cur.botId, text: body, kind: 'dm', ticket: cur.id },
|
|
1562
|
+
);
|
|
1563
|
+
return tickets.get(cur.id) ?? cur;
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* Open a ticket for `target`, asked from `senderSessionId` (a bot's home or a ticket Session),
|
|
1568
|
+
* and start it when a slot is free. Returns the ticket; a start that failed shows as stage `failed`.
|
|
1569
|
+
*/
|
|
1570
|
+
async function openTicket(sender, target, text, senderSessionId, { title, thread: chosen } = {}) {
|
|
1571
|
+
const body = String(text ?? '').trim();
|
|
1572
|
+
if (body === '') throw new Error('text must not be empty');
|
|
1573
|
+
if (sender.id === target.id) throw new Error('a bot cannot message itself');
|
|
1574
|
+
if (!service(ctx, 'sessionController')) throw new Error('tasks need the Web profile (no session controller here)');
|
|
1575
|
+
const parent = ticketOf(senderSessionId);
|
|
1576
|
+
const { origin, thread } = originOfTurn(senderSessionId, chosen);
|
|
1577
|
+
if (!admitPair(sender.id, target.id)) throw pairRefusal(sender, target);
|
|
1578
|
+
const t = tickets.create({
|
|
1579
|
+
title,
|
|
1580
|
+
text: body,
|
|
1581
|
+
botId: target.id,
|
|
1582
|
+
requester: { kind: 'session', sessionId: senderSessionId, botId: sender.id, ...(parent ? { ticketId: parent.id } : {}) },
|
|
1583
|
+
origin,
|
|
1584
|
+
threads: thread ? [thread] : [],
|
|
1585
|
+
});
|
|
1586
|
+
store.log({ from: sender.id, to: target.id, text: body, kind: 'dm', ticket: t.id });
|
|
1587
|
+
quietFailures.add(t.id);
|
|
1588
|
+
try {
|
|
1589
|
+
await pump();
|
|
1590
|
+
} finally {
|
|
1591
|
+
quietFailures.delete(t.id);
|
|
1592
|
+
}
|
|
1593
|
+
return tickets.get(t.id) ?? t;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
/** A worker reports on its ticket. `progress` is only recorded; the rest reach the requester. */
|
|
1597
|
+
async function reportTicket(t, status, text) {
|
|
1598
|
+
if (!REPORT_STATUSES.includes(status)) throw new Error('a report to whoever asked needs a status: progress, done, blocked or question');
|
|
1599
|
+
const body = String(text ?? '').trim();
|
|
1600
|
+
if (body === '') throw new Error('text must not be empty');
|
|
1601
|
+
if (t.archivedAt) throw new Error(`task ${t.id} is archived; nobody reads reports on it`);
|
|
1602
|
+
const wasOpen = !t.ended;
|
|
1603
|
+
const next = tickets.addReport(t.id, { status, text: body });
|
|
1604
|
+
const index = next.reports.length - 1;
|
|
1605
|
+
const report = next.reports[index];
|
|
1606
|
+
let relayed = false;
|
|
1607
|
+
// An ended task's late words, or a sub-task's report to a task that has ended since, wake no one:
|
|
1608
|
+
// they are kept on the task (its reports) and the panel shows them.
|
|
1609
|
+
const parent = next.requester?.ticketId ? tickets.get(next.requester.ticketId) : undefined;
|
|
1610
|
+
const unread = !wasOpen ? 'ended' : next.requester?.ticketId && (!parent || parent.ended) ? 'parent' : '';
|
|
1611
|
+
if (status !== 'progress' && !unread) {
|
|
1612
|
+
store.log({ from: next.botId, to: next.requester?.botId ?? 'user', text: body, kind: 'dm', ticket: next.id, status });
|
|
1613
|
+
// A ticket the user asked for has no Session to tell: the panel shows it (attention).
|
|
1614
|
+
if (next.requester?.kind === 'session') {
|
|
1615
|
+
// The requester's turn takes this ticket's origin Thread as an input when the relay arrives in it
|
|
1616
|
+
// (its `user/message`, see RELAY_KINDS below), not here: a turn ending in between would lose it.
|
|
1617
|
+
relayed = await notifyRequester(next, reportRelayText(next, report, cardCtx()), { key: `report:${next.id}:${index}:${report.at}` });
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
if (status === 'done' && wasOpen) ticketEnded(next);
|
|
1621
|
+
return { ticket: next, relayed, ...(unread ? { unread, ...(parent ? { parent: parent.id } : {}) } : {}) };
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
/** A person (the panel) or the requester ends a ticket (stop, or close as done); either cancels its running turn. */
|
|
1625
|
+
function endTicket(t, { by, outcome, error }) {
|
|
1626
|
+
const wasOpen = !t.ended;
|
|
1627
|
+
const next = tickets.end(t.id, { by, outcome, ...(error ? { error } : {}) });
|
|
1628
|
+
if (next.sessionId) {
|
|
1629
|
+
try {
|
|
1630
|
+
agents()?.get?.(next.sessionId)?.cancel?.(by === 'user' ? { kind: 'user' } : { kind: 'hook', reason: `bots: task ${t.id} ${outcome === 'done' ? 'closed' : 'stopped'}` });
|
|
1631
|
+
} catch {
|
|
1632
|
+
// Nothing running.
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (wasOpen) ticketEnded(next);
|
|
1636
|
+
else slots.release(next.id);
|
|
1637
|
+
// The requester learns of it next time it works; it need not wake for it.
|
|
1638
|
+
if (by === 'user' && next.requester?.kind === 'session') {
|
|
1639
|
+
void notifyRequester(next, `[${outcome === 'done' ? 'Closed' : 'Stopped'}] The user ${outcome === 'done' ? 'closed' : 'stopped'} task ${next.id} (${handleOf(next.botId)}: ${next.title}).`, { mode: 'inject', key: `ended:${next.id}:${next.ended.at}` });
|
|
1640
|
+
}
|
|
1641
|
+
return next;
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/**
|
|
1645
|
+
* A retry: open the ticket again and hand the assignment over afresh. From the panel (`by`
|
|
1646
|
+
* 'user', even one the user stopped), or from the requester (`sender`, a bot, with its Session);
|
|
1647
|
+
* a requester cannot retry a ticket the user stopped.
|
|
1648
|
+
*/
|
|
1649
|
+
async function retryTicket(t, { sender = null, senderSessionId = '' } = {}) {
|
|
1650
|
+
const back = tickets.resume(t.id, { force: !sender });
|
|
1651
|
+
if (back === null && sender && !t.archivedAt) throw new Error(`task ${t.id} was stopped by the user; it stays stopped (open a new task if the work is still wanted)`);
|
|
1652
|
+
if (!back) throw new Error(`task ${t.id} is archived; open a new task instead`);
|
|
1653
|
+
tickets.touch(back.id, sender ? { requester: true } : { human: true });
|
|
1654
|
+
if (!back.startedAt) {
|
|
1655
|
+
await pump();
|
|
1656
|
+
return tickets.get(back.id) ?? back;
|
|
1657
|
+
}
|
|
1658
|
+
const who = sender ? `@${sender.handle}` : 'The user';
|
|
1659
|
+
const note = `[Retry] ${who} asked you to take task ${back.id} up again. Check what is already done before you repeat anything, then go on and report as usual.\n\n${assignmentText(back, cardCtx())}`;
|
|
1660
|
+
const source = sender && senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' };
|
|
1661
|
+
// A person's retry may take the extra slot; the requester's waits for a free one like new work.
|
|
1662
|
+
await toTicket(back, { content: [{ type: 'text', text: note }], source, key: `retry:${back.id}:${back.updatedAt}`, human: !sender });
|
|
1663
|
+
return tickets.get(back.id) ?? back;
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
/** A ticket Session went idle: a ticket that waits on others (question, blocked, stalled) gives its slot back. */
|
|
1667
|
+
function ticketIdle(t) {
|
|
1668
|
+
if (!t || t.ended) return;
|
|
1669
|
+
const stage = stageOf(t);
|
|
1670
|
+
if ((stage === 'question' || stage === 'failed' || stage === 'stalled') && slots.release(t.id)) void pump();
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
// --- the task watchdog (PLAN-0.8 §4.5): deterministic rules from lib/watchdog.mjs ---------------
|
|
1674
|
+
const agentStatusOf = (sessionId) => (sessionId && agents()?.get?.(sessionId)?.status === 'running' ? 'running' : 'idle');
|
|
1675
|
+
|
|
1676
|
+
/**
|
|
1677
|
+
* What keeps a ticket Session busy in the background: its shell jobs still running (Harness
|
|
1678
|
+
* `jobs.list`) and its subagents still running (`subagents.listChildren`, or `listDescendants` as
|
|
1679
|
+
* Harness 0.2.2 has it). Nothing is waited for; a service that is missing counts nothing.
|
|
1680
|
+
*/
|
|
1681
|
+
async function backgroundOf(sessionId) {
|
|
1682
|
+
let n = 0;
|
|
1683
|
+
const jobs = service(ctx, 'jobs');
|
|
1684
|
+
try {
|
|
1685
|
+
if (typeof jobs?.list === 'function') n += (jobs.list(sessionId) ?? []).filter((j) => j?.owner === sessionId && (j.status === 'running' || j.status === 'stopping')).length;
|
|
1686
|
+
} catch {
|
|
1687
|
+
// No job registry view for this Session.
|
|
1688
|
+
}
|
|
1689
|
+
const subagents = service(ctx, 'subagents');
|
|
1690
|
+
try {
|
|
1691
|
+
const list = typeof subagents?.listChildren === 'function' ? subagents.listChildren.bind(subagents) : typeof subagents?.listDescendants === 'function' ? subagents.listDescendants.bind(subagents) : null;
|
|
1692
|
+
if (list) n += ((await list(sessionId, AbortSignal.timeout(5000))) ?? []).filter((c) => c && c.kind !== 'diagnostic' && c.activity === 'running').length;
|
|
1693
|
+
} catch {
|
|
1694
|
+
// A catalog that cannot be read counts nothing.
|
|
1695
|
+
}
|
|
1696
|
+
return n;
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
/** The time a bot's home last spoke to a person (a reply in the timeline), for reminders. */
|
|
1700
|
+
function lastReplyAt(botId) {
|
|
1701
|
+
const rows = store.messages({ bot: botId, limit: 2000 });
|
|
1702
|
+
// Plain text that reached no chat (`notSent`: the turn had several) told nobody.
|
|
1703
|
+
for (let i = rows.length - 1; i >= 0; i -= 1) if (rows[i].from === botId && rows[i].kind === 'reply' && !rows[i].notSent) return Number(rows[i].at) || 0;
|
|
1704
|
+
return 0;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
/** One watchdog pass (the 5-minute sweep): status checks, stalls, and reminders for requesters with nothing left to wait for. */
|
|
1708
|
+
async function watch(now = nowMs()) {
|
|
1709
|
+
const stallMinutes = settings.get().tickets.stallMinutes;
|
|
1710
|
+
const open = tickets.open();
|
|
1711
|
+
const items = [];
|
|
1712
|
+
for (const t of open) {
|
|
1713
|
+
// A ticket whose messages wait for a slot is `queued`: it is not judged until it has one. One
|
|
1714
|
+
// waiting for the person's answer to its question is not quiet either.
|
|
1715
|
+
const stage = stageOf(t);
|
|
1716
|
+
if (stage !== 'working' || askingIn(t.sessionId)) continue;
|
|
1717
|
+
const status = agentStatusOf(t.sessionId);
|
|
1718
|
+
// A sub-task still working (or waiting for a slot) is this ticket's background work too: it waits for its report.
|
|
1719
|
+
const children = tickets.children(t.id).filter((c) => ['working', 'queued'].includes(stageOf(c))).length;
|
|
1720
|
+
items.push({ ticket: t, stage, agentStatus: status, backgroundJobs: status === 'idle' ? children + (t.sessionId ? await backgroundOf(t.sessionId) : 0) : 0 });
|
|
1721
|
+
}
|
|
1722
|
+
for (const action of checkTickets(items, { stallMinutes }, now)) {
|
|
1723
|
+
const t = tickets.get(action.ticketId);
|
|
1724
|
+
if (!t || t.ended) continue;
|
|
1725
|
+
try {
|
|
1726
|
+
if (action.kind === 'nudge') {
|
|
1727
|
+
tickets.patch(t.id, { nudgedAt: now });
|
|
1728
|
+
await toTicket(t, { content: [{ type: 'text', text: nudgeText(t) }], source: sourceFrom(t.requester), key: `nudge:${t.id}:${now}` });
|
|
1729
|
+
} else {
|
|
1730
|
+
const stalled = tickets.patch(t.id, { stalledAt: now });
|
|
1731
|
+
store.log({ from: t.botId, to: t.requester?.botId ?? 'user', text: `Task ${t.id} stalled: no report after a status check.`, kind: 'dm', ticket: t.id, status: 'stalled' });
|
|
1732
|
+
if (slots.release(t.id)) void pump();
|
|
1733
|
+
// A ticket the user asked for has no Session to tell: the panel shows it (attention).
|
|
1734
|
+
if (stalled.requester?.kind === 'session') await notifyRequester(stalled, stalledNoticeText(stalled, cardCtx()), { key: `stalled:${t.id}:${now}` });
|
|
1735
|
+
}
|
|
1736
|
+
} catch (error) {
|
|
1737
|
+
ctx.logger?.warn?.(`bots: watchdog on task ${t.id}: ${error?.message ?? error}`);
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
// Requesters whose every task settled and who have said nothing since: one reminder per batch.
|
|
1741
|
+
const all = tickets.list({ archived: false });
|
|
1742
|
+
const facts = (sessionId) => {
|
|
1743
|
+
const asTicket = ticketOf(sessionId);
|
|
1744
|
+
// A task that has ended asks nothing more of anyone: it is not reminded.
|
|
1745
|
+
if (asTicket?.ended) return { status: 'idle', ended: true };
|
|
1746
|
+
const bot = botOfSession(sessionId);
|
|
1747
|
+
const mine = all.filter((x) => x.requester?.sessionId === sessionId);
|
|
1748
|
+
const remindedAt = Math.max(0, ...mine.map((x) => Number(x.remindedAt) || 0));
|
|
1749
|
+
const reportedAt = asTicket ? Number(asTicket.reports.at(-1)?.at) || 0 : bot ? lastReplyAt(bot.id) : 0;
|
|
1750
|
+
return { status: agents()?.get?.(sessionId) ? agentStatusOf(sessionId) : 'offline', reportedAt, remindedAt };
|
|
1751
|
+
};
|
|
1752
|
+
for (const r of requesterReminders(all.map((t) => ({ ticket: t, stage: stageOf(t) })), facts, now)) {
|
|
1753
|
+
const list = r.ticketIds.map((id) => tickets.get(id)).filter(Boolean);
|
|
1754
|
+
if (!list.length) continue;
|
|
1755
|
+
try {
|
|
1756
|
+
const key = `remind:${r.sessionId}:${now}`;
|
|
1757
|
+
reminded.set(`${MESSAGE_PREFIX}${key}`, list.map((t) => t.id));
|
|
1758
|
+
if (reminded.size > 200) reminded.delete(reminded.keys().next().value);
|
|
1759
|
+
if (await notifyRequester(list[0], reminderText(list, cardCtx()), { key })) {
|
|
1760
|
+
for (const t of list) tickets.patch(t.id, { remindedAt: now });
|
|
1761
|
+
}
|
|
1762
|
+
} catch (error) {
|
|
1763
|
+
ctx.logger?.warn?.(`bots: reminder for ${r.sessionId}: ${error?.message ?? error}`);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
/** ticketId → the pending "continue" after a temporary error. Cleared on dispose. */
|
|
1769
|
+
const retryTimers = new Map();
|
|
1770
|
+
ctx.effect(() => () => {
|
|
1771
|
+
for (const timer of retryTimers.values()) clearTimer(timer);
|
|
1772
|
+
retryTimers.clear();
|
|
1773
|
+
}, 'bots: task retry timers');
|
|
1774
|
+
|
|
1775
|
+
/**
|
|
1776
|
+
* A ticket Session's turn failed (`agent/error`). A temporary error (HTTP 408, 429, 5xx, a dropped
|
|
1777
|
+
* connection) gets a "continue" after 15, 30 and 60 s; then, or for any other error, the ticket
|
|
1778
|
+
* fails and its requester hears of it.
|
|
1779
|
+
*/
|
|
1780
|
+
function ticketError(t, error) {
|
|
1781
|
+
if (!t || t.ended || retryTimers.has(t.id)) return;
|
|
1782
|
+
if (error?.name === 'AbortError') return; // stopped on purpose (Harness reports no cancellation here anyway)
|
|
1783
|
+
// A model failure is an `LlmError` whose `failure` holds the facts (`status`, `message`, `code`).
|
|
1784
|
+
const facts = error?.failure && typeof error.failure === 'object' ? error.failure : error;
|
|
1785
|
+
const reason = String(facts?.message ?? error?.message ?? error?.error?.message ?? (typeof error === 'string' ? error : '') ?? '').trim() || 'the model call failed';
|
|
1786
|
+
const delay = isTransient(facts) || isTransient(error) ? retryDelay(t.retries) : undefined;
|
|
1787
|
+
if (delay !== undefined) {
|
|
1788
|
+
const attempt = (t.retries ?? 0) + 1;
|
|
1789
|
+
const timer = setTimer(() => {
|
|
1790
|
+
retryTimers.delete(t.id);
|
|
1791
|
+
const cur = tickets.get(t.id);
|
|
1792
|
+
if (!cur || cur.ended || agentStatusOf(cur.sessionId) === 'running') return;
|
|
1793
|
+
tickets.patch(cur.id, { retries: attempt, error: reason });
|
|
1794
|
+
void toTicket(cur, { content: [{ type: 'text', text: retryText(cur, { attempt, error: reason }) }], source: sourceFrom(cur.requester), key: `continue:${cur.id}:${attempt}:${nowMs()}` }).catch((e) =>
|
|
1795
|
+
ctx.logger?.warn?.(`bots: retrying task ${cur.id}: ${e?.message ?? e}`),
|
|
1796
|
+
);
|
|
1797
|
+
}, delay);
|
|
1798
|
+
timer?.unref?.();
|
|
1799
|
+
retryTimers.set(t.id, timer);
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
const failed = tickets.end(t.id, { by: 'system', outcome: 'failed', error: reason });
|
|
1803
|
+
if (!failed) return;
|
|
1804
|
+
store.log({ from: failed.botId, to: failed.requester?.botId ?? 'user', text: `Task ${failed.id} failed: ${reason}`, kind: 'dm', ticket: failed.id, status: 'failed' });
|
|
1805
|
+
ticketEnded(failed);
|
|
1806
|
+
if (failed.requester?.kind === 'session') void notifyRequester(failed, failedNoticeText(failed, cardCtx()), { key: `failed:${failed.id}:${failed.ended.at}` });
|
|
1807
|
+
}
|
|
1808
|
+
ctx.on('agent/error', (payload) => {
|
|
1809
|
+
try {
|
|
1810
|
+
ticketError(ticketOf(payload?.agent?.session?.id), payload?.error);
|
|
1811
|
+
} catch (error) {
|
|
1812
|
+
ctx.logger?.warn?.(`bots: a task error: ${error?.message ?? error}`);
|
|
1813
|
+
}
|
|
1814
|
+
});
|
|
1815
|
+
// A ticket's background jobs starting or ending are events of that ticket (the watchdog's clock).
|
|
1816
|
+
ctx.inject?.(['jobs'], (scope) => {
|
|
1817
|
+
const jobs = scope?.jobs ?? service(scope, 'jobs');
|
|
1818
|
+
if (typeof jobs?.events?.subscribe !== 'function') return;
|
|
1819
|
+
const off = jobs.events.subscribe({ owners: 'all' }, (event) => {
|
|
1820
|
+
const owner = event?.job?.owner ?? event?.owner;
|
|
1821
|
+
const t = owner ? ticketOf(owner) : undefined;
|
|
1822
|
+
if (t && (event.type === 'registered' || event.type === 'settled')) tickets.touch(t.id);
|
|
1823
|
+
});
|
|
1824
|
+
if (typeof off !== 'function') return;
|
|
1825
|
+
if (typeof scope.effect === 'function') scope.effect(() => off, 'bots: task background jobs');
|
|
1826
|
+
else ctx.effect(() => off, 'bots: task background jobs');
|
|
1827
|
+
});
|
|
1828
|
+
|
|
1829
|
+
/**
|
|
1830
|
+
* After a restart (PLAN-0.8 §4.5): a working ticket whose Session was in the middle of a turn
|
|
1831
|
+
* (its stored log ends inside a turn, or with the turn Harness closed as `interrupted` when it
|
|
1832
|
+
* resumed it), or holds input it never took, gets one recovery note: look before repeating
|
|
1833
|
+
* anything, then go on. A Session that had to be made anew gets its assignment again, and so does
|
|
1834
|
+
* one whose stored log holds no message at all (the assignment never landed). Idle tickets that
|
|
1835
|
+
* had reported stay as they are. The note's id names the interrupted turn, so a second restart
|
|
1836
|
+
* before it is read sends nothing new, while a recovery turn cut off again gets its own note.
|
|
1837
|
+
*/
|
|
1838
|
+
async function recoverTickets() {
|
|
1839
|
+
if (!service(ctx, 'sessionController')) return;
|
|
1840
|
+
for (const t of tickets.open()) {
|
|
1841
|
+
if (!t.startedAt || !t.sessionId || stageOf(t) !== 'working') continue;
|
|
1842
|
+
try {
|
|
1843
|
+
const events = await readHistory(t.sessionId);
|
|
1844
|
+
const info = {};
|
|
1845
|
+
const agent = await ticketAgent(t, info);
|
|
1846
|
+
const cur = tickets.get(t.id) ?? t;
|
|
1847
|
+
const pending = pendingOf(agent).length > 0;
|
|
1848
|
+
// The first event of the latest turn that did not end cleanly: one the log ends inside, or one
|
|
1849
|
+
// Harness closed as `interrupted` with no turn after it (none: the log ends after a clean turn).
|
|
1850
|
+
// A recovery turn cut off by a second restart is a turn of its own, so it gets a note of its own.
|
|
1851
|
+
let interrupted = null;
|
|
1852
|
+
let inTurn = false;
|
|
1853
|
+
let lastEnd = 0;
|
|
1854
|
+
(events ?? []).forEach((e, i) => {
|
|
1855
|
+
const seq = e?.seq ?? i;
|
|
1856
|
+
if (e?.type === 'turn/end') {
|
|
1857
|
+
lastEnd = seq;
|
|
1858
|
+
inTurn = false;
|
|
1859
|
+
if (e.data?.reason?.kind !== 'interrupted') interrupted = null;
|
|
1860
|
+
} else if (!inTurn && ['turn/start', 'user/message', 'assistant/message', 'tool/call', 'tool/result'].includes(e?.type)) {
|
|
1861
|
+
inTurn = true;
|
|
1862
|
+
interrupted = seq;
|
|
1863
|
+
}
|
|
1864
|
+
});
|
|
1865
|
+
// A stored log, read whole (shorter than the tail read), without a single message: the Session was
|
|
1866
|
+
// made and the start recorded, but the assignment never landed (Harness went down in between). Its
|
|
1867
|
+
// own id keeps one still in the inbox from doubling.
|
|
1868
|
+
const neverTook = Array.isArray(events) && events.length < HISTORY_TAIL && !events.some((e) => e?.type === 'user/message');
|
|
1869
|
+
if (info.created) {
|
|
1870
|
+
await sendTo(agent, { content: [{ type: 'text', text: `${recoveryNoteText(cur)}\n\n${assignmentText(cur, cardCtx())}` }], source: sourceFrom(cur.requester), mode: 'steer', key: `recover:${cur.id}:new` });
|
|
1871
|
+
} else if (neverTook) {
|
|
1872
|
+
await sendTo(agent, { content: [{ type: 'text', text: assignmentText(cur, cardCtx()) }], source: sourceFrom(cur.requester), mode: 'steer', key: `assign:${cur.id}` });
|
|
1873
|
+
} else if (interrupted !== null || pending) {
|
|
1874
|
+
const mark = interrupted !== null ? `t${interrupted}` : `p${lastEnd}`;
|
|
1875
|
+
await sendTo(agent, { content: [{ type: 'text', text: recoveryNoteText(cur) }], source: sourceFrom(cur.requester), mode: 'steer', key: `recover:${cur.id}:${mark}` });
|
|
1876
|
+
}
|
|
1877
|
+
} catch (error) {
|
|
1878
|
+
ctx.logger?.warn?.(`bots: recovering task ${t.id}: ${error?.message ?? error}`);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
/** Archive the Sessions of tickets ended `archiveHours` ago, run the watchdog; keep the file small. */
|
|
1884
|
+
async function ticketUpkeep(now = nowMs()) {
|
|
1885
|
+
const hours = settings.get().tickets.archiveHours;
|
|
1886
|
+
for (const t of tickets.list({ open: false, archived: false })) {
|
|
1887
|
+
if (now - (t.ended?.at ?? 0) < hours * 3_600_000) continue;
|
|
1888
|
+
if (t.sessionId && (openTasks.has(t.sessionId) || agents()?.get?.(t.sessionId)?.status === 'running')) continue;
|
|
1889
|
+
if (t.sessionId) {
|
|
1890
|
+
uninstall(t.sessionId);
|
|
1891
|
+
forgetSession(t.sessionId);
|
|
1892
|
+
try {
|
|
1893
|
+
await service(ctx, 'workspaceRegistry')?.archiveSession?.(t.sessionId);
|
|
1894
|
+
} catch (error) {
|
|
1895
|
+
ctx.logger?.warn?.(`bots: archiving the conversation of task ${t.id}: ${error?.message ?? error}`);
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
tickets.archive(t.id);
|
|
1899
|
+
slots.release(t.id);
|
|
1900
|
+
}
|
|
1901
|
+
await watch(now);
|
|
1902
|
+
tickets.flush();
|
|
1903
|
+
tickets.prune();
|
|
1904
|
+
await pump();
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
// After a restart: tickets that were working keep their slots and, once Harness is up, get their
|
|
1908
|
+
// recovery notes; queued ones start then.
|
|
1909
|
+
for (const t of tickets.open()) if (t.startedAt && stageOf(t) === 'working') slots.acquire(t.id);
|
|
1910
|
+
/** The startup pass, once: recovery notes, then the queue. Resolves when done (tests wait on it). */
|
|
1911
|
+
let startupDone = null;
|
|
1912
|
+
const startup = () => (startupDone ??= recoverTickets()
|
|
1913
|
+
.catch((error) => ctx.logger?.warn?.(`bots: task recovery: ${error?.message ?? error}`))
|
|
1914
|
+
.then(() => pump())
|
|
1915
|
+
.catch(() => {}));
|
|
1916
|
+
ctx.effect(() => {
|
|
1917
|
+
const timer = setTimer(() => void startup(), deps.startupPumpMs ?? STARTUP_PUMP_MS);
|
|
1918
|
+
timer?.unref?.();
|
|
1919
|
+
return () => clearTimer(timer);
|
|
1920
|
+
}, 'bots: recover working tasks, start queued ones');
|
|
1921
|
+
|
|
900
1922
|
// --- chat channels: Telegram, Discord, Feishu / Lark, Slack -------------------------------
|
|
1923
|
+
/**
|
|
1924
|
+
* A person's follow-up on a Thread with live tickets (lib/threads.mjs `routeInbound`): it goes
|
|
1925
|
+
* into each ticket Session as their message (a done ticket opens again; a follow-up may take the
|
|
1926
|
+
* extra slot), and the Router (the channel owner's home) is told without being woken. That notice
|
|
1927
|
+
* is no input of its turn: its replies do not go to that Thread because of it.
|
|
1928
|
+
*/
|
|
1929
|
+
async function followUp(list, { header, body }, { threadKey: key, origin, owner, key: messageKey }) {
|
|
1930
|
+
const router = owner ? store.get(owner.id) : null;
|
|
1931
|
+
// A message handed out again after a restart that the Router already took (it opened these very
|
|
1932
|
+
// tickets) is no follow-up: it is not run twice.
|
|
1933
|
+
if (messageKey && router?.sessionId) {
|
|
1934
|
+
await loadHistory(router.sessionId);
|
|
1935
|
+
if (deliveredIds.get(router.sessionId)?.has(`${MESSAGE_PREFIX}${messageKey}`)) return [];
|
|
1936
|
+
}
|
|
1937
|
+
const sessions = [];
|
|
1938
|
+
const reached = [];
|
|
1939
|
+
let lastError = null;
|
|
1940
|
+
for (const t of list) {
|
|
1941
|
+
const cur = tickets.get(t.id) ?? t;
|
|
1942
|
+
try {
|
|
1943
|
+
const next = await appendToTicket(cur, body, { human: true, header: `${header}${threadNote(key)}`, chat: { kind: origin?.kind, who: origin?.who, threadKey: key }, ...(messageKey ? { key: `${messageKey}:${cur.id}` } : {}) });
|
|
1944
|
+
reached.push(next);
|
|
1945
|
+
if (next.sessionId) sessions.push(next.sessionId);
|
|
1946
|
+
} catch (error) {
|
|
1947
|
+
lastError = error;
|
|
1948
|
+
ctx.logger?.warn?.(`bots: a follow-up did not reach task ${cur.id}: ${error?.message ?? error}`);
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
if (!reached.length) throw lastError ?? new Error('no task took the follow-up');
|
|
1952
|
+
if (router?.sessionId) {
|
|
1953
|
+
try {
|
|
1954
|
+
const found = await service(ctx, 'sessionController')?.resolveAgent?.(router.sessionId);
|
|
1955
|
+
if (found?.agent) {
|
|
1956
|
+
// The Thread's label names the chat app already ("Telegram · Kada"), so no `via` beside it.
|
|
1957
|
+
const text = followUpNoticeText({ tickets: reached, thread: key, who: origin?.who, ...(tickets.thread(key)?.label ? {} : { via: CHANNEL_LABELS[origin?.kind] ?? origin?.kind }), text: body }, cardCtx());
|
|
1958
|
+
await sendTo(found.agent, { content: [{ type: 'text', text }], source: { kind: 'agent-message', form: 'relay' }, mode: 'inject', key: `followup:${messageKey ?? randomUUID()}` });
|
|
1959
|
+
}
|
|
1960
|
+
} catch (error) {
|
|
1961
|
+
ctx.logger?.warn?.(`bots: the follow-up notice for @${router.handle}: ${error?.message ?? error}`);
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
return sessions;
|
|
1965
|
+
}
|
|
1966
|
+
|
|
901
1967
|
const channels = createChannels({
|
|
902
1968
|
file: join(dir, 'channels.json'),
|
|
903
1969
|
bots: () => store.list(),
|
|
904
1970
|
entries: () => templates(),
|
|
905
|
-
// A chat message is a user prompt like one typed in the panel, after a line naming where it came from
|
|
906
|
-
|
|
1971
|
+
// A chat message is a user prompt like one typed in the panel, after a line naming where it came from
|
|
1972
|
+
// and its Thread (so the bot can name it in bot_reply). Its id comes from the chat message's, so a
|
|
1973
|
+
// message handed out again after a restart is not run twice.
|
|
1974
|
+
deliver: async (target, { header, body }, meta = {}) => {
|
|
907
1975
|
await autoTopic(store.get(target.id) ?? target, 'user');
|
|
908
1976
|
const agent = await agentOf(store.get(target.id) ?? target);
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
1977
|
+
const sent = await sendTo(agent, {
|
|
1978
|
+
content: [
|
|
1979
|
+
{ type: 'text', text: `${header}${threadNote(meta.threadKey)}` },
|
|
1980
|
+
{ type: 'text', text: body },
|
|
1981
|
+
],
|
|
1982
|
+
source: { kind: 'user' },
|
|
1983
|
+
mode: homeMode(target),
|
|
1984
|
+
...(meta.key ? { key: meta.key } : {}),
|
|
1985
|
+
});
|
|
1986
|
+
return { sessionId: agent.session.id, messageId: sent.message.id, ...(sent.skipped ? { skipped: true } : {}) };
|
|
912
1987
|
},
|
|
1988
|
+
toTickets: (list, msg, meta) => followUp(list, msg, meta),
|
|
1989
|
+
subscribers: (key) => tickets.subscribers(key),
|
|
1990
|
+
knownThread: (key) => tickets.thread(key),
|
|
1991
|
+
ticketThread: (id) => tickets.get(String(id ?? ''))?.origin?.threadKey,
|
|
913
1992
|
running: (sessionId) => agents()?.get?.(sessionId)?.status === 'running',
|
|
914
1993
|
newTopic: (bot) => newTopic(bot, 'manual'),
|
|
915
1994
|
...(deps.loadConnector ? { loadConnector: deps.loadConnector } : {}),
|
|
@@ -929,43 +2008,151 @@ export function apply(ctx, config, deps = {}) {
|
|
|
929
2008
|
const trigger = new Map();
|
|
930
2009
|
/** Sessions whose current turn already sent a bot_send_message. */
|
|
931
2010
|
const answered = new Set();
|
|
2011
|
+
/**
|
|
2012
|
+
* Per home Session, its turn so far (dropped at the turn's end): `other`, an input that was no report
|
|
2013
|
+
* or note about a task (a person's message, a schedule run, a teammate's DM); `reports`, the tasks
|
|
2014
|
+
* whose reports or notes came in; and since the latest input, `answers`, those of them it messaged
|
|
2015
|
+
* with bot_send_message (`ticket`), and `acted`, any other bot_send_message (a new task, say).
|
|
2016
|
+
*/
|
|
2017
|
+
const turnState = new Map();
|
|
2018
|
+
/**
|
|
2019
|
+
* Closing words that reach no one: the turn's only inputs were reports, and all the bot did about
|
|
2020
|
+
* them was answer those tasks. Anything more (a person in the turn, a new task) and its text is a
|
|
2021
|
+
* message to the person.
|
|
2022
|
+
*/
|
|
2023
|
+
const closingOnly = (sessionId) => {
|
|
2024
|
+
const st = turnState.get(sessionId);
|
|
2025
|
+
return Boolean(st) && !st.other && st.reports.size > 0 && st.answers.size > 0 && !st.acted;
|
|
2026
|
+
};
|
|
2027
|
+
/** A tool call's arguments as an object (`argsRaw` or Harness's `arguments`, a JSON string). */
|
|
2028
|
+
const callArgs = (b) => {
|
|
2029
|
+
const raw = b?.argsRaw ?? b?.arguments ?? b?.args ?? b?.input;
|
|
2030
|
+
if (raw && typeof raw === 'object') return raw;
|
|
2031
|
+
try {
|
|
2032
|
+
const v = JSON.parse(String(raw ?? ''));
|
|
2033
|
+
return v && typeof v === 'object' ? v : {};
|
|
2034
|
+
} catch {
|
|
2035
|
+
return {};
|
|
2036
|
+
}
|
|
2037
|
+
};
|
|
2038
|
+
/** Drop what is kept per Session for one that is gone: an archived task's, a topic left behind, a removed bot's. */
|
|
2039
|
+
function forgetSession(sessionId) {
|
|
2040
|
+
if (!sessionId) return;
|
|
2041
|
+
memoText.delete(sessionId);
|
|
2042
|
+
memoStale.delete(sessionId);
|
|
2043
|
+
deliveredIds.delete(sessionId);
|
|
2044
|
+
historyRead.delete(sessionId);
|
|
2045
|
+
trigger.delete(sessionId);
|
|
2046
|
+
answered.delete(sessionId);
|
|
2047
|
+
turnState.delete(sessionId);
|
|
2048
|
+
activity.clear(sessionId);
|
|
2049
|
+
}
|
|
932
2050
|
/** Kinds of user message that start (or join) a task. */
|
|
933
2051
|
const TASK_KINDS = new Set(['user', 'schedule', 'agent-message']);
|
|
2052
|
+
/** The tickets a relay is about, from its message id (`bots:report:<id>:…`) or its sender (a ticket Session). */
|
|
2053
|
+
function relayTickets(message) {
|
|
2054
|
+
const id = String(message?.id ?? '');
|
|
2055
|
+
const m = /^bots:([a-z-]+):(t[a-z0-9]{8}):/.exec(id);
|
|
2056
|
+
if (m && RELAY_KINDS.has(m[1])) return [tickets.get(m[2])].filter(Boolean);
|
|
2057
|
+
if (/^bots:remind:/.test(id)) return [...(reminded.get(id) ?? [])].map((x) => tickets.get(x)).filter(Boolean);
|
|
2058
|
+
if (/^bots:/.test(id)) return [];
|
|
2059
|
+
const sender = ticketOf(message?.source?.senderSessionId);
|
|
2060
|
+
return sender ? [sender] : [];
|
|
2061
|
+
}
|
|
2062
|
+
/** Reminder message id → the tickets it names (their origin Threads join the requester's turn). */
|
|
2063
|
+
const reminded = new Map();
|
|
934
2064
|
ctx.on('session/event', (session, event) => {
|
|
935
2065
|
let bot;
|
|
936
2066
|
let via = null;
|
|
937
2067
|
let kind;
|
|
2068
|
+
let ticket;
|
|
938
2069
|
try {
|
|
939
|
-
bot =
|
|
2070
|
+
bot = botOfSession(session?.id);
|
|
940
2071
|
if (!bot || !event) return;
|
|
941
|
-
|
|
2072
|
+
ticket = ticketOf(session.id);
|
|
2073
|
+
if (event.type === 'user/message') noteDelivered(session.id, event.data?.id);
|
|
2074
|
+
if (ticket) {
|
|
2075
|
+
// A ticket Session talks to no one directly: its reports go through bot_send_message, its
|
|
2076
|
+
// plain text stays in it (no timeline reply, nothing to a chat app).
|
|
2077
|
+
tickets.touch(ticket.id);
|
|
2078
|
+
if (event.type === 'user/message') {
|
|
2079
|
+
kind = event.data?.source?.kind;
|
|
2080
|
+
trigger.set(session.id, kind);
|
|
2081
|
+
} else if (event.type === 'turn/end') {
|
|
2082
|
+
channels.noteTurnEnd(session.id);
|
|
2083
|
+
// A turn that went through ends a run of temporary errors.
|
|
2084
|
+
if (event.data?.reason?.kind === 'completed' && ticket.retries > 0 && !ticket.ended) tickets.patch(ticket.id, { retries: 0 });
|
|
2085
|
+
}
|
|
2086
|
+
} else if (event.type === 'user/message') {
|
|
942
2087
|
kind = event.data?.source?.kind;
|
|
2088
|
+
const id = String(event.data?.id ?? '');
|
|
943
2089
|
// The Harness tells a session about task edits made elsewhere; that is not a delivery.
|
|
944
2090
|
if (kind === 'schedule' && /^\[SCHEDULE CHANGE\]/.test(textOf(event.data.content))) kind = 'schedule-notice';
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
2091
|
+
if (/^bots:followup:/.test(id)) {
|
|
2092
|
+
// A follow-up went to its tasks directly; this notice (injected, it woke nothing) is no input of the turn.
|
|
2093
|
+
kind = 'followup-notice';
|
|
2094
|
+
} else {
|
|
2095
|
+
// A report (or notice) on a ticket this conversation asked for: answering it is speaking to the user.
|
|
2096
|
+
const about = kind === 'agent-message' ? relayTickets(event.data) : [];
|
|
2097
|
+
// A note that a drawing the bot asked for ended is news for the person too, like a report.
|
|
2098
|
+
const isReport = kind === 'agent-message' && (about.length > 0 || /^bots:(?:report|failed|ended|stalled|remind|avatar):/.test(id));
|
|
2099
|
+
trigger.set(session.id, isReport ? 'report' : kind);
|
|
2100
|
+
answered.delete(session.id);
|
|
2101
|
+
const st = turnState.get(session.id) ?? { other: false, reports: new Set() };
|
|
2102
|
+
if (isReport) for (const t of about) st.reports.add(t.id);
|
|
2103
|
+
else if (kind !== 'schedule-notice') st.other = true;
|
|
2104
|
+
st.answers = new Set();
|
|
2105
|
+
st.acted = false;
|
|
2106
|
+
turnState.set(session.id, st);
|
|
2107
|
+
const said = textOf(event.data.content);
|
|
2108
|
+
// A chat message adds its Thread to the turn's; a panel message adds the panel (lib/threads.mjs).
|
|
2109
|
+
via = channels.noteUserMessage(session.id, bot, kind, said, { id, report: isReport });
|
|
2110
|
+
// A drawing's note: the answer goes to the chats the person asked for it in.
|
|
2111
|
+
for (const o of drawingOrigins.get(id) ?? []) channels.noteInput(session.id, { threadKey: o.threadKey, origin: o });
|
|
2112
|
+
drawingOrigins.delete(id);
|
|
2113
|
+
// A report's ticket came from a Thread: the answer to the person goes there (PLAN-0.8 §4.3).
|
|
2114
|
+
for (const t of about) {
|
|
2115
|
+
const key = t.origin?.threadKey;
|
|
2116
|
+
if (!key) continue;
|
|
2117
|
+
const th = tickets.thread(key);
|
|
2118
|
+
// The answer quotes the message that started the task, not whatever was said there last.
|
|
2119
|
+
channels.noteInput(session.id, { threadKey: key, origin: { ...(t.origin?.who ? { who: t.origin.who } : {}), ...(th?.label ? { label: th.label } : {}), ...(t.origin?.replyTo ? { replyTo: t.origin.replyTo } : {}) }, ticket: t.id });
|
|
2120
|
+
}
|
|
2121
|
+
const thread = via ? via.threadKey : panelThreadKey(session.id);
|
|
2122
|
+
if (kind === 'user') store.log(via ? { from: 'user', to: bot.id, text: via.body, kind: 'user', via: via.kind, who: via.who, ...(thread ? { thread } : {}) } : { from: 'user', to: bot.id, text: said, kind: 'user', ...(thread ? { thread } : {}) });
|
|
2123
|
+
else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: said, kind: 'system' });
|
|
2124
|
+
}
|
|
952
2125
|
} else if (event.type === 'assistant/message') {
|
|
953
2126
|
const content = event.data?.message?.content ?? [];
|
|
954
2127
|
const calls = content.filter((b) => b?.type === 'tool-call');
|
|
955
2128
|
if (calls.some((b) => (b.name ?? b.toolName) === 'bot_send_message')) answered.add(session.id);
|
|
2129
|
+
const st = turnState.get(session.id);
|
|
2130
|
+
for (const b of calls) {
|
|
2131
|
+
if (!st || (b.name ?? b.toolName) !== 'bot_send_message') continue;
|
|
2132
|
+
const id = String(callArgs(b).ticket ?? '').trim().replace(/^(?:ticket|task)\//, '');
|
|
2133
|
+
if (id && st.reports.has(id)) st.answers.add(id);
|
|
2134
|
+
else st.acted = true;
|
|
2135
|
+
}
|
|
956
2136
|
const text = calls.length > 0 ? '' : textOf(content);
|
|
957
2137
|
const why = trigger.get(session.id);
|
|
958
2138
|
// Shown in the bot's chat: what it says to the user. Hidden: acknowledging a schedule notice,
|
|
959
|
-
//
|
|
960
|
-
//
|
|
961
|
-
|
|
2139
|
+
// the closing words of a turn that answered a bot by DM, and those of a turn whose only inputs
|
|
2140
|
+
// were reports and that only answered those tasks (they reach no one). The dispatcher reporting
|
|
2141
|
+
// back after its teammates answered is a message to the user, and so is any bot passing on a
|
|
2142
|
+
// report from a task it asked for, also in a turn where it hands out more work.
|
|
2143
|
+
const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id))) || (why === 'report' && closingOnly(session.id));
|
|
962
2144
|
if (text && !hidden) {
|
|
963
|
-
//
|
|
2145
|
+
// To the turn's one chat Thread; with several (or the panel and a chat) it stays in the panel,
|
|
2146
|
+
// and bot_reply says where each answer goes.
|
|
2147
|
+
const plan = channels.replyPlan(session.id);
|
|
964
2148
|
const sent = channels.noteReply(session.id, text);
|
|
965
|
-
|
|
2149
|
+
const thread = sent ? sent.threadKey : panelThreadKey(session.id);
|
|
2150
|
+
const choices = plan.mode === 'choose' ? plan.origins.filter((o) => o.kind !== 'panel').map((o) => o.threadKey) : [];
|
|
2151
|
+
store.log({ from: bot.id, to: 'user', text, kind: 'reply', ...(sent ? { via: sent.kind } : {}), ...(thread ? { thread } : {}), ...(choices.length ? { notSent: true, choices } : {}) });
|
|
966
2152
|
}
|
|
967
2153
|
} else if (event.type === 'turn/end') {
|
|
968
2154
|
channels.noteTurnEnd(session.id);
|
|
2155
|
+
turnState.delete(session.id);
|
|
969
2156
|
}
|
|
970
2157
|
} catch {
|
|
971
2158
|
// The timeline must never disturb a conversation.
|
|
@@ -978,7 +2165,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
978
2165
|
if (!TASK_KINDS.has(kind)) return;
|
|
979
2166
|
const task = openTasks.get(sid) ?? startTask(bot, sid, kind, event, via);
|
|
980
2167
|
const said = textOf(event.data?.content);
|
|
981
|
-
const who = kind === 'schedule' ? 'scheduled' : kind === 'agent-message' ? 'bot message' : via ? `user via ${via.kind}` : 'user';
|
|
2168
|
+
const who = kind === 'schedule' ? 'scheduled' : kind === 'agent-message' ? (ticket ? 'task message' : 'bot message') : via ? `user via ${via.kind}` : 'user';
|
|
982
2169
|
logLine(task, `[${who}] ${via ? via.body : said}`);
|
|
983
2170
|
} else if (event.type === 'assistant/message') {
|
|
984
2171
|
const msg = event.data?.message ?? {};
|
|
@@ -1014,17 +2201,178 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1014
2201
|
ctx.logger?.debug?.(`bots: usage: ${error?.message ?? error}`);
|
|
1015
2202
|
}
|
|
1016
2203
|
});
|
|
2204
|
+
// What a bot's home or task Session does right now, for the panel (lib/activity.mjs).
|
|
2205
|
+
ctx.on('session/event', (session, event) => {
|
|
2206
|
+
try {
|
|
2207
|
+
if (session?.id && botOfSession(session.id)) activity.note(session.id, event);
|
|
2208
|
+
} catch {
|
|
2209
|
+
// Live status is a nicety.
|
|
2210
|
+
}
|
|
2211
|
+
});
|
|
1017
2212
|
// The surest sign a task is over: the bot's Agent went idle.
|
|
1018
2213
|
ctx.on('agent/status', (payload) => {
|
|
1019
2214
|
try {
|
|
1020
2215
|
const sid = payload?.agent?.session?.id;
|
|
2216
|
+
if (sid && payload.status === 'idle') activity.clear(sid);
|
|
1021
2217
|
if (sid && payload.status === 'idle' && openTasks.has(sid)) settleSoon(sid, 300);
|
|
1022
2218
|
else if (sid && payload.status === 'idle' && memoStale.delete(sid)) memoText.delete(sid);
|
|
2219
|
+
if (sid && payload.status === 'idle') ticketIdle(ticketOf(sid));
|
|
1023
2220
|
} catch {
|
|
1024
2221
|
// Ignored.
|
|
1025
2222
|
}
|
|
1026
2223
|
});
|
|
1027
2224
|
|
|
2225
|
+
// --- questions a bot asks (Harness's ask_user_question), answered from the panel too --------------
|
|
2226
|
+
/** The code of a user-questions error (`UserQuestionError`, or one a Client sent back as plain data). */
|
|
2227
|
+
const codeOf = (error) => (error && typeof error === 'object' && typeof error.code === 'string' ? error.code : '');
|
|
2228
|
+
/** One question as the panel shows it; an approval or a plan review only by its text (the conversation answers it). */
|
|
2229
|
+
function askItem(q, native) {
|
|
2230
|
+
const options = Array.isArray(q?.options) ? q.options.filter((o) => typeof o?.label === 'string').map((o) => ({ label: o.label, ...(typeof o.description === 'string' && o.description ? { description: o.description } : {}) })) : null;
|
|
2231
|
+
return {
|
|
2232
|
+
id: String(q?.id ?? ''),
|
|
2233
|
+
question: String(q?.question ?? ''),
|
|
2234
|
+
...(native
|
|
2235
|
+
? {}
|
|
2236
|
+
: {
|
|
2237
|
+
...(typeof q.header === 'string' && q.header ? { header: q.header } : {}),
|
|
2238
|
+
...(typeof q.detail === 'string' && q.detail ? { detail: q.detail } : {}),
|
|
2239
|
+
...(options ? { options } : {}),
|
|
2240
|
+
...(q.multiSelect === true ? { multiSelect: true } : {}),
|
|
2241
|
+
}),
|
|
2242
|
+
};
|
|
2243
|
+
}
|
|
2244
|
+
/** A waiting question in state (`asks`). */
|
|
2245
|
+
const askView = (a) => ({ id: a.id, botId: a.botId, sessionId: a.sessionId, ...(a.ticketId ? { ticketId: a.ticketId } : {}), at: a.at, ...(a.native ? { native: true } : {}), ...(a.continued ? { continued: true } : {}), questions: a.questions });
|
|
2246
|
+
/** The chats the asking turn came from (a home's), or the chat its task came from, hear once that it waits for an answer in Harness. */
|
|
2247
|
+
function askNotice(ask, bot) {
|
|
2248
|
+
const targets = ask.ticketId ? [channels.resolveReply(ask.sessionId, { ticket: ask.ticketId })] : channels.current(ask.sessionId);
|
|
2249
|
+
for (const target of targets) {
|
|
2250
|
+
if (!target || target.kind === 'panel' || !target.chatId) continue;
|
|
2251
|
+
try {
|
|
2252
|
+
channels.replyTo(ask.sessionId, target, askNoticeText(bot, ask.questions));
|
|
2253
|
+
} catch (error) {
|
|
2254
|
+
ctx.logger?.info?.(`bots: question notice: ${error?.message ?? error}`);
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* One `user-questions/request` (the Agent-scoped waterfall `ctx.userQuestions.ask` runs). A request
|
|
2260
|
+
* from a bot's home or a task Session is recorded and settles with whichever answers first: the
|
|
2261
|
+
* rest of the chain (`next()`: the Harness window's card) or the panel (`answerAsk`). When no window
|
|
2262
|
+
* can ask (`NO_PROVIDER`) it waits for the panel; the request's abort, or any other failure, ends
|
|
2263
|
+
* it. The chain gets a signal that also aborts once the panel answered, so the window's card closes.
|
|
2264
|
+
* A timed question whose wait ran out (`ASK_TIMED_OUT`) stays answerable (`continued`): the panel
|
|
2265
|
+
* answers it through `userQuestions.answer`. Approvals and plan reviews are only recorded; the
|
|
2266
|
+
* conversation answers them.
|
|
2267
|
+
*/
|
|
2268
|
+
function askRequest(request, next) {
|
|
2269
|
+
const sessionId = request?.agent?.session?.id;
|
|
2270
|
+
const bot = botOfSession(sessionId);
|
|
2271
|
+
const questions = Array.isArray(request?.questions) ? request.questions : [];
|
|
2272
|
+
if (!bot || questions.length === 0) return next();
|
|
2273
|
+
const native = questions.some((q) => q?.intent?.kind === 'approval' || q?.intent?.kind === 'plan-review');
|
|
2274
|
+
const ticket = ticketOf(sessionId);
|
|
2275
|
+
const ask = { id: `ask-${randomUUID()}`, botId: bot.id, sessionId, ...(ticket ? { ticketId: ticket.id } : {}), at: nowMs(), ...(native ? { native: true } : {}), questions: questions.map((q) => askItem(q, native)) };
|
|
2276
|
+
asks.set(ask.id, ask);
|
|
2277
|
+
askNotice(ask, bot);
|
|
2278
|
+
const chain = () => {
|
|
2279
|
+
try {
|
|
2280
|
+
return Promise.resolve(next());
|
|
2281
|
+
} catch (error) {
|
|
2282
|
+
return Promise.reject(error);
|
|
2283
|
+
}
|
|
2284
|
+
};
|
|
2285
|
+
if (native) return chain().finally(() => asks.delete(ask.id));
|
|
2286
|
+
const original = request.signal instanceof AbortSignal ? request.signal : undefined;
|
|
2287
|
+
const panel = new AbortController();
|
|
2288
|
+
try {
|
|
2289
|
+
request.signal = original ? AbortSignal.any([original, panel.signal]) : panel.signal;
|
|
2290
|
+
} catch {
|
|
2291
|
+
// A frozen request keeps its own signal: the window's card then stays until the call ends.
|
|
2292
|
+
}
|
|
2293
|
+
const callId = request.wait?.timed === true && typeof request.wait.callId === 'string' ? request.wait.callId : '';
|
|
2294
|
+
return new Promise((resolve, reject) => {
|
|
2295
|
+
let done = false;
|
|
2296
|
+
const finish = (ok, value) => {
|
|
2297
|
+
if (done) return;
|
|
2298
|
+
done = true;
|
|
2299
|
+
original?.removeEventListener('abort', onAbort);
|
|
2300
|
+
delete ask.settle;
|
|
2301
|
+
if (!ok && callId && codeOf(value) === 'ASK_TIMED_OUT') Object.assign(ask, { continued: true, callId });
|
|
2302
|
+
else asks.delete(ask.id);
|
|
2303
|
+
panel.abort(new Error('the question was settled'));
|
|
2304
|
+
(ok ? resolve : reject)(value);
|
|
2305
|
+
};
|
|
2306
|
+
const onAbort = () => finish(false, original.reason);
|
|
2307
|
+
ask.settle = (answer) => finish(true, answer);
|
|
2308
|
+
if (original?.aborted) return onAbort();
|
|
2309
|
+
original?.addEventListener('abort', onAbort, { once: true });
|
|
2310
|
+
chain().then(
|
|
2311
|
+
(answer) => finish(true, answer),
|
|
2312
|
+
(error) => {
|
|
2313
|
+
if (codeOf(error) !== 'NO_PROVIDER') finish(false, error);
|
|
2314
|
+
},
|
|
2315
|
+
);
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2318
|
+
// First in the chain: the Harness forwards the request to its window and holds it there until that
|
|
2319
|
+
// card is answered, so a listener after it would never hear of the question while a window is open.
|
|
2320
|
+
ctx.on('user-questions/request', (request, next) => askRequest(request, next), { prepend: true });
|
|
2321
|
+
// A continued question answered in the conversation: its reply reaches the Session.
|
|
2322
|
+
ctx.on('session/event', (session, event) => {
|
|
2323
|
+
const source = event?.type === 'user/message' ? event.data?.source : null;
|
|
2324
|
+
if (source?.kind !== 'user-question-reply') return;
|
|
2325
|
+
for (const a of asks.values()) if (a.continued && a.sessionId === session?.id && a.callId === source.callId) asks.delete(a.id);
|
|
2326
|
+
});
|
|
2327
|
+
|
|
2328
|
+
/** One item per question, ids matching; labels among its options; a single-select question takes one answer. A reason when not. */
|
|
2329
|
+
function checkAnswers(questions, answers) {
|
|
2330
|
+
if (!Array.isArray(answers) || answers.length !== questions.length) return `give one answer for each of the ${questions.length} question(s)`;
|
|
2331
|
+
const out = [];
|
|
2332
|
+
for (const q of questions) {
|
|
2333
|
+
const mine = answers.filter((a) => a && typeof a === 'object' && a.id === q.id);
|
|
2334
|
+
if (mine.length !== 1) return `answer question "${q.id}" exactly once`;
|
|
2335
|
+
const a = mine[0];
|
|
2336
|
+
if (!Array.isArray(a.selected) || a.selected.some((s) => typeof s !== 'string')) return `"selected" of question "${q.id}" must be a list of option labels`;
|
|
2337
|
+
const selected = [...new Set(a.selected)];
|
|
2338
|
+
const custom = typeof a.custom === 'string' ? a.custom.trim().slice(0, 4000) : '';
|
|
2339
|
+
const unknown = selected.find((s) => !(q.options ?? []).some((o) => o.label === s));
|
|
2340
|
+
if (unknown !== undefined) return `"${unknown}" is not an option of question "${q.id}"`;
|
|
2341
|
+
if (selected.length === 0 && !custom) return `question "${q.id}" has no answer`;
|
|
2342
|
+
if (!q.multiSelect && selected.length + (custom ? 1 : 0) > 1) return `question "${q.id}" takes one answer`;
|
|
2343
|
+
out.push({ id: q.id, selected, ...(custom ? { custom } : {}) });
|
|
2344
|
+
}
|
|
2345
|
+
return out;
|
|
2346
|
+
}
|
|
2347
|
+
/** POST /asks/:id/answer `{answers}`: the panel answers a waiting question; the timeline shows what was answered. */
|
|
2348
|
+
async function answerAsk(id, body) {
|
|
2349
|
+
const ask = asks.get(String(id ?? ''));
|
|
2350
|
+
if (!ask) return { ok: false, reason: 'no such question: it was answered already or is no longer waiting' };
|
|
2351
|
+
if (ask.native) return { ok: false, reason: 'this one is answered in the conversation' };
|
|
2352
|
+
const items = checkAnswers(ask.questions, body?.answers);
|
|
2353
|
+
if (typeof items === 'string') return { ok: false, reason: items };
|
|
2354
|
+
if (ask.continued) {
|
|
2355
|
+
const uq = service(ctx, 'userQuestions');
|
|
2356
|
+
const agent = agents()?.get?.(ask.sessionId);
|
|
2357
|
+
if (typeof uq?.answer !== 'function' || !agent) return { ok: false, reason: 'the conversation is not running; answer the question there' };
|
|
2358
|
+
try {
|
|
2359
|
+
const taken = await uq.answer(agent, ask.callId, { answers: items });
|
|
2360
|
+
asks.delete(ask.id);
|
|
2361
|
+
if (!taken) return { ok: false, reason: 'the question is no longer waiting for an answer' };
|
|
2362
|
+
} catch (error) {
|
|
2363
|
+
if (codeOf(error) === 'REPLY_QUEUED') asks.delete(ask.id);
|
|
2364
|
+
return { ok: false, reason: error?.message ?? String(error) };
|
|
2365
|
+
}
|
|
2366
|
+
} else if (ask.settle) ask.settle({ answers: items });
|
|
2367
|
+
else return { ok: false, reason: 'the question is no longer waiting for an answer' };
|
|
2368
|
+
const said = (q) => {
|
|
2369
|
+
const a = items.find((x) => x.id === q.id);
|
|
2370
|
+
return `${q.question}\n→ ${[...a.selected, ...(a.custom ? [a.custom] : [])].join(', ')}`;
|
|
2371
|
+
};
|
|
2372
|
+
store.log({ from: 'user', to: ask.botId, text: ask.questions.map(said).join('\n\n'), kind: 'user', ...(ask.ticketId ? { ticket: ask.ticketId } : { thread: panelThreadKey(ask.sessionId) }) });
|
|
2373
|
+
return { ok: true };
|
|
2374
|
+
}
|
|
2375
|
+
|
|
1028
2376
|
// --- schedules ------------------------------------------------------------------------
|
|
1029
2377
|
const schedule = () => {
|
|
1030
2378
|
const s = service(ctx, 'schedule');
|
|
@@ -1073,6 +2421,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1073
2421
|
|
|
1074
2422
|
// --- bot lifecycle helpers -----------------------------------------------------------
|
|
1075
2423
|
async function removeBot(bot) {
|
|
2424
|
+
dropDrawing(bot.id, 'deleted');
|
|
1076
2425
|
try {
|
|
1077
2426
|
for (const task of await schedulesOf(bot)) await schedule().edit({ id: task.id, action: 'delete' });
|
|
1078
2427
|
} catch {
|
|
@@ -1080,12 +2429,32 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1080
2429
|
}
|
|
1081
2430
|
if (bot.sessionId) {
|
|
1082
2431
|
uninstall(bot.sessionId);
|
|
2432
|
+
forgetSession(bot.sessionId);
|
|
1083
2433
|
try {
|
|
1084
2434
|
service(ctx, 'workspaceRegistry')?.archiveSession?.(bot.sessionId);
|
|
1085
2435
|
} catch {
|
|
1086
2436
|
// The conversation stays where it is.
|
|
1087
2437
|
}
|
|
1088
2438
|
}
|
|
2439
|
+
// Its tickets end with it; their conversations are archived now.
|
|
2440
|
+
for (const t of tickets.list({ botId: bot.id, archived: false })) {
|
|
2441
|
+
if (!t.ended) endTicket(t, { by: 'system', outcome: 'stopped' });
|
|
2442
|
+
if (t.sessionId) {
|
|
2443
|
+
uninstall(t.sessionId);
|
|
2444
|
+
forgetSession(t.sessionId);
|
|
2445
|
+
try {
|
|
2446
|
+
await service(ctx, 'workspaceRegistry')?.archiveSession?.(t.sessionId);
|
|
2447
|
+
} catch {
|
|
2448
|
+
// Archived at the next upkeep, or left as it is.
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
tickets.archive(t.id);
|
|
2452
|
+
}
|
|
2453
|
+
// The tasks it asked for (from its home or its tasks) end too: nobody is left to read their reports.
|
|
2454
|
+
// They stay in the panel, stopped, where the user can still retry one.
|
|
2455
|
+
for (const t of tickets.list({ open: true })) {
|
|
2456
|
+
if (t.requester?.botId === bot.id) endTicket(t, { by: 'system', outcome: 'stopped', error: `@${bot.handle}, who asked for it, was removed` });
|
|
2457
|
+
}
|
|
1089
2458
|
store.remove(bot.id);
|
|
1090
2459
|
memory.dropBot(bot.id);
|
|
1091
2460
|
topics.drop(bot.id);
|
|
@@ -1098,10 +2467,12 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1098
2467
|
}
|
|
1099
2468
|
|
|
1100
2469
|
function applyModel(bot) {
|
|
1101
|
-
|
|
1102
|
-
|
|
2470
|
+
if (!bot.model) return;
|
|
2471
|
+
const live = agents();
|
|
2472
|
+
const ids = [bot.sessionId, ...tickets.list({ botId: bot.id, open: true }).map((t) => t.sessionId)].filter(Boolean);
|
|
2473
|
+
for (const id of ids) {
|
|
1103
2474
|
try {
|
|
1104
|
-
|
|
2475
|
+
live?.get?.(id)?.model?.select?.(selectionOf(bot.model));
|
|
1105
2476
|
} catch {
|
|
1106
2477
|
// Kept on its current model.
|
|
1107
2478
|
}
|
|
@@ -1128,11 +2499,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1128
2499
|
'It must read clearly at 32×32 pixels.',
|
|
1129
2500
|
].join(' ');
|
|
1130
2501
|
}
|
|
1131
|
-
|
|
2502
|
+
/** Draw a picture for `bot` with the Images plugin's generate_image; its bytes and type. `signal` gives up on it. */
|
|
2503
|
+
async function drawAvatar(bot, extra, signal) {
|
|
1132
2504
|
const tool = imageTool();
|
|
1133
2505
|
if (!tool) throw new Error('the Images plugin (generate_image) is not installed or turned off');
|
|
1134
2506
|
const controller = new AbortController();
|
|
1135
|
-
const timer = setTimeout(() => controller.abort(), 300_000);
|
|
2507
|
+
const timer = setTimeout(() => controller.abort(new Error('the image service did not answer within 5 minutes')), 300_000);
|
|
2508
|
+
const stop = () => controller.abort(signal?.reason ?? new Error('stopped'));
|
|
2509
|
+
if (signal?.aborted) stop();
|
|
2510
|
+
else signal?.addEventListener?.('abort', stop, { once: true });
|
|
1136
2511
|
let value;
|
|
1137
2512
|
try {
|
|
1138
2513
|
for (let attempt = 1; ; attempt += 1) {
|
|
@@ -1142,7 +2517,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1142
2517
|
} catch (error) {
|
|
1143
2518
|
const message = String(error?.message ?? error);
|
|
1144
2519
|
// Gateways drop long image requests now and then; those are worth another try.
|
|
1145
|
-
|
|
2520
|
+
// Given up on (out of time, or replaced): why, rather than the tool's own abort message.
|
|
2521
|
+
if (controller.signal.aborted) throw new Error(controller.signal.reason instanceof Error ? controller.signal.reason.message : message);
|
|
2522
|
+
if (attempt >= AVATAR_ATTEMPTS || !TRANSIENT.test(message)) {
|
|
1146
2523
|
throw new Error(TRANSIENT.test(message) ? `the image service failed ${attempt} times in a row (${message}); try again in a moment` : message);
|
|
1147
2524
|
}
|
|
1148
2525
|
ctx.logger?.warn?.(`bots: avatar for @${bot.handle}, attempt ${attempt} failed: ${message}; retrying`);
|
|
@@ -1151,20 +2528,305 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1151
2528
|
}
|
|
1152
2529
|
} finally {
|
|
1153
2530
|
clearTimeout(timer);
|
|
2531
|
+
signal?.removeEventListener?.('abort', stop);
|
|
1154
2532
|
}
|
|
1155
2533
|
const path = value?.images?.[0]?.path;
|
|
1156
2534
|
const type = value?.images?.[0]?.mediaType;
|
|
1157
2535
|
if (!path || !/^image\/(png|jpeg|webp|gif)$/.test(String(type))) throw new Error('the image model returned no picture');
|
|
1158
2536
|
const bytes = readFileSync(path);
|
|
1159
2537
|
if (bytes.length > 8 * 1024 * 1024) throw new Error('the generated picture is too large');
|
|
2538
|
+
return { bytes, type };
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2541
|
+
/**
|
|
2542
|
+
* Drawings under way, by bot: only the latest asked for a bot counts. `sessionId`: the bot
|
|
2543
|
+
* conversation that asked (it gets a note when the drawing ends), none for a person's own
|
|
2544
|
+
* conversation or the panel (they wait for it). Kept in memory only: a restart drops them, and
|
|
2545
|
+
* nobody hears of one dropped that way.
|
|
2546
|
+
*/
|
|
2547
|
+
const drawings = new Map();
|
|
2548
|
+
/** Message id of a drawing's note → the Threads of the turn that asked for it (the answer to the person goes there). */
|
|
2549
|
+
const drawingOrigins = new Map();
|
|
2550
|
+
/** One drawing whose outcome nobody waits for any more: an avatar change since replaced it. */
|
|
2551
|
+
function dropDrawing(botId, by) {
|
|
2552
|
+
const job = drawings.get(botId);
|
|
2553
|
+
if (!job) return;
|
|
2554
|
+
drawings.delete(botId);
|
|
2555
|
+
job.droppedBy = by ?? 'panel';
|
|
2556
|
+
job.controller.abort(new Error('replaced by a newer avatar change'));
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Draw `bot`'s avatar: the drawing replaces any still under way for it, and its picture is saved
|
|
2560
|
+
* when it is still the latest asked once it is ready. `job.done` resolves to the bot with its new
|
|
2561
|
+
* picture, or rejects with why not (`dropped`: replaced meanwhile, or the bot is gone).
|
|
2562
|
+
*/
|
|
2563
|
+
function startDrawing(bot, extra, { sessionId = null, by = null } = {}) {
|
|
2564
|
+
dropDrawing(bot.id, sessionId ?? 'panel');
|
|
2565
|
+
const job = { id: `a${randomUUID().replace(/-/g, '').slice(0, 12)}`, botId: bot.id, handle: bot.handle, name: bot.name, sessionId, by, at: nowMs(), controller: new AbortController() };
|
|
2566
|
+
drawings.set(bot.id, job);
|
|
2567
|
+
const current = () => drawings.get(bot.id) === job;
|
|
2568
|
+
job.done = (async () => {
|
|
2569
|
+
try {
|
|
2570
|
+
const { bytes, type } = await drawAvatar(store.get(bot.id) ?? bot, extra, job.controller.signal);
|
|
2571
|
+
const now = store.get(bot.id);
|
|
2572
|
+
if (!current() || !now) throw Object.assign(new Error(now ? 'its avatar was changed meanwhile' : 'the bot was deleted'), { dropped: true });
|
|
2573
|
+
return savePicture(now, bytes, type, 'ai');
|
|
2574
|
+
} catch (error) {
|
|
2575
|
+
if (error?.dropped || (current() && store.get(bot.id))) throw error;
|
|
2576
|
+
throw Object.assign(new Error(store.get(bot.id) ? 'its avatar was changed meanwhile' : 'the bot was deleted'), { dropped: true });
|
|
2577
|
+
} finally {
|
|
2578
|
+
if (current()) drawings.delete(bot.id);
|
|
2579
|
+
}
|
|
2580
|
+
})();
|
|
2581
|
+
return job;
|
|
2582
|
+
}
|
|
2583
|
+
/** Draw `bot`'s avatar and wait for it (the panel, a person's own conversation): the bot with its picture. */
|
|
2584
|
+
async function generateAvatar(bot, extra) {
|
|
2585
|
+
if (!imageTool()) throw new Error('the Images plugin (generate_image) is not installed or turned off');
|
|
2586
|
+
try {
|
|
2587
|
+
return await startDrawing(bot, extra).done;
|
|
2588
|
+
} catch (error) {
|
|
2589
|
+
throw new Error(error?.dropped ? `no picture was saved: ${error.message}` : String(error?.message ?? error));
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
/**
|
|
2593
|
+
* A drawing a bot asked for goes on without it: the caller's turn goes on, and its conversation
|
|
2594
|
+
* gets one note when the drawing ends (ready, or why not). A home takes it steered, so drawings that
|
|
2595
|
+
* end together arrive together; a task's Session takes it like any message for its task (once it
|
|
2596
|
+
* has a worker slot), unless the task has ended. A drawing replaced from the same conversation, or
|
|
2597
|
+
* dropped by a restart, sends nothing.
|
|
2598
|
+
*/
|
|
2599
|
+
function drawInBackground(bot, extra, caller) {
|
|
2600
|
+
const job = startDrawing(bot, extra, { sessionId: caller.sessionId, by: caller.bot.id });
|
|
2601
|
+
// The Threads of the asking turn: the note's answer goes back where the person asked.
|
|
2602
|
+
const origins = (() => {
|
|
2603
|
+
try {
|
|
2604
|
+
return channels.replyPlan(caller.sessionId).origins.map(({ body: _b, tickets: _t, ...o }) => o).filter((o) => o.threadKey);
|
|
2605
|
+
} catch {
|
|
2606
|
+
return [];
|
|
2607
|
+
}
|
|
2608
|
+
})();
|
|
2609
|
+
const who = `@${job.handle}`;
|
|
2610
|
+
job.done.then(
|
|
2611
|
+
(saved) => noteDrawing(job, origins, `[Avatar ready] The new avatar of ${who} (${saved?.name ?? job.name}) is ready and shows in Bots now. Tell the person if they are waiting for it.`),
|
|
2612
|
+
(error) => {
|
|
2613
|
+
const reason = String(error?.message ?? error).slice(0, 300);
|
|
2614
|
+
if (!error?.dropped) return noteDrawing(job, origins, `[Avatar failed] The picture for ${who} could not be drawn: ${reason}. Its avatar is unchanged.`);
|
|
2615
|
+
if (job.droppedBy !== job.sessionId) return noteDrawing(job, origins, `[Avatar dropped] The picture for ${who} was not used: ${reason}.`);
|
|
2616
|
+
return undefined;
|
|
2617
|
+
},
|
|
2618
|
+
);
|
|
2619
|
+
return job;
|
|
2620
|
+
}
|
|
2621
|
+
/** A drawing's note to the conversation that asked for it (`job.sessionId`): see `drawInBackground`. */
|
|
2622
|
+
async function noteDrawing(job, origins, text) {
|
|
2623
|
+
try {
|
|
2624
|
+
const key = `avatar:${job.id}`;
|
|
2625
|
+
const content = [{ type: 'text', text }];
|
|
2626
|
+
const source = { kind: 'agent-message', form: 'relay' };
|
|
2627
|
+
const t = ticketOf(job.sessionId);
|
|
2628
|
+
if (t) {
|
|
2629
|
+
const cur = tickets.get(t.id);
|
|
2630
|
+
if (cur && !cur.ended && !cur.archivedAt) await toTicket(cur, { content, source, key });
|
|
2631
|
+
return;
|
|
2632
|
+
}
|
|
2633
|
+
const asker = store.get(job.by);
|
|
2634
|
+
if (!asker) return;
|
|
2635
|
+
if (origins.length) {
|
|
2636
|
+
drawingOrigins.set(`${MESSAGE_PREFIX}${key}`, origins);
|
|
2637
|
+
// A note never delivered (Harness gone meanwhile) leaves nothing behind for long.
|
|
2638
|
+
while (drawingOrigins.size > 200) drawingOrigins.delete(drawingOrigins.keys().next().value);
|
|
2639
|
+
}
|
|
2640
|
+
// The asking bot may have started a new topic since: the note goes to the conversation it has now.
|
|
2641
|
+
await sendTo(await agentOf(asker), { content, source, mode: 'steer', key });
|
|
2642
|
+
} catch (error) {
|
|
2643
|
+
ctx.logger?.warn?.(`bots: the note about @${job.handle}'s avatar did not arrive: ${error?.message ?? error}`);
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
/** Store `bytes` as the bot's picture avatar. */
|
|
2647
|
+
function savePicture(bot, bytes, type, source) {
|
|
1160
2648
|
mkdirSync(join(dir, 'avatars'), { recursive: true });
|
|
1161
2649
|
writeFileSync(join(dir, 'avatars', bot.id), bytes);
|
|
1162
2650
|
writeFileSync(join(dir, 'avatars', `${bot.id}.type`), type);
|
|
1163
|
-
return store.patch(bot.id, { avatar: { kind: 'image', source:
|
|
2651
|
+
return store.patch(bot.id, { avatar: { kind: 'image', ...(source ? { source } : {}), url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
|
|
2652
|
+
}
|
|
2653
|
+
/** The image type of `bytes` by its first bytes: PNG, JPEG, WebP or GIF; else ''. */
|
|
2654
|
+
function pictureType(bytes) {
|
|
2655
|
+
if (bytes.length > 8 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';
|
|
2656
|
+
if (bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
|
2657
|
+
if (bytes.length > 12 && bytes.toString('latin1', 0, 4) === 'RIFF' && bytes.toString('latin1', 8, 12) === 'WEBP') return 'image/webp';
|
|
2658
|
+
if (bytes.length > 6 && /^GIF8[79]a$/.test(bytes.toString('latin1', 0, 6))) return 'image/gif';
|
|
2659
|
+
return '';
|
|
2660
|
+
}
|
|
2661
|
+
/** A picture file on this computer becomes the bot's avatar (a tool's `avatar_file`). */
|
|
2662
|
+
function avatarFromFile(bot, file) {
|
|
2663
|
+
const path = String(file ?? '').trim().replace(/^~(?=\/)/, homedir());
|
|
2664
|
+
if (!isAbsolute(path)) throw new Error('avatar_file must be an absolute path to an image file');
|
|
2665
|
+
let bytes;
|
|
2666
|
+
try {
|
|
2667
|
+
if (statSync(path).size > MAX_AVATAR) throw new Error('the image is larger than 2 MB');
|
|
2668
|
+
bytes = readFileSync(path);
|
|
2669
|
+
} catch (error) {
|
|
2670
|
+
throw new Error(/2 MB/.test(String(error?.message)) ? error.message : `cannot read ${path}: ${error?.code ?? error?.message ?? error}`);
|
|
2671
|
+
}
|
|
2672
|
+
const type = pictureType(bytes);
|
|
2673
|
+
if (!type) throw new Error('avatar_file must be a PNG, JPEG, WebP or GIF image');
|
|
2674
|
+
return savePicture(bot, bytes, type);
|
|
2675
|
+
}
|
|
2676
|
+
/** Back to letters: the picture is removed. */
|
|
2677
|
+
function clearPicture(bot) {
|
|
2678
|
+
for (const f of [bot.id, `${bot.id}.type`]) rmSync(join(dir, 'avatars', f), { force: true });
|
|
2679
|
+
return store.patch(bot.id, { avatar: { kind: 'initials', color: bot.avatar.color } });
|
|
2680
|
+
}
|
|
2681
|
+
const AVATAR_PARAMS = {
|
|
2682
|
+
avatar_prompt: {
|
|
2683
|
+
type: 'string',
|
|
2684
|
+
description:
|
|
2685
|
+
'Draw a picture avatar with AI from this description of the look and style (e.g. "photorealistic portrait of a woman in her thirties, studio light"). Needs the Images plugin (the result says so when it is not available). Called from a bot\'s conversation, the drawing runs in the background: the call returns at once and a note arrives in this conversation when the picture is ready (or why it failed), so never wait or poll for it. A restart of Harness drops a drawing still under way, without a note.',
|
|
2686
|
+
},
|
|
2687
|
+
avatar_file: { type: 'string', description: 'Absolute path of an image file on this computer (PNG, JPEG, WebP or GIF, at most 2 MB) to use as the avatar picture.' },
|
|
2688
|
+
};
|
|
2689
|
+
/**
|
|
2690
|
+
* Apply a tool's picture arguments to `bot`; the note says what happened (a failed drawing leaves
|
|
2691
|
+
* the rest of the change in place). From a bot's conversation (`caller.bot`), a drawing runs in the
|
|
2692
|
+
* background and the note says a message will come; from a person's own conversation it is awaited.
|
|
2693
|
+
* Any other avatar change replaces a drawing still under way.
|
|
2694
|
+
*/
|
|
2695
|
+
async function applyPicture(bot, args, caller = {}) {
|
|
2696
|
+
const by = caller.sessionId ?? 'panel';
|
|
2697
|
+
if (typeof args.avatar_file === 'string' && args.avatar_file.trim()) {
|
|
2698
|
+
const saved = avatarFromFile(bot, args.avatar_file);
|
|
2699
|
+
dropDrawing(bot.id, by);
|
|
2700
|
+
return { bot: saved, note: ' Its avatar is now that picture.' };
|
|
2701
|
+
}
|
|
2702
|
+
if (typeof args.avatar_prompt === 'string' && args.avatar_prompt.trim()) {
|
|
2703
|
+
if (!imageGenAvailable()) return { bot, note: ' No picture was drawn: AI avatars need the Images plugin (generate_image), which is not installed or is turned off. The user can install it from the plugin market, or upload a picture on the bot\'s Profile page; avatar_file takes an image file.' };
|
|
2704
|
+
if (caller.bot && caller.sessionId) {
|
|
2705
|
+
drawInBackground(bot, args.avatar_prompt, caller);
|
|
2706
|
+
return { bot, drawing: true, note: ' Its avatar picture is being drawn in the background (often a minute or more); the current avatar stays until then. A note arrives in this conversation when it is ready, or with the reason if it fails: do not wait or poll for it, carry on.' };
|
|
2707
|
+
}
|
|
2708
|
+
try {
|
|
2709
|
+
return { bot: await generateAvatar(bot, args.avatar_prompt), note: ' Its avatar is now a picture drawn from that description.' };
|
|
2710
|
+
} catch (error) {
|
|
2711
|
+
return { bot, note: ` The picture could not be drawn: ${String(error?.message ?? error).slice(0, 300)}` };
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
if (args.avatar_clear === true && bot.avatar.kind === 'image') {
|
|
2715
|
+
dropDrawing(bot.id, by);
|
|
2716
|
+
return { bot: clearPicture(bot), note: ' Its avatar is back to letters.' };
|
|
2717
|
+
}
|
|
2718
|
+
if (args.avatar_clear === true || args.initials || args.color) dropDrawing(bot.id, by);
|
|
2719
|
+
return { bot, note: '' };
|
|
2720
|
+
}
|
|
2721
|
+
|
|
2722
|
+
// --- who calls a tool ----------------------------------------------------------------------
|
|
2723
|
+
/**
|
|
2724
|
+
* Who calls a tool: the conversation it runs in; or, for a Harness subagent or fork (its Session
|
|
2725
|
+
* header says `origin: 'subagent'` and names the `parentSession` that made it), the bot home or task
|
|
2726
|
+
* Session it descends from, which it then acts as (a helper inside task t1 is task t1, with its
|
|
2727
|
+
* limits). `bot`: that conversation's bot; none for a person's own conversation (a top-level Session
|
|
2728
|
+
* no bot owns, or a helper of one). `restricted`: a helper whose line cannot be traced to a
|
|
2729
|
+
* conversation (a creator that is gone was no bot's, or a loop); it acts for no one.
|
|
2730
|
+
* @returns {{sessionId: string|undefined, bot?: object, restricted?: true}}
|
|
2731
|
+
*/
|
|
2732
|
+
function actorOf(exec) {
|
|
2733
|
+
const own = exec?.agent?.session?.id;
|
|
2734
|
+
const ownBot = botOfSession(own);
|
|
2735
|
+
if (!own || ownBot) return { sessionId: own, ...(ownBot ? { bot: ownBot } : {}) };
|
|
2736
|
+
const live = agents();
|
|
2737
|
+
let header = exec.agent.session.header ?? live?.get?.(own)?.session?.header;
|
|
2738
|
+
const seen = new Set([own]);
|
|
2739
|
+
while (header?.origin === 'subagent' && typeof header.parentSession === 'string' && header.parentSession !== '') {
|
|
2740
|
+
const parent = header.parentSession;
|
|
2741
|
+
if (seen.has(parent)) return { sessionId: own, restricted: true };
|
|
2742
|
+
seen.add(parent);
|
|
2743
|
+
const bot = botOfSession(parent);
|
|
2744
|
+
if (bot) return { sessionId: parent, bot };
|
|
2745
|
+
const up = live?.get?.(parent);
|
|
2746
|
+
if (!up) return { sessionId: own, restricted: true };
|
|
2747
|
+
// A live creator without a header cannot be a helper itself: a top-level conversation.
|
|
2748
|
+
header = up.session?.header ?? {};
|
|
2749
|
+
}
|
|
2750
|
+
return { sessionId: own };
|
|
2751
|
+
}
|
|
2752
|
+
/** The caller (`actorOf`); one that acts for no one is refused. */
|
|
2753
|
+
function actor(exec) {
|
|
2754
|
+
const a = actorOf(exec);
|
|
2755
|
+
if (a.restricted) throw new Error('this conversation is a helper whose starting conversation cannot be traced (it is gone), so it cannot act on bots or tasks; report what you found to whoever started you instead');
|
|
2756
|
+
return a;
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
// --- what bot_recall reads ---------------------------------------------------------------
|
|
2760
|
+
/**
|
|
2761
|
+
* Who reads with bot_recall (an `actorOf` caller): a ticket Session (limited to its task), the router
|
|
2762
|
+
* home, another home; a helper that cannot be traced reads nothing; else unlimited (the user).
|
|
2763
|
+
*/
|
|
2764
|
+
function viewerOf(caller) {
|
|
2765
|
+
if (caller?.restricted) return { kind: 'restricted' };
|
|
2766
|
+
const sessionId = caller?.sessionId;
|
|
2767
|
+
const t = ticketOf(sessionId);
|
|
2768
|
+
if (t) return { kind: 'ticket', ticketId: t.id };
|
|
2769
|
+
const bot = store.bySession(sessionId);
|
|
2770
|
+
if (!bot) return undefined;
|
|
2771
|
+
return isRouterHome(bot, sessionId) ? { kind: 'router' } : { kind: 'home' };
|
|
2772
|
+
}
|
|
2773
|
+
/** Threads as bot_recall reads them: stored with tickets, seen lately in a chat, or a panel conversation; the timeline's latest messages there. */
|
|
2774
|
+
const recallThreads = {
|
|
2775
|
+
thread: (key) => {
|
|
2776
|
+
const stored = tickets.thread(key);
|
|
2777
|
+
if (stored) return stored;
|
|
2778
|
+
const info = channels.threadInfo(key);
|
|
2779
|
+
if (info) return { key, kind: info.kind, label: threadLabel(info) };
|
|
2780
|
+
return isPanelThread(key) ? { key, kind: 'panel', label: threadLabel(key) } : undefined;
|
|
2781
|
+
},
|
|
2782
|
+
subscribers: (key) => tickets.subscribers(key),
|
|
2783
|
+
recent: (key) =>
|
|
2784
|
+
store
|
|
2785
|
+
.messages({ limit: 2000 })
|
|
2786
|
+
.filter((m) => m.thread === key)
|
|
2787
|
+
.slice(-10)
|
|
2788
|
+
.map((m) => ({ at: m.at, who: m.from === 'user' ? m.who || 'the user' : m.from === 'schedule' ? 'schedule' : handleOf(m.from), text: m.text })),
|
|
2789
|
+
};
|
|
2790
|
+
/** One stored Session event as a transcript line, or ''. */
|
|
2791
|
+
function eventLine(e) {
|
|
2792
|
+
const d = e?.data ?? {};
|
|
2793
|
+
if (e?.type === 'user/message') {
|
|
2794
|
+
const said = textOf(d.content);
|
|
2795
|
+
return said ? `[${d.source?.kind === 'user' ? 'user' : 'message'}] ${said}` : '';
|
|
2796
|
+
}
|
|
2797
|
+
if (e?.type === 'assistant/message') {
|
|
2798
|
+
const parts = [];
|
|
2799
|
+
for (const b of Array.isArray(d.message?.content) ? d.message.content : []) {
|
|
2800
|
+
if (b?.type === 'text' && b.text?.trim()) parts.push(`[assistant] ${b.text.trim()}`);
|
|
2801
|
+
else if (b?.type === 'tool-call') {
|
|
2802
|
+
let args = '';
|
|
2803
|
+
try {
|
|
2804
|
+
args = typeof b.argsRaw === 'string' ? b.argsRaw : JSON.stringify(b.args ?? b.arguments ?? b.input ?? {});
|
|
2805
|
+
} catch {
|
|
2806
|
+
args = '';
|
|
2807
|
+
}
|
|
2808
|
+
parts.push(`[tool] ${b.name ?? b.toolName ?? 'tool'} ${args.slice(0, 400)}`);
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
return parts.join('\n');
|
|
2812
|
+
}
|
|
2813
|
+
if (e?.type === 'tool/result') {
|
|
2814
|
+
const said = textOf(d.message?.content ?? d.content);
|
|
2815
|
+
return said ? `[result] ${said.slice(0, 600)}` : '';
|
|
2816
|
+
}
|
|
2817
|
+
return '';
|
|
2818
|
+
}
|
|
2819
|
+
/** A ticket Session's conversation: from its stored log when Harness has one, else from the runs this process recorded. */
|
|
2820
|
+
async function transcriptOf(t) {
|
|
2821
|
+
const events = t.sessionId ? await readHistory(t.sessionId).catch(() => null) : null;
|
|
2822
|
+
const fromLog = (events ?? []).map(eventLine).filter(Boolean);
|
|
2823
|
+
if (fromLog.length) return fromLog;
|
|
2824
|
+
const lines = [...(doneLogs.get(t.id) ?? []), ...(ticketLogs.get(t.id)?.log ?? []), ...(t.sessionId ? openTasks.get(t.sessionId)?.log ?? [] : [])];
|
|
2825
|
+
return lines.length ? lines : `(No transcript of task ${t.id} is kept here; its reports are at ticket/${t.id}/reports.)`;
|
|
1164
2826
|
}
|
|
1165
2827
|
|
|
1166
2828
|
// --- the model's tools ------------------------------------------------------------------
|
|
1167
|
-
const callerBot = (exec) =>
|
|
2829
|
+
const callerBot = (exec) => actor(exec).bot;
|
|
1168
2830
|
const resolve = (ref, what = 'bot') => {
|
|
1169
2831
|
const bot = store.find(ref);
|
|
1170
2832
|
if (!bot) throw new Error(`no ${what} "${ref}". Known bots: ${store.list().map((b) => `@${b.handle}`).join(', ') || 'none'}`);
|
|
@@ -1206,7 +2868,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1206
2868
|
const sk = b.skills.filter((s) => s.enabled).map((s) => s.name);
|
|
1207
2869
|
const ap = b.apps.filter((a) => a.enabled).map((a) => a.name);
|
|
1208
2870
|
const ts = tasks.filter((t) => t.botId === b.id).map((t) => `${t.title} (${t.describe}${t.status !== 'active' ? `, ${t.status}` : ''})`);
|
|
1209
|
-
|
|
2871
|
+
const open = tickets.list({ botId: b.id, open: true }).length;
|
|
2872
|
+
return [`${card(b)} [${botStatus(b)}${open ? `, ${open} open task${open === 1 ? '' : 's'}` : ''}]${b.bio ? `: ${b.bio}` : ''}`, sk.length ? ` skills: ${sk.join(', ')}` : '', ap.length ? ` apps: ${ap.join(', ')}` : '', ts.length ? ` scheduled: ${ts.join('; ')}` : ''].filter(Boolean).join('\n');
|
|
1210
2873
|
});
|
|
1211
2874
|
return { ok: true, text: lines.length ? lines.join('\n') : 'No bots yet.', bots: bots.map(face) };
|
|
1212
2875
|
},
|
|
@@ -1221,11 +2884,13 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1221
2884
|
persona: { type: 'string', description: 'Who the bot is and how it works, in the second person ("You are …"). Several sentences.' },
|
|
1222
2885
|
initials: { type: 'string', description: 'Avatar letters, at most two; derived from the name (pinyin initials for a Chinese name) when left out.' },
|
|
1223
2886
|
color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
|
|
2887
|
+
...AVATAR_PARAMS,
|
|
1224
2888
|
skills: { ...skillInput, description: 'Skills to give it.' },
|
|
1225
2889
|
},
|
|
1226
2890
|
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
|
|
1227
2891
|
execute: async (args, exec) => {
|
|
1228
|
-
const
|
|
2892
|
+
const caller = actor(exec);
|
|
2893
|
+
const by = caller.bot;
|
|
1229
2894
|
tooManySkills((args.skills ?? []).length);
|
|
1230
2895
|
const bot = store.save(
|
|
1231
2896
|
{
|
|
@@ -1238,12 +2903,13 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1238
2903
|
},
|
|
1239
2904
|
{ createdBy: by?.id ?? 'user' },
|
|
1240
2905
|
);
|
|
1241
|
-
|
|
2906
|
+
const pic = await applyPicture(bot, args, caller);
|
|
2907
|
+
return { ok: true, text: `Created ${card(pic.bot)}. Message it with bot_send_message to @${bot.handle}.${pic.note}${offNote(args.skills, bot)}`, bot: face(pic.bot) };
|
|
1242
2908
|
},
|
|
1243
2909
|
}),
|
|
1244
2910
|
defineTool({
|
|
1245
2911
|
name: 'bot_update',
|
|
1246
|
-
description: "Change a bot: name, bio, persona, avatar, skills, or make it the dispatcher. Only the fields you pass change.",
|
|
2912
|
+
description: "Change a bot (yourself included): name, bio, persona, avatar (letters and colour, a picture drawn by AI, or an image file), skills, or make it the dispatcher. Only the fields you pass change.",
|
|
1247
2913
|
parameters: {
|
|
1248
2914
|
bot: { type: 'string', required: true, description: '@handle, id or name of the bot.' },
|
|
1249
2915
|
name: { type: 'string' },
|
|
@@ -1251,12 +2917,16 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1251
2917
|
persona: { type: 'string', description: 'Replaces the whole persona.' },
|
|
1252
2918
|
initials: { type: 'string', description: 'Avatar letters, at most two.' },
|
|
1253
2919
|
color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
|
|
2920
|
+
...AVATAR_PARAMS,
|
|
2921
|
+
avatar_clear: { type: 'boolean', description: 'true to remove the avatar picture and go back to letters.' },
|
|
1254
2922
|
add_skills: { ...skillInput, description: `Skills to add (a skill with the same name is replaced). At most ${MAX_SKILLS_ON} can be on at once; past that they are added switched off.` },
|
|
1255
2923
|
remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
|
|
1256
2924
|
make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
|
|
1257
2925
|
},
|
|
1258
2926
|
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
|
|
1259
|
-
execute: async (args) => {
|
|
2927
|
+
execute: async (args, exec) => {
|
|
2928
|
+
// A helper whose line cannot be traced still changes bots, as before; it waits for a drawing.
|
|
2929
|
+
const caller = actorOf(exec);
|
|
1260
2930
|
const bot = resolve(args.bot);
|
|
1261
2931
|
const next = { id: bot.id };
|
|
1262
2932
|
for (const k of ['name', 'bio', 'persona']) if (typeof args[k] === 'string') next[k] = args[k];
|
|
@@ -1267,8 +2937,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1267
2937
|
tooManySkills(next.skills.length);
|
|
1268
2938
|
}
|
|
1269
2939
|
if (args.make_dispatcher === true) next.role = 'primary';
|
|
1270
|
-
const
|
|
1271
|
-
|
|
2940
|
+
const pic = await applyPicture(store.save(next), args, caller.restricted ? {} : caller);
|
|
2941
|
+
const saved = pic.bot;
|
|
2942
|
+
return { ok: true, text: `Updated ${card(saved)}.${pic.note}${offNote(args.add_skills, saved)}`, bot: face(saved) };
|
|
1272
2943
|
},
|
|
1273
2944
|
}),
|
|
1274
2945
|
defineTool({
|
|
@@ -1286,19 +2957,191 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1286
2957
|
}),
|
|
1287
2958
|
defineTool({
|
|
1288
2959
|
name: 'bot_send_message',
|
|
2960
|
+
description: [
|
|
2961
|
+
'Message another bot, or report on the task this conversation works on. Make the text self-contained: the other bot cannot see this conversation. Do not reply to acknowledgements.',
|
|
2962
|
+
"- To delegate: `to` (the bot's @handle) and `text`. Depending on how the team works, this opens a task (ticket) that the bot works on in a conversation of its own, or drops the text into that bot's own conversation; the result says which. Either way the call returns at once and the answer (a report, or a bot message) arrives here by itself: never wait or poll for it.",
|
|
2963
|
+
'- When this turn involves several chats, name the one a new task is for with `thread` (its key), so its report answers there.',
|
|
2964
|
+
'- To add to an open task you asked for (an answer to its question, a change): `ticket` (its id) and `text`.',
|
|
2965
|
+
'- In a task conversation, to report to whoever asked: leave out `to`, give `text` and a `status` (progress, done, blocked, question).',
|
|
2966
|
+
].join('\n'),
|
|
2967
|
+
parameters: {
|
|
2968
|
+
to: { type: 'string', description: '@handle (or id / name) of the bot. Leave it out to report on your own task.' },
|
|
2969
|
+
text: { type: 'string', required: true, description: 'The whole message or report.' },
|
|
2970
|
+
ticket: { type: 'string', description: 'Id of an open task to add this message to.' },
|
|
2971
|
+
status: { type: 'string', enum: REPORT_STATUSES, description: 'Required when reporting from a task conversation: progress (an update worth keeping), done (with the result), blocked, question.' },
|
|
2972
|
+
title: { type: 'string', description: 'A short title for a new task; taken from the first line of text when left out.' },
|
|
2973
|
+
thread: { type: 'string', description: 'Only when this turn involves several chats: the key of the thread (as the message header "(thread …)" shows it) the new task is for. Its report then answers there, and follow-ups there reach the task. Left out with several chats, the task belongs to none of them.' },
|
|
2974
|
+
},
|
|
2975
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from, ...(v.ticket ? { ticket: v.ticket } : {}) }) },
|
|
2976
|
+
isConcurrencySafe: () => true,
|
|
2977
|
+
execute: async (args, exec) => {
|
|
2978
|
+
const { sessionId, bot: sender } = actor(exec);
|
|
2979
|
+
const mine = ticketOf(sessionId);
|
|
2980
|
+
const named = args.to !== undefined && String(args.to).trim() !== '' ? resolve(args.to) : null;
|
|
2981
|
+
const wantTicket = typeof args.ticket === 'string' && args.ticket.trim() !== '' ? args.ticket.trim().replace(/^ticket\//, '') : '';
|
|
2982
|
+
const row = (t) => ticketRow(t);
|
|
2983
|
+
const status = typeof args.status === 'string' && args.status.trim() !== '' ? args.status.trim().toLowerCase() : '';
|
|
2984
|
+
|
|
2985
|
+
// In a ticket Session: a report to whoever asked (no `to`, the requester, or its own ticket).
|
|
2986
|
+
if (mine && sender) {
|
|
2987
|
+
const requesterBot = mine.requester?.botId;
|
|
2988
|
+
const isReport = wantTicket ? wantTicket === mine.id : !named || (named.id === requesterBot && named.id !== sender.id);
|
|
2989
|
+
if (isReport) {
|
|
2990
|
+
if (!status) throw new Error(`a report on task ${mine.id} needs a status: progress (an update), done (with the result), blocked or question`);
|
|
2991
|
+
const { ticket, relayed, unread, parent } = await reportTicket(mine, status, args.text);
|
|
2992
|
+
const to = requesterBot ? store.get(requesterBot) : null;
|
|
2993
|
+
const said =
|
|
2994
|
+
status === 'progress'
|
|
2995
|
+
? `Recorded on task ${ticket.id}; progress does not interrupt whoever asked. Go on with the work.`
|
|
2996
|
+
: unread
|
|
2997
|
+
? `Recorded "${status}" on task ${ticket.id}, but nobody is told: ${unread === 'ended' ? `the task has ended (${stageOf(ticket)})` : `the task that asked for it${parent ? `, ${parent},` : ''} has ended`}. The report is kept on the task; end your turn now.`
|
|
2998
|
+
: `Reported "${status}" on task ${ticket.id} to ${to ? `@${to.handle}` : 'the user'}${relayed || !to ? '' : ' (it could not be reached just now; the report is kept on the task)'}.${status === 'done' ? ' The task is done: end your turn without a summary.' : ' An answer will arrive here by itself; end your turn now.'}`;
|
|
2999
|
+
return { ok: true, text: said, ticket: row(ticket), to: face(to), from: face(sender) };
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
if (status) throw new Error(mine ? `\`status\` is for reports to whoever asked for task ${mine.id} (leave out "to"); to ask @${named?.handle ?? 'a bot'} for help, leave out \`status\`` : '`status` is only for reports from a task conversation; leave it out here');
|
|
3003
|
+
|
|
3004
|
+
// Adding to an existing ticket.
|
|
3005
|
+
if (wantTicket) {
|
|
3006
|
+
const t = tickets.get(wantTicket);
|
|
3007
|
+
if (!t) throw new Error(`no task ${wantTicket}`);
|
|
3008
|
+
if (named && named.id !== t.botId) throw new Error(`task ${t.id} belongs to ${handleOf(t.botId)}, not @${named.handle}; leave out "to" or name its bot`);
|
|
3009
|
+
if (!mayAppend(t, sender, sessionId)) throw new Error(`task ${t.id} was not asked for from this conversation; message its bot with a new task instead`);
|
|
3010
|
+
const next = await appendToTicket(t, args.text, { sender: sender ?? null, senderSessionId: sessionId });
|
|
3011
|
+
const target = store.get(next.botId);
|
|
3012
|
+
const waits = next.startedAt && parkedOf(next).length > 0 ? ': every worker slot is taken, so it is handed over when one frees' : '';
|
|
3013
|
+
return { ok: true, text: `Added to task ${next.id} (${stageOf(next)}${waits}). ${handleOf(next.botId)}'s report will arrive here by itself; do not wait for it.`, ticket: row(next), to: face(target), from: face(sender) };
|
|
3014
|
+
}
|
|
3015
|
+
if (!named) throw new Error(mine ? 'say which bot with `to`, or leave it out and give a `status` to report on your task' : 'say which bot with `to`');
|
|
3016
|
+
|
|
3017
|
+
// A new ticket: from a task conversation (a sub-task), or from a bot's home when tasks are on.
|
|
3018
|
+
const chosen = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : '';
|
|
3019
|
+
if (sender && sessionId && (mine || (ticketsOn() && sender.sessionId === sessionId))) {
|
|
3020
|
+
const t = await openTicket(sender, named, args.text, sessionId, { title: args.title, thread: chosen });
|
|
3021
|
+
const stage = stageOf(t);
|
|
3022
|
+
const said =
|
|
3023
|
+
stage === 'failed'
|
|
3024
|
+
? `Task ${t.id} for @${named.handle} could not start: ${t.error ?? 'unknown error'}.`
|
|
3025
|
+
: `Opened task ${t.id} for @${named.handle} (${stage === 'queued' ? 'queued: it starts when another task finishes' : stage}). Its report will arrive here by itself; never wait or poll for it — go on with other work or end your turn.`;
|
|
3026
|
+
return { ok: stage !== 'failed', text: said, ticket: row(t), stage, to: face(named), from: face(sender) };
|
|
3027
|
+
}
|
|
3028
|
+
// 0.7: into the other bot's home (the user from any conversation; any home in hands-on mode).
|
|
3029
|
+
if (chosen) throw new Error('`thread` is for opening a task; this message goes to the bot\'s own conversation, so leave it out');
|
|
3030
|
+
await deliver(sender ?? null, named, args.text, sessionId);
|
|
3031
|
+
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) };
|
|
3032
|
+
},
|
|
3033
|
+
}),
|
|
3034
|
+
defineTool({
|
|
3035
|
+
name: 'bot_reply',
|
|
3036
|
+
description:
|
|
3037
|
+
'Send text to a chat: the chat a task came from (`ticket`: its id) or a chat thread (`thread`: its key, as message headers "(thread …)" and task cards show it). Use it when this turn involves more than one chat, so each answer reaches its own chat; your plain text then stays in the panel. With a single chat in the turn, plain text goes there already.',
|
|
3038
|
+
parameters: {
|
|
3039
|
+
ticket: { type: 'string', description: 'Id of a task (t…): the reply goes to the chat that task came from.' },
|
|
3040
|
+
thread: { type: 'string', description: 'Key of a chat thread of this turn (or of a task you know of).' },
|
|
3041
|
+
text: { type: 'string', required: true, description: 'The reply, as the person should read it.' },
|
|
3042
|
+
},
|
|
3043
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ via: v.via, thread: v.thread }) },
|
|
3044
|
+
execute: async (args, exec) => {
|
|
3045
|
+
const { sessionId, bot } = actor(exec);
|
|
3046
|
+
if (ticketOf(sessionId)) throw new Error('a task conversation talks to no chat: report with bot_send_message (leave out "to"), and whoever asked passes it on');
|
|
3047
|
+
if (!bot) throw new Error("bot_reply answers from a bot's own conversation; this conversation has no chats");
|
|
3048
|
+
const body = String(args.text ?? '').trim();
|
|
3049
|
+
if (body === '') throw new Error('text must not be empty');
|
|
3050
|
+
const thread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim().replace(/^thread\//, '') : '';
|
|
3051
|
+
const ticketId = typeof args.ticket === 'string' && args.ticket.trim() !== '' ? args.ticket.trim().replace(/^(?:ticket|task)\//, '') : '';
|
|
3052
|
+
const options = () => {
|
|
3053
|
+
const list = channels.current(sessionId).filter((o) => o.kind !== 'panel');
|
|
3054
|
+
return list.length
|
|
3055
|
+
? `This turn's chats: ${list.map((o) => `${o.threadKey} (${threadLabel(o)}${o.tickets?.length ? `; task ${o.tickets.join(', ')}` : ''})`).join('; ')}.`
|
|
3056
|
+
: 'This turn has no chat; a task id names the chat it came from.';
|
|
3057
|
+
};
|
|
3058
|
+
if (!thread && !ticketId) throw new Error(`say where: \`ticket\` (a task id) or \`thread\` (a thread key). ${options()}`);
|
|
3059
|
+
const target = channels.resolveReply(sessionId, thread ? { thread } : { ticket: ticketId });
|
|
3060
|
+
if (!target) throw new Error(`${thread ? `no chat thread "${thread}"` : `no chat for task ${ticketId}`} can be reached from here. ${options()}`);
|
|
3061
|
+
if (target.kind === 'panel') {
|
|
3062
|
+
store.log({ from: bot.id, to: 'user', text: body, kind: 'reply', thread: panelThreadKey(sessionId) });
|
|
3063
|
+
return { ok: true, text: 'That thread is the panel: the reply is shown there.', thread: target.threadKey };
|
|
3064
|
+
}
|
|
3065
|
+
channels.replyTo(sessionId, target, body);
|
|
3066
|
+
store.log({ from: bot.id, to: 'user', text: body, kind: 'reply', via: target.kind, thread: target.threadKey });
|
|
3067
|
+
return { ok: true, text: `Sent to ${threadLabel(target)}.`, thread: target.threadKey, via: target.kind };
|
|
3068
|
+
},
|
|
3069
|
+
}),
|
|
3070
|
+
defineTool({
|
|
3071
|
+
name: 'bot_recall',
|
|
1289
3072
|
description:
|
|
1290
|
-
|
|
3073
|
+
'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.',
|
|
1291
3074
|
parameters: {
|
|
1292
|
-
|
|
1293
|
-
|
|
3075
|
+
ref: { type: 'string', required: true, description: 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key> or bot/<handle>.' },
|
|
3076
|
+
offset: { type: 'number', description: 'Where the next page starts: the `next_offset` of the last one.' },
|
|
1294
3077
|
},
|
|
1295
|
-
output: { schema: anyValue, render: (_a, v) => text(v.text)
|
|
3078
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text) },
|
|
1296
3079
|
isConcurrencySafe: () => true,
|
|
1297
3080
|
execute: async (args, exec) => {
|
|
1298
|
-
const
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
3081
|
+
const result = await readResource(String(args.ref ?? ''), {
|
|
3082
|
+
viewer: viewerOf(actorOf(exec)),
|
|
3083
|
+
tickets,
|
|
3084
|
+
threads: recallThreads,
|
|
3085
|
+
bots: store.list(),
|
|
3086
|
+
stageOf,
|
|
3087
|
+
transcript: (t) => transcriptOf(t),
|
|
3088
|
+
offset: args.offset,
|
|
3089
|
+
now: nowMs(),
|
|
3090
|
+
});
|
|
3091
|
+
return { ok: true, ...result, text: JSON.stringify(result, null, 1) };
|
|
3092
|
+
},
|
|
3093
|
+
}),
|
|
3094
|
+
defineTool({
|
|
3095
|
+
name: 'bot_ticket',
|
|
3096
|
+
description:
|
|
3097
|
+
'Act on a task (ticket) you asked for: `stop` it (its work is cancelled), `close` it as done, `retry` it (its bot takes it up again from the assignment), or `status` (asks its bot for a report when it is idle; the report arrives here by itself, never wait for it). From a task conversation you can act only on the sub-tasks it opened.',
|
|
3098
|
+
parameters: {
|
|
3099
|
+
id: { type: 'string', required: true, description: 'The task id (t…), as on its card.' },
|
|
3100
|
+
action: { type: 'string', required: true, enum: ['stop', 'close', 'retry', 'status'] },
|
|
3101
|
+
},
|
|
3102
|
+
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ ticket: v.ticket }) },
|
|
3103
|
+
execute: async (args, exec) => {
|
|
3104
|
+
const caller = actor(exec);
|
|
3105
|
+
const sessionId = caller.sessionId;
|
|
3106
|
+
const sender = caller.bot ?? null;
|
|
3107
|
+
const id = String(args.id ?? '').trim().replace(/^(?:ticket|task)\//, '');
|
|
3108
|
+
const action = String(args.action ?? '').trim().toLowerCase();
|
|
3109
|
+
if (!['stop', 'close', 'retry', 'status'].includes(action)) throw new Error('action is one of stop, close, retry, status');
|
|
3110
|
+
const t = tickets.get(id);
|
|
3111
|
+
if (!t) throw new Error(`no task ${id}. bot_recall {"ref":"tickets"} lists them.`);
|
|
3112
|
+
const mine = ticketOf(sessionId);
|
|
3113
|
+
if (mine) {
|
|
3114
|
+
if (t.parentId !== mine.id) throw new Error(`from task ${mine.id} you can act only on the sub-tasks it opened${t.id === mine.id ? '; to finish this task, report "done" with bot_send_message' : ''}`);
|
|
3115
|
+
} else if (sender && !mayAppend(t, sender, sessionId)) {
|
|
3116
|
+
throw new Error(`task ${t.id} was not asked for from this conversation; only whoever asked for it (or the dispatcher) can ${action} it`);
|
|
3117
|
+
}
|
|
3118
|
+
if (t.archivedAt) throw new Error(`task ${t.id} is archived; open a new task instead`);
|
|
3119
|
+
const by = sender ? 'requester' : 'user';
|
|
3120
|
+
const bot = handleOf(t.botId);
|
|
3121
|
+
let next = t;
|
|
3122
|
+
let said = '';
|
|
3123
|
+
if (action === 'stop' || action === 'close') {
|
|
3124
|
+
next = endTicket(t, { by, outcome: action === 'stop' ? 'stopped' : 'done' });
|
|
3125
|
+
said = action === 'stop' ? `Stopped task ${t.id} (${bot}).` : `Closed task ${t.id} (${bot}) as done.`;
|
|
3126
|
+
} else if (action === 'retry') {
|
|
3127
|
+
next = await retryTicket(t, sender ? { sender, senderSessionId: sessionId } : {});
|
|
3128
|
+
said = `Task ${t.id} (${bot}) is ${stageOf(next)} again; its report will arrive here by itself.`;
|
|
3129
|
+
} else if (t.ended) {
|
|
3130
|
+
said = `Task ${t.id} (${bot}) is ${stageOf(t)}; there is no work to report on. bot_recall reads its reports.`;
|
|
3131
|
+
} else if (!t.startedAt) {
|
|
3132
|
+
said = `Task ${t.id} (${bot}) is queued: it has not started yet.`;
|
|
3133
|
+
} else if (parkedOf(t).length > 0) {
|
|
3134
|
+
said = `Task ${t.id} (${bot}) waits for a free worker slot; the messages for it are handed over then, and its report arrives here by itself.`;
|
|
3135
|
+
} else if (agentStatusOf(t.sessionId) === 'running') {
|
|
3136
|
+
said = `${bot} is working on task ${t.id} right now; its next report arrives here by itself.`;
|
|
3137
|
+
} else {
|
|
3138
|
+
const who = sender ? `@${sender.handle}` : 'The user';
|
|
3139
|
+
const ask = `[Status request] ${who} asks how task ${t.id} ("${t.title}") stands. Report now with bot_send_message: "progress" with what is done and what is left, "done" with the result if it is finished, "blocked" or "question" if you are stuck.`;
|
|
3140
|
+
// A person's question may take the extra slot; a bot's waits for a free one.
|
|
3141
|
+
const { parked } = await toTicket(t, { content: [{ type: 'text', text: ask }], source: sender && sessionId ? { kind: 'agent-message', form: 'relay', senderSessionId: sessionId } : { kind: 'user' }, key: `status:${t.id}:${nowMs()}`, human: !sender });
|
|
3142
|
+
said = parked ? `Every worker slot is taken: ${bot} gets the status request on task ${t.id} when one frees; the report arrives here by itself, do not wait for it.` : `Asked ${bot} for a status report on task ${t.id}; it arrives here by itself, do not wait for it.`;
|
|
3143
|
+
}
|
|
3144
|
+
return { ok: true, text: said, ticket: ticketRow(tickets.get(next.id) ?? next) };
|
|
1302
3145
|
},
|
|
1303
3146
|
}),
|
|
1304
3147
|
defineTool({
|
|
@@ -1321,7 +3164,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1321
3164
|
},
|
|
1322
3165
|
output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot, task: v.task }) },
|
|
1323
3166
|
execute: async (args, exec) => {
|
|
1324
|
-
const
|
|
3167
|
+
const actorId = exec?.agent?.session?.id;
|
|
1325
3168
|
const bot = args.bot ? resolve(args.bot) : callerBot(exec) ?? store.primary();
|
|
1326
3169
|
if (!bot && (args.action === 'create' || args.action === 'list')) throw new Error('say which bot with `bot`');
|
|
1327
3170
|
switch (args.action) {
|
|
@@ -1332,15 +3175,15 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1332
3175
|
case 'create':
|
|
1333
3176
|
case 'update': {
|
|
1334
3177
|
const timing = args.kind ? timingFrom(args, zone) : undefined;
|
|
1335
|
-
const task = await scheduleSave(bot, { id: args.action === 'update' ? args.id : undefined, title: args.title, prompt: args.prompt, timing },
|
|
3178
|
+
const task = await scheduleSave(bot, { id: args.action === 'update' ? args.id : undefined, title: args.title, prompt: args.prompt, timing }, actorId);
|
|
1336
3179
|
return { ok: true, bot: face(bot), task, text: `${args.action === 'create' ? 'Scheduled' : 'Updated'} "${task.title}" for @${bot.handle}: ${task.describe}; next at ${task.scheduledAt} (id ${task.id}).` };
|
|
1337
3180
|
}
|
|
1338
3181
|
case 'delete':
|
|
1339
|
-
checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'delete' },
|
|
3182
|
+
checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'delete' }, actorId));
|
|
1340
3183
|
return { ok: true, text: `Deleted task ${args.id}.` };
|
|
1341
3184
|
case 'pause':
|
|
1342
3185
|
case 'resume': {
|
|
1343
|
-
const task = entryView(checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'update', patch: { active: args.action === 'resume' } },
|
|
3186
|
+
const task = entryView(checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'update', patch: { active: args.action === 'resume' } }, actorId)));
|
|
1344
3187
|
return { ok: true, task, text: `${args.action === 'pause' ? 'Paused' : 'Resumed'} "${task.title}".` };
|
|
1345
3188
|
}
|
|
1346
3189
|
case 'run':
|
|
@@ -1397,21 +3240,30 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1397
3240
|
}),
|
|
1398
3241
|
defineTool({
|
|
1399
3242
|
name: 'memory_search',
|
|
1400
|
-
description:
|
|
3243
|
+
description:
|
|
3244
|
+
"Search long-term memory, the team's work journal (what every bot did, task by task), daily digests, and tasks (their titles and reports), for words in the query. Use it when the user refers to earlier work that is not in this conversation; a task it finds can be read with bot_recall (ticket/<id>).",
|
|
1401
3245
|
parameters: { query: { type: 'string', required: true, description: 'Words that should all appear.' } },
|
|
1402
3246
|
output: { schema: anyValue, render: (_a, v) => text(v.text) },
|
|
1403
3247
|
isConcurrencySafe: () => true,
|
|
1404
3248
|
execute: async (args, exec) => {
|
|
1405
|
-
const me =
|
|
3249
|
+
const { sessionId, bot: me } = actor(exec);
|
|
1406
3250
|
const r = memory.search(args.query, { bot: me?.id ?? '' });
|
|
1407
3251
|
const tz = tzMinutes();
|
|
1408
3252
|
const when = (ms) => new Date(ms + tz * 60_000).toISOString().slice(0, 16).replace('T', ' ');
|
|
3253
|
+
// A task conversation finds only what it may read with bot_recall: its task, the parent, the sub-tasks;
|
|
3254
|
+
// journal lines of those tasks, none of other work (lines without a task, digests of everyone's day).
|
|
3255
|
+
const mine = ticketOf(sessionId);
|
|
3256
|
+
const scope = mine ? new Set([mine.id, mine.parentId, ...tickets.children(mine.id).map((c) => c.id)].filter(Boolean)) : null;
|
|
3257
|
+
const found = searchTickets(args.query, tickets.list().filter((t) => !scope || scope.has(t.id)));
|
|
3258
|
+
const journal = scope ? r.journal.filter((j) => j.ticket && scope.has(j.ticket)) : r.journal;
|
|
3259
|
+
const digests = scope ? [] : r.digests;
|
|
1409
3260
|
const lines = [
|
|
1410
3261
|
...r.notes.map((n) => `[${n.id}] (${n.scope === 'team' ? 'team' : 'yours'}) ${n.text}`),
|
|
1411
|
-
...
|
|
1412
|
-
...
|
|
3262
|
+
...journal.map((j) => `${when(j.at)} @${store.get(j.bot)?.handle ?? 'removed'}: ${j.summary || j.title}${j.ticket ? ` (task ${j.ticket})` : ''}`),
|
|
3263
|
+
...digests.map((d) => `Digest ${d.date}: ${d.text.slice(0, 600)}`),
|
|
3264
|
+
...found.map((f) => `Task ${f.ticket.id} (${handleOf(f.ticket.botId)}, ${stageOf(f.ticket)}): ${f.ticket.title}${f.where === 'report' ? ` — ${f.status} report: ${f.snippet}` : ''} [bot_recall "ticket/${f.ticket.id}"]`),
|
|
1413
3265
|
];
|
|
1414
|
-
return { ok: true, text: lines.length ? lines.join('\n') : `Nothing in memory matches "${args.query}"
|
|
3266
|
+
return { ok: true, text: lines.length ? lines.join('\n') : `Nothing in memory matches "${args.query}".`, tickets: found.map((f) => f.ticket.id) };
|
|
1415
3267
|
},
|
|
1416
3268
|
}),
|
|
1417
3269
|
];
|
|
@@ -1535,6 +3387,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1535
3387
|
skills: skills.map((s) => ({ name: s.name, description: String(s.description ?? '').slice(0, 300) })),
|
|
1536
3388
|
ocu: { installed: ocu !== '', path: ocu || OCU_PATHS[0] },
|
|
1537
3389
|
mcp: Boolean(mcpClient),
|
|
3390
|
+
// Off for a router dispatcher unless its bot lists them in `tools.routerAllow`.
|
|
3391
|
+
routerDeny: [...ROUTER_DENY],
|
|
1538
3392
|
zone,
|
|
1539
3393
|
};
|
|
1540
3394
|
}
|
|
@@ -1695,6 +3549,7 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1695
3549
|
sweeping = true;
|
|
1696
3550
|
try {
|
|
1697
3551
|
for (const bot of store.list()) await autoTopic(bot, 'sweep');
|
|
3552
|
+
await ticketUpkeep().catch((error) => ctx.logger?.warn?.(`bots: task upkeep: ${error?.message ?? error}`));
|
|
1698
3553
|
if (dreamDue()) await dream({ reason: 'schedule' }).catch((error) => ctx.logger?.warn?.(`bots: dream: ${error?.message ?? error}`));
|
|
1699
3554
|
if (settings.get().codex.sync) await codexSync.syncOnce().catch((error) => ctx.logger?.warn?.(`bots: codex login sync: ${error?.message ?? error}`));
|
|
1700
3555
|
} finally {
|
|
@@ -1720,9 +3575,10 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1720
3575
|
const overrides = settings.get().prices;
|
|
1721
3576
|
const catalog = prices.peek();
|
|
1722
3577
|
const running = [...openTasks.values()].map(({ log, size, replied, ...t }) => t);
|
|
3578
|
+
const names = new Map(tickets.list().map((t) => [t.id, { title: t.title, botId: t.botId }]));
|
|
1723
3579
|
const r = report(
|
|
1724
3580
|
{ calls: ledger.calls(), tasks: ledger.tasks(), running },
|
|
1725
|
-
{ range: url.searchParams.get('range') || '7d', bot: url.searchParams.get('bot') || '', tz: Number.isFinite(tz) ? tz : tzMinutes(), price: (m) => priceOf(m, overrides, catalog), schedules: scheduleTitles },
|
|
3581
|
+
{ range: url.searchParams.get('range') || '7d', bot: url.searchParams.get('bot') || '', tz: Number.isFinite(tz) ? tz : tzMinutes(), price: (m) => priceOf(m, overrides, catalog), schedules: scheduleTitles, tickets: names },
|
|
1726
3582
|
);
|
|
1727
3583
|
return { ...r, priceList: prices.status() };
|
|
1728
3584
|
}
|
|
@@ -1760,9 +3616,29 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1760
3616
|
/** A bot as the page sees it: channel tokens masked. */
|
|
1761
3617
|
const publicBot = (bot) => (bot ? maskBot(bot, templates()) : bot);
|
|
1762
3618
|
|
|
3619
|
+
/**
|
|
3620
|
+
* Tickets that need a person (not archived): an unanswered question, a failure, a stall; and a
|
|
3621
|
+
* ticket the user asked for whose latest report (done, blocked, question) has no Session to go to,
|
|
3622
|
+
* until the user answers it or closes the ticket.
|
|
3623
|
+
*/
|
|
3624
|
+
const ATTENTION = new Set(['question', 'failed', 'stalled']);
|
|
3625
|
+
const needsPerson = (t) => {
|
|
3626
|
+
if (ATTENTION.has(stageOf(t))) return true;
|
|
3627
|
+
if (t.requester?.kind === 'session') return false;
|
|
3628
|
+
const last = t.reports.at(-1);
|
|
3629
|
+
return Boolean(last && last.status !== 'progress' && t.ended?.by !== 'user' && !((t.lastHumanAt ?? 0) > last.at));
|
|
3630
|
+
};
|
|
1763
3631
|
function state() {
|
|
1764
3632
|
const tpl = templates();
|
|
1765
3633
|
const today = todayByBot(ledger.calls(), tzMinutes());
|
|
3634
|
+
const live = tickets.list({ archived: false });
|
|
3635
|
+
const waiting = pendingAsks();
|
|
3636
|
+
const counts = new Map();
|
|
3637
|
+
for (const t of live) {
|
|
3638
|
+
const stage = stageOf(t);
|
|
3639
|
+
const c = counts.get(t.botId) ?? counts.set(t.botId, { working: 0, question: 0, stalled: 0, queued: 0 }).get(t.botId);
|
|
3640
|
+
if (stage in c) c[stage] += 1;
|
|
3641
|
+
}
|
|
1766
3642
|
const bots = store.list().map((b) => {
|
|
1767
3643
|
const appIssues = {};
|
|
1768
3644
|
for (const app of b.apps) {
|
|
@@ -1795,11 +3671,69 @@ export function apply(ctx, config, deps = {}) {
|
|
|
1795
3671
|
topic: topic && topic.sessionId === b.sessionId ? { startedAt: topic.startedAt, lastActiveAt: topic.lastActiveAt, tasks: topic.tasks, context: topic.lastPrompt } : null,
|
|
1796
3672
|
usageToday: today[b.id] ?? 0,
|
|
1797
3673
|
memoryNotes: memory.notes(b.id).length,
|
|
3674
|
+
tickets: counts.get(b.id) ?? { working: 0, question: 0, stalled: 0, queued: 0 },
|
|
3675
|
+
// Questions its own conversation waits to have answered (`asks`); a task's count under `attention`.
|
|
3676
|
+
asking: waiting.filter((a) => a.botId === b.id && !a.ticketId).length,
|
|
3677
|
+
...liveOf(b),
|
|
1798
3678
|
};
|
|
1799
3679
|
});
|
|
1800
3680
|
const sessionMap = {};
|
|
1801
3681
|
for (const b of bots) if (b.sessionId) sessionMap[b.sessionId] = b.id;
|
|
1802
|
-
|
|
3682
|
+
// Ticket Sessions carry their bot's badge in Harness too; `ticketMap` says which task each one is.
|
|
3683
|
+
const ticketMap = {};
|
|
3684
|
+
for (const t of live) {
|
|
3685
|
+
if (!t.sessionId || !store.get(t.botId)) continue;
|
|
3686
|
+
sessionMap[t.sessionId] = t.botId;
|
|
3687
|
+
ticketMap[t.sessionId] = t.id;
|
|
3688
|
+
}
|
|
3689
|
+
const s = settings.get();
|
|
3690
|
+
return {
|
|
3691
|
+
// The Host's clock, so the page can time what runs.
|
|
3692
|
+
at: nowMs(),
|
|
3693
|
+
bots,
|
|
3694
|
+
primaryId: store.primary()?.id ?? null,
|
|
3695
|
+
sessionMap,
|
|
3696
|
+
ticketMap,
|
|
3697
|
+
messageCount: store.messageCount(),
|
|
3698
|
+
version: store.version(),
|
|
3699
|
+
limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON },
|
|
3700
|
+
teamNotes: memory.notes('team').length,
|
|
3701
|
+
dispatcher: s.dispatcher,
|
|
3702
|
+
// The setting asks for a router, and the dispatcher has a teammate to hand work to: it routes now.
|
|
3703
|
+
routerActive: routerActive(),
|
|
3704
|
+
routerNoticePending: s.routerNotice === 'pending',
|
|
3705
|
+
// A task whose conversation waits for an answer to its question needs you too (its row says `asking`).
|
|
3706
|
+
attention: live.filter((t) => needsPerson(t) || askingIn(t.sessionId)).sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 50).map(ticketRow),
|
|
3707
|
+
asks: waiting.sort((a, b) => a.at - b.at).map(askView),
|
|
3708
|
+
// What each running task Session does now, by task id (with its bot); a bot's home under `bots[].activity`.
|
|
3709
|
+
taskActivity: taskActivity(),
|
|
3710
|
+
// How the panel shows what bots say to each other ('line' | 'short' | 'full').
|
|
3711
|
+
display: s.display,
|
|
3712
|
+
};
|
|
3713
|
+
}
|
|
3714
|
+
/** A bot's live fields in state: what its home does now (`activity`), and a picture being drawn for it (`avatarPending`). */
|
|
3715
|
+
function liveOf(b) {
|
|
3716
|
+
const now = activity.get(b.sessionId);
|
|
3717
|
+
return { ...(now ? { activity: now } : {}), ...(drawings.has(b.id) ? { avatarPending: true } : {}) };
|
|
3718
|
+
}
|
|
3719
|
+
/** Task id → what its running Session does now, with the task's bot and title. */
|
|
3720
|
+
function taskActivity() {
|
|
3721
|
+
const out = {};
|
|
3722
|
+
for (const sid of activity.sessions()) {
|
|
3723
|
+
const t = ticketOf(sid);
|
|
3724
|
+
const now = t && !t.ended ? activity.get(sid) : undefined;
|
|
3725
|
+
if (now) out[t.id] = { ...now, botId: t.botId, title: t.title };
|
|
3726
|
+
}
|
|
3727
|
+
return out;
|
|
3728
|
+
}
|
|
3729
|
+
/**
|
|
3730
|
+
* GET /activity: only what moves while bots work, for the panel to poll often while something
|
|
3731
|
+
* runs: each bot's status and live fields, and the running tasks' activity.
|
|
3732
|
+
*/
|
|
3733
|
+
function activityView() {
|
|
3734
|
+
const bots = {};
|
|
3735
|
+
for (const b of store.list()) bots[b.id] = { status: botStatus(b), ...liveOf(b) };
|
|
3736
|
+
return { ok: true, at: nowMs(), bots, taskActivity: taskActivity() };
|
|
1803
3737
|
}
|
|
1804
3738
|
|
|
1805
3739
|
let ocuInstalling = false;
|
|
@@ -2076,11 +4010,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2076
4010
|
if (!m) return { ok: false, reason: 'send a PNG, JPEG, WebP or GIF image' };
|
|
2077
4011
|
const bytes = Buffer.from(m[2], 'base64');
|
|
2078
4012
|
if (bytes.length > MAX_AVATAR) return { ok: false, reason: 'the image is larger than 2 MB' };
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
writeFileSync(join(dir, 'avatars', `${bot.id}.type`), m[1]);
|
|
2082
|
-
const saved = store.patch(bot.id, { avatar: { kind: 'image', url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
|
|
2083
|
-
return { ok: true, bot: publicBot(saved) };
|
|
4013
|
+
dropDrawing(bot.id, 'panel');
|
|
4014
|
+
return { ok: true, bot: publicBot(savePicture(bot, bytes, m[1])) };
|
|
2084
4015
|
},
|
|
2085
4016
|
},
|
|
2086
4017
|
'avatar/generate': {
|
|
@@ -2094,8 +4025,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2094
4025
|
post: (body) => {
|
|
2095
4026
|
const bot = store.get(String(body.id ?? ''));
|
|
2096
4027
|
if (!bot) return { ok: false, reason: 'no such bot' };
|
|
2097
|
-
|
|
2098
|
-
return { ok: true, bot: publicBot(
|
|
4028
|
+
dropDrawing(bot.id, 'panel');
|
|
4029
|
+
return { ok: true, bot: publicBot(clearPicture(bot)) };
|
|
2099
4030
|
},
|
|
2100
4031
|
},
|
|
2101
4032
|
'ocu/install': {
|
|
@@ -2133,6 +4064,8 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2133
4064
|
'schedules/run': { post: async (body) => (checkEntry(await schedule().run({ id: String(body.id ?? '') })), { ok: true }) },
|
|
2134
4065
|
// Usage, prices, memory, topics, settings, model sources.
|
|
2135
4066
|
usage: { get: (url) => usageReport(url) },
|
|
4067
|
+
// The live part of `state`, cheap enough to poll every second or two while bots work.
|
|
4068
|
+
activity: { get: () => activityView() },
|
|
2136
4069
|
prices: {
|
|
2137
4070
|
get: () => pricesView(),
|
|
2138
4071
|
post: (body) => {
|
|
@@ -2152,9 +4085,17 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2152
4085
|
const patch = body.patch && typeof body.patch === 'object' ? { ...body.patch } : {};
|
|
2153
4086
|
delete patch.codex;
|
|
2154
4087
|
delete patch.prices;
|
|
2155
|
-
|
|
4088
|
+
// Picking a dispatcher mode is having seen the notice about it.
|
|
4089
|
+
if (patch.dispatcher !== undefined) patch.routerNotice = 'dismissed';
|
|
4090
|
+
const saved = settings.save(patch);
|
|
4091
|
+
settingsChanged();
|
|
4092
|
+
return { ok: true, settings: saved };
|
|
2156
4093
|
},
|
|
2157
4094
|
},
|
|
4095
|
+
// The one-time notice that an upgraded team's dispatcher now routes: dismissed for good.
|
|
4096
|
+
'router-notice/dismiss': { post: () => (settings.save({ routerNotice: 'dismissed' }), { ok: true, routerNoticePending: false }) },
|
|
4097
|
+
// Tasks (tickets), PLAN-0.8 §6.3. `tickets/:id…` and `threads/:key` are under `paramRoutes`.
|
|
4098
|
+
tickets: { get: (url) => ticketList(url) },
|
|
2158
4099
|
memory: { get: (url) => memoryView(url.searchParams.get('bot') ?? 'team') },
|
|
2159
4100
|
'memory/put': {
|
|
2160
4101
|
post: (body) => {
|
|
@@ -2199,9 +4140,110 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2199
4140
|
'channels/reconnect': { post: (body) => ({ ok: channels.reconnect(String(body.botId ?? ''), String(body.appId ?? '')) }) },
|
|
2200
4141
|
};
|
|
2201
4142
|
|
|
4143
|
+
/** GET /tickets?bot=&stage=&limit=&offset=: rows, the latest change first; `stage` may list several (a,b). */
|
|
4144
|
+
function ticketList(url) {
|
|
4145
|
+
const bot = url.searchParams.get('bot') || undefined;
|
|
4146
|
+
const stage = (url.searchParams.get('stage') ?? '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
4147
|
+
const archived = url.searchParams.get('archived');
|
|
4148
|
+
const limit = Math.min(200, Math.max(1, Math.floor(Number(url.searchParams.get('limit')) || 50)));
|
|
4149
|
+
const offset = Math.max(0, Math.floor(Number(url.searchParams.get('offset')) || 0));
|
|
4150
|
+
const all = tickets
|
|
4151
|
+
.list({ botId: bot, ...(stage.length ? { stage } : {}), ...(archived === '0' || archived === 'false' ? { archived: false } : archived === '1' || archived === 'true' ? { archived: true } : {}) })
|
|
4152
|
+
.sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt);
|
|
4153
|
+
const items = all.slice(offset, offset + limit).map(ticketRow);
|
|
4154
|
+
return { items, next_offset: offset + limit < all.length ? offset + limit : null };
|
|
4155
|
+
}
|
|
4156
|
+
/** GET /threads/:key: a Thread, the tickets subscribed to it and what was said there lately. */
|
|
4157
|
+
function threadRoute(key) {
|
|
4158
|
+
const th = tickets.thread(key);
|
|
4159
|
+
const parsed = parseThreadKey(key);
|
|
4160
|
+
if (!th && !parsed) return { ok: false, reason: 'no such thread' };
|
|
4161
|
+
const recent = store
|
|
4162
|
+
.messages({ limit: 2000 })
|
|
4163
|
+
.filter((m) => m.thread === key)
|
|
4164
|
+
.slice(-10)
|
|
4165
|
+
.map((m) => ({ at: m.at, from: m.from, to: m.to, ...(m.who ? { who: m.who } : {}), text: clip(String(m.text ?? ''), 300).text }));
|
|
4166
|
+
return { key, label: th?.label ?? threadLabel(key), kind: th?.kind ?? parsed?.kind ?? '', tickets: tickets.subscribers(key).map(ticketRow), recent };
|
|
4167
|
+
}
|
|
4168
|
+
const ticketOr404 = (id) => {
|
|
4169
|
+
const t = tickets.get(String(id ?? ''));
|
|
4170
|
+
if (!t) throw new Error('no such task');
|
|
4171
|
+
return t;
|
|
4172
|
+
};
|
|
4173
|
+
/** Routes with a path parameter: `tickets/<id>[/<action>]`, `threads/<key>` (the key URI-encoded). */
|
|
4174
|
+
const paramRoutes = {
|
|
4175
|
+
tickets: {
|
|
4176
|
+
get: (rest) => {
|
|
4177
|
+
if (rest.length !== 1) throw new Error('no such route');
|
|
4178
|
+
return ticketView(ticketOr404(rest[0]));
|
|
4179
|
+
},
|
|
4180
|
+
post: async (rest, body) => {
|
|
4181
|
+
const [id, action] = rest;
|
|
4182
|
+
const t = ticketOr404(id);
|
|
4183
|
+
switch (action) {
|
|
4184
|
+
case 'stop':
|
|
4185
|
+
return { ok: true, ...ticketView(endTicket(t, { by: 'user', outcome: 'stopped' })) };
|
|
4186
|
+
case 'close':
|
|
4187
|
+
return { ok: true, ...ticketView(endTicket(t, { by: 'user', outcome: 'done' })) };
|
|
4188
|
+
case 'retry':
|
|
4189
|
+
return { ok: true, ...ticketView(await retryTicket(t)) };
|
|
4190
|
+
case 'message':
|
|
4191
|
+
return { ok: true, ...ticketView(await appendToTicket(t, body.text, { human: true, force: true })) };
|
|
4192
|
+
default:
|
|
4193
|
+
throw new Error('no such route');
|
|
4194
|
+
}
|
|
4195
|
+
},
|
|
4196
|
+
},
|
|
4197
|
+
threads: {
|
|
4198
|
+
get: (rest) => threadRoute(rest.join('/')),
|
|
4199
|
+
},
|
|
4200
|
+
// `asks/<id>/answer`: the panel answers a bot's question (state `asks`).
|
|
4201
|
+
asks: {
|
|
4202
|
+
post: (rest, body) => {
|
|
4203
|
+
if (rest.length !== 2 || rest[1] !== 'answer') throw new Error('no such route');
|
|
4204
|
+
return answerAsk(rest[0], body);
|
|
4205
|
+
},
|
|
4206
|
+
},
|
|
4207
|
+
};
|
|
4208
|
+
/** One request as the web server would route it (also for tests): exact routes, then the parameter ones. */
|
|
4209
|
+
async function request(method, path, body = {}) {
|
|
4210
|
+
const url = new URL(path, 'http://localhost');
|
|
4211
|
+
const rel = url.pathname.startsWith(`${R}/`) ? url.pathname.slice(R.length + 1) : url.pathname.replace(/^\//, '');
|
|
4212
|
+
const exact = routes[rel];
|
|
4213
|
+
if (exact) return method === 'GET' ? exact.get(url) : exact.post(body);
|
|
4214
|
+
const [head, ...parts] = rel.split('/');
|
|
4215
|
+
const route = paramRoutes[head];
|
|
4216
|
+
if (!route) throw new Error('no such route');
|
|
4217
|
+
const rest = head === 'threads' ? [decodeURIComponent(parts.join('/'))] : parts.map((p) => decodeURIComponent(p));
|
|
4218
|
+
if (method === 'GET' && route.get) return route.get(rest, url);
|
|
4219
|
+
if (method === 'POST' && route.post) return route.post(rest, body);
|
|
4220
|
+
throw new Error('no such route');
|
|
4221
|
+
}
|
|
4222
|
+
/** The ticket settings or the dispatcher mode changed: slots, router homes and the queue follow. */
|
|
4223
|
+
function settingsChanged() {
|
|
4224
|
+
slots.setMax(settings.get().tickets.maxWorking);
|
|
4225
|
+
reapply();
|
|
4226
|
+
void pump();
|
|
4227
|
+
}
|
|
4228
|
+
|
|
2202
4229
|
const mountRoutes = (scope) => {
|
|
2203
4230
|
const web = scope.webServer;
|
|
2204
4231
|
if (!web?.register) return;
|
|
4232
|
+
for (const head of Object.keys(paramRoutes)) {
|
|
4233
|
+
scope.effect(() =>
|
|
4234
|
+
web.register({
|
|
4235
|
+
kind: 'prefix',
|
|
4236
|
+
path: `${R}/${head}`,
|
|
4237
|
+
handler: (req, res) => {
|
|
4238
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
4239
|
+
if (req.method === 'GET') return serveJson(res, () => request('GET', `${url.pathname}${url.search}`));
|
|
4240
|
+
if (req.method === 'POST') return postJson(req, res, (body) => request('POST', url.pathname, body));
|
|
4241
|
+
res.statusCode = 405;
|
|
4242
|
+
res.end();
|
|
4243
|
+
},
|
|
4244
|
+
}),
|
|
4245
|
+
);
|
|
4246
|
+
}
|
|
2205
4247
|
for (const [path, route] of Object.entries(routes)) {
|
|
2206
4248
|
scope.effect(() =>
|
|
2207
4249
|
web.register({
|
|
@@ -2223,7 +4265,9 @@ export function apply(ctx, config, deps = {}) {
|
|
|
2223
4265
|
if (typeof ctx.inject === 'function') ctx.inject(['webServer'], mountRoutes);
|
|
2224
4266
|
else if (ctx.webServer) mountRoutes({ webServer: ctx.webServer, effect: (fn) => ctx.effect(fn) });
|
|
2225
4267
|
|
|
2226
|
-
|
|
4268
|
+
/** For tests: which per-Session records this process still keeps for `sessionId`. */
|
|
4269
|
+
const tracked = (sessionId) => ({ trigger: trigger.has(sessionId), answered: answered.has(sessionId), turn: turnState.has(sessionId), delivered: deliveredIds.has(sessionId), history: historyRead.has(sessionId) });
|
|
4270
|
+
return { store, state, deliver, install, reconcile, installed, routes, channels, memory, ledger, topics, settings, newTopic, dream, sweep, userSend, openTasks, codexSync, finishTask, tickets, slots, pump, botOfSession, request, ticketView, ticketUpkeep, watch, startup, recoverTickets, tracked };
|
|
2227
4271
|
}
|
|
2228
4272
|
|
|
2229
4273
|
function serveAvatar(dir, req, res) {
|