@kadaliao/dsh-bots 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cards.mjs ADDED
@@ -0,0 +1,582 @@
1
+ /**
2
+ * What models read about tickets (tasks) and threads: compact cards, the
3
+ * notices relayed between conversations, and the paged reader behind
4
+ * `bot_recall`. Inline & Spill: long text is clipped where it is shown, the
5
+ * full length rides along, and every id on a card can be expanded with
6
+ * `readResource`. Pure functions; the ticket store, thread store, stage rule
7
+ * and transcripts are injected. Shapes follow PLAN-0.8 §10.
8
+ *
9
+ * @module @kadaliao/dsh-bots/lib/cards
10
+ */
11
+
12
+ /** Characters of a report relayed to the requester. */
13
+ export const REPORT_CHARS = 600;
14
+ /** Characters of the assignment in a worker's first message. */
15
+ export const ASSIGNMENT_CHARS = 1500;
16
+ /** Characters of a report or message preview on a card. */
17
+ export const PREVIEW_CHARS = 200;
18
+ /** Characters of one text page. */
19
+ export const PAGE_CHARS = 4000;
20
+ /** Items of one list page, and the most a caller may ask for. */
21
+ export const PAGE_ITEMS = 20;
22
+ export const MAX_ITEMS = 50;
23
+ /** Recent messages shown for a thread. */
24
+ export const RECENT_MESSAGES = 10;
25
+
26
+ /**
27
+ * The ticket store as this module reads it. An array of tickets works too.
28
+ * @typedef {object} TicketsView
29
+ * @property {(id: string) => object|undefined} get
30
+ * @property {() => object[]} list - every ticket, archived ones included.
31
+ * @property {(id: string) => object[]} [children] - sub-tickets; defaults to `list()` filtered by `parentId`.
32
+ */
33
+
34
+ /**
35
+ * The thread store as this module reads it. A Map, an array of threads or a
36
+ * `(key) => thread` function works for `ticketCard`.
37
+ * @typedef {object} ThreadsView
38
+ * @property {(key: string) => object|undefined} thread - or `get(key)`; the ticket store (which has `thread`) works as is.
39
+ * @property {(key: string) => Array<object|string>} [subscribers] - tickets (or ids) subscribed to a thread; defaults to `thread.tickets`.
40
+ * @property {(key: string) => Array<{at?: number|string, who?: string, text: string}>|Promise<Array<object>>} [recent] - latest messages, oldest first.
41
+ */
42
+
43
+ /**
44
+ * Who reads: the router (dispatcher home), any bot's home, or a ticket session.
45
+ * @typedef {{kind: 'router'|'home'|'ticket'|'restricted', ticketId?: string}} Viewer
46
+ */
47
+
48
+ /**
49
+ * What text builders need besides the ticket.
50
+ * @typedef {object} CardContext
51
+ * @property {object[]|Map|Function} [bots] - bots ({id, handle, name}), a Map by id, or `(id) => bot`.
52
+ * @property {ThreadsView|Map|object[]|Function} [threads]
53
+ * @property {TicketsView|object[]} [tickets] - for children ids.
54
+ * @property {object[]} [children] - sub-tickets (or ids), when the caller has them.
55
+ * @property {string} [stage] - the ticket's stage, when known.
56
+ * @property {(ticket: object, opts: {now: number}) => string} [stageOf] - otherwise asked here.
57
+ * @property {number} [now]
58
+ */
59
+
60
+ const toMs = (v) => (typeof v === 'number' ? v : v ? Date.parse(v) : NaN);
61
+ const iso = (v) => {
62
+ const ms = toMs(v);
63
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
64
+ };
65
+ const quote = (s) => JSON.stringify(String(s ?? ''));
66
+ const recallHint = (ref) => `bot_recall {"ref":${quote(ref)}}`;
67
+
68
+ /** Drop undefined, null, '' and empty arrays so cards stay compact. */
69
+ function compact(obj) {
70
+ const out = {};
71
+ for (const [k, v] of Object.entries(obj)) {
72
+ if (v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)) continue;
73
+ if (v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0) continue;
74
+ out[k] = v;
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * One entry of an injected source: function, Map, array, or an object with
81
+ * `method(key)` (`thread` for threads, so the ticket store itself, whose `get`
82
+ * returns tickets, can serve as the thread source) or `get(key)`.
83
+ */
84
+ function lookup(src, key, field = 'id', method = 'get') {
85
+ if (!src || key === undefined || key === null) return undefined;
86
+ if (typeof src === 'function') return src(key);
87
+ if (src instanceof Map) return src.get(key);
88
+ if (Array.isArray(src)) return src.find((x) => x?.[field] === key);
89
+ if (typeof src[method] === 'function') return src[method](key);
90
+ if (typeof src.get === 'function') return src.get(key);
91
+ return undefined;
92
+ }
93
+
94
+ const botOf = (bots, id) => lookup(bots, id);
95
+ const handleOf = (bots, id) => {
96
+ const b = botOf(bots, id);
97
+ return b?.handle ? `@${b.handle}` : '(removed bot)';
98
+ };
99
+ const threadOf = (threads, key) => lookup(threads, key, 'key', 'thread');
100
+
101
+ /** The ticket store as {get, list, children}. */
102
+ function ticketsView(src) {
103
+ if (!src) return { get: () => undefined, list: () => [], children: () => [] };
104
+ if (Array.isArray(src)) {
105
+ return { get: (id) => src.find((t) => t.id === id), list: () => src, children: (id) => src.filter((t) => t.parentId === id) };
106
+ }
107
+ const list = () => (typeof src.list === 'function' ? src.list() ?? [] : []);
108
+ return {
109
+ get: (id) => (typeof src.get === 'function' ? src.get(id) : list().find((t) => t.id === id)),
110
+ list,
111
+ children: (id) => (typeof src.children === 'function' ? src.children(id) ?? [] : list().filter((t) => t.parentId === id)),
112
+ };
113
+ }
114
+
115
+ /** The stage of a ticket from the context: given, computed, or stored on the ticket. */
116
+ function stageIn(ticket, ctx = {}) {
117
+ if (ctx.stage !== undefined) return ctx.stage;
118
+ if (typeof ctx.stageOf === 'function') return ctx.stageOf(ticket, { now: ctx.now ?? Date.now() });
119
+ return ticket.stage;
120
+ }
121
+
122
+ const parentOf = (t) => t.parentId ?? t.requester?.ticketId;
123
+ const lastReport = (t) => (Array.isArray(t.reports) && t.reports.length ? t.reports[t.reports.length - 1] : undefined);
124
+
125
+ function childIds(ticket, ctx) {
126
+ const kids = ctx.children ?? ticket.children ?? (ctx.tickets ? ticketsView(ctx.tickets).children(ticket.id) : []);
127
+ return (kids ?? []).map((k) => (typeof k === 'string' ? k : k?.id)).filter(Boolean);
128
+ }
129
+
130
+ /**
131
+ * Text cut to at most `max` characters (an ellipsis included), with the full
132
+ * length when it was cut.
133
+ * @param {string} text
134
+ * @param {number} max
135
+ * @returns {{text: string, chars?: number}}
136
+ */
137
+ export function clip(text, max) {
138
+ const s = String(text ?? '');
139
+ if (s.length <= max) return { text: s };
140
+ let end = Math.max(0, max - 1);
141
+ const c = s.charCodeAt(end - 1);
142
+ if (c >= 0xd800 && c <= 0xdbff) end -= 1;
143
+ return { text: `${s.slice(0, end).trimEnd()}…`, chars: s.length };
144
+ }
145
+
146
+ /** Who asked, on a card: '@atlas' or 'user'. A parent ticket shows as `parent`. */
147
+ function requesterOf(t, bots) {
148
+ const r = t.requester ?? {};
149
+ if (r.kind === 'user' || !r.botId) return 'user';
150
+ return handleOf(bots, r.botId);
151
+ }
152
+
153
+ /** Who asked, in a sentence: '@atlas', '@coder (task t…)', 'the user'. */
154
+ function requesterPhrase(t, bots) {
155
+ const who = requesterOf(t, bots);
156
+ const parent = parentOf(t);
157
+ if (who === 'user') return parent ? `task ${parent}` : 'the user';
158
+ return parent ? `${who} (task ${parent})` : who;
159
+ }
160
+
161
+ /** Where a ticket came from, in a sentence: 'Kada in #general (Slack)', or ''. */
162
+ function originPhrase(t, threads) {
163
+ const o = t.origin ?? {};
164
+ const label = threadOf(threads, o.threadKey)?.label;
165
+ const parts = [o.who, label ? `in ${label}` : '', o.via ? `(${o.via})` : ''].filter(Boolean);
166
+ return parts.join(' ');
167
+ }
168
+
169
+ /**
170
+ * A compact card for one ticket. Every id on it can be read with
171
+ * `readResource`: `id`, `parent` and `children` as `ticket/<id>`, the origin
172
+ * thread and `threads` as `thread/<key>`, `bot` as `bot/<handle>`.
173
+ * @param {object} ticket
174
+ * @param {CardContext} [ctx]
175
+ * @returns {{id: string, title: string, bot: string, stage?: string, requester: string, parent?: string, children?: string[], origin?: {thread?: string, label?: string, via?: string, who?: string}, threads?: string[], last_report?: {status: string, at?: string, preview: string}, error?: string, archived?: true, updated_at?: string}}
176
+ */
177
+ export function ticketCard(ticket, ctx = {}) {
178
+ const t = ticket;
179
+ const stage = stageIn(t, ctx);
180
+ const o = t.origin ?? {};
181
+ const report = lastReport(t);
182
+ return compact({
183
+ id: t.id,
184
+ title: t.title,
185
+ bot: handleOf(ctx.bots, t.botId),
186
+ stage,
187
+ requester: requesterOf(t, ctx.bots),
188
+ parent: parentOf(t),
189
+ children: childIds(t, ctx),
190
+ origin: compact({ thread: o.threadKey, label: threadOf(ctx.threads, o.threadKey)?.label, via: o.via, who: o.who }),
191
+ threads: (t.threads ?? []).filter((k) => k !== o.threadKey),
192
+ last_report: report ? compact({ status: report.status, at: iso(report.at), preview: clip(String(report.text ?? '').trim(), PREVIEW_CHARS).text }) : undefined,
193
+ error: stage === 'failed' && t.error ? clip(t.error, PREVIEW_CHARS).text : undefined,
194
+ archived: t.archivedAt ? true : undefined,
195
+ updated_at: iso(t.updatedAt),
196
+ });
197
+ }
198
+
199
+ /** A list row: the card without children, extra threads and error. */
200
+ function ticketRow(t, ctx) {
201
+ const { children, threads, error, ...row } = ticketCard(t, { ...ctx, children: [] });
202
+ return row;
203
+ }
204
+
205
+ const NEXT_STEP = {
206
+ done: () => 'Pass the result on to whoever asked for it.',
207
+ question: (t, bot) => `${bot} needs an answer to go on. Answer with bot_send_message (ticket: ${quote(t.id)}) if you know it; otherwise ask the person and send their answer the same way.`,
208
+ blocked: (t, bot) => `${bot} is blocked. Unblock it with bot_send_message (ticket: ${quote(t.id)}), ask the person what to do, or stop the task with bot_ticket.`,
209
+ progress: () => 'No action needed; more reports will follow.',
210
+ };
211
+
212
+ /**
213
+ * What the requester reads when a worker reports: who, the status, the
214
+ * report (≤ 600 characters, with a pointer to the full text when cut), the
215
+ * ticket card and the next step.
216
+ * @param {object} ticket
217
+ * @param {{status: string, text: string, at?: number|string}} report
218
+ * @param {CardContext} [ctx]
219
+ */
220
+ export function reportRelayText(ticket, report, ctx = {}) {
221
+ const bot = handleOf(ctx.bots, ticket.botId);
222
+ const status = report?.status ?? 'progress';
223
+ const body = clip(String(report?.text ?? '').trim(), REPORT_CHARS);
224
+ const lines = [`Report from ${bot} on task ${ticket.id} — status: ${status}`, body.text || '(empty report)'];
225
+ if (body.chars) lines.push(`[${REPORT_CHARS} of ${body.chars} characters shown. Read the whole report with ${recallHint(`ticket/${ticket.id}/reports`)}.]`);
226
+ lines.push('', `Task: ${JSON.stringify(ticketCard(ticket, ctx))}`, (NEXT_STEP[status] ?? NEXT_STEP.progress)(ticket, bot));
227
+ return lines.join('\n');
228
+ }
229
+
230
+ /**
231
+ * The first message a worker reads in its ticket session: the task, up to
232
+ * 1500 characters of the assignment, who asked and from where, and how to
233
+ * report.
234
+ * @param {object} ticket
235
+ * @param {CardContext} [ctx]
236
+ */
237
+ export function assignmentText(ticket, ctx = {}) {
238
+ const body = clip(String(ticket.text ?? '').trim(), ASSIGNMENT_CHARS);
239
+ const origin = originPhrase(ticket, ctx.threads);
240
+ const lines = [`New task ${ticket.id} from ${requesterPhrase(ticket, ctx.bots)}: ${String(ticket.title ?? '').trim()}`];
241
+ if (origin) lines.push(`It started with ${origin}.`);
242
+ lines.push('', body.text || '(no details: the title is the whole task)');
243
+ if (body.chars) lines.push(`[${ASSIGNMENT_CHARS} of ${body.chars} characters shown. Read the rest with ${recallHint(`ticket/${ticket.id}/text`)}.]`);
244
+ lines.push(
245
+ '',
246
+ 'Report with bot_send_message (leave out "to") and a status: "done" with the result when you are finished, "progress" for an update worth keeping, "question" when you need an answer, "blocked" when you cannot go on. Your plain text reaches no one.',
247
+ );
248
+ return lines.join('\n');
249
+ }
250
+
251
+ /** `t1 (@coder, working: Fix the login bug)` for notices. */
252
+ function ticketPhrase(t, ctx) {
253
+ const stage = stageIn(t, { ...ctx, stage: undefined });
254
+ return `${t.id} (${handleOf(ctx.bots, t.botId)}${stage ? `, ${stage}` : ''}: ${String(t.title ?? '').trim()})`;
255
+ }
256
+
257
+ /**
258
+ * What the router gets injected (without waking) when a person's follow-up
259
+ * on a subscribed thread went straight to the tickets.
260
+ * @param {{tickets: object[], thread?: string|object, who?: string, via?: string, text: string}} notice
261
+ * @param {CardContext} [ctx]
262
+ */
263
+ export function followUpNoticeText(notice, ctx = {}) {
264
+ const tickets = notice?.tickets ?? [];
265
+ const key = typeof notice?.thread === 'string' ? notice.thread : notice?.thread?.key;
266
+ const thread = typeof notice?.thread === 'object' && notice.thread ? notice.thread : threadOf(ctx.threads, key);
267
+ const where = [thread?.label ? `in ${thread.label}` : '', notice?.via ? `(${notice.via})` : ''].filter(Boolean).join(' ');
268
+ const noun = tickets.length === 1 ? 'task' : 'tasks';
269
+ return [
270
+ `[follow_up] ${notice?.who || 'Someone'}${where ? ` ${where}` : ''} wrote about ${noun} ${tickets.map((t) => ticketPhrase(t, ctx)).join(', ')}${key ? ` on thread ${key}` : ''}:`,
271
+ quote(clip(String(notice?.text ?? '').trim(), PREVIEW_CHARS).text),
272
+ `It went to the ${noun} directly and needs no reply from you. Stop a task with bot_ticket only if the person asks to stop it.`,
273
+ ].join('\n');
274
+ }
275
+
276
+ /**
277
+ * Bots 0.9: a worker's report went to the person as it is, in the topic or chat its task came
278
+ * from. Its requester is told without being woken (the note is "good to know"): it need not pass
279
+ * the result on, and a `question` is the person's to answer there.
280
+ * @param {object} ticket
281
+ * @param {{status?: string, text?: string}} report
282
+ * @param {CardContext & {where?: string}} [ctx] - `where`: how that topic or chat reads ("Panel · topic …")
283
+ */
284
+ export function shownNoticeText(ticket, report, ctx = {}) {
285
+ const status = report?.status ?? 'done';
286
+ const next =
287
+ status === 'done'
288
+ ? 'The task is done. This needs no reply: do not repeat the result.'
289
+ : status === 'question'
290
+ ? 'The person answers it there, and the answer goes to the task directly. This needs no reply from you.'
291
+ : 'The person sees it there. It needs no reply from you, unless you can unblock the task: then add to it with bot_send_message (ticket: its id).';
292
+ return [
293
+ `[Shown] ${handleOf(ctx.bots, ticket.botId)}'s report on task ${ticketPhrase(ticket, ctx)} — status: ${status} — went to the person as it is${ctx.where ? `, in ${ctx.where}` : ''}:`,
294
+ quote(clip(String(report?.text ?? '').trim(), PREVIEW_CHARS).text),
295
+ next,
296
+ ].join('\n');
297
+ }
298
+
299
+ /** How many tasks a panel message header lists for the dispatcher. */
300
+ export const HEADER_TASKS = 8;
301
+
302
+ /**
303
+ * The line a message typed in the panel reaches a bot's home with (Bots 0.9): its topic, as
304
+ * `bot_reply` and `bot_send_message` name it (`[Panel] (thread p…)`); for a reply in a topic,
305
+ * the message it answers; and for the dispatcher the tasks a message may continue (`open`: open
306
+ * ones, or ones that finished lately; at most `HEADER_TASKS`).
307
+ * @param {{topic: string, replyTo?: {who?: string, text?: string}, open?: object[]}} what
308
+ * @param {CardContext} [ctx]
309
+ */
310
+ export function panelHeaderText({ topic, replyTo, open = [] } = {}, ctx = {}) {
311
+ const lines = [`[Panel]${topic ? ` (thread ${topic})` : ''}`];
312
+ const quoted = String(replyTo?.text ?? '').trim();
313
+ if (quoted) lines.push(`In reply to ${replyTo.who || 'a message'}: ${quote(clip(quoted, 160).text)}`);
314
+ const listed = open.slice(0, HEADER_TASKS);
315
+ if (listed.length) lines.push(`Open tasks: ${listed.map((t) => ticketPhrase(t, ctx)).join('; ')}`);
316
+ return lines.join('\n');
317
+ }
318
+
319
+ /**
320
+ * Prepended when a ticket that was working is restarted after Harness came
321
+ * back: look before repeating anything that left the conversation.
322
+ * @param {object} ticket
323
+ */
324
+ export function recoveryNoteText(ticket) {
325
+ return [
326
+ `[Recovery] DeepSeek Harness restarted while you were working on task ${ticket.id}: ${quote(String(ticket.title ?? '').trim())}.`,
327
+ 'Before you go on, check what you already did: files in the working directory, commands you ran, messages, posts or commits you sent, anything outside this conversation. Do not repeat an outside action that already happened.',
328
+ 'Then continue where you left off, and report with bot_send_message as usual.',
329
+ ].join('\n');
330
+ }
331
+
332
+ /**
333
+ * The one status check a quiet worker gets from the watchdog.
334
+ * @param {object} ticket
335
+ */
336
+ export function nudgeText(ticket) {
337
+ return [
338
+ `[Status check] Task ${ticket.id} (${quote(String(ticket.title ?? '').trim())}) has had no report for a while and nothing is running.`,
339
+ 'Report now with bot_send_message: "done" with the result if it is finished, "progress" with what is left if you are still on it, "blocked" or "question" if you are stuck. Without a report the task is marked stalled.',
340
+ ].join('\n');
341
+ }
342
+
343
+ /**
344
+ * What the requester reads when the watchdog marks a ticket stalled.
345
+ * @param {object} ticket
346
+ * @param {CardContext} [ctx]
347
+ */
348
+ export function stalledNoticeText(ticket, ctx = {}) {
349
+ return [
350
+ `[Stalled] Task ${ticket.id} (${handleOf(ctx.bots, ticket.botId)}: ${String(ticket.title ?? '').trim()}) stopped making progress: its conversation is idle, nothing runs in the background, and it did not answer a status check.`,
351
+ `Decide what to do: send it a message with bot_send_message (ticket: ${quote(ticket.id)}), retry or stop it with bot_ticket, or tell the person.`,
352
+ ].join('\n');
353
+ }
354
+
355
+ /**
356
+ * What the requester reads when a ticket failed for good (retries used up).
357
+ * @param {object} ticket
358
+ * @param {CardContext} [ctx]
359
+ */
360
+ export function failedNoticeText(ticket, ctx = {}) {
361
+ const why = ticket.error ? ` Last error: ${clip(String(ticket.error).trim(), PREVIEW_CHARS).text}` : '';
362
+ return [
363
+ `[Failed] Task ${ticket.id} (${handleOf(ctx.bots, ticket.botId)}: ${String(ticket.title ?? '').trim()}) failed.${why}`,
364
+ 'Retry it with bot_ticket, hand it to another bot, or tell the person.',
365
+ ].join('\n');
366
+ }
367
+
368
+ /**
369
+ * The "continue" a worker gets after a temporary error, before retries run out.
370
+ * @param {object} ticket
371
+ * @param {{attempt?: number, error?: string}} [info]
372
+ */
373
+ export function retryText(ticket, info = {}) {
374
+ const why = info.error ? ` (${clip(String(info.error).trim(), PREVIEW_CHARS).text})` : '';
375
+ return `[Retry${info.attempt ? ` ${info.attempt}` : ''}] The last step of task ${ticket.id} failed with a temporary error${why}. Continue where you left off; do not repeat outside actions that already went through.`;
376
+ }
377
+
378
+ /**
379
+ * The one reminder a requester gets when every ticket it waited for has
380
+ * settled and it has not told anyone.
381
+ * @param {object[]} tickets
382
+ * @param {CardContext} [ctx]
383
+ */
384
+ export function reminderText(tickets, ctx = {}) {
385
+ return [
386
+ `[Reminder] Every task you were waiting for has settled: ${(tickets ?? []).map((t) => ticketPhrase(t, ctx)).join(', ')}.`,
387
+ 'Tell whoever asked what came of them; bot_recall reads the details.',
388
+ ].join('\n');
389
+ }
390
+
391
+ const RANK = { question: 0, stalled: 0, working: 0, queued: 0, failed: 1, done: 2, stopped: 2 };
392
+ /** Open tickets first, then failed, then ended, archived last; newest first within each. */
393
+ function sortTickets(tickets, ctx) {
394
+ const rank = (t, stage) => (t.archivedAt ? 3 : RANK[stage] ?? (t.ended ? 2 : 0));
395
+ return tickets
396
+ .map((t) => ({ t, stage: stageIn(t, ctx) }))
397
+ .sort((a, b) => rank(a.t, a.stage) - rank(b.t, b.stage) || (toMs(b.t.updatedAt) || 0) - (toMs(a.t.updatedAt) || 0));
398
+ }
399
+
400
+ function itemPage(entries, offset, limit, row) {
401
+ const start = Math.max(0, Math.floor(Number(offset) || 0));
402
+ const size = Math.min(MAX_ITEMS, Math.max(1, Math.floor(Number(limit) || PAGE_ITEMS)));
403
+ const end = Math.min(entries.length, start + size);
404
+ const page = { items: entries.slice(start, end).map(row), total: entries.length };
405
+ if (end < entries.length) page.next_offset = end;
406
+ return page;
407
+ }
408
+
409
+ function textPage(text, offset, size = PAGE_CHARS) {
410
+ const total = text.length;
411
+ const start = Math.min(total, Math.max(0, Math.floor(Number(offset) || 0)));
412
+ let end = Math.min(total, start + size);
413
+ if (end < total && end > start + 1) {
414
+ const c = text.charCodeAt(end - 1);
415
+ if (c >= 0xd800 && c <= 0xdbff) end -= 1;
416
+ }
417
+ return compact({ text: text.slice(start, end), offset: start, chars: total, next_offset: end < total ? end : undefined });
418
+ }
419
+
420
+ /** `tickets` · `ticket/<id>[/text|/reports|/transcript]` · `thread/<key>` · `bot/<handle>`; also `task/…`, a bare ticket id and `@handle`. */
421
+ function parseRef(ref) {
422
+ const s = String(ref ?? '').trim().replace(/^\/+/, '').replace(/\/+$/, '');
423
+ if (/^(?:tickets|tasks)$/i.test(s)) return { kind: 'tickets' };
424
+ let m = /^(?:tickets?|tasks?)\/([^/\s]+)(?:\/(text|reports|transcript))?$/i.exec(s);
425
+ if (m) return { kind: m[2]?.toLowerCase() ?? 'ticket', id: m[1] };
426
+ m = /^threads?\/(.+)$/i.exec(s);
427
+ if (m) return { kind: 'thread', key: m[1] };
428
+ m = /^(?:bots?\/)?@([^/\s]+)$/.exec(s) ?? /^bots?\/([^/\s]+)$/i.exec(s);
429
+ if (m) return { kind: 'bot', handle: m[1] };
430
+ if (/^t[0-9a-z]{8}$/.test(s)) return { kind: 'ticket', id: s };
431
+ return undefined;
432
+ }
433
+
434
+ const REFS = 'tickets, ticket/<id>, ticket/<id>/text, ticket/<id>/reports, ticket/<id>/transcript, thread/<key> or bot/<handle>';
435
+
436
+ /**
437
+ * What a ticket viewer may read: its ticket, the parent, the children, and its threads. A `restricted`
438
+ * viewer (a helper conversation whose owner cannot be traced) reads nothing. Others read everything (null).
439
+ */
440
+ function scopeOf(viewer, view) {
441
+ if (viewer?.kind === 'restricted') throw new Error('bot_recall: this conversation cannot be traced to a bot or a task, so it reads no tasks.');
442
+ if (viewer?.kind !== 'ticket') return null;
443
+ const self = viewer.ticketId ? view.get(viewer.ticketId) : undefined;
444
+ if (!self) throw new Error(`bot_recall: this conversation's task${viewer.ticketId ? ` ${viewer.ticketId}` : ''} is not on record.`);
445
+ const ids = new Set([self.id]);
446
+ const parent = parentOf(self);
447
+ if (parent) ids.add(parent);
448
+ for (const c of view.children(self.id)) if (c?.id) ids.add(c.id);
449
+ const threads = new Set([...(self.threads ?? []), self.origin?.threadKey].filter(Boolean));
450
+ return { self, ids, threads };
451
+ }
452
+
453
+ /** A card as a ticket viewer sees it: only ids it can read (no sibling tasks, no threads it is not on). */
454
+ function scoped(card, scope) {
455
+ if (!scope) return card;
456
+ const out = { ...card };
457
+ if (out.children) out.children = out.children.filter((id) => scope.ids.has(id));
458
+ if (out.threads) out.threads = out.threads.filter((k) => scope.threads.has(k));
459
+ if (out.origin?.thread && !scope.threads.has(out.origin.thread)) {
460
+ const { thread, ...rest } = out.origin;
461
+ out.origin = rest;
462
+ }
463
+ return compact(out);
464
+ }
465
+
466
+ const outOfScope = (what, scope) =>
467
+ new Error(`bot_recall: ${what} is outside this task. From task ${scope.self.id} you can read that task, its parent and its sub-tasks, and the threads it belongs to.`);
468
+
469
+ function reportsText(t) {
470
+ const reports = Array.isArray(t.reports) ? t.reports : [];
471
+ if (reports.length === 0) return `No reports on task ${t.id} yet.`;
472
+ return [...reports]
473
+ .reverse()
474
+ .map((r) => `--- ${[iso(r.at), r.status].filter(Boolean).join(' · ')} ---\n${String(r.text ?? '').trim()}`)
475
+ .join('\n\n');
476
+ }
477
+
478
+ function transcriptText(raw) {
479
+ if (typeof raw === 'string') return raw;
480
+ return (Array.isArray(raw) ? raw : [])
481
+ .map((e) => (typeof e === 'string' ? e : `${e?.role ?? e?.who ?? 'message'}: ${String(e?.text ?? '').trim()}`))
482
+ .join('\n\n');
483
+ }
484
+
485
+ /**
486
+ * The reader behind `bot_recall`. Lists come in pages of 20 items (`limit` up
487
+ * to 50) and text in pages of 4000 characters; a page that is not the last
488
+ * carries `next_offset`. Throws an Error with a model-facing message for an
489
+ * unknown ref, a missing ticket/thread/bot, or a ref a ticket viewer may not
490
+ * read.
491
+ *
492
+ * | ref | result |
493
+ * | --- | --- |
494
+ * | `tickets` | `{items: rows, total, next_offset?}`, open tickets first |
495
+ * | `ticket/<id>` | `{card, text, chars?, more}`: the card, a preview of the assignment, and the refs below |
496
+ * | `ticket/<id>/text` | the full assignment, paged |
497
+ * | `ticket/<id>/reports` | every report, newest first, paged |
498
+ * | `ticket/<id>/transcript` | the ticket session's transcript, paged |
499
+ * | `thread/<key>` | `{thread, items: subscribed tickets, total, recent?}` |
500
+ * | `bot/<handle>` | `{bot, items: its tickets, total}`, open ones first |
501
+ *
502
+ * @param {string} ref
503
+ * @param {object} opts
504
+ * @param {Viewer} [opts.viewer] - who reads; a ticket viewer is limited to its own ticket, the parent, the children and its threads, and the cards it gets leave out ids beyond those; a restricted viewer reads nothing. Absent means unrestricted.
505
+ * @param {TicketsView|object[]} opts.tickets
506
+ * @param {ThreadsView} [opts.threads]
507
+ * @param {object[]|Map|Function} [opts.bots]
508
+ * @param {(ticket: object, opts: {now: number}) => string} [opts.stageOf]
509
+ * @param {(ticket: object) => string|Array<object|string>|Promise<string|Array<object|string>>} [opts.transcript] - the ticket session's messages.
510
+ * @param {number} [opts.offset]
511
+ * @param {number} [opts.limit] - list page size, 1–50.
512
+ * @param {number} [opts.now]
513
+ * @returns {Promise<object>}
514
+ */
515
+ export async function readResource(ref, opts = {}) {
516
+ const now = opts.now ?? Date.now();
517
+ const view = ticketsView(opts.tickets);
518
+ const threads = opts.threads;
519
+ const ctx = { bots: opts.bots, threads, stageOf: opts.stageOf, tickets: view, now };
520
+ const scope = scopeOf(opts.viewer, view);
521
+ const r = parseRef(ref);
522
+ if (!r) throw new Error(`bot_recall: unknown ref ${quote(ref)}. Use ${REFS}.`);
523
+ const refText = r.kind === 'tickets' ? 'tickets' : r.kind === 'thread' ? `thread/${r.key}` : r.kind === 'bot' ? `bot/${r.handle}` : r.kind === 'ticket' ? `ticket/${r.id}` : `ticket/${r.id}/${r.kind}`;
524
+ const rows = (entries) => itemPage(entries, opts.offset, opts.limit, ({ t, stage }) => scoped(ticketRow(t, { ...ctx, stage }), scope));
525
+
526
+ if (r.kind === 'tickets') {
527
+ const all = view.list().filter((t) => !scope || scope.ids.has(t.id));
528
+ return { ref: refText, ...rows(sortTickets(all, ctx)) };
529
+ }
530
+
531
+ if (r.kind === 'bot') {
532
+ const want = r.handle.toLowerCase();
533
+ const list = Array.isArray(opts.bots) ? opts.bots : opts.bots instanceof Map ? [...opts.bots.values()] : [];
534
+ const bot = list.find((b) => String(b.handle ?? '').toLowerCase() === want || b.id === r.handle);
535
+ if (!bot) throw new Error(`bot_recall: no bot @${r.handle}. bot_list shows the team.`);
536
+ const mine = view.list().filter((t) => t.botId === bot.id && (!scope || scope.ids.has(t.id)));
537
+ return {
538
+ ref: refText,
539
+ bot: compact({ handle: `@${bot.handle}`, name: bot.name, bio: bot.bio, dispatcher: bot.role === 'primary' ? true : undefined }),
540
+ ...rows(sortTickets(mine, ctx)),
541
+ };
542
+ }
543
+
544
+ if (r.kind === 'thread') {
545
+ if (scope && !scope.threads.has(r.key)) throw outOfScope(`thread ${r.key}`, scope);
546
+ const thread = threadOf(threads, r.key);
547
+ if (!thread) throw new Error(`bot_recall: no thread ${r.key}.`);
548
+ const subs = typeof threads?.subscribers === 'function' ? threads.subscribers(r.key) ?? [] : thread.tickets ?? [];
549
+ const subscribed = subs
550
+ .map((s) => (typeof s === 'string' ? view.get(s) : s))
551
+ .filter((t) => t && (!scope || scope.ids.has(t.id)));
552
+ const recent = typeof threads?.recent === 'function' ? (await threads.recent(r.key)) ?? [] : [];
553
+ const out = {
554
+ ref: refText,
555
+ thread: compact({ key: thread.key ?? r.key, kind: thread.kind, label: thread.label, last_at: iso(thread.lastAt) }),
556
+ ...rows(sortTickets(subscribed, ctx)),
557
+ };
558
+ if (recent.length) out.recent = recent.slice(-RECENT_MESSAGES).map((m) => compact({ at: iso(m.at), who: m.who, text: clip(String(m.text ?? '').trim(), PREVIEW_CHARS * 1.5).text }));
559
+ return out;
560
+ }
561
+
562
+ if (scope && !scope.ids.has(r.id)) throw outOfScope(`task ${r.id}`, scope);
563
+ const t = view.get(r.id);
564
+ if (!t) throw new Error(`bot_recall: no task ${r.id}. bot_recall {"ref":"tickets"} lists them.`);
565
+
566
+ if (r.kind === 'ticket') {
567
+ const text = clip(String(t.text ?? '').trim(), PREVIEW_CHARS);
568
+ return compact({
569
+ ref: refText,
570
+ card: scoped(ticketCard(t, ctx), scope),
571
+ text: text.text,
572
+ chars: text.chars,
573
+ more: [`ticket/${t.id}/text`, `ticket/${t.id}/reports`, `ticket/${t.id}/transcript`],
574
+ });
575
+ }
576
+ if (r.kind === 'text') return { ref: refText, ...textPage(String(t.text ?? '').trim(), opts.offset) };
577
+ if (r.kind === 'reports') return { ref: refText, ...textPage(reportsText(t), opts.offset) };
578
+ // transcript
579
+ if (!t.sessionId) throw new Error(`bot_recall: task ${t.id} has not started yet, so it has no transcript.`);
580
+ if (typeof opts.transcript !== 'function') throw new Error(`bot_recall: the transcript of task ${t.id} cannot be read here.`);
581
+ return { ref: refText, ...textPage(transcriptText(await opts.transcript(t)), opts.offset) };
582
+ }