@kadaliao/dsh-bots 0.7.0 → 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.
@@ -0,0 +1,722 @@
1
+ /**
2
+ * Tickets: work one bot hands to another. A ticket has one worker bot, its own
3
+ * Harness Session (`ticket-<id>`), one requester (a Session, or the user), the
4
+ * Threads (outside conversations) it is subscribed to, and the structured
5
+ * reports its worker sent. Its stage is its own: an idle Session is not a
6
+ * finished ticket.
7
+ *
8
+ * `tickets.json` under the bots cache holds `{version: 1, tickets, threads}` in
9
+ * the shapes of docs/PLAN-0.8.md §10, plus `lastRequesterAt` (below). It is read
10
+ * on first use and written whole through a temp file and a rename; a missing
11
+ * file (ENOENT) starts empty, one that is not JSON in the expected shape is set
12
+ * aside as `tickets.json.corrupt-<time>` before the first write replaces it, and
13
+ * any other read error (permissions, a directory in its place) throws, so the
14
+ * caller fails instead of writing over a file it could not read. Fields this
15
+ * module does not know (set through `patch`) are kept.
16
+ *
17
+ * Stages ({@link stageOf}): the first row that matches wins. "Answered" means a
18
+ * message from outside the worker reached the ticket after that report: a
19
+ * person's (`lastHumanAt`) or the requester's (`lastRequesterAt`, an addition to
20
+ * §10: a parent ticket's worker or the Router answering a `question` must clear
21
+ * it as a person's answer does).
22
+ *
23
+ * | stage | stored fields |
24
+ * | ---------- | --------------------------------------------------------------------------------- |
25
+ * | `failed` | `ended.outcome === 'failed'`, or open and the latest report is an unanswered `blocked` |
26
+ * | `question` | open and the latest report is an unanswered `question` |
27
+ * | `stalled` | open and `stalledAt` is set (the watchdog stores it; a report, an answer or `resume` clears it) |
28
+ * | `queued` | open and no `startedAt` (a started ticket put back in the queue has `startedAt` cleared), or messages wait in `parked` for a slot |
29
+ * | `working` | open: started and nothing above (running, a background job, or not judged yet) |
30
+ * | `done` | `ended.outcome === 'done'`: a `done` report, or closed by the requester or user |
31
+ * | `stopped` | `ended.outcome === 'stopped'`: stopped by a person, the requester or the system |
32
+ *
33
+ * "Open" is no `ended`. An archived ticket is always ended. Reports never reopen
34
+ * a ticket; only {@link createTickets}'s `resume` does.
35
+ *
36
+ * Worker slots ({@link createSlots}) are in memory only: after a restart the
37
+ * caller acquires them again for the tickets it restarts. Messages for a
38
+ * started ticket that has no slot wait on the ticket itself (`parked`, an
39
+ * array the caller sets through `patch`), so they outlast a restart.
40
+ *
41
+ * @module @kadaliao/dsh-bots/lib/tickets
42
+ */
43
+
44
+ import { randomInt } from 'node:crypto';
45
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
46
+ import { join } from 'node:path';
47
+
48
+ export const STAGES = ['failed', 'question', 'stalled', 'queued', 'working', 'done', 'stopped'];
49
+ export const REPORT_STATUSES = ['progress', 'done', 'blocked', 'question'];
50
+ export const END_BY = ['worker', 'requester', 'user', 'system'];
51
+ export const OUTCOMES = ['done', 'stopped', 'failed'];
52
+
53
+ /** Longest title, in characters. */
54
+ export const MAX_TITLE = 120;
55
+ /** Longest delegated text one ticket keeps. */
56
+ export const MAX_TEXT = 50_000;
57
+ /** Longest text one report keeps. */
58
+ export const MAX_REPORT = 20_000;
59
+ /** Reports one ticket keeps; past this the oldest go. */
60
+ export const KEEP_REPORTS = 200;
61
+ /** Archived tickets {@link createTickets}'s `prune` keeps by default. */
62
+ export const KEEP_ENDED = 500;
63
+ /** Worker slots when no number is given. */
64
+ export const DEFAULT_MAX_WORKING = 4;
65
+
66
+ export const TICKET_ID_RE = /^t[a-z0-9]{8}$/;
67
+ const SESSION_PREFIX = 'ticket-';
68
+ const ALNUM = 'abcdefghijklmnopqrstuvwxyz0123456789';
69
+ const MAX_KEY = 500;
70
+ const MAX_LABEL = 200;
71
+
72
+ /** `t` and 8 random lowercase letters and digits. */
73
+ export function newTicketId() {
74
+ let id = 't';
75
+ for (let i = 0; i < 8; i += 1) id += ALNUM[randomInt(ALNUM.length)];
76
+ return id;
77
+ }
78
+
79
+ /** The Session a ticket runs in. */
80
+ export const sessionIdOf = (ticketId) => `${SESSION_PREFIX}${ticketId}`;
81
+
82
+ /** The ticket id inside a ticket Session's id, or ''. */
83
+ export function ticketIdOf(sessionId) {
84
+ const s = String(sessionId ?? '');
85
+ const id = s.startsWith(SESSION_PREFIX) ? s.slice(SESSION_PREFIX.length) : '';
86
+ return TICKET_ID_RE.test(id) ? id : '';
87
+ }
88
+
89
+ /** One line of at most `max` characters (code points); a cut one ends with `…`. */
90
+ export function clampTitle(text, max = MAX_TITLE) {
91
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
92
+ const chars = [...s];
93
+ return chars.length <= max ? s : `${chars.slice(0, Math.max(0, max - 1)).join('').trimEnd()}…`;
94
+ }
95
+
96
+ /** A title from delegated text: its first line with words on it. */
97
+ export function titleFrom(text) {
98
+ const line = String(text ?? '').split('\n').find((l) => l.trim() !== '') ?? '';
99
+ return clampTitle(line);
100
+ }
101
+
102
+ const str = (v, max = MAX_TEXT) => (typeof v === 'string' ? v.slice(0, max) : '');
103
+ const time = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : 0);
104
+
105
+ /** Not ended. */
106
+ export const isOpen = (ticket) => !ticket?.ended;
107
+
108
+ /** Messages waiting on a started ticket for a worker slot (`parked`), oldest first. */
109
+ export const parkedOf = (ticket) => (Array.isArray(ticket?.parked) ? ticket.parked : []);
110
+
111
+ /** Still takes messages from its Threads: not archived, and not stopped by a person. */
112
+ export const isLive = (ticket) => Boolean(ticket) && !ticket.archivedAt && !(ticket.ended?.by === 'user' && ticket.ended.outcome === 'stopped');
113
+
114
+ /**
115
+ * The stage of a ticket, from its stored fields (table in the module header).
116
+ * @param {object} ticket
117
+ * @param {{now?: number}} [_at] - accepted for symmetry with the watchdog, unused: time-based
118
+ * judgements are the watchdog's, which stores `stalledAt`.
119
+ * @returns {'failed'|'question'|'stalled'|'queued'|'working'|'done'|'stopped'}
120
+ */
121
+ export function stageOf(ticket, _at) {
122
+ const t = ticket ?? {};
123
+ const open = !t.ended;
124
+ const last = Array.isArray(t.reports) ? t.reports.at(-1) : undefined;
125
+ const unanswered = (r) => Math.max(time(t.lastHumanAt), time(t.lastRequesterAt)) <= time(r.at);
126
+ if (t.ended?.outcome === 'failed' || (open && last?.status === 'blocked' && unanswered(last))) return 'failed';
127
+ if (open && last?.status === 'question' && unanswered(last)) return 'question';
128
+ if (open && t.stalledAt) return 'stalled';
129
+ if (open && (!t.startedAt || parkedOf(t).length > 0)) return 'queued';
130
+ if (open) return 'working';
131
+ if (t.ended.outcome === 'done') return 'done';
132
+ return 'stopped';
133
+ }
134
+
135
+ /**
136
+ * Worker slots: at most `max` tickets work at once, plus one extra slot that
137
+ * only a person's message may take, so new work cannot crowd out a follow-up.
138
+ * The extra slot is simply "one beyond `max`": once any slot frees, the next
139
+ * person's message can use it again.
140
+ * @param {number} [max]
141
+ */
142
+ export function createSlots(max = DEFAULT_MAX_WORKING) {
143
+ const capOf = (n) => (Number.isFinite(Number(n)) ? Math.max(1, Math.floor(Number(n))) : DEFAULT_MAX_WORKING);
144
+ let cap = capOf(max);
145
+ const held = new Set();
146
+ return {
147
+ /** Take a slot for `ticketId`; true when it holds one (again) now. */
148
+ acquire(ticketId, { human = false } = {}) {
149
+ if (!ticketId) return false;
150
+ if (held.has(ticketId)) return true;
151
+ if (held.size < cap || (human && held.size < cap + 1)) {
152
+ held.add(ticketId);
153
+ return true;
154
+ }
155
+ return false;
156
+ },
157
+ /** Free the slot of `ticketId`; true when it held one. */
158
+ release(ticketId) {
159
+ return held.delete(ticketId);
160
+ },
161
+ holds(ticketId) {
162
+ return held.has(ticketId);
163
+ },
164
+ count() {
165
+ return held.size;
166
+ },
167
+ max() {
168
+ return cap;
169
+ },
170
+ /** A new limit; holders keep their slots, new ones wait until the count is under it. */
171
+ setMax(n) {
172
+ cap = capOf(n);
173
+ },
174
+ };
175
+ }
176
+
177
+ /** Kind, app, chat and root from a Thread key (`kind:appKey:chatId[:rootId]`, `panel:<sessionId>`). */
178
+ function partsOfKey(key) {
179
+ const [kind = '', ...rest] = key.split(':');
180
+ if (kind === 'panel') return { kind, appKey: '', chatId: rest.join(':') };
181
+ const [appKey = '', chatId = '', ...root] = rest;
182
+ return { kind, appKey, chatId, ...(root.length > 0 && root.join(':') !== '' ? { rootId: root.join(':') } : {}) };
183
+ }
184
+
185
+ const validKey = (key) => typeof key === 'string' && key !== '' && key.length <= MAX_KEY;
186
+
187
+ function normalizeRequester(r) {
188
+ const out = { kind: r?.kind === 'session' || (r?.kind !== 'user' && typeof r?.sessionId === 'string' && r.sessionId) ? 'session' : 'user' };
189
+ for (const k of ['sessionId', 'botId', 'ticketId']) if (typeof r?.[k] === 'string' && r[k] !== '') out[k] = r[k];
190
+ return out;
191
+ }
192
+
193
+ function normalizeOrigin(o) {
194
+ const out = {};
195
+ if (validKey(o?.threadKey)) out.threadKey = o.threadKey;
196
+ for (const k of ['via', 'who']) if (typeof o?.[k] === 'string' && o[k] !== '') out[k] = o[k].slice(0, MAX_LABEL);
197
+ // The chat message that started it, which an answer in its Thread quotes.
198
+ if ((typeof o?.replyTo === 'string' && o.replyTo !== '') || Number.isFinite(o?.replyTo)) out.replyTo = String(o.replyTo).slice(0, MAX_KEY);
199
+ return out;
200
+ }
201
+
202
+ function normalizeReport(r) {
203
+ if (!r || !REPORT_STATUSES.includes(r.status)) return null;
204
+ return { at: time(r.at), status: r.status, text: str(r.text, MAX_REPORT) };
205
+ }
206
+
207
+ const OPTIONAL_TIMES = ['startedAt', 'lastEventAt', 'lastHumanAt', 'lastRequesterAt', 'nudgedAt', 'stalledAt', 'archivedAt'];
208
+
209
+ /** A stored ticket as read back: known fields checked, unknown ones kept, `null` when unusable. */
210
+ function normalizeTicket(raw) {
211
+ if (!raw || typeof raw !== 'object' || typeof raw.id !== 'string' || raw.id === '' || typeof raw.botId !== 'string' || raw.botId === '') return null;
212
+ const t = { ...raw };
213
+ t.title = clampTitle(raw.title) || titleFrom(raw.text);
214
+ t.text = str(raw.text);
215
+ t.sessionId = typeof raw.sessionId === 'string' && raw.sessionId !== '' ? raw.sessionId : null;
216
+ t.requester = normalizeRequester(raw.requester);
217
+ t.origin = normalizeOrigin(raw.origin);
218
+ t.threads = [...new Set((Array.isArray(raw.threads) ? raw.threads : []).filter(validKey))];
219
+ t.reports = (Array.isArray(raw.reports) ? raw.reports : []).map(normalizeReport).filter(Boolean).slice(-KEEP_REPORTS);
220
+ t.createdAt = time(raw.createdAt);
221
+ t.updatedAt = time(raw.updatedAt) || t.createdAt;
222
+ t.retries = Number.isInteger(raw.retries) && raw.retries > 0 ? raw.retries : 0;
223
+ for (const k of OPTIONAL_TIMES) {
224
+ if (time(raw[k])) t[k] = time(raw[k]);
225
+ else delete t[k];
226
+ }
227
+ if (typeof raw.parentId !== 'string' || raw.parentId === '') delete t.parentId;
228
+ if (typeof raw.error !== 'string') delete t.error;
229
+ if (raw.ended && typeof raw.ended === 'object') {
230
+ t.ended = { at: time(raw.ended.at) || t.updatedAt, by: END_BY.includes(raw.ended.by) ? raw.ended.by : 'system', outcome: OUTCOMES.includes(raw.ended.outcome) ? raw.ended.outcome : 'stopped' };
231
+ } else {
232
+ delete t.ended;
233
+ }
234
+ if (t.archivedAt && !t.ended) t.ended = { at: t.archivedAt, by: 'system', outcome: 'stopped' };
235
+ return t;
236
+ }
237
+
238
+ function normalizeThread(raw) {
239
+ if (!raw || typeof raw !== 'object' || !validKey(raw.key)) return null;
240
+ const th = { key: raw.key, ...partsOfKey(raw.key), tickets: Array.isArray(raw.tickets) ? raw.tickets.filter((x) => typeof x === 'string') : [], lastAt: time(raw.lastAt) };
241
+ applyMeta(th, raw);
242
+ return th;
243
+ }
244
+
245
+ /** Copy the descriptive fields of `meta` onto a Thread record. */
246
+ function applyMeta(th, meta) {
247
+ for (const k of ['kind', 'appKey', 'chatId', 'rootId']) if (typeof meta?.[k] === 'string' && meta[k] !== '') th[k] = meta[k].slice(0, MAX_KEY);
248
+ if (typeof meta?.label === 'string' && meta.label.trim() !== '') th.label = clampTitle(meta.label, MAX_LABEL);
249
+ }
250
+
251
+ /**
252
+ * The tickets file under `dir`.
253
+ *
254
+ * Returned tickets and Threads are the stored objects: read them, change them
255
+ * through these methods. Every change is written at once, except a plain
256
+ * {@link touch} (a Session event), which waits for the next write or `flush()`.
257
+ *
258
+ * @param {string} dir
259
+ * @param {{now?: () => number}} [options] - `now`: the clock (tests).
260
+ */
261
+ export function createTickets(dir, { now = Date.now } = {}) {
262
+ const file = join(dir, 'tickets.json');
263
+ /** @type {{version: 1, tickets: object[], threads: object[]}|null} */
264
+ let data = null;
265
+ const byId = new Map();
266
+ const byKey = new Map();
267
+ const listeners = new Set();
268
+ let dirty = false;
269
+
270
+ /** Keep an unparseable file as `tickets.json.corrupt-<time>`; an earlier one is never replaced. */
271
+ const setAside = () => {
272
+ try {
273
+ let to = `${file}.corrupt-${now()}`;
274
+ for (let n = 1; existsSync(to); n += 1) to = `${file}.corrupt-${now()}-${n}`;
275
+ renameSync(file, to);
276
+ } catch {
277
+ // It goes when the next write replaces it.
278
+ }
279
+ };
280
+
281
+ const load = () => {
282
+ if (data) return data;
283
+ let parsed = null;
284
+ let text = null;
285
+ try {
286
+ text = readFileSync(file, 'utf8');
287
+ } catch (error) {
288
+ // No file is a first run; one that cannot be read must not be written over.
289
+ if (error?.code !== 'ENOENT') throw new Error(`cannot read ${file} (${error?.code ?? error?.message ?? error}); fix or move it, tasks are not loaded until then`, { cause: error });
290
+ }
291
+ if (text !== null) {
292
+ try {
293
+ parsed = JSON.parse(text);
294
+ } catch {
295
+ parsed = null;
296
+ }
297
+ if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.tickets)) {
298
+ parsed = null;
299
+ setAside();
300
+ }
301
+ }
302
+ data = { version: 1, tickets: [], threads: [] };
303
+ for (const raw of parsed?.tickets ?? []) {
304
+ const t = normalizeTicket(raw);
305
+ if (!t || byId.has(t.id)) continue;
306
+ data.tickets.push(t);
307
+ byId.set(t.id, t);
308
+ }
309
+ for (const raw of Array.isArray(parsed?.threads) ? parsed.threads : []) {
310
+ const th = normalizeThread(raw);
311
+ if (!th || byKey.has(th.key)) continue;
312
+ data.threads.push(th);
313
+ byKey.set(th.key, th);
314
+ }
315
+ // The tickets' own lists are the truth: Thread lists keep their order, lose what the
316
+ // tickets do not say, and gain what they do.
317
+ const subscribed = new Map();
318
+ for (const t of data.tickets) {
319
+ for (const key of t.threads) {
320
+ if (!subscribed.has(key)) subscribed.set(key, []);
321
+ subscribed.get(key).push(t.id);
322
+ }
323
+ }
324
+ for (const th of data.threads) {
325
+ const ids = subscribed.get(th.key) ?? [];
326
+ th.tickets = [...new Set([...th.tickets.filter((id) => ids.includes(id)), ...ids])];
327
+ }
328
+ for (const [key, ids] of subscribed) {
329
+ if (byKey.has(key)) continue;
330
+ const th = { key, ...partsOfKey(key), tickets: ids, lastAt: 0 };
331
+ data.threads.push(th);
332
+ byKey.set(key, th);
333
+ }
334
+ return data;
335
+ };
336
+
337
+ const save = () => {
338
+ dirty = false;
339
+ try {
340
+ mkdirSync(dir, { recursive: true });
341
+ // Delegated work can quote anything the user said: readable by this user only.
342
+ writeFileSync(`${file}.tmp`, JSON.stringify(data), { encoding: 'utf8', mode: 0o600 });
343
+ renameSync(`${file}.tmp`, file);
344
+ } catch {
345
+ dirty = true; // Kept in memory; the next write tries again.
346
+ }
347
+ };
348
+
349
+ const changed = (ticket = null) => {
350
+ save();
351
+ for (const fn of listeners) {
352
+ try {
353
+ fn(ticket);
354
+ } catch {
355
+ // A listener must not break a write.
356
+ }
357
+ }
358
+ };
359
+
360
+ const ensureThread = (key, meta) => {
361
+ let th = byKey.get(key);
362
+ if (!th) {
363
+ th = { key, ...partsOfKey(key), tickets: [], lastAt: now() };
364
+ data.threads.push(th);
365
+ byKey.set(key, th);
366
+ }
367
+ if (meta) {
368
+ applyMeta(th, meta);
369
+ th.lastAt = time(meta.lastAt) || now();
370
+ }
371
+ return th;
372
+ };
373
+
374
+ /** Subscribe without writing; true when something changed. */
375
+ const link = (t, key, meta) => {
376
+ if (!validKey(key)) return false;
377
+ const th = ensureThread(key, meta);
378
+ let did = Boolean(meta);
379
+ if (!t.threads.includes(key)) {
380
+ t.threads.push(key);
381
+ did = true;
382
+ }
383
+ if (!th.tickets.includes(t.id)) {
384
+ th.tickets.push(t.id);
385
+ did = true;
386
+ }
387
+ return did;
388
+ };
389
+
390
+ const unlink = (t, key) => {
391
+ const had = t.threads.includes(key);
392
+ t.threads = t.threads.filter((k) => k !== key);
393
+ const th = byKey.get(key);
394
+ if (th) th.tickets = th.tickets.filter((id) => id !== t.id);
395
+ return had;
396
+ };
397
+
398
+ const find = (id) => {
399
+ load();
400
+ return typeof id === 'string' ? byId.get(id) : undefined;
401
+ };
402
+
403
+ return {
404
+ file,
405
+
406
+ /**
407
+ * Open a ticket. Throws a readable error without a bot or without any text.
408
+ * `parentId` defaults to the requesting ticket (`requester.ticketId`); the
409
+ * origin Thread is subscribed, as is each of `threads` (keys, or Thread
410
+ * metadata with a `key`).
411
+ * @param {{title?: string, text: string, botId: string, requester?: object, parentId?: string, origin?: {threadKey?: string, via?: string, who?: string}, threads?: Array<string|{key: string}>}} input
412
+ */
413
+ create({ title, text, botId, requester, parentId, origin, threads = [] } = {}) {
414
+ load();
415
+ if (typeof botId !== 'string' || botId === '') throw new Error('a ticket needs the bot that does the work');
416
+ const body = str(text);
417
+ const name = clampTitle(title) || titleFrom(body);
418
+ if (name === '') throw new Error('a ticket needs a title or text');
419
+ let id = newTicketId();
420
+ while (byId.has(id)) id = newTicketId();
421
+ const at = now();
422
+ const req = normalizeRequester(requester);
423
+ const parent = typeof parentId === 'string' && parentId !== '' ? parentId : req.ticketId;
424
+ const t = {
425
+ id,
426
+ title: name,
427
+ text: body,
428
+ botId,
429
+ sessionId: null,
430
+ requester: req,
431
+ ...(parent ? { parentId: parent } : {}),
432
+ origin: normalizeOrigin(origin),
433
+ threads: [],
434
+ reports: [],
435
+ createdAt: at,
436
+ updatedAt: at,
437
+ retries: 0,
438
+ };
439
+ data.tickets.push(t);
440
+ byId.set(id, t);
441
+ if (t.origin.threadKey) link(t, t.origin.threadKey);
442
+ for (const th of Array.isArray(threads) ? threads : []) {
443
+ if (typeof th === 'string') link(t, th);
444
+ else if (th && typeof th === 'object') link(t, th.key, th);
445
+ }
446
+ changed(t);
447
+ return t;
448
+ },
449
+
450
+ get: find,
451
+
452
+ /**
453
+ * Tickets, newest first.
454
+ * @param {{botId?: string, stage?: string|string[], open?: boolean, archived?: boolean}} [filter]
455
+ * `open`: true for not ended, false for ended; `archived` likewise.
456
+ */
457
+ list({ botId, stage, open, archived } = {}) {
458
+ load();
459
+ const stages = stage === undefined ? null : new Set([stage].flat());
460
+ const at = now();
461
+ return data.tickets
462
+ .filter(
463
+ (t) =>
464
+ (botId === undefined || t.botId === botId) &&
465
+ (open === undefined || isOpen(t) === open) &&
466
+ (archived === undefined || Boolean(t.archivedAt) === archived) &&
467
+ (!stages || stages.has(stageOf(t, { now: at }))),
468
+ )
469
+ .reverse();
470
+ },
471
+
472
+ /** Tickets not ended, oldest first (the queue's order). */
473
+ open() {
474
+ load();
475
+ return data.tickets.filter(isOpen);
476
+ },
477
+
478
+ /** The tickets `id` handed on, oldest first. */
479
+ children(id) {
480
+ load();
481
+ return data.tickets.filter((t) => t.parentId === id);
482
+ },
483
+
484
+ /**
485
+ * The ticket a Session belongs to: its stored `sessionId`, or a `ticket-<id>`
486
+ * Session not stored yet (it is being created).
487
+ */
488
+ bySession(sessionId) {
489
+ load();
490
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined;
491
+ const t = byId.get(ticketIdOf(sessionId));
492
+ if (t && (t.sessionId === sessionId || t.sessionId === null)) return t;
493
+ return data.tickets.find((x) => x.sessionId === sessionId);
494
+ },
495
+
496
+ /**
497
+ * Set fields as given (`undefined` removes one); `id` stays, `title` is
498
+ * clamped, and a new `threads` list subscribes and unsubscribes to match.
499
+ */
500
+ patch(id, fields) {
501
+ const t = find(id);
502
+ if (!t) return undefined;
503
+ const { id: _id, threads, ...rest } = fields ?? {};
504
+ const title = t.title;
505
+ for (const [k, v] of Object.entries(rest)) {
506
+ if (v === undefined) delete t[k];
507
+ else t[k] = v;
508
+ }
509
+ if ('title' in rest) t.title = clampTitle(rest.title) || title;
510
+ if (Array.isArray(threads)) {
511
+ const want = threads.filter(validKey);
512
+ for (const key of [...t.threads]) if (!want.includes(key)) unlink(t, key);
513
+ for (const key of want) link(t, key);
514
+ }
515
+ t.updatedAt = now();
516
+ changed(t);
517
+ return t;
518
+ },
519
+
520
+ /**
521
+ * The ticket started in its Session (default `ticket-<id>`). A first start
522
+ * time is kept (a restart delivers it again); to queue a started ticket
523
+ * again, `patch(id, {startedAt: undefined})`.
524
+ */
525
+ start(id, { sessionId } = {}) {
526
+ const t = find(id);
527
+ if (!t) return undefined;
528
+ const at = now();
529
+ t.sessionId = typeof sessionId === 'string' && sessionId !== '' ? sessionId : t.sessionId ?? sessionIdOf(t.id);
530
+ t.startedAt ??= at;
531
+ t.lastEventAt = at;
532
+ t.updatedAt = at;
533
+ changed(t);
534
+ return t;
535
+ },
536
+
537
+ /**
538
+ * A report from the worker. Any report clears `nudgedAt` and `stalledAt`; a
539
+ * `done` one ends an open ticket (by 'worker', outcome 'done'). Throws on an
540
+ * unknown status.
541
+ * @param {string} id
542
+ * @param {{status: 'progress'|'done'|'blocked'|'question', text?: string}} report
543
+ */
544
+ addReport(id, { status, text } = {}) {
545
+ if (!REPORT_STATUSES.includes(status)) throw new Error(`a report status is one of ${REPORT_STATUSES.join(', ')}`);
546
+ const t = find(id);
547
+ if (!t) return undefined;
548
+ const at = now();
549
+ t.reports = [...t.reports, { at, status, text: str(text, MAX_REPORT) }].slice(-KEEP_REPORTS);
550
+ delete t.nudgedAt;
551
+ delete t.stalledAt;
552
+ t.lastEventAt = at;
553
+ t.updatedAt = at;
554
+ if (status === 'done' && !t.ended) t.ended = { at, by: 'worker', outcome: 'done' };
555
+ changed(t);
556
+ return t;
557
+ },
558
+
559
+ /**
560
+ * End a ticket (again: the newest end wins, so a requester may close a failed one).
561
+ * Throws on an unknown `by` or `outcome`.
562
+ * @param {string} id
563
+ * @param {{by: 'worker'|'requester'|'user'|'system', outcome: 'done'|'stopped'|'failed', error?: string}} end
564
+ */
565
+ end(id, { by, outcome, error } = {}) {
566
+ if (!END_BY.includes(by)) throw new Error(`a ticket is ended by one of ${END_BY.join(', ')}`);
567
+ if (!OUTCOMES.includes(outcome)) throw new Error(`a ticket ends as one of ${OUTCOMES.join(', ')}`);
568
+ const t = find(id);
569
+ if (!t) return undefined;
570
+ const at = now();
571
+ t.ended = { at, by, outcome };
572
+ if (typeof error === 'string' && error !== '') t.error = error.slice(0, MAX_REPORT);
573
+ t.updatedAt = at;
574
+ changed(t);
575
+ return t;
576
+ },
577
+
578
+ /**
579
+ * Open an ended ticket again (a follow-up after `done`, a retry): clears
580
+ * `ended`, `stalledAt` and `nudgedAt`, and sets `retries` back to 0. Refused
581
+ * (`null`) when archived, or when a person stopped it unless `force` (that
582
+ * person asking for it again). A ticket failed by an unanswered `blocked`
583
+ * report stays failed until a message answers it ({@link touch}).
584
+ * @returns {object|null|undefined} the ticket, `null` when refused, `undefined` when unknown
585
+ */
586
+ resume(id, { force = false } = {}) {
587
+ const t = find(id);
588
+ if (!t) return undefined;
589
+ if (t.archivedAt) return null;
590
+ if (!force && t.ended?.by === 'user' && t.ended.outcome === 'stopped') return null;
591
+ delete t.ended;
592
+ delete t.stalledAt;
593
+ delete t.nudgedAt;
594
+ t.retries = 0;
595
+ t.updatedAt = now();
596
+ changed(t);
597
+ return t;
598
+ },
599
+
600
+ /**
601
+ * Something happened in the ticket: sets `lastEventAt`. A message from a
602
+ * person (`human`) or from the requester (`requester`) also sets
603
+ * `lastHumanAt` / `lastRequesterAt`, answers a `question` or `blocked`
604
+ * report, and clears `nudgedAt` / `stalledAt`; it is written at once. A plain
605
+ * event is kept in memory until the next write or `flush()`.
606
+ */
607
+ touch(id, { human = false, requester = false } = {}) {
608
+ const t = find(id);
609
+ if (!t) return undefined;
610
+ const at = now();
611
+ t.lastEventAt = at;
612
+ if (!human && !requester) {
613
+ dirty = true;
614
+ return t;
615
+ }
616
+ if (human) t.lastHumanAt = at;
617
+ if (requester) t.lastRequesterAt = at;
618
+ delete t.nudgedAt;
619
+ delete t.stalledAt;
620
+ t.updatedAt = at;
621
+ changed(t);
622
+ return t;
623
+ },
624
+
625
+ /** Archive a ticket; one still open is ended first (stopped by the system). */
626
+ archive(id) {
627
+ const t = find(id);
628
+ if (!t) return undefined;
629
+ const at = now();
630
+ t.ended ??= { at, by: 'system', outcome: 'stopped' };
631
+ t.archivedAt ??= at;
632
+ t.updatedAt = at;
633
+ changed(t);
634
+ return t;
635
+ },
636
+
637
+ /** Subscribe a ticket to a Thread, made from its key (and `threadMeta`) when new. */
638
+ subscribe(id, threadKey, threadMeta) {
639
+ const t = find(id);
640
+ if (!t) return undefined;
641
+ if (link(t, threadKey, threadMeta ? { ...threadMeta, key: threadKey } : undefined)) {
642
+ t.updatedAt = now();
643
+ changed(t);
644
+ }
645
+ return t;
646
+ },
647
+
648
+ unsubscribe(id, threadKey) {
649
+ const t = find(id);
650
+ if (!t) return undefined;
651
+ if (unlink(t, threadKey)) {
652
+ t.updatedAt = now();
653
+ changed(t);
654
+ }
655
+ return t;
656
+ },
657
+
658
+ thread(key) {
659
+ load();
660
+ return typeof key === 'string' ? byKey.get(key) : undefined;
661
+ },
662
+
663
+ /**
664
+ * The tickets subscribed to a Thread, in the order they subscribed. `live`:
665
+ * only those that still take its messages ({@link isLive}).
666
+ */
667
+ subscribers(threadKey, { live = false } = {}) {
668
+ load();
669
+ const th = typeof threadKey === 'string' ? byKey.get(threadKey) : undefined;
670
+ if (!th) return [];
671
+ return th.tickets.map((id) => byId.get(id)).filter((t) => t && (!live || isLive(t)));
672
+ },
673
+
674
+ /**
675
+ * Record a Thread's metadata (`{key, kind?, appKey?, chatId?, rootId?, label?, lastAt?}`)
676
+ * and its latest activity (`lastAt`, default now). Its tickets are left as they are.
677
+ */
678
+ upsertThread(meta) {
679
+ load();
680
+ if (!validKey(meta?.key)) return undefined;
681
+ const th = ensureThread(meta.key, meta);
682
+ changed(null);
683
+ return th;
684
+ },
685
+
686
+ /** `fn(ticket)` after each write: the ticket that changed, or `null` (Thread metadata, a prune). Returns an unsubscribe. */
687
+ onChange(fn) {
688
+ listeners.add(fn);
689
+ return () => listeners.delete(fn);
690
+ },
691
+
692
+ /**
693
+ * Retention: keep the newest `keepEnded` archived tickets (by `archivedAt`),
694
+ * drop older ones, then drop Threads no ticket is subscribed to. Tickets not
695
+ * archived are never dropped.
696
+ * @returns {{tickets: number, threads: number}} how many went
697
+ */
698
+ prune({ keepEnded = KEEP_ENDED } = {}) {
699
+ load();
700
+ const keep = Number.isFinite(Number(keepEnded)) ? Math.max(0, Math.floor(Number(keepEnded))) : KEEP_ENDED;
701
+ const archived = data.tickets.filter((t) => t.archivedAt).sort((a, b) => a.archivedAt - b.archivedAt || a.createdAt - b.createdAt);
702
+ const drop = new Set(archived.slice(0, Math.max(0, archived.length - keep)).map((t) => t.id));
703
+ if (drop.size > 0) {
704
+ data.tickets = data.tickets.filter((t) => !drop.has(t.id));
705
+ for (const id of drop) byId.delete(id);
706
+ for (const th of data.threads) th.tickets = th.tickets.filter((id) => !drop.has(id));
707
+ }
708
+ const empty = data.threads.filter((th) => th.tickets.length === 0);
709
+ for (const th of empty) byKey.delete(th.key);
710
+ if (empty.length > 0) data.threads = data.threads.filter((th) => th.tickets.length > 0);
711
+ const gone = { tickets: drop.size, threads: empty.length };
712
+ if (gone.tickets > 0 || gone.threads > 0) changed(null);
713
+ return gone;
714
+ },
715
+
716
+ /** Write what plain touches left in memory. */
717
+ flush() {
718
+ load();
719
+ if (dirty) save();
720
+ },
721
+ };
722
+ }