@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.
- package/README.md +31 -0
- package/client.js +646 -621
- package/dist/cli.js +32 -12
- package/dist/context.js +21 -9
- package/dist/cron.js +1 -1
- package/dist/desk.js +75 -26
- package/dist/engine.js +160 -77
- package/dist/fs-safe.js +1 -1
- package/dist/host.js +1 -0
- package/dist/http-plugin.js +6 -2
- package/dist/http.js +61 -23
- package/dist/inbox.js +10 -7
- package/dist/index.js +115 -28
- package/dist/live-diff.js +3 -1
- package/dist/live-snapshot.js +3 -1
- package/dist/provision.js +2 -0
- package/dist/runtime-registry.js +4 -4
- package/dist/session-files.js +1 -1
- package/dist/session-previews.js +5 -1
- package/dist/store.js +20 -5
- package/dist/tools.js +62 -26
- package/dist/triggers.js +83 -39
- package/dist/work-admit.js +124 -8
- package/dist/work-child.js +9 -6
- package/dist/work-http.js +4 -2
- package/dist/work-ledger.js +16 -14
- package/dist/work-mock-host.js +8 -6
- package/dist/work-mock.js +20 -19
- package/dist/work-tickets.js +156 -72
- package/dist/work-tools.js +2 -2
- package/dist/work-worker.js +213 -71
- package/package.json +8 -4
- package/public/assets/{index-ByU9a3Lh.js → index-D0tTt7E4.js} +37 -37
- package/public/assets/{index-Be82iGwe.css → index-PyqSrdBb.css} +1 -1
- package/public/index.html +2 -2
package/dist/work-worker.js
CHANGED
|
@@ -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 ??
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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 {
|
|
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 {
|
|
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), {
|
|
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), {
|
|
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 {
|
|
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), {
|
|
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
|
-
|
|
303
|
+
const resultEventId = args.resultEventId;
|
|
304
|
+
if (typeof resultEventId !== 'string' || resultEventId === '')
|
|
282
305
|
return toolError('VALIDATION', 'resultEventId is required.');
|
|
283
|
-
|
|
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(
|
|
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
|
|
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
|
|
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
|
-
|
|
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(
|
|
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
|
|
370
|
+
store.db
|
|
371
|
+
.prepare(`
|
|
346
372
|
UPDATE user_deliveries SET status = 'abandoned'
|
|
347
373
|
WHERE result_event_id = ? AND status = 'intent'
|
|
348
|
-
`)
|
|
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
|
-
|
|
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
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
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', () => {
|
|
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') &&
|
|
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', () => {
|
|
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
|
|
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') &&
|
|
509
|
-
|
|
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), {
|
|
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
|
|
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
|
-
`)
|
|
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
|
|
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
|
-
`)
|
|
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 ??
|
|
621
|
-
|
|
622
|
-
|
|
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') &&
|
|
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)
|
|
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
|
-
`)
|
|
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
|
|
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' ||
|
|
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
|
-
|
|
821
|
-
|
|
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
|
|
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
|
|
864
|
-
wallMs
|
|
865
|
-
ceilingWall:
|
|
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
|
-
? {
|
|
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 {
|
|
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
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
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.
|
|
962
|
-
|
|
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.
|
|
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 &&
|
|
34
|
-
"test": "node
|
|
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"
|