@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.2

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.
@@ -47,7 +47,7 @@ export function renderNotice(lines) {
47
47
  ].join('\n');
48
48
  }
49
49
  /**
50
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
50
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
51
51
  * @param {{
52
52
  * pid: number,
53
53
  * inflight: Set<string>,
@@ -82,7 +82,7 @@ export async function reconcileInputs(book, deps) {
82
82
  }
83
83
  }
84
84
  /**
85
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
85
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
86
86
  * @param {{
87
87
  * pid: number,
88
88
  * inflight: Set<string>,
@@ -123,7 +123,7 @@ export async function reconcileNotices(book, deps) {
123
123
  }
124
124
  }
125
125
  /**
126
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
126
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
127
127
  * @param {Record<string, any>} input
128
128
  * @param {{
129
129
  * pid: number,
@@ -140,7 +140,9 @@ export async function pushInput(book, input, deps) {
140
140
  try {
141
141
  budget = { ...budget, ...JSON.parse(ticket.budget_json) };
142
142
  }
143
- catch { /* host default */ }
143
+ catch {
144
+ /* host default */
145
+ }
144
146
  const text = book.readBriefing(input.payload_hash);
145
147
  const body = renderBriefing({ text, revision: input.briefing_revision, budget, kind: input.kind });
146
148
  deps.inflight.add(input.native_message_id);
@@ -149,10 +151,10 @@ export async function pushInput(book, input, deps) {
149
151
  attempts: input.flush_attempts,
150
152
  markFlushing: () => book.markInputFlush(input.id, 'flushing', deps.pid, '', null, true),
151
153
  push: () => deps.push(attempt.child_session_id, input.native_message_id, body),
152
- markAccepted: (seq) => book.noteInputAccepted(input, seq),
153
- markAmbiguous: (error) => book.markInputFlush(input.id, 'ambiguous', deps.pid, error, null, false),
154
- markDead: (error) => book.markInputFlush(input.id, 'dead', deps.pid, error, null, false),
155
- markRetry: (error) => book.markInputFlush(input.id, 'intent', deps.pid, error, null, false),
154
+ markAccepted: seq => book.noteInputAccepted(input, seq),
155
+ markAmbiguous: error => book.markInputFlush(input.id, 'ambiguous', deps.pid, error, null, false),
156
+ markDead: error => book.markInputFlush(input.id, 'dead', deps.pid, error, null, false),
157
+ markRetry: error => book.markInputFlush(input.id, 'intent', deps.pid, error, null, false),
156
158
  });
157
159
  }
158
160
  finally {
@@ -160,7 +162,7 @@ export async function pushInput(book, input, deps) {
160
162
  }
161
163
  }
162
164
  /**
163
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
165
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
164
166
  * @param {string} nativeId
165
167
  * @param {string} owner
166
168
  * @param {string} text
@@ -178,10 +180,10 @@ export async function pushNotice(book, nativeId, owner, text, attempts, deps) {
178
180
  attempts,
179
181
  markFlushing: () => book.markNoticeGroup(nativeId, 'flushing', deps.pid, '', null, true),
180
182
  push: () => deps.push(owner, nativeId, text),
181
- markAccepted: (seq) => book.markNoticeGroup(nativeId, 'accepted', deps.pid, '', seq, false),
182
- markAmbiguous: (error) => book.markNoticeGroup(nativeId, 'ambiguous', deps.pid, error, null, false),
183
- markDead: (error) => book.markNoticeGroup(nativeId, 'dead', deps.pid, error, null, false),
184
- markRetry: (error) => book.markNoticeGroup(nativeId, 'intent', deps.pid, error, null, false),
183
+ markAccepted: seq => book.markNoticeGroup(nativeId, 'accepted', deps.pid, '', seq, false),
184
+ markAmbiguous: error => book.markNoticeGroup(nativeId, 'ambiguous', deps.pid, error, null, false),
185
+ markDead: error => book.markNoticeGroup(nativeId, 'dead', deps.pid, error, null, false),
186
+ markRetry: error => book.markNoticeGroup(nativeId, 'intent', deps.pid, error, null, false),
185
187
  });
186
188
  }
187
189
  finally {
@@ -213,5 +215,5 @@ export function messageIdOf(event) {
213
215
  */
214
216
  export function reasonKindOf(event) {
215
217
  const reason = event?.data?.reason;
216
- return reason && typeof reason === 'object' ? reason.kind ?? '' : '';
218
+ return reason && typeof reason === 'object' ? (reason.kind ?? '') : '';
217
219
  }
@@ -16,13 +16,13 @@ export async function startWorkMock(options) {
16
16
  const clock = { ms: Date.now() };
17
17
  const now = options.now ?? (() => new Date(clock.ms));
18
18
  const work = createWorkRuntime(store, engine, {
19
- createChild: (spec) => world.createChild(spec),
19
+ createChild: spec => world.createChild(spec),
20
20
  push: (sessionId, messageId, text) => world.push(sessionId, messageId, text),
21
21
  logHas: (sessionId, messageId) => world.logHas(sessionId, messageId),
22
22
  remove: (sessionId, messageId) => world.remove(sessionId, messageId),
23
- pendingIds: (sessionId) => world.pendingIds(sessionId),
23
+ pendingIds: sessionId => world.pendingIds(sessionId),
24
24
  cancel: (sessionId, cancelOptions) => world.cancel(sessionId, cancelOptions),
25
- snapshot: (sessionId) => world.snapshot(sessionId),
25
+ snapshot: sessionId => world.snapshot(sessionId),
26
26
  now,
27
27
  pid: process.pid,
28
28
  });
@@ -119,14 +119,16 @@ export async function startWorkMock(options) {
119
119
  try {
120
120
  store.close();
121
121
  }
122
- catch { /* closed */ }
122
+ catch {
123
+ /* closed */
124
+ }
123
125
  resolve();
124
126
  });
125
127
  }),
126
128
  };
127
129
  }
128
130
  /**
129
- * @param {ReturnType<import('./work-worker.js').createWorkRuntime>} work
131
+ * @param {ReturnType<typeof import('./work-worker.js').createWorkRuntime>} work
130
132
  * @param {unknown} ticketId
131
133
  */
132
134
  function statusOf(work, ticketId) {
@@ -154,7 +156,7 @@ function send(res, status, body) {
154
156
  function readJson(req) {
155
157
  return new Promise((resolve, reject) => {
156
158
  const chunks = [];
157
- req.on('data', chunk => chunks.push(chunk));
159
+ req.on('data', (chunk) => chunks.push(chunk));
158
160
  req.on('end', () => {
159
161
  const raw = Buffer.concat(chunks).toString('utf8');
160
162
  if (raw === '') {
package/dist/work-mock.js CHANGED
@@ -43,29 +43,25 @@ export function createMockWorld() {
43
43
  },
44
44
  seeUser(sessionId, messageId, turn) {
45
45
  const slot = session(sessionId);
46
- append(slot, 'user/message', { id: messageId, turn, message: { id: messageId } });
47
- return slot.events.at(-1);
46
+ return append(slot, 'user/message', { id: messageId, turn, message: { id: messageId } });
48
47
  },
49
48
  endTurn(sessionId, turn, reasonKind) {
50
49
  const slot = session(sessionId);
51
- append(slot, 'turn/end', { turn, reason: { kind: reasonKind } });
52
- return slot.events.at(-1);
50
+ return append(slot, 'turn/end', { turn, reason: { kind: reasonKind } });
53
51
  },
54
52
  toolCall(sessionId, name, args) {
55
53
  const slot = session(sessionId);
56
- append(slot, 'tool/call', { name, arguments: args });
57
- return slot.events.at(-1);
54
+ return append(slot, 'tool/call', { name, arguments: args });
58
55
  },
59
56
  assistant(sessionId, text) {
60
57
  const slot = session(sessionId);
61
- append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
62
- return slot.events.at(-1);
58
+ return append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
63
59
  },
64
60
  forgetLog(sessionId, messageId) {
65
61
  const slot = session(sessionId);
66
- slot.events = slot.events.filter(event => !(event.type === 'agent/inbox/spliced'
67
- && Array.isArray(event.data?.inserted)
68
- && event.data.inserted.some(item => item?.id === messageId)));
62
+ slot.events = slot.events.filter(event => !(event.type === 'agent/inbox/spliced' &&
63
+ Array.isArray(event.data?.inserted) &&
64
+ event.data.inserted.some((item) => item?.id === messageId)));
69
65
  slot.nextTurn = slot.nextTurn.filter(item => item.id !== messageId);
70
66
  },
71
67
  async createChild(spec) {
@@ -84,13 +80,13 @@ export function createMockWorld() {
84
80
  const slot = session(sessionId);
85
81
  if (!slot.nextTurn.some(item => item.id === messageId))
86
82
  slot.nextTurn.push({ id: messageId, text });
87
- const seq = append(slot, 'agent/inbox/spliced', { inserted: [{ id: messageId }], target: 'next-turn' });
88
- return { ok: true, ambiguous: false, seq, target: 'next-turn' };
83
+ const event = append(slot, 'agent/inbox/spliced', { inserted: [{ id: messageId }], target: 'next-turn' });
84
+ return { ok: true, ambiguous: false, seq: event.seq, target: 'next-turn' };
89
85
  },
90
86
  async logHas(sessionId, messageId) {
91
- return session(sessionId).events.some(event => (event.type === 'agent/inbox/spliced'
92
- && Array.isArray(event.data?.inserted)
93
- && event.data.inserted.some(item => item?.id === messageId)));
87
+ return session(sessionId).events.some(event => event.type === 'agent/inbox/spliced' &&
88
+ Array.isArray(event.data?.inserted) &&
89
+ event.data.inserted.some((item) => item?.id === messageId));
94
90
  },
95
91
  async remove(sessionId, messageId) {
96
92
  const slot = session(sessionId);
@@ -125,7 +121,8 @@ export function createMockWorld() {
125
121
  */
126
122
  function append(slot, type, data) {
127
123
  slot.seq += 1;
128
- slot.events.push({ type, seq: slot.seq, data });
129
- return slot.seq;
124
+ const event = { type, seq: slot.seq, data };
125
+ slot.events.push(event);
126
+ return event;
130
127
  }
131
128
  }
@@ -83,16 +83,20 @@ export function createTicketBook(db, root, now = () => new Date()) {
83
83
  * @param {string} owner
84
84
  */
85
85
  function countActive(owner) {
86
- return db.prepare(`
86
+ return db
87
+ .prepare(`
87
88
  SELECT COUNT(*) AS n FROM work_tickets
88
89
  WHERE owner_session_id = ? AND status IN ('accepted','enqueued','started','needs_user')
89
- `).get(owner).n;
90
+ `)
91
+ .get(owner).n;
90
92
  }
91
93
  function countGlobal() {
92
- return db.prepare(`
94
+ return db
95
+ .prepare(`
93
96
  SELECT COUNT(*) AS n FROM work_tickets
94
97
  WHERE status IN ('accepted','enqueued','started','needs_user')
95
- `).get().n;
98
+ `)
99
+ .get().n;
96
100
  }
97
101
  /**
98
102
  * @param {string} owner
@@ -101,17 +105,21 @@ export function createTicketBook(db, root, now = () => new Date()) {
101
105
  function byIdempotency(owner, key) {
102
106
  if (key == null)
103
107
  return null;
104
- return db.prepare(`
108
+ return (db
109
+ .prepare(`
105
110
  SELECT * FROM work_tickets WHERE owner_session_id = ? AND idempotency_key = ?
106
- `).get(owner, key) ?? null;
111
+ `)
112
+ .get(owner, key) ?? null);
107
113
  }
108
114
  /**
109
115
  * @param {string} sessionId
110
116
  */
111
117
  function attemptForChild(sessionId) {
112
- return db.prepare(`
118
+ return (db
119
+ .prepare(`
113
120
  SELECT * FROM work_attempts WHERE child_session_id = ? ORDER BY fencing_token DESC LIMIT 1
114
- `).get(sessionId) ?? null;
121
+ `)
122
+ .get(sessionId) ?? null);
115
123
  }
116
124
  /**
117
125
  * @param {string} nativeId
@@ -175,7 +183,10 @@ export function createTicketBook(db, root, now = () => new Date()) {
175
183
  cancel_requested_revision, created_at, updated_at
176
184
  ) VALUES (?, ?, NULL, 1, 1, 'accepted', 'none', ?, ?, ?, ?, NULL, ?, NULL, ?, ?)
177
185
  `).run(ticketId, input.owner, attemptId, hash, input.correlationId ?? '', input.idempotencyKey, JSON.stringify(input.budget), stamp, stamp);
178
- return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId) };
186
+ return {
187
+ ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId),
188
+ attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId),
189
+ };
179
190
  }
180
191
  /**
181
192
  * @param {string} ticketId
@@ -276,22 +287,34 @@ export function createTicketBook(db, root, now = () => new Date()) {
276
287
  return { error: 'NOT_FOUND' };
277
288
  const allowed = kind === 'supply'
278
289
  ? ticket.status === 'needs_user' || ticket.status === 'enqueued'
279
- : ticket.status === 'accepted' || ticket.status === 'enqueued' || ticket.status === 'started' || ticket.status === 'needs_user' || ticket.status === 'ready';
290
+ : ticket.status === 'accepted' ||
291
+ ticket.status === 'enqueued' ||
292
+ ticket.status === 'started' ||
293
+ ticket.status === 'needs_user' ||
294
+ ticket.status === 'ready';
280
295
  if (!allowed)
281
- return { error: 'VALIDATION', message: `Ticket status ${ticket.status} cannot ${kind === 'supply' ? 'supply' : 'redirect'}.` };
296
+ return {
297
+ error: 'VALIDATION',
298
+ message: `Ticket status ${ticket.status} cannot ${kind === 'supply' ? 'supply' : 'redirect'}.`,
299
+ };
282
300
  if (!ticket.child_session_id)
283
- return { error: 'VALIDATION', message: 'The worker session does not exist yet, so this generation cannot be changed.' };
301
+ return {
302
+ error: 'VALIDATION',
303
+ message: 'The worker session does not exist yet, so this generation cannot be changed.',
304
+ };
284
305
  const expected = expectedRevision == null ? ticket.revision : expectedRevision;
285
306
  if (expected !== ticket.revision)
286
307
  return { error: 'CAS_CONFLICT' };
287
308
  const nextRevision = ticket.revision + 1;
288
309
  const nextBrief = ticket.briefing_revision + 1;
289
310
  const hash = writeBriefing(text);
290
- const info = db.prepare(`
311
+ const info = db
312
+ .prepare(`
291
313
  UPDATE work_tickets
292
314
  SET revision = ?, briefing_revision = ?, briefing_hash = ?, review_status = 'none', updated_at = ?
293
315
  WHERE id = ? AND revision = ?
294
- `).run(nextRevision, nextBrief, hash, iso(), ticketId, expected);
316
+ `)
317
+ .run(nextRevision, nextBrief, hash, iso(), ticketId, expected);
295
318
  if (info.changes !== 1)
296
319
  return { error: 'CAS_CONFLICT' };
297
320
  abandonOpenDeliveries(ticketId, nextBrief);
@@ -325,11 +348,13 @@ export function createTicketBook(db, root, now = () => new Date()) {
325
348
  if (expected !== ticket.revision)
326
349
  return { error: 'CAS_CONFLICT' };
327
350
  const next = ticket.revision + 1;
328
- const info = db.prepare(`
351
+ const info = db
352
+ .prepare(`
329
353
  UPDATE work_tickets
330
354
  SET revision = ?, status = 'cancelled', cancel_requested_revision = ?, updated_at = ?
331
355
  WHERE id = ? AND revision = ?
332
- `).run(next, next, iso(), ticketId, expected);
356
+ `)
357
+ .run(next, next, iso(), ticketId, expected);
333
358
  if (info.changes !== 1)
334
359
  return { error: 'CAS_CONFLICT' };
335
360
  db.prepare(`
@@ -371,12 +396,14 @@ export function createTicketBook(db, root, now = () => new Date()) {
371
396
  const token = (previous?.fencing_token ?? 0) + 1;
372
397
  const attemptId = randomUUID();
373
398
  const next = ticket.revision + 1;
374
- const info = db.prepare(`
399
+ const info = db
400
+ .prepare(`
375
401
  UPDATE work_tickets
376
402
  SET revision = ?, briefing_revision = 1, status = 'accepted', review_status = 'none',
377
403
  active_attempt_id = ?, cancel_requested_revision = NULL, updated_at = ?
378
404
  WHERE id = ? AND revision = ?
379
- `).run(next, attemptId, iso(), ticketId, expected);
405
+ `)
406
+ .run(next, attemptId, iso(), ticketId, expected);
380
407
  if (info.changes !== 1)
381
408
  return { error: 'CAS_CONFLICT' };
382
409
  if (previous) {
@@ -396,7 +423,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
396
423
  kind: 'briefing',
397
424
  text: briefing,
398
425
  });
399
- return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId), input };
426
+ return {
427
+ ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId),
428
+ attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId),
429
+ input,
430
+ };
400
431
  }
401
432
  /**
402
433
  * @param {{
@@ -442,13 +473,14 @@ export function createTicketBook(db, root, now = () => new Date()) {
442
473
  }
443
474
  const ticket = row('SELECT * FROM work_tickets WHERE id = ?', found.ticket_id);
444
475
  const attempt = row('SELECT * FROM work_attempts WHERE id = ?', found.attempt_id);
445
- const matches = Boolean(ticket && attempt
446
- && ticket.active_attempt_id === found.attempt_id
447
- && attempt.fencing_token === found.fencing_token
448
- && ticket.briefing_revision === found.briefing_revision
449
- && ticket.status !== 'cancelled'
450
- && ticket.status !== 'failed'
451
- && ticket.status !== 'delivered');
476
+ const matches = Boolean(ticket &&
477
+ attempt &&
478
+ ticket.active_attempt_id === found.attempt_id &&
479
+ attempt.fencing_token === found.fencing_token &&
480
+ ticket.briefing_revision === found.briefing_revision &&
481
+ ticket.status !== 'cancelled' &&
482
+ ticket.status !== 'failed' &&
483
+ ticket.status !== 'delivered');
452
484
  if (!matches || reasonKind !== 'completed') {
453
485
  db.prepare(`UPDATE work_events SET apply_status = 'stale', turn_end_reason = ? WHERE event_id = ?`).run(reasonKind || '', eventId);
454
486
  return row('SELECT * FROM work_events WHERE event_id = ?', eventId);
@@ -516,9 +548,7 @@ export function createTicketBook(db, root, now = () => new Date()) {
516
548
  const beforeTokens = Number(budget.maxTokens) || ceilings.maxTokens;
517
549
  const wallAdd = Number(add.wallMs);
518
550
  const tokenAdd = Number(add.maxTokens);
519
- const wallMs = Number.isFinite(wallAdd) && wallAdd > 0
520
- ? Math.min(ceilings.wallMs, beforeWall + Math.floor(wallAdd))
521
- : beforeWall;
551
+ const wallMs = Number.isFinite(wallAdd) && wallAdd > 0 ? Math.min(ceilings.wallMs, beforeWall + Math.floor(wallAdd)) : beforeWall;
522
552
  const maxTokens = Number.isFinite(tokenAdd) && tokenAdd > 0
523
553
  ? Math.min(ceilings.maxTokens, beforeTokens + Math.floor(tokenAdd))
524
554
  : beforeTokens;
@@ -577,15 +607,20 @@ export function createTicketBook(db, root, now = () => new Date()) {
577
607
  }
578
608
  function expireQuiet() {
579
609
  const failed = [];
580
- const running = db.prepare(`
610
+ const running = db
611
+ .prepare(`
581
612
  SELECT t.id AS ticket_id, t.budget_json, t.status AS ticket_status, a.id AS attempt_id, a.status AS attempt_status,
582
613
  a.lease_until, a.current_input_id
583
614
  FROM work_tickets t
584
615
  JOIN work_attempts a ON a.id = t.active_attempt_id
585
616
  WHERE t.status IN ('enqueued','started')
586
- `).all();
617
+ `)
618
+ .all();
587
619
  for (const item of running) {
588
- if (item.ticket_status === 'started' && item.attempt_status === 'started' && item.lease_until && Date.parse(item.lease_until) <= now().getTime()) {
620
+ if (item.ticket_status === 'started' &&
621
+ item.attempt_status === 'started' &&
622
+ item.lease_until &&
623
+ Date.parse(item.lease_until) <= now().getTime()) {
589
624
  failRunning(item.ticket_id, 'lease');
590
625
  failed.push(item.ticket_id);
591
626
  continue;
@@ -596,7 +631,9 @@ export function createTicketBook(db, root, now = () => new Date()) {
596
631
  try {
597
632
  wall = JSON.parse(item.budget_json).wallMs ?? wall;
598
633
  }
599
- catch { /* host default */ }
634
+ catch {
635
+ /* host default */
636
+ }
600
637
  if (input && input.flush_status === 'accepted' && Date.parse(input.updated_at) + wall <= now().getTime()) {
601
638
  failRunning(item.ticket_id, 'enqueue-wall');
602
639
  failed.push(item.ticket_id);
@@ -618,9 +655,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
618
655
  * }} input
619
656
  */
620
657
  function insertDelivery(input) {
621
- const existing = db.prepare(`
658
+ const existing = db
659
+ .prepare(`
622
660
  SELECT * FROM user_deliveries WHERE ticket_id = ? AND result_event_id = ?
623
- `).get(input.ticketId, input.eventId);
661
+ `)
662
+ .get(input.ticketId, input.eventId);
624
663
  if (existing)
625
664
  return { row: existing, already: true };
626
665
  const id = randomUUID();
@@ -637,9 +676,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
637
676
  * @param {string} eventId
638
677
  */
639
678
  function deliveryForEvent(ticketId, eventId) {
640
- return db.prepare(`
679
+ return (db
680
+ .prepare(`
641
681
  SELECT * FROM user_deliveries WHERE ticket_id = ? AND result_event_id = ?
642
- `).get(ticketId, eventId) ?? null;
682
+ `)
683
+ .get(ticketId, eventId) ?? null);
643
684
  }
644
685
  /**
645
686
  * @param {string} ticketId
@@ -680,9 +721,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
680
721
  * @param {string} owner
681
722
  */
682
723
  function visibleTickets(owner) {
683
- const rows = db.prepare(`
724
+ const rows = db
725
+ .prepare(`
684
726
  SELECT * FROM work_tickets WHERE owner_session_id = ? ORDER BY updated_at DESC
685
- `).all(owner);
727
+ `)
728
+ .all(owner);
686
729
  const open = rows.filter(item => item.status !== 'delivered' && item.status !== 'cancelled' && item.status !== 'failed');
687
730
  const closed = rows.filter(item => !open.includes(item)).slice(0, 8);
688
731
  return [...open, ...closed];
@@ -701,26 +744,34 @@ export function createTicketBook(db, root, now = () => new Date()) {
701
744
  }
702
745
  /** Stable across unchanged rows. Lease touches are not part of it. */
703
746
  function liveStamp() {
704
- const tickets = db.prepare(`
747
+ const tickets = db
748
+ .prepare(`
705
749
  SELECT id, status, briefing_revision, IFNULL(child_session_id, '') AS child_session_id,
706
750
  IFNULL(active_attempt_id, '') AS active_attempt_id, briefing_hash, updated_at
707
751
  FROM work_tickets ORDER BY id
708
- `).all();
709
- const events = db.prepare(`
752
+ `)
753
+ .all();
754
+ const events = db
755
+ .prepare(`
710
756
  SELECT event_id, apply_status, payload_hash FROM work_events ORDER BY event_id
711
- `).all();
712
- const attempts = db.prepare(`
757
+ `)
758
+ .all();
759
+ const attempts = db
760
+ .prepare(`
713
761
  SELECT id, IFNULL(started_at, '') AS started_at FROM work_attempts ORDER BY id
714
- `).all();
762
+ `)
763
+ .all();
715
764
  return JSON.stringify([tickets, events, attempts]);
716
765
  }
717
766
  /** Delivered and cancelled tickets do not light a bot, so they stay out of signals. */
718
767
  function signalMap() {
719
- const rows = db.prepare(`
768
+ const rows = db
769
+ .prepare(`
720
770
  SELECT owner_session_id, status FROM work_tickets
721
771
  WHERE status != 'delivered' AND status != 'cancelled'
722
772
  ORDER BY updated_at DESC
723
- `).all();
773
+ `)
774
+ .all();
724
775
  /** @type {Record<string, string[]>} */
725
776
  const signals = {};
726
777
  for (const item of rows) {
@@ -763,12 +814,16 @@ export function createTicketBook(db, root, now = () => new Date()) {
763
814
  return [];
764
815
  const ids = picked.map(item => item.id);
765
816
  const marks = ids.map(() => '?').join(',');
766
- const attempts = db.prepare(`
817
+ const attempts = db
818
+ .prepare(`
767
819
  SELECT id, ticket_id, started_at FROM work_attempts WHERE ticket_id IN (${marks})
768
- `).all(...ids);
769
- const events = db.prepare(`
820
+ `)
821
+ .all(...ids);
822
+ const events = db
823
+ .prepare(`
770
824
  SELECT * FROM work_events WHERE ticket_id IN (${marks}) ORDER BY created_at
771
- `).all(...ids);
825
+ `)
826
+ .all(...ids);
772
827
  /** @type {Map<string, Array<{ id: string, started_at: string | null }>>} */
773
828
  const byAttempt = new Map();
774
829
  for (const attempt of attempts) {
@@ -813,7 +868,10 @@ export function createTicketBook(db, root, now = () => new Date()) {
813
868
  ticket: found,
814
869
  attempts: db.prepare('SELECT * FROM work_attempts WHERE ticket_id = ? ORDER BY fencing_token').all(id),
815
870
  inputs: db.prepare('SELECT * FROM work_inputs WHERE ticket_id = ? ORDER BY created_at').all(id),
816
- events: db.prepare('SELECT * FROM work_events WHERE ticket_id = ? ORDER BY created_at').all(id).map(event => ({
871
+ events: db
872
+ .prepare('SELECT * FROM work_events WHERE ticket_id = ? ORDER BY created_at')
873
+ .all(id)
874
+ .map(event => ({
817
875
  ...event,
818
876
  text: readBriefing(event.payload_hash),
819
877
  })),
@@ -825,45 +883,54 @@ export function createTicketBook(db, root, now = () => new Date()) {
825
883
  * @param {string} owner
826
884
  */
827
885
  function eventsWithoutNotice(owner) {
828
- return db.prepare(`
886
+ return db
887
+ .prepare(`
829
888
  SELECT e.* FROM work_events e
830
889
  JOIN work_tickets t ON t.id = e.ticket_id
831
890
  WHERE t.owner_session_id = ? AND e.notice_id IS NULL AND e.apply_status != 'stale'
832
891
  ORDER BY e.created_at
833
- `).all(owner);
892
+ `)
893
+ .all(owner);
834
894
  }
835
895
  /**
836
896
  * @param {string} owner
837
897
  */
838
898
  function pendingWake(owner) {
839
899
  const events = eventsWithoutNotice(owner);
840
- const cancels = db.prepare(`
900
+ const cancels = db
901
+ .prepare(`
841
902
  SELECT * FROM work_tickets t
842
903
  WHERE t.owner_session_id = ? AND t.status = 'cancelled' AND t.cancel_requested_revision IS NOT NULL
843
904
  AND NOT EXISTS (
844
905
  SELECT 1 FROM work_notices n
845
906
  WHERE n.ticket_id = t.id AND n.event_id = 'cancel:' || t.cancel_requested_revision
846
907
  )
847
- `).all(owner);
908
+ `)
909
+ .all(owner);
848
910
  return { events, cancels };
849
911
  }
850
912
  /**
851
913
  * @param {string} owner
852
914
  */
853
915
  function openNotice(owner) {
854
- const rows = db.prepare(`SELECT flush_status, observe_status FROM work_notices WHERE owner_session_id = ?`).all(owner);
855
- return rows.some(item => OPEN_NOTICE_FLUSH.has(item.flush_status) || (item.flush_status === 'accepted' && item.observe_status !== 'completed'));
916
+ const rows = db
917
+ .prepare(`SELECT flush_status, observe_status FROM work_notices WHERE owner_session_id = ?`)
918
+ .all(owner);
919
+ return rows.some(item => OPEN_NOTICE_FLUSH.has(item.flush_status) ||
920
+ (item.flush_status === 'accepted' && item.observe_status !== 'completed'));
856
921
  }
857
922
  /**
858
923
  * @param {string} owner
859
924
  */
860
925
  function openDelivery(owner) {
861
- const found = db.prepare(`
926
+ const found = db
927
+ .prepare(`
862
928
  SELECT 1 AS ok FROM deliveries
863
929
  WHERE target_session_id = ? AND kind IN ('message','timer','webhook')
864
930
  AND status IN ('intent','flushing','accepted','claimed','started')
865
931
  LIMIT 1
866
- `).get(owner);
932
+ `)
933
+ .get(owner);
867
934
  return found != null;
868
935
  }
869
936
  /**
@@ -878,20 +945,26 @@ export function createTicketBook(db, root, now = () => new Date()) {
878
945
  * @param {string} owner
879
946
  */
880
947
  function latestNoticeAt(owner) {
881
- const found = db.prepare(`
948
+ const found = db
949
+ .prepare(`
882
950
  SELECT created_at FROM work_notices WHERE owner_session_id = ? ORDER BY created_at DESC LIMIT 1
883
- `).get(owner);
951
+ `)
952
+ .get(owner);
884
953
  return found ? Date.parse(found.created_at) : null;
885
954
  }
886
955
  function flushInputs() {
887
- return db.prepare(`
956
+ return db
957
+ .prepare(`
888
958
  SELECT * FROM work_inputs WHERE flush_status IN ('intent','flushing','ambiguous') ORDER BY created_at
889
- `).all();
959
+ `)
960
+ .all();
890
961
  }
891
962
  function flushNotices() {
892
- return db.prepare(`
963
+ return db
964
+ .prepare(`
893
965
  SELECT * FROM work_notices WHERE flush_status IN ('intent','flushing','ambiguous') ORDER BY created_at
894
- `).all();
966
+ `)
967
+ .all();
895
968
  }
896
969
  /**
897
970
  * @param {string} id
@@ -974,9 +1047,11 @@ export function createTicketBook(db, root, now = () => new Date()) {
974
1047
  * @param {string} owner
975
1048
  */
976
1049
  function intentsFor(owner) {
977
- return db.prepare(`
1050
+ return db
1051
+ .prepare(`
978
1052
  SELECT * FROM user_deliveries WHERE owner_session_id = ? AND status = 'intent' ORDER BY created_at
979
- `).all(owner);
1053
+ `)
1054
+ .all(owner);
980
1055
  }
981
1056
  /**
982
1057
  * One native wake id shared by every event in the merged notice.
@@ -1007,19 +1082,28 @@ export function createTicketBook(db, root, now = () => new Date()) {
1007
1082
  return db.prepare('SELECT * FROM work_attempts WHERE ticket_id = ? ORDER BY fencing_token').all(ticketId);
1008
1083
  }
1009
1084
  function ownerIds() {
1010
- return db.prepare(`SELECT DISTINCT owner_session_id AS id FROM work_tickets`).all().map(item => item.id);
1085
+ return db
1086
+ .prepare(`SELECT DISTINCT owner_session_id AS id FROM work_tickets`)
1087
+ .all()
1088
+ .map(item => item.id);
1011
1089
  }
1012
1090
  function childIds() {
1013
- return db.prepare(`
1091
+ return db
1092
+ .prepare(`
1014
1093
  SELECT DISTINCT child_session_id AS id FROM work_attempts
1015
1094
  WHERE child_session_id IS NOT NULL
1016
- `).all().map(item => item.id);
1095
+ `)
1096
+ .all()
1097
+ .map(item => item.id);
1017
1098
  }
1018
1099
  /**
1019
1100
  * @param {string} owner
1020
1101
  */
1021
1102
  function noticeIds(owner) {
1022
- return new Set(db.prepare(`SELECT native_message_id FROM work_notices WHERE owner_session_id = ?`).all(owner).map(item => item.native_message_id));
1103
+ return new Set(db
1104
+ .prepare(`SELECT native_message_id FROM work_notices WHERE owner_session_id = ?`)
1105
+ .all(owner)
1106
+ .map(item => item.native_message_id));
1023
1107
  }
1024
1108
  }
1025
1109
  /**