@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 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.
@@ -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);
@@ -3,7 +3,7 @@ import { sha256 } from "./fs-safe.js";
3
3
  import { toolError } from "./errors.js";
4
4
  import { createTicketBook } from "./work-tickets.js";
5
5
  import { decideAdmission, budgetTrip, estimateWorkerBudget, DEFAULT_WORK_BUDGET } from "./work-admit.js";
6
- import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderNotice } from "./work-ledger.js";
6
+ import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderNotice, } from "./work-ledger.js";
7
7
  const KINDS = new Set(['progress', 'question', 'artifact', 'result', 'failure']);
8
8
  const LABEL = {
9
9
  accepted: 'accepted',
@@ -36,11 +36,12 @@ export function createWorkRuntime(store, engine, options = {}) {
36
36
  const arms = new Map();
37
37
  /** @type {Map<string, number>} */
38
38
  const holds = new Map();
39
- const schedule = options.schedule ?? ((fn, ms) => {
40
- const timer = setTimeout(fn, ms);
41
- timer.unref?.();
42
- return () => clearTimeout(timer);
43
- });
39
+ const schedule = options.schedule ??
40
+ ((fn, ms) => {
41
+ const timer = setTimeout(fn, ms);
42
+ timer.unref?.();
43
+ return () => clearTimeout(timer);
44
+ });
44
45
  const deps = {
45
46
  pid,
46
47
  inflight,
@@ -109,12 +110,16 @@ export function createWorkRuntime(store, engine, options = {}) {
109
110
  const existing = book.byIdempotency(owner, key);
110
111
  if (existing) {
111
112
  if (existing.briefing_hash !== sha256(briefing))
112
- return { error: toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for a different task.') };
113
+ return {
114
+ error: toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for a different task.'),
115
+ };
113
116
  return { replay: existing };
114
117
  }
115
118
  }
116
119
  if (book.countActive(owner) >= limits.perBot || book.countGlobal() >= limits.global) {
117
- return { error: toolError('BUDGET', 'Unfinished tickets already hit the host concurrency limit, so no row was created.') };
120
+ return {
121
+ error: toolError('BUDGET', 'Unfinished tickets already hit the host concurrency limit, so no row was created.'),
122
+ };
118
123
  }
119
124
  return {
120
125
  created: book.insertAccepted({
@@ -151,7 +156,10 @@ export function createWorkRuntime(store, engine, options = {}) {
151
156
  });
152
157
  });
153
158
  const flushed = await pushInput(book, input, deps);
154
- return publicDispatch(book.ticket(ticket.id), { flush: flushWord(flushed), nativeMessageId: input.native_message_id });
159
+ return publicDispatch(book.ticket(ticket.id), {
160
+ flush: flushWord(flushed),
161
+ nativeMessageId: input.native_message_id,
162
+ });
155
163
  }
156
164
  /**
157
165
  * @param {string} owner
@@ -188,7 +196,10 @@ export function createWorkRuntime(store, engine, options = {}) {
188
196
  if (!resident)
189
197
  return { ...publicDispatch(advanced.ticket), flush: 'pending', message: 'Only a resident host continues' };
190
198
  const flushed = await pushInput(book, advanced.input, deps);
191
- return publicDispatch(book.ticket(found.ticket.id), { flush: flushWord(flushed), nativeMessageId: advanced.input.native_message_id });
199
+ return publicDispatch(book.ticket(found.ticket.id), {
200
+ flush: flushWord(flushed),
201
+ nativeMessageId: advanced.input.native_message_id,
202
+ });
192
203
  }
193
204
  /**
194
205
  * @param {string} owner
@@ -212,7 +223,12 @@ export function createWorkRuntime(store, engine, options = {}) {
212
223
  if (resident && note !== '' && cancelled.input)
213
224
  await pushInput(book, cancelled.input, deps);
214
225
  await removeUnclaimed(owner, cancelled.ticket.id);
215
- return { ok: true, ticketId: cancelled.ticket.id, ticketStatus: cancelled.ticket.status, already: cancelled.already === true };
226
+ return {
227
+ ok: true,
228
+ ticketId: cancelled.ticket.id,
229
+ ticketStatus: cancelled.ticket.status,
230
+ already: cancelled.already === true,
231
+ };
216
232
  }
217
233
  /**
218
234
  * @param {string} owner
@@ -269,7 +285,10 @@ export function createWorkRuntime(store, engine, options = {}) {
269
285
  if (ensured.error)
270
286
  return ensured.error;
271
287
  const flushed = await pushInput(book, retried.input, deps);
272
- return publicDispatch(book.ticket(retried.ticket.id), { flush: flushWord(flushed), nativeMessageId: retried.input.native_message_id });
288
+ return publicDispatch(book.ticket(retried.ticket.id), {
289
+ flush: flushWord(flushed),
290
+ nativeMessageId: retried.input.native_message_id,
291
+ });
273
292
  }
274
293
  /**
275
294
  * @param {string} owner
@@ -278,13 +297,15 @@ export function createWorkRuntime(store, engine, options = {}) {
278
297
  async function publish(owner, args) {
279
298
  if (!engine.isBot(owner))
280
299
  return toolError('FORBIDDEN', 'An ordinary session cannot publish.');
281
- if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
300
+ const resultEventId = args.resultEventId;
301
+ if (typeof resultEventId !== 'string' || resultEventId === '')
282
302
  return toolError('VALIDATION', 'resultEventId is required.');
283
- if (typeof args.text !== 'string' || args.text.trim() === '' || args.text.length > 16000)
303
+ const text = args.text;
304
+ if (typeof text !== 'string' || text.trim() === '' || text.length > 16000)
284
305
  return toolError('VALIDATION', 'text is empty or too long.');
285
306
  const turn = args.turn == null ? null : String(args.turn);
286
307
  const saved = await store.write('work', () => {
287
- const event = book.event(args.resultEventId);
308
+ const event = book.event(resultEventId);
288
309
  if (!event)
289
310
  return toolError('NOT_FOUND', 'No such result.');
290
311
  const ticket = book.ticket(event.ticket_id);
@@ -309,14 +330,14 @@ export function createWorkRuntime(store, engine, options = {}) {
309
330
  attemptId: attempt.id,
310
331
  fencingToken: attempt.fencing_token,
311
332
  briefingRevision: event.briefing_revision,
312
- text: args.text,
333
+ text,
313
334
  turn,
314
335
  });
315
336
  return {
316
337
  ok: true,
317
338
  publishId: delivery.row.publish_id,
318
339
  already: delivery.already,
319
- text: args.text,
340
+ text,
320
341
  status: delivery.row.status,
321
342
  ticketId: ticket.id,
322
343
  };
@@ -330,10 +351,11 @@ export function createWorkRuntime(store, engine, options = {}) {
330
351
  async function reject(owner, args) {
331
352
  if (!engine.isBot(owner))
332
353
  return toolError('FORBIDDEN', 'An ordinary session cannot reject a candidate.');
333
- if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
354
+ const resultEventId = args.resultEventId;
355
+ if (typeof resultEventId !== 'string' || resultEventId === '')
334
356
  return toolError('VALIDATION', 'resultEventId is required.');
335
357
  return store.write('work', () => {
336
- const event = book.event(args.resultEventId);
358
+ const event = book.event(resultEventId);
337
359
  if (!event)
338
360
  return toolError('NOT_FOUND', 'No such result.');
339
361
  const ticket = book.ticket(event.ticket_id);
@@ -342,10 +364,12 @@ export function createWorkRuntime(store, engine, options = {}) {
342
364
  if (event.kind !== 'result' || event.apply_status !== 'applied')
343
365
  return toolError('VALIDATION', 'There is no candidate to reject yet.');
344
366
  book.setReview(ticket.id, 'rejected');
345
- store.db.prepare(`
367
+ store.db
368
+ .prepare(`
346
369
  UPDATE user_deliveries SET status = 'abandoned'
347
370
  WHERE result_event_id = ? AND status = 'intent'
348
- `).run(event.event_id);
371
+ `)
372
+ .run(event.event_id);
349
373
  return { ok: true, reviewStatus: 'rejected', ticketId: ticket.id };
350
374
  });
351
375
  }
@@ -364,20 +388,20 @@ export function createWorkRuntime(store, engine, options = {}) {
364
388
  if (!attempt)
365
389
  return toolError('FORBIDDEN', 'This session is not a worker, so it cannot report.');
366
390
  const bound = turns.get(sessionId);
367
- const input = bound ? book.inputByNative(bound.messageId) : null;
391
+ if (!bound)
392
+ return toolError('NOT_FOUND', 'This round has no matching briefing.');
393
+ const input = book.inputByNative(bound.messageId);
368
394
  if (!input || input.attempt_id !== attempt.id)
369
395
  return toolError('NOT_FOUND', 'This round has no matching briefing.');
370
396
  const ticket = book.ticket(input.ticket_id);
371
397
  if (!ticket)
372
398
  return toolError('NOT_FOUND', 'The ticket does not exist.');
373
- const current = ticket.active_attempt_id === attempt.id
374
- && ticket.briefing_revision === input.briefing_revision
375
- && ticket.status !== 'cancelled'
376
- && ticket.status !== 'failed'
377
- && ticket.status !== 'delivered';
378
- const applyStatus = current && (kind === 'progress' || kind === 'artifact')
379
- ? 'applied'
380
- : (current ? 'pending_completion' : 'stale');
399
+ const current = ticket.active_attempt_id === attempt.id &&
400
+ ticket.briefing_revision === input.briefing_revision &&
401
+ ticket.status !== 'cancelled' &&
402
+ ticket.status !== 'failed' &&
403
+ ticket.status !== 'delivered';
404
+ const applyStatus = current && (kind === 'progress' || kind === 'artifact') ? 'applied' : current ? 'pending_completion' : 'stale';
381
405
  const saved = await store.write('work', () => book.insertEvent({
382
406
  ticketId: ticket.id,
383
407
  attemptId: attempt.id,
@@ -401,7 +425,9 @@ export function createWorkRuntime(store, engine, options = {}) {
401
425
  async function tick() {
402
426
  await reconcileInputs(book, deps);
403
427
  await reconcileNotices(book, deps);
404
- await store.write('work', () => { book.expireQuiet(); });
428
+ await store.write('work', () => {
429
+ book.expireQuiet();
430
+ });
405
431
  for (const owner of book.ownerIds()) {
406
432
  if (engine.isBot(owner))
407
433
  await admit(owner);
@@ -427,7 +453,8 @@ export function createWorkRuntime(store, engine, options = {}) {
427
453
  }
428
454
  const terminalTimes = [];
429
455
  for (const event of wake.events) {
430
- if ((event.kind === 'question' || event.kind === 'result' || event.kind === 'failure') && event.apply_status === 'applied') {
456
+ if ((event.kind === 'question' || event.kind === 'result' || event.kind === 'failure') &&
457
+ event.apply_status === 'applied') {
431
458
  terminalTimes.push(Date.parse(event.created_at));
432
459
  }
433
460
  }
@@ -472,7 +499,9 @@ export function createWorkRuntime(store, engine, options = {}) {
472
499
  }
473
500
  if (items.length === 0)
474
501
  return { admitted: false, reason: 'empty' };
475
- await store.write('work', () => { book.insertNotices(nativeId, owner, items); });
502
+ await store.write('work', () => {
503
+ book.insertNotices(nativeId, owner, items);
504
+ });
476
505
  const flushed = await pushNotice(book, nativeId, owner, renderNotice(items.map(item => item.line)), 0, deps);
477
506
  return { admitted: true, nativeMessageId: nativeId, flush: flushWord(flushed), ...decision };
478
507
  }
@@ -483,7 +512,8 @@ export function createWorkRuntime(store, engine, options = {}) {
483
512
  * @param {Record<string, any>} event
484
513
  */
485
514
  function noticeLine(ticket, event) {
486
- const head = `${ticket.id} ${ticket.status} (${LABEL[ticket.status] ?? ticket.status}) rev ${ticket.briefing_revision} ${event.kind}`;
515
+ const status = String(ticket.status);
516
+ const head = `${ticket.id} ${status} (${LABEL[status] ?? status}) rev ${ticket.briefing_revision} ${event.kind}`;
487
517
  const text = book.detail(ticket.id)?.events?.find(item => item.event_id === event.event_id)?.text ?? '';
488
518
  if (text.startsWith('[foundations:extension]')) {
489
519
  return [head, `eventId: ${event.event_id}`, text].join('\n');
@@ -505,8 +535,14 @@ export function createWorkRuntime(store, engine, options = {}) {
505
535
  return;
506
536
  noteBudget(sessionId, event);
507
537
  const nativeId = messageIdOf(event);
508
- if ((event.type === 'user/message' || event.type === 'agent/inbox/claimed') && nativeId && book.inputByNative(nativeId)) {
509
- turns.set(sessionId, { messageId: nativeId, turn: event.data?.turn ?? null, seq: typeof event.seq === 'number' ? event.seq : null });
538
+ if ((event.type === 'user/message' || event.type === 'agent/inbox/claimed') &&
539
+ nativeId &&
540
+ book.inputByNative(nativeId)) {
541
+ turns.set(sessionId, {
542
+ messageId: nativeId,
543
+ turn: event.data?.turn ?? null,
544
+ seq: typeof event.seq === 'number' ? event.seq : null,
545
+ });
510
546
  }
511
547
  if (event.type === 'user/message' && engine.isBot(sessionId))
512
548
  holds.delete(sessionId);
@@ -566,7 +602,11 @@ export function createWorkRuntime(store, engine, options = {}) {
566
602
  }
567
603
  catch {
568
604
  return {
569
- error: publicDispatch(book.ticket(ticket.id), { flush: 'pending', childSessionId: null, nativeMessageId: null }),
605
+ error: publicDispatch(book.ticket(ticket.id), {
606
+ flush: 'pending',
607
+ childSessionId: null,
608
+ nativeMessageId: null,
609
+ }),
570
610
  };
571
611
  }
572
612
  }
@@ -582,11 +622,13 @@ export function createWorkRuntime(store, engine, options = {}) {
582
622
  return { error: toolError('NOT_FOUND', 'No such ticket.') };
583
623
  return { ticket };
584
624
  }
585
- const rows = store.db.prepare(`
625
+ const rows = store.db
626
+ .prepare(`
586
627
  SELECT * FROM work_tickets WHERE owner_session_id = ?
587
628
  ${statuses ? `AND status IN (${statuses.map(() => '?').join(',')})` : ''}
588
629
  ORDER BY updated_at DESC
589
- `).all(owner, ...(statuses ?? []));
630
+ `)
631
+ .all(owner, ...(statuses ?? []));
590
632
  if (rows.length !== 1)
591
633
  return { error: toolError('VALIDATION', 'Name the ticket.') };
592
634
  return { ticket: rows[0] };
@@ -595,7 +637,7 @@ export function createWorkRuntime(store, engine, options = {}) {
595
637
  * @param {unknown} value
596
638
  */
597
639
  function revisionOf(value) {
598
- return Number.isInteger(value) ? value : null;
640
+ return typeof value === 'number' && Number.isInteger(value) ? value : null;
599
641
  }
600
642
  /**
601
643
  * @param {string} owner
@@ -604,9 +646,11 @@ export function createWorkRuntime(store, engine, options = {}) {
604
646
  function correlationOf(owner, value) {
605
647
  if (typeof value !== 'string' || value === '')
606
648
  return '';
607
- const found = store.db.prepare(`
649
+ const found = store.db
650
+ .prepare(`
608
651
  SELECT 1 AS ok FROM deliveries WHERE id = ? AND (sender_session_id = ? OR target_session_id = ?)
609
- `).get(value, owner, owner);
652
+ `)
653
+ .get(value, owner, owner);
610
654
  return found ? value : '';
611
655
  }
612
656
  /**
@@ -617,9 +661,12 @@ export function createWorkRuntime(store, engine, options = {}) {
617
661
  const fresh = book.ticket(ticket.id) ?? ticket;
618
662
  const attempt = fresh.active_attempt_id ? book.attempt(fresh.active_attempt_id) : null;
619
663
  const input = attempt ? book.currentInput(attempt) : null;
620
- const flush = extra.flush ?? (input?.flush_status === 'accepted'
621
- ? 'accepted'
622
- : (input?.flush_status === 'ambiguous' || input?.flush_status === 'flushing' ? 'ambiguous' : 'pending'));
664
+ const flush = extra.flush ??
665
+ (input?.flush_status === 'accepted'
666
+ ? 'accepted'
667
+ : input?.flush_status === 'ambiguous' || input?.flush_status === 'flushing'
668
+ ? 'ambiguous'
669
+ : 'pending');
623
670
  const dispatched = flush === 'accepted' || (fresh.status !== 'accepted' && fresh.status !== 'failed' && fresh.status !== 'cancelled');
624
671
  return {
625
672
  ok: true,
@@ -735,15 +782,21 @@ export function createWorkRuntime(store, engine, options = {}) {
735
782
  for (const event of events) {
736
783
  const name = event.data?.name ?? event.data?.toolName;
737
784
  const args = parseArgs(event.data?.arguments ?? event.data?.args ?? event.data?.result);
738
- if ((event.type === 'tool/call' || event.type === 'tool/result') && name === 'foundations_publish' && typeof args?.resultEventId === 'string') {
785
+ if ((event.type === 'tool/call' || event.type === 'tool/result') &&
786
+ name === 'foundations_publish' &&
787
+ typeof args?.resultEventId === 'string') {
739
788
  waiting = args.resultEventId;
740
789
  }
741
790
  if (event.type === 'user/message' && notices.has(messageIdOf(event)))
742
791
  continue;
743
792
  if (event.type === 'assistant/message' && waiting && typeof event.seq === 'number') {
744
- const ticketRows = book.ownerIds().includes(owner) ? store.db.prepare(`
793
+ const ticketRows = book.ownerIds().includes(owner)
794
+ ? store.db
795
+ .prepare(`
745
796
  SELECT * FROM user_deliveries WHERE owner_session_id = ? AND result_event_id = ? AND status = 'intent'
746
- `).get(owner, waiting) : null;
797
+ `)
798
+ .get(owner, waiting)
799
+ : null;
747
800
  if (ticketRows)
748
801
  book.bindDelivery(ticketRows.publish_id, event.seq);
749
802
  waiting = null;
@@ -766,7 +819,9 @@ export function createWorkRuntime(store, engine, options = {}) {
766
819
  * @param {string} ticketId
767
820
  */
768
821
  async function removeUnclaimed(owner, ticketId) {
769
- const rows = store.db.prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`).all(ticketId);
822
+ const rows = store.db
823
+ .prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`)
824
+ .all(ticketId);
770
825
  const seen = new Set();
771
826
  for (const row of rows) {
772
827
  if (seen.has(row.native_message_id))
@@ -790,7 +845,8 @@ export function createWorkRuntime(store, engine, options = {}) {
790
845
  return;
791
846
  if (role === 'main' && (event.type === 'tool/call' || event.type === 'tool/result')) {
792
847
  const name = event.data?.name ?? event.data?.toolName;
793
- if (name === 'foundations_dispatch' || (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
848
+ if (name === 'foundations_dispatch' ||
849
+ (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
794
850
  tightenMain(sessionId);
795
851
  }
796
852
  }
@@ -883,7 +939,14 @@ export function createWorkRuntime(store, engine, options = {}) {
883
939
  const previous = arms.get(sessionId);
884
940
  clearBudget(sessionId);
885
941
  const caps = role === 'main'
886
- ? { maxSteps: limits.chatMaxSteps, wallMs: limits.chatWallMs, maxTokens: Number.POSITIVE_INFINITY, ceilingWall: limits.chatWallMs, ceilingTokens: Number.POSITIVE_INFINITY, extensionOpen: false }
942
+ ? {
943
+ maxSteps: limits.chatMaxSteps,
944
+ wallMs: limits.chatWallMs,
945
+ maxTokens: Number.POSITIVE_INFINITY,
946
+ ceilingWall: limits.chatWallMs,
947
+ ceilingTokens: Number.POSITIVE_INFINITY,
948
+ extensionOpen: false,
949
+ }
887
950
  : workerCaps(sessionId);
888
951
  const state = {
889
952
  turn,
@@ -929,7 +992,9 @@ export function createWorkRuntime(store, engine, options = {}) {
929
992
  maxTokens = Math.min(limits.workerMaxTokens, Math.max(1000, parsed.maxTokens));
930
993
  extensionOpen = parsed.extension === 'open';
931
994
  }
932
- catch { /* host ceiling */ }
995
+ catch {
996
+ /* host ceiling */
997
+ }
933
998
  }
934
999
  return {
935
1000
  maxSteps: Number.POSITIVE_INFINITY,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thready-web/dsh-bot-plugin",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.2",
4
4
  "type": "module",
5
5
  "description": "DSH bot plugin: session persona, memory, work, hash routing, and the workbench. Pinned to @deepseek-ai/dsh 0.2.2-rc.1.",
6
6
  "license": "MIT",
@@ -30,14 +30,18 @@
30
30
  },
31
31
  "scripts": {
32
32
  "build": "node build.mjs",
33
- "type-check": "tsc -p tsconfig.typecheck.json --noEmit && node type-check-tests.mjs",
34
- "test": "node --test test/store.test.ts test/skills.test.ts test/context.test.ts test/tools.test.ts test/triggers.test.ts test/provision.test.ts test/inbox-read.test.ts test/work.test.ts test/work-eval.test.ts test/router.test.ts test/desk.test.ts test/session-files.test.ts test/session-previews.test.ts test/cdc.test.ts test/live-diff.test.ts test/live-snapshot.test.ts ui/src/live.test.ts ui/src/follow.test.ts ui/src/work.test.ts ui/src/session-snapshot.test.ts",
35
- "test:host": "npm run build && node --test test/host-integration.test.ts && node --test test/triggers-host.test.ts"
33
+ "type-check": "tsc -p tsconfig.typecheck.json --noEmit && tsc -p tsconfig.client.json --noEmit",
34
+ "test": "node scripts/unit-tests.mjs",
35
+ "test:host": "npm run build && node --test test/host-integration.test.ts && node --test test/triggers-host.test.ts",
36
+ "format": "biome format --write src test ui/src client.js scripts",
37
+ "format:check": "biome check src test ui/src client.js scripts"
36
38
  },
37
39
  "engines": {
38
40
  "node": ">=22.18.0"
39
41
  },
40
42
  "devDependencies": {
43
+ "@biomejs/biome": "^2.6.6",
44
+ "@deepseek-ai/cordis": "~4.1.0",
41
45
  "@types/node": "^24.10.0",
42
46
  "esbuild": "^0.25.0",
43
47
  "typescript": "^5.9.3"