@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.
@@ -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',
@@ -15,6 +15,8 @@ const LABEL = {
15
15
  cancelled: 'cancelled',
16
16
  failed: 'failed',
17
17
  };
18
+ /** Message id prefix of the inbox notice sent after a main-session budget trip. */
19
+ export const BUDGET_NOTICE_PREFIX = 'foundations-budget:';
18
20
  /**
19
21
  * Host-side ticket protocol. The model is not called from here.
20
22
  * Native inbox delivery stays in `options.push` / `options.pendingIds`.
@@ -36,11 +38,12 @@ export function createWorkRuntime(store, engine, options = {}) {
36
38
  const arms = new Map();
37
39
  /** @type {Map<string, number>} */
38
40
  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
- });
41
+ const schedule = options.schedule ??
42
+ ((fn, ms) => {
43
+ const timer = setTimeout(fn, ms);
44
+ timer.unref?.();
45
+ return () => clearTimeout(timer);
46
+ });
44
47
  const deps = {
45
48
  pid,
46
49
  inflight,
@@ -74,6 +77,7 @@ export function createWorkRuntime(store, engine, options = {}) {
74
77
  admit,
75
78
  observeSession,
76
79
  observeClaimed,
80
+ gateStep,
77
81
  isWorkerSession,
78
82
  summaries: (owner) => book.summaries(owner),
79
83
  detail: (id) => book.detail(id),
@@ -109,12 +113,16 @@ export function createWorkRuntime(store, engine, options = {}) {
109
113
  const existing = book.byIdempotency(owner, key);
110
114
  if (existing) {
111
115
  if (existing.briefing_hash !== sha256(briefing))
112
- return { error: toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for a different task.') };
116
+ return {
117
+ error: toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for a different task.'),
118
+ };
113
119
  return { replay: existing };
114
120
  }
115
121
  }
116
122
  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.') };
123
+ return {
124
+ error: toolError('BUDGET', 'Unfinished tickets already hit the host concurrency limit, so no row was created.'),
125
+ };
118
126
  }
119
127
  return {
120
128
  created: book.insertAccepted({
@@ -151,7 +159,10 @@ export function createWorkRuntime(store, engine, options = {}) {
151
159
  });
152
160
  });
153
161
  const flushed = await pushInput(book, input, deps);
154
- return publicDispatch(book.ticket(ticket.id), { flush: flushWord(flushed), nativeMessageId: input.native_message_id });
162
+ return publicDispatch(book.ticket(ticket.id), {
163
+ flush: flushWord(flushed),
164
+ nativeMessageId: input.native_message_id,
165
+ });
155
166
  }
156
167
  /**
157
168
  * @param {string} owner
@@ -188,7 +199,10 @@ export function createWorkRuntime(store, engine, options = {}) {
188
199
  if (!resident)
189
200
  return { ...publicDispatch(advanced.ticket), flush: 'pending', message: 'Only a resident host continues' };
190
201
  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 });
202
+ return publicDispatch(book.ticket(found.ticket.id), {
203
+ flush: flushWord(flushed),
204
+ nativeMessageId: advanced.input.native_message_id,
205
+ });
192
206
  }
193
207
  /**
194
208
  * @param {string} owner
@@ -207,12 +221,17 @@ export function createWorkRuntime(store, engine, options = {}) {
207
221
  return toolError(cancelled.error, cancelled.message ?? 'Cancel failed.');
208
222
  const child = cancelled.ticket.child_session_id;
209
223
  if (resident && child && options.cancel) {
210
- await options.cancel(child, { keepInbox: note !== '' });
224
+ await options.cancel(child, { keepInbox: note !== '', reason: 'ticket-cancel' });
211
225
  }
212
226
  if (resident && note !== '' && cancelled.input)
213
227
  await pushInput(book, cancelled.input, deps);
214
228
  await removeUnclaimed(owner, cancelled.ticket.id);
215
- return { ok: true, ticketId: cancelled.ticket.id, ticketStatus: cancelled.ticket.status, already: cancelled.already === true };
229
+ return {
230
+ ok: true,
231
+ ticketId: cancelled.ticket.id,
232
+ ticketStatus: cancelled.ticket.status,
233
+ already: cancelled.already === true,
234
+ };
216
235
  }
217
236
  /**
218
237
  * @param {string} owner
@@ -233,7 +252,7 @@ export function createWorkRuntime(store, engine, options = {}) {
233
252
  state.clear?.();
234
253
  }
235
254
  if (resident && child && options.cancel)
236
- await options.cancel(child, { keepInbox: false });
255
+ await options.cancel(child, { keepInbox: false, reason: 'grant-denied' });
237
256
  return { ok: true, ticketId: found.ticket.id, ticketStatus: 'failed', denied: true };
238
257
  }
239
258
  const added = await store.write('work', () => book.extendBudget(found.ticket.id, {
@@ -269,7 +288,10 @@ export function createWorkRuntime(store, engine, options = {}) {
269
288
  if (ensured.error)
270
289
  return ensured.error;
271
290
  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 });
291
+ return publicDispatch(book.ticket(retried.ticket.id), {
292
+ flush: flushWord(flushed),
293
+ nativeMessageId: retried.input.native_message_id,
294
+ });
273
295
  }
274
296
  /**
275
297
  * @param {string} owner
@@ -278,13 +300,15 @@ export function createWorkRuntime(store, engine, options = {}) {
278
300
  async function publish(owner, args) {
279
301
  if (!engine.isBot(owner))
280
302
  return toolError('FORBIDDEN', 'An ordinary session cannot publish.');
281
- if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
303
+ const resultEventId = args.resultEventId;
304
+ if (typeof resultEventId !== 'string' || resultEventId === '')
282
305
  return toolError('VALIDATION', 'resultEventId is required.');
283
- if (typeof args.text !== 'string' || args.text.trim() === '' || args.text.length > 16000)
306
+ const text = args.text;
307
+ if (typeof text !== 'string' || text.trim() === '' || text.length > 16000)
284
308
  return toolError('VALIDATION', 'text is empty or too long.');
285
309
  const turn = args.turn == null ? null : String(args.turn);
286
310
  const saved = await store.write('work', () => {
287
- const event = book.event(args.resultEventId);
311
+ const event = book.event(resultEventId);
288
312
  if (!event)
289
313
  return toolError('NOT_FOUND', 'No such result.');
290
314
  const ticket = book.ticket(event.ticket_id);
@@ -309,14 +333,14 @@ export function createWorkRuntime(store, engine, options = {}) {
309
333
  attemptId: attempt.id,
310
334
  fencingToken: attempt.fencing_token,
311
335
  briefingRevision: event.briefing_revision,
312
- text: args.text,
336
+ text,
313
337
  turn,
314
338
  });
315
339
  return {
316
340
  ok: true,
317
341
  publishId: delivery.row.publish_id,
318
342
  already: delivery.already,
319
- text: args.text,
343
+ text,
320
344
  status: delivery.row.status,
321
345
  ticketId: ticket.id,
322
346
  };
@@ -330,10 +354,11 @@ export function createWorkRuntime(store, engine, options = {}) {
330
354
  async function reject(owner, args) {
331
355
  if (!engine.isBot(owner))
332
356
  return toolError('FORBIDDEN', 'An ordinary session cannot reject a candidate.');
333
- if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
357
+ const resultEventId = args.resultEventId;
358
+ if (typeof resultEventId !== 'string' || resultEventId === '')
334
359
  return toolError('VALIDATION', 'resultEventId is required.');
335
360
  return store.write('work', () => {
336
- const event = book.event(args.resultEventId);
361
+ const event = book.event(resultEventId);
337
362
  if (!event)
338
363
  return toolError('NOT_FOUND', 'No such result.');
339
364
  const ticket = book.ticket(event.ticket_id);
@@ -342,10 +367,12 @@ export function createWorkRuntime(store, engine, options = {}) {
342
367
  if (event.kind !== 'result' || event.apply_status !== 'applied')
343
368
  return toolError('VALIDATION', 'There is no candidate to reject yet.');
344
369
  book.setReview(ticket.id, 'rejected');
345
- store.db.prepare(`
370
+ store.db
371
+ .prepare(`
346
372
  UPDATE user_deliveries SET status = 'abandoned'
347
373
  WHERE result_event_id = ? AND status = 'intent'
348
- `).run(event.event_id);
374
+ `)
375
+ .run(event.event_id);
349
376
  return { ok: true, reviewStatus: 'rejected', ticketId: ticket.id };
350
377
  });
351
378
  }
@@ -364,20 +391,20 @@ export function createWorkRuntime(store, engine, options = {}) {
364
391
  if (!attempt)
365
392
  return toolError('FORBIDDEN', 'This session is not a worker, so it cannot report.');
366
393
  const bound = turns.get(sessionId);
367
- const input = bound ? book.inputByNative(bound.messageId) : null;
394
+ if (!bound)
395
+ return toolError('NOT_FOUND', 'This round has no matching briefing.');
396
+ const input = book.inputByNative(bound.messageId);
368
397
  if (!input || input.attempt_id !== attempt.id)
369
398
  return toolError('NOT_FOUND', 'This round has no matching briefing.');
370
399
  const ticket = book.ticket(input.ticket_id);
371
400
  if (!ticket)
372
401
  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');
402
+ const current = ticket.active_attempt_id === attempt.id &&
403
+ ticket.briefing_revision === input.briefing_revision &&
404
+ ticket.status !== 'cancelled' &&
405
+ ticket.status !== 'failed' &&
406
+ ticket.status !== 'delivered';
407
+ const applyStatus = current && (kind === 'progress' || kind === 'artifact') ? 'applied' : current ? 'pending_completion' : 'stale';
381
408
  const saved = await store.write('work', () => book.insertEvent({
382
409
  ticketId: ticket.id,
383
410
  attemptId: attempt.id,
@@ -401,7 +428,9 @@ export function createWorkRuntime(store, engine, options = {}) {
401
428
  async function tick() {
402
429
  await reconcileInputs(book, deps);
403
430
  await reconcileNotices(book, deps);
404
- await store.write('work', () => { book.expireQuiet(); });
431
+ await store.write('work', () => {
432
+ book.expireQuiet();
433
+ });
405
434
  for (const owner of book.ownerIds()) {
406
435
  if (engine.isBot(owner))
407
436
  await admit(owner);
@@ -427,7 +456,8 @@ export function createWorkRuntime(store, engine, options = {}) {
427
456
  }
428
457
  const terminalTimes = [];
429
458
  for (const event of wake.events) {
430
- if ((event.kind === 'question' || event.kind === 'result' || event.kind === 'failure') && event.apply_status === 'applied') {
459
+ if ((event.kind === 'question' || event.kind === 'result' || event.kind === 'failure') &&
460
+ event.apply_status === 'applied') {
431
461
  terminalTimes.push(Date.parse(event.created_at));
432
462
  }
433
463
  }
@@ -472,7 +502,9 @@ export function createWorkRuntime(store, engine, options = {}) {
472
502
  }
473
503
  if (items.length === 0)
474
504
  return { admitted: false, reason: 'empty' };
475
- await store.write('work', () => { book.insertNotices(nativeId, owner, items); });
505
+ await store.write('work', () => {
506
+ book.insertNotices(nativeId, owner, items);
507
+ });
476
508
  const flushed = await pushNotice(book, nativeId, owner, renderNotice(items.map(item => item.line)), 0, deps);
477
509
  return { admitted: true, nativeMessageId: nativeId, flush: flushWord(flushed), ...decision };
478
510
  }
@@ -483,7 +515,8 @@ export function createWorkRuntime(store, engine, options = {}) {
483
515
  * @param {Record<string, any>} event
484
516
  */
485
517
  function noticeLine(ticket, event) {
486
- const head = `${ticket.id} ${ticket.status} (${LABEL[ticket.status] ?? ticket.status}) rev ${ticket.briefing_revision} ${event.kind}`;
518
+ const status = String(ticket.status);
519
+ const head = `${ticket.id} ${status} (${LABEL[status] ?? status}) rev ${ticket.briefing_revision} ${event.kind}`;
487
520
  const text = book.detail(ticket.id)?.events?.find(item => item.event_id === event.event_id)?.text ?? '';
488
521
  if (text.startsWith('[foundations:extension]')) {
489
522
  return [head, `eventId: ${event.event_id}`, text].join('\n');
@@ -505,8 +538,14 @@ export function createWorkRuntime(store, engine, options = {}) {
505
538
  return;
506
539
  noteBudget(sessionId, event);
507
540
  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 });
541
+ if ((event.type === 'user/message' || event.type === 'agent/inbox/claimed') &&
542
+ nativeId &&
543
+ book.inputByNative(nativeId)) {
544
+ turns.set(sessionId, {
545
+ messageId: nativeId,
546
+ turn: event.data?.turn ?? null,
547
+ seq: typeof event.seq === 'number' ? event.seq : null,
548
+ });
510
549
  }
511
550
  if (event.type === 'user/message' && engine.isBot(sessionId))
512
551
  holds.delete(sessionId);
@@ -566,7 +605,11 @@ export function createWorkRuntime(store, engine, options = {}) {
566
605
  }
567
606
  catch {
568
607
  return {
569
- error: publicDispatch(book.ticket(ticket.id), { flush: 'pending', childSessionId: null, nativeMessageId: null }),
608
+ error: publicDispatch(book.ticket(ticket.id), {
609
+ flush: 'pending',
610
+ childSessionId: null,
611
+ nativeMessageId: null,
612
+ }),
570
613
  };
571
614
  }
572
615
  }
@@ -582,11 +625,13 @@ export function createWorkRuntime(store, engine, options = {}) {
582
625
  return { error: toolError('NOT_FOUND', 'No such ticket.') };
583
626
  return { ticket };
584
627
  }
585
- const rows = store.db.prepare(`
628
+ const rows = store.db
629
+ .prepare(`
586
630
  SELECT * FROM work_tickets WHERE owner_session_id = ?
587
631
  ${statuses ? `AND status IN (${statuses.map(() => '?').join(',')})` : ''}
588
632
  ORDER BY updated_at DESC
589
- `).all(owner, ...(statuses ?? []));
633
+ `)
634
+ .all(owner, ...(statuses ?? []));
590
635
  if (rows.length !== 1)
591
636
  return { error: toolError('VALIDATION', 'Name the ticket.') };
592
637
  return { ticket: rows[0] };
@@ -595,7 +640,7 @@ export function createWorkRuntime(store, engine, options = {}) {
595
640
  * @param {unknown} value
596
641
  */
597
642
  function revisionOf(value) {
598
- return Number.isInteger(value) ? value : null;
643
+ return typeof value === 'number' && Number.isInteger(value) ? value : null;
599
644
  }
600
645
  /**
601
646
  * @param {string} owner
@@ -604,9 +649,11 @@ export function createWorkRuntime(store, engine, options = {}) {
604
649
  function correlationOf(owner, value) {
605
650
  if (typeof value !== 'string' || value === '')
606
651
  return '';
607
- const found = store.db.prepare(`
652
+ const found = store.db
653
+ .prepare(`
608
654
  SELECT 1 AS ok FROM deliveries WHERE id = ? AND (sender_session_id = ? OR target_session_id = ?)
609
- `).get(value, owner, owner);
655
+ `)
656
+ .get(value, owner, owner);
610
657
  return found ? value : '';
611
658
  }
612
659
  /**
@@ -617,9 +664,12 @@ export function createWorkRuntime(store, engine, options = {}) {
617
664
  const fresh = book.ticket(ticket.id) ?? ticket;
618
665
  const attempt = fresh.active_attempt_id ? book.attempt(fresh.active_attempt_id) : null;
619
666
  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'));
667
+ const flush = extra.flush ??
668
+ (input?.flush_status === 'accepted'
669
+ ? 'accepted'
670
+ : input?.flush_status === 'ambiguous' || input?.flush_status === 'flushing'
671
+ ? 'ambiguous'
672
+ : 'pending');
623
673
  const dispatched = flush === 'accepted' || (fresh.status !== 'accepted' && fresh.status !== 'failed' && fresh.status !== 'cancelled');
624
674
  return {
625
675
  ok: true,
@@ -735,15 +785,21 @@ export function createWorkRuntime(store, engine, options = {}) {
735
785
  for (const event of events) {
736
786
  const name = event.data?.name ?? event.data?.toolName;
737
787
  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') {
788
+ if ((event.type === 'tool/call' || event.type === 'tool/result') &&
789
+ name === 'foundations_publish' &&
790
+ typeof args?.resultEventId === 'string') {
739
791
  waiting = args.resultEventId;
740
792
  }
741
793
  if (event.type === 'user/message' && notices.has(messageIdOf(event)))
742
794
  continue;
743
795
  if (event.type === 'assistant/message' && waiting && typeof event.seq === 'number') {
744
- const ticketRows = book.ownerIds().includes(owner) ? store.db.prepare(`
796
+ const ticketRows = book.ownerIds().includes(owner)
797
+ ? store.db
798
+ .prepare(`
745
799
  SELECT * FROM user_deliveries WHERE owner_session_id = ? AND result_event_id = ? AND status = 'intent'
746
- `).get(owner, waiting) : null;
800
+ `)
801
+ .get(owner, waiting)
802
+ : null;
747
803
  if (ticketRows)
748
804
  book.bindDelivery(ticketRows.publish_id, event.seq);
749
805
  waiting = null;
@@ -766,7 +822,9 @@ export function createWorkRuntime(store, engine, options = {}) {
766
822
  * @param {string} ticketId
767
823
  */
768
824
  async function removeUnclaimed(owner, ticketId) {
769
- const rows = store.db.prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`).all(ticketId);
825
+ const rows = store.db
826
+ .prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`)
827
+ .all(ticketId);
770
828
  const seen = new Set();
771
829
  for (const row of rows) {
772
830
  if (seen.has(row.native_message_id))
@@ -790,7 +848,8 @@ export function createWorkRuntime(store, engine, options = {}) {
790
848
  return;
791
849
  if (role === 'main' && (event.type === 'tool/call' || event.type === 'tool/result')) {
792
850
  const name = event.data?.name ?? event.data?.toolName;
793
- if (name === 'foundations_dispatch' || (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
851
+ if (name === 'foundations_dispatch' ||
852
+ (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
794
853
  tightenMain(sessionId);
795
854
  }
796
855
  }
@@ -799,6 +858,13 @@ export function createWorkRuntime(store, engine, options = {}) {
799
858
  return;
800
859
  }
801
860
  const state = arms.get(sessionId);
861
+ if (role === 'main' &&
862
+ state &&
863
+ (event.type === 'user/message' || event.type === 'agent/inbox/claimed') &&
864
+ (messageIdOf(event) ?? '').startsWith(BUDGET_NOTICE_PREFIX)) {
865
+ state.budgetNotice = true;
866
+ return;
867
+ }
802
868
  if (event.type === 'assistant/message' && role === 'worker' && state) {
803
869
  const seq = typeof event.seq === 'number' ? event.seq : null;
804
870
  if (seq != null && state.lastSeq != null && seq <= state.lastSeq)
@@ -817,8 +883,72 @@ export function createWorkRuntime(store, engine, options = {}) {
817
883
  const live = state ?? arm(sessionId, event.data?.turn ?? 0, role);
818
884
  const step = Number(event.data?.step);
819
885
  live.steps = Number.isFinite(step) ? Math.max(live.steps, step) : live.steps + 1;
820
- if (role === 'main')
821
- consider(sessionId, live, false);
886
+ // The main step cap is enforced in gateStep (agent/pre-step), before the next
887
+ // step starts. Cancelling here would abort a turn whose last step already
888
+ // ended naturally and record it as aborted.
889
+ }
890
+ /**
891
+ * `agent/pre-step` gate for a bot main session. Refuses the next step once the
892
+ * turn has used its step or wall budget. A turn whose last step ended without
893
+ * a tool call never reaches this gate, so it still ends `completed`.
894
+ * Messages claimed for this step (a user steer) always enter: dropping them on
895
+ * a refusal would lose user input.
896
+ * @param {string} sessionId
897
+ * @param {{ turn?: number, step?: number, claimed?: number }} position
898
+ */
899
+ function gateStep(sessionId, position = {}) {
900
+ if (budgetRole(sessionId) !== 'main')
901
+ return { kind: 'enter' };
902
+ const state = arms.get(sessionId);
903
+ if (!state || state.role !== 'main' || state.closing)
904
+ return { kind: 'enter' };
905
+ if ((position.claimed ?? 0) > 0)
906
+ return { kind: 'enter' };
907
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
908
+ const reason = budgetTrip({
909
+ steps: state.steps,
910
+ elapsedMs: elapsed,
911
+ maxSteps: state.limits.maxSteps,
912
+ wallMs: state.limits.wallMs,
913
+ });
914
+ if (reason !== 'steps' && reason !== 'wall')
915
+ return { kind: 'enter' };
916
+ const trip = tripMain(sessionId, state, reason, elapsed, 'pre-step');
917
+ return { kind: 'reject', trip };
918
+ }
919
+ /**
920
+ * Record, log, and announce one main-session budget trip.
921
+ * @param {string} sessionId
922
+ * @param {BudgetArm} state
923
+ * @param {'steps' | 'wall'} reason
924
+ * @param {number} elapsed
925
+ * @param {'pre-step' | 'timer'} via
926
+ */
927
+ function tripMain(sessionId, state, reason, elapsed, via) {
928
+ const trip = {
929
+ reason,
930
+ cause: `main-budget:${reason}`,
931
+ turn: state.turn,
932
+ steps: state.steps,
933
+ elapsedMs: elapsed,
934
+ maxSteps: state.limits.maxSteps,
935
+ wallMs: state.limits.wallMs,
936
+ via,
937
+ notify: !state.budgetNotice,
938
+ };
939
+ if (state.tripped)
940
+ return { ...trip, notify: false };
941
+ state.tripped = true;
942
+ options.log?.('warn', `session-foundations: main budget ${trip.cause} session=${sessionId} turn=${trip.turn} steps=${trip.steps}/${trip.maxSteps} elapsedMs=${trip.elapsedMs}/${trip.wallMs} via=${via}`, { sessionId, ...trip });
943
+ if (trip.notify) {
944
+ try {
945
+ options.onMainBudget?.(sessionId, trip);
946
+ }
947
+ catch {
948
+ /* the notice is best effort; the log line above stays */
949
+ }
950
+ }
951
+ return trip;
822
952
  }
823
953
  /**
824
954
  * @param {string} sessionId
@@ -850,7 +980,8 @@ export function createWorkRuntime(store, engine, options = {}) {
850
980
  return { ok: true };
851
981
  }
852
982
  /**
853
- * A dispatch or a host tool leaves the chat budget and uses the short cap.
983
+ * A dispatch or a host tool moves the turn onto the `main*` cap. The cap can
984
+ * only tighten: with the defaults (main == chat) this changes nothing.
854
985
  * @param {string} sessionId
855
986
  */
856
987
  function tightenMain(sessionId) {
@@ -858,11 +989,15 @@ export function createWorkRuntime(store, engine, options = {}) {
858
989
  if (!state || state.role !== 'main' || state.tight || state.closing || state.tripped)
859
990
  return;
860
991
  state.tight = true;
992
+ const maxSteps = Math.min(state.limits.maxSteps, limits.mainMaxSteps);
993
+ const wallMs = Math.min(state.limits.wallMs, limits.mainWallMs);
994
+ if (maxSteps === state.limits.maxSteps && wallMs === state.limits.wallMs)
995
+ return;
861
996
  state.limits = {
862
997
  ...state.limits,
863
- maxSteps: limits.mainMaxSteps,
864
- wallMs: limits.mainWallMs,
865
- ceilingWall: limits.mainWallMs,
998
+ maxSteps,
999
+ wallMs,
1000
+ ceilingWall: wallMs,
866
1001
  };
867
1002
  state.clear?.();
868
1003
  const elapsed = Math.max(0, now().getTime() - state.startedAt);
@@ -883,7 +1018,14 @@ export function createWorkRuntime(store, engine, options = {}) {
883
1018
  const previous = arms.get(sessionId);
884
1019
  clearBudget(sessionId);
885
1020
  const caps = role === 'main'
886
- ? { maxSteps: limits.chatMaxSteps, wallMs: limits.chatWallMs, maxTokens: Number.POSITIVE_INFINITY, ceilingWall: limits.chatWallMs, ceilingTokens: Number.POSITIVE_INFINITY, extensionOpen: false }
1021
+ ? {
1022
+ maxSteps: limits.chatMaxSteps,
1023
+ wallMs: limits.chatWallMs,
1024
+ maxTokens: Number.POSITIVE_INFINITY,
1025
+ ceilingWall: limits.chatWallMs,
1026
+ ceilingTokens: Number.POSITIVE_INFINITY,
1027
+ extensionOpen: false,
1028
+ }
887
1029
  : workerCaps(sessionId);
888
1030
  const state = {
889
1031
  turn,
@@ -895,6 +1037,7 @@ export function createWorkRuntime(store, engine, options = {}) {
895
1037
  tight: false,
896
1038
  limits: caps,
897
1039
  tripped: false,
1040
+ budgetNotice: false,
898
1041
  extensionOpen: false,
899
1042
  closing: false,
900
1043
  clear: () => { },
@@ -929,7 +1072,9 @@ export function createWorkRuntime(store, engine, options = {}) {
929
1072
  maxTokens = Math.min(limits.workerMaxTokens, Math.max(1000, parsed.maxTokens));
930
1073
  extensionOpen = parsed.extension === 'open';
931
1074
  }
932
- catch { /* host ceiling */ }
1075
+ catch {
1076
+ /* host ceiling */
1077
+ }
933
1078
  }
934
1079
  return {
935
1080
  maxSteps: Number.POSITIVE_INFINITY,
@@ -949,17 +1094,14 @@ export function createWorkRuntime(store, engine, options = {}) {
949
1094
  if (state.closing)
950
1095
  return;
951
1096
  if (state.role === 'main') {
952
- const elapsed = fromTimer ? state.limits.wallMs : now().getTime() - state.startedAt;
953
- const reason = budgetTrip({
954
- steps: state.steps,
955
- elapsedMs: elapsed,
956
- maxSteps: state.limits.maxSteps,
957
- wallMs: state.limits.wallMs,
958
- });
959
- if (!reason || state.tripped)
1097
+ // Step caps are enforced by gateStep before the next step. Only the wall
1098
+ // timer stops a step that is still running; the arm is cleared on
1099
+ // turn/end, so a finished turn is never cancelled here.
1100
+ if (!fromTimer || state.tripped)
960
1101
  return;
961
- state.tripped = true;
962
- Promise.resolve(options.cancel?.(sessionId, { keepInbox: true })).catch(() => { });
1102
+ const elapsed = Math.max(state.limits.wallMs, now().getTime() - state.startedAt);
1103
+ const trip = tripMain(sessionId, state, 'wall', elapsed, 'timer');
1104
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: true, reason: trip.cause })).catch(() => { });
963
1105
  return;
964
1106
  }
965
1107
  const elapsed = Math.max(0, now().getTime() - state.startedAt);
@@ -1053,7 +1195,7 @@ export function createWorkRuntime(store, engine, options = {}) {
1053
1195
  return;
1054
1196
  state.closing = true;
1055
1197
  state.clear?.();
1056
- Promise.resolve(options.cancel?.(sessionId, { keepInbox: false })).catch(() => { });
1198
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: false, reason: `worker-budget:${reason}` })).catch(() => { });
1057
1199
  const attempt = book.attemptForChild(sessionId);
1058
1200
  if (attempt)
1059
1201
  book.failRunning(attempt.ticket_id, reason);
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.3",
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 && node --test test/budget-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"