@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.3

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.
@@ -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
  /**
@@ -12,7 +12,7 @@ const OUTPUT = {
12
12
  /**
13
13
  * Bot tools plus the worker report. Execute checks the host session.
14
14
  * Model arguments never supply owner, attempt, or fence.
15
- * @param {ReturnType<import('./work-worker.js').createWorkRuntime>} work
15
+ * @param {ReturnType<typeof import('./work-worker.js').createWorkRuntime>} work
16
16
  * @param {import('./engine.js').Engine} engine
17
17
  */
18
18
  export function workToolDefinitions(work, engine) {
@@ -113,7 +113,7 @@ export function workToolDefinitions(work, engine) {
113
113
  ownerSessionId: { type: 'string', description: 'Ignored.' },
114
114
  },
115
115
  required: ['kind', 'text'],
116
- }, (args, hostId) => {
116
+ }, async (args, hostId) => {
117
117
  if (engine.isBot(hostId))
118
118
  return toolError('FORBIDDEN', 'The main session cannot report in place of the worker.');
119
119
  return work.report(hostId, args);