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

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.
@@ -0,0 +1,1108 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { sha256 } from "./fs-safe.js";
3
+ import { toolError } from "./errors.js";
4
+ import { createTicketBook } from "./work-tickets.js";
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";
7
+ const KINDS = new Set(['progress', 'question', 'artifact', 'result', 'failure']);
8
+ const LABEL = {
9
+ accepted: 'accepted',
10
+ enqueued: 'enqueued',
11
+ started: 'started',
12
+ needs_user: 'needs user',
13
+ ready: 'candidate',
14
+ delivered: 'delivered',
15
+ cancelled: 'cancelled',
16
+ failed: 'failed',
17
+ };
18
+ /**
19
+ * Host-side ticket protocol. The model is not called from here.
20
+ * Native inbox delivery stays in `options.push` / `options.pendingIds`.
21
+ * @param {import('./store.js').Store} store
22
+ * @param {import('./engine.js').Engine} engine
23
+ */
24
+ export function createWorkRuntime(store, engine, options = {}) {
25
+ const now = options.now ?? (() => new Date());
26
+ const limits = { ...DEFAULT_WORK_BUDGET, ...options.budget };
27
+ const pid = options.pid ?? process.pid;
28
+ const resident = options.resident !== false;
29
+ const book = createTicketBook(store.db, store.root, now);
30
+ const inflight = new Set();
31
+ /** @type {Map<string, { messageId: string, turn: number | null, seq: number | null }>} */
32
+ const turns = new Map();
33
+ /** @type {Map<string, string>} */
34
+ const wakeTurns = new Map();
35
+ /** @type {Map<string, { turn: number, startedAt: number, steps: number, tokens: number, lastSeq: number | null, role: 'main' | 'worker', tight: boolean, limits: { maxSteps: number, wallMs: number, maxTokens: number, ceilingWall: number, ceilingTokens: number }, tripped: boolean, extensionOpen: boolean, closing: boolean, clear: () => void }>} */
36
+ const arms = new Map();
37
+ /** @type {Map<string, number>} */
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
+ });
44
+ const deps = {
45
+ pid,
46
+ inflight,
47
+ logHas: async (sessionId, messageId) => {
48
+ if (!options.logHas)
49
+ return false;
50
+ return await options.logHas(sessionId, messageId);
51
+ },
52
+ push: async (sessionId, messageId, text) => {
53
+ if (!options.push)
54
+ return { ok: false, ambiguous: true, error: 'no-push' };
55
+ return options.push(sessionId, messageId, text);
56
+ },
57
+ noticeText: (nativeId) => noticeText(nativeId),
58
+ };
59
+ return {
60
+ limits,
61
+ book,
62
+ dispatch,
63
+ supply,
64
+ redirect,
65
+ cancelTicket,
66
+ retry,
67
+ grant,
68
+ publish,
69
+ reject,
70
+ report,
71
+ holdNotices,
72
+ releaseHold,
73
+ tick,
74
+ admit,
75
+ observeSession,
76
+ observeClaimed,
77
+ isWorkerSession,
78
+ summaries: (owner) => book.summaries(owner),
79
+ detail: (id) => book.detail(id),
80
+ liveStamp: () => book.liveStamp(),
81
+ liveBoard: (sessionId) => book.liveBoard(sessionId),
82
+ liveBoardAll: () => book.liveBoardAll(),
83
+ project,
84
+ };
85
+ /**
86
+ * @param {string} sessionId
87
+ */
88
+ function isWorkerSession(sessionId) {
89
+ return book.attemptForChild(sessionId) != null;
90
+ }
91
+ /**
92
+ * @param {string} owner
93
+ * @param {Record<string, unknown>} args
94
+ */
95
+ async function dispatch(owner, args) {
96
+ if (!engine.isBot(owner))
97
+ return toolError('FORBIDDEN', 'An ordinary session stays on one loop and cannot dispatch work.');
98
+ if (typeof args.parentTicketId === 'string' && args.parentTicketId !== '') {
99
+ return toolError('VALIDATION', 'The MVP does not accept child tickets.');
100
+ }
101
+ const briefing = typeof args.briefing === 'string' ? args.briefing.trim() : '';
102
+ if (briefing === '' || briefing.length > 16000)
103
+ return toolError('VALIDATION', 'briefing is empty or too long.');
104
+ const key = typeof args.idempotencyKey === 'string' && args.idempotencyKey.trim() !== '' ? args.idempotencyKey.trim() : null;
105
+ const suggestion = args.budget && typeof args.budget === 'object' ? args.budget : null;
106
+ const budget = estimateWorkerBudget(briefing, suggestion, limits);
107
+ const prepared = await store.write('work', () => {
108
+ if (key) {
109
+ const existing = book.byIdempotency(owner, key);
110
+ if (existing) {
111
+ 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 { replay: existing };
114
+ }
115
+ }
116
+ 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.') };
118
+ }
119
+ return {
120
+ created: book.insertAccepted({
121
+ owner,
122
+ briefing,
123
+ idempotencyKey: key,
124
+ correlationId: correlationOf(owner, args.correlationId),
125
+ budget,
126
+ }),
127
+ };
128
+ });
129
+ if (prepared.error)
130
+ return prepared.error;
131
+ if (prepared.replay)
132
+ return publicDispatch(prepared.replay, { replayed: true });
133
+ const ticket = prepared.created.ticket;
134
+ if (!resident) {
135
+ return { ...publicDispatch(ticket), flush: 'pending', resident: false, message: 'Only a resident host continues' };
136
+ }
137
+ const created = await ensureChild(ticket);
138
+ if (created.error)
139
+ return created.error;
140
+ const input = await store.write('work', () => {
141
+ const current = book.ticket(ticket.id);
142
+ const attempt = book.attempt(current.active_attempt_id);
143
+ if (attempt?.current_input_id)
144
+ return book.input(attempt.current_input_id);
145
+ return book.insertInput({
146
+ ticketId: current.id,
147
+ attemptId: attempt.id,
148
+ revision: current.briefing_revision,
149
+ kind: 'briefing',
150
+ text: briefing,
151
+ });
152
+ });
153
+ const flushed = await pushInput(book, input, deps);
154
+ return publicDispatch(book.ticket(ticket.id), { flush: flushWord(flushed), nativeMessageId: input.native_message_id });
155
+ }
156
+ /**
157
+ * @param {string} owner
158
+ * @param {Record<string, unknown>} args
159
+ */
160
+ async function supply(owner, args) {
161
+ return retarget(owner, args, 'supply');
162
+ }
163
+ /**
164
+ * @param {string} owner
165
+ * @param {Record<string, unknown>} args
166
+ */
167
+ async function redirect(owner, args) {
168
+ return retarget(owner, args, 'redirect');
169
+ }
170
+ /**
171
+ * @param {string} owner
172
+ * @param {Record<string, unknown>} args
173
+ * @param {'supply' | 'redirect'} kind
174
+ */
175
+ async function retarget(owner, args, kind) {
176
+ if (!engine.isBot(owner))
177
+ return toolError('FORBIDDEN', 'An ordinary session cannot change a ticket.');
178
+ const text = typeof args.text === 'string' ? args.text.trim() : '';
179
+ if (text === '' || text.length > 16000)
180
+ return toolError('VALIDATION', 'text is empty or too long.');
181
+ const found = resolveTicket(owner, args.ticketId, kind === 'supply' ? ['needs_user', 'enqueued'] : null);
182
+ if (found.error)
183
+ return found.error;
184
+ const expected = revisionOf(args.expectedRevision);
185
+ const advanced = await store.write('work', () => book.advanceGeneration(found.ticket.id, expected, kind, text));
186
+ if (advanced.error)
187
+ return toolError(advanced.error, advanced.message ?? 'Changing the generation failed.');
188
+ if (!resident)
189
+ return { ...publicDispatch(advanced.ticket), flush: 'pending', message: 'Only a resident host continues' };
190
+ 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 });
192
+ }
193
+ /**
194
+ * @param {string} owner
195
+ * @param {Record<string, unknown>} args
196
+ */
197
+ async function cancelTicket(owner, args) {
198
+ if (!engine.isBot(owner))
199
+ return toolError('FORBIDDEN', 'An ordinary session cannot cancel a ticket.');
200
+ const found = resolveTicket(owner, args.ticketId, null);
201
+ if (found.error)
202
+ return found.error;
203
+ const note = typeof args.note === 'string' ? args.note.trim() : '';
204
+ const expected = revisionOf(args.expectedRevision);
205
+ const cancelled = await store.write('work', () => book.markCancelled(found.ticket.id, expected, note));
206
+ if (cancelled.error)
207
+ return toolError(cancelled.error, cancelled.message ?? 'Cancel failed.');
208
+ const child = cancelled.ticket.child_session_id;
209
+ if (resident && child && options.cancel) {
210
+ await options.cancel(child, { keepInbox: note !== '' });
211
+ }
212
+ if (resident && note !== '' && cancelled.input)
213
+ await pushInput(book, cancelled.input, deps);
214
+ await removeUnclaimed(owner, cancelled.ticket.id);
215
+ return { ok: true, ticketId: cancelled.ticket.id, ticketStatus: cancelled.ticket.status, already: cancelled.already === true };
216
+ }
217
+ /**
218
+ * @param {string} owner
219
+ * @param {Record<string, unknown>} args
220
+ */
221
+ async function grant(owner, args) {
222
+ if (!engine.isBot(owner))
223
+ return toolError('FORBIDDEN', 'An ordinary session cannot grant more budget.');
224
+ const found = resolveTicket(owner, args.ticketId, null);
225
+ if (found.error)
226
+ return found.error;
227
+ if (args.deny === true) {
228
+ const failed = await store.write('work', () => book.failRunning(found.ticket.id, 'grant-denied'));
229
+ const child = failed?.child_session_id;
230
+ const state = child ? arms.get(child) : null;
231
+ if (state) {
232
+ state.closing = true;
233
+ state.clear?.();
234
+ }
235
+ if (resident && child && options.cancel)
236
+ await options.cancel(child, { keepInbox: false });
237
+ return { ok: true, ticketId: found.ticket.id, ticketStatus: 'failed', denied: true };
238
+ }
239
+ const added = await store.write('work', () => book.extendBudget(found.ticket.id, {
240
+ wallMs: typeof args.wallMs === 'number' ? args.wallMs : undefined,
241
+ maxTokens: typeof args.maxTokens === 'number' ? args.maxTokens : undefined,
242
+ }, { wallMs: limits.workerWallMs, maxTokens: limits.workerMaxTokens }));
243
+ if (added.error)
244
+ return toolError(added.error, added.message ?? 'No budget was added.');
245
+ const child = added.ticket.child_session_id;
246
+ if (child)
247
+ releaseArm(child, added.budget);
248
+ return {
249
+ ok: true,
250
+ ticketId: added.ticket.id,
251
+ ticketStatus: added.ticket.status,
252
+ wallMs: added.budget.wallMs,
253
+ maxTokens: added.budget.maxTokens,
254
+ };
255
+ }
256
+ async function retry(owner, args) {
257
+ if (!engine.isBot(owner))
258
+ return toolError('FORBIDDEN', 'An ordinary session cannot retry a ticket.');
259
+ const found = resolveTicket(owner, args.ticketId, ['failed', 'cancelled']);
260
+ if (found.error)
261
+ return found.error;
262
+ const expected = revisionOf(args.expectedRevision);
263
+ const retried = await store.write('work', () => book.insertRetry(found.ticket.id, expected));
264
+ if (retried.error)
265
+ return toolError(retried.error, retried.message ?? 'Retry failed.');
266
+ if (!resident)
267
+ return { ...publicDispatch(retried.ticket), flush: 'pending', message: 'Only a resident host continues' };
268
+ const ensured = await ensureChild(retried.ticket);
269
+ if (ensured.error)
270
+ return ensured.error;
271
+ 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 });
273
+ }
274
+ /**
275
+ * @param {string} owner
276
+ * @param {Record<string, unknown>} args
277
+ */
278
+ async function publish(owner, args) {
279
+ if (!engine.isBot(owner))
280
+ return toolError('FORBIDDEN', 'An ordinary session cannot publish.');
281
+ if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
282
+ return toolError('VALIDATION', 'resultEventId is required.');
283
+ if (typeof args.text !== 'string' || args.text.trim() === '' || args.text.length > 16000)
284
+ return toolError('VALIDATION', 'text is empty or too long.');
285
+ const turn = args.turn == null ? null : String(args.turn);
286
+ const saved = await store.write('work', () => {
287
+ const event = book.event(args.resultEventId);
288
+ if (!event)
289
+ return toolError('NOT_FOUND', 'No such result.');
290
+ const ticket = book.ticket(event.ticket_id);
291
+ if (!ticket || ticket.owner_session_id !== owner)
292
+ return toolError('FORBIDDEN', 'This result does not belong to this session.');
293
+ if (ticket.review_status === 'rejected')
294
+ return toolError('REJECTED', 'This candidate was already rejected.');
295
+ if (event.kind !== 'result' || event.apply_status !== 'applied')
296
+ return toolError('VALIDATION', 'The result has not finished reconciliation.');
297
+ if (event.briefing_revision !== ticket.briefing_revision)
298
+ return toolError('VALIDATION', 'The result generation is stale.');
299
+ const attempt = book.attempt(ticket.active_attempt_id);
300
+ if (!attempt || attempt.id !== event.attempt_id || attempt.fencing_token !== event.fencing_token) {
301
+ return toolError('VALIDATION', 'The result execution generation has changed.');
302
+ }
303
+ if (ticket.status === 'cancelled' || ticket.status === 'failed')
304
+ return toolError('VALIDATION', 'This ticket can no longer be published.');
305
+ const delivery = book.insertDelivery({
306
+ ticketId: ticket.id,
307
+ eventId: event.event_id,
308
+ owner,
309
+ attemptId: attempt.id,
310
+ fencingToken: attempt.fencing_token,
311
+ briefingRevision: event.briefing_revision,
312
+ text: args.text,
313
+ turn,
314
+ });
315
+ return {
316
+ ok: true,
317
+ publishId: delivery.row.publish_id,
318
+ already: delivery.already,
319
+ text: args.text,
320
+ status: delivery.row.status,
321
+ ticketId: ticket.id,
322
+ };
323
+ });
324
+ return saved;
325
+ }
326
+ /**
327
+ * @param {string} owner
328
+ * @param {Record<string, unknown>} args
329
+ */
330
+ async function reject(owner, args) {
331
+ if (!engine.isBot(owner))
332
+ return toolError('FORBIDDEN', 'An ordinary session cannot reject a candidate.');
333
+ if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
334
+ return toolError('VALIDATION', 'resultEventId is required.');
335
+ return store.write('work', () => {
336
+ const event = book.event(args.resultEventId);
337
+ if (!event)
338
+ return toolError('NOT_FOUND', 'No such result.');
339
+ const ticket = book.ticket(event.ticket_id);
340
+ if (!ticket || ticket.owner_session_id !== owner)
341
+ return toolError('FORBIDDEN', 'This result does not belong to this session.');
342
+ if (event.kind !== 'result' || event.apply_status !== 'applied')
343
+ return toolError('VALIDATION', 'There is no candidate to reject yet.');
344
+ book.setReview(ticket.id, 'rejected');
345
+ store.db.prepare(`
346
+ UPDATE user_deliveries SET status = 'abandoned'
347
+ WHERE result_event_id = ? AND status = 'intent'
348
+ `).run(event.event_id);
349
+ return { ok: true, reviewStatus: 'rejected', ticketId: ticket.id };
350
+ });
351
+ }
352
+ /**
353
+ * @param {string} sessionId child session
354
+ * @param {Record<string, unknown>} args
355
+ */
356
+ async function report(sessionId, args) {
357
+ const kind = typeof args.kind === 'string' ? args.kind : '';
358
+ if (!KINDS.has(kind))
359
+ return toolError('VALIDATION', 'kind must be progress, question, artifact, result, or failure.');
360
+ const text = typeof args.text === 'string' ? args.text : '';
361
+ if (text.trim() === '' || text.length > 16000)
362
+ return toolError('VALIDATION', 'text is empty or too long.');
363
+ const attempt = book.attemptForChild(sessionId);
364
+ if (!attempt)
365
+ return toolError('FORBIDDEN', 'This session is not a worker, so it cannot report.');
366
+ const bound = turns.get(sessionId);
367
+ const input = bound ? book.inputByNative(bound.messageId) : null;
368
+ if (!input || input.attempt_id !== attempt.id)
369
+ return toolError('NOT_FOUND', 'This round has no matching briefing.');
370
+ const ticket = book.ticket(input.ticket_id);
371
+ if (!ticket)
372
+ 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');
381
+ const saved = await store.write('work', () => book.insertEvent({
382
+ ticketId: ticket.id,
383
+ attemptId: attempt.id,
384
+ fencingToken: attempt.fencing_token,
385
+ briefingRevision: input.briefing_revision,
386
+ kind,
387
+ text,
388
+ applyStatus,
389
+ }));
390
+ if (saved.duplicate || !saved.event)
391
+ return toolError('REPLAY', 'This event was already written.');
392
+ const until = new Date(now().getTime() + limits.leaseMs).toISOString();
393
+ book.touchLease(attempt.id, until, typeof bound.seq === 'number' ? bound.seq : null);
394
+ return {
395
+ ok: true,
396
+ eventId: saved.event.event_id,
397
+ applyStatus: saved.event.apply_status,
398
+ kind,
399
+ };
400
+ }
401
+ async function tick() {
402
+ await reconcileInputs(book, deps);
403
+ await reconcileNotices(book, deps);
404
+ await store.write('work', () => { book.expireQuiet(); });
405
+ for (const owner of book.ownerIds()) {
406
+ if (engine.isBot(owner))
407
+ await admit(owner);
408
+ }
409
+ for (const child of book.childIds())
410
+ await reconcileChild(child);
411
+ for (const owner of book.ownerIds())
412
+ await reconcileOwner(owner);
413
+ }
414
+ /**
415
+ * @param {string} owner
416
+ */
417
+ async function admit(owner) {
418
+ const wake = book.pendingWake(owner);
419
+ if (wake.events.length === 0 && wake.cancels.length === 0)
420
+ return { admitted: false, reason: 'empty' };
421
+ let pending = null;
422
+ try {
423
+ pending = options.pendingIds ? await options.pendingIds(owner) : null;
424
+ }
425
+ catch {
426
+ pending = null;
427
+ }
428
+ const terminalTimes = [];
429
+ for (const event of wake.events) {
430
+ if ((event.kind === 'question' || event.kind === 'result' || event.kind === 'failure') && event.apply_status === 'applied') {
431
+ terminalTimes.push(Date.parse(event.created_at));
432
+ }
433
+ }
434
+ for (const ticket of wake.cancels)
435
+ terminalTimes.push(Date.parse(ticket.updated_at));
436
+ const heldUntil = holds.get(owner);
437
+ if (heldUntil != null && now().getTime() < heldUntil)
438
+ return { admitted: false, reason: 'interrupt-hold' };
439
+ if (heldUntil != null)
440
+ holds.delete(owner);
441
+ const decision = decideAdmission({
442
+ pendingIds: pending,
443
+ backgroundIds: book.backgroundIds(owner),
444
+ noticeOpen: book.openNotice(owner),
445
+ deliveryOpen: book.openDelivery(owner),
446
+ lastNoticeAt: book.latestNoticeAt(owner),
447
+ nowMs: now().getTime(),
448
+ mergeWindowMs: limits.mergeWindowMs,
449
+ terminalSince: terminalTimes.length === 0 ? null : Math.min(...terminalTimes),
450
+ starveMs: limits.starveMs,
451
+ });
452
+ if (!decision.admit)
453
+ return { admitted: false, ...decision };
454
+ const nativeId = randomUUID();
455
+ const items = [];
456
+ for (const event of wake.events) {
457
+ const ticket = book.ticket(event.ticket_id);
458
+ if (!ticket)
459
+ continue;
460
+ items.push({
461
+ ticketId: ticket.id,
462
+ eventId: event.event_id,
463
+ line: noticeLine(ticket, event),
464
+ });
465
+ }
466
+ for (const ticket of wake.cancels) {
467
+ items.push({
468
+ ticketId: ticket.id,
469
+ eventId: `cancel:${ticket.cancel_requested_revision}`,
470
+ line: `${ticket.id} cancelled rev ${ticket.briefing_revision}`,
471
+ });
472
+ }
473
+ if (items.length === 0)
474
+ return { admitted: false, reason: 'empty' };
475
+ await store.write('work', () => { book.insertNotices(nativeId, owner, items); });
476
+ const flushed = await pushNotice(book, nativeId, owner, renderNotice(items.map(item => item.line)), 0, deps);
477
+ return { admitted: true, nativeMessageId: nativeId, flush: flushWord(flushed), ...decision };
478
+ }
479
+ /**
480
+ * Progress stays a status line. Result and failure carry the body so the
481
+ * main bot writes the user-visible reply instead of leaving it on the card.
482
+ * @param {Record<string, any>} ticket
483
+ * @param {Record<string, any>} event
484
+ */
485
+ function noticeLine(ticket, event) {
486
+ const head = `${ticket.id} ${ticket.status} (${LABEL[ticket.status] ?? ticket.status}) rev ${ticket.briefing_revision} ${event.kind}`;
487
+ const text = book.detail(ticket.id)?.events?.find(item => item.event_id === event.event_id)?.text ?? '';
488
+ if (text.startsWith('[foundations:extension]')) {
489
+ return [head, `eventId: ${event.event_id}`, text].join('\n');
490
+ }
491
+ if (event.kind !== 'result' && event.kind !== 'failure')
492
+ return head;
493
+ const body = text.length > 8000 ? `${text.slice(0, 8000)}\n…` : text;
494
+ const ask = event.kind === 'result'
495
+ ? 'This is a successful result. Call foundations_publish now. Use the eventId below as resultEventId and the words you want the user to see as text. After the tool returns, write that same text as the reply to the user. Do not only restate the status, and do not ask the user to paste the body back.'
496
+ : 'This is a failed result. Now tell the user the reason and the next step in your own words. Do not only restate the status, and do not ask the user to paste the body back.';
497
+ return [head, `eventId: ${event.event_id}`, ask, '---', body].join('\n');
498
+ }
499
+ /**
500
+ * @param {string} sessionId
501
+ * @param {Record<string, any>} event
502
+ */
503
+ function observeSession(sessionId, event) {
504
+ if (!event || typeof event.type !== 'string')
505
+ return;
506
+ noteBudget(sessionId, event);
507
+ 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 });
510
+ }
511
+ if (event.type === 'user/message' && engine.isBot(sessionId))
512
+ holds.delete(sessionId);
513
+ if (event.type === 'user/message' && nativeId) {
514
+ const input = book.inputByNative(nativeId);
515
+ if (input) {
516
+ book.markStarted(input.ticket_id, nativeId);
517
+ const attempt = book.attempt(input.attempt_id);
518
+ if (attempt)
519
+ book.touchLease(attempt.id, new Date(now().getTime() + limits.leaseMs).toISOString(), typeof event.seq === 'number' ? event.seq : null);
520
+ }
521
+ if (engine.isBot(sessionId) && book.noticeIds(sessionId).has(nativeId)) {
522
+ book.setNoticeObserve(nativeId, 'started');
523
+ if (event.data?.turn != null)
524
+ wakeTurns.set(`${sessionId}:${event.data.turn}`, nativeId);
525
+ }
526
+ }
527
+ if (event.type === 'turn/end')
528
+ applyTurnEnd(sessionId, event.data?.turn ?? null, reasonKindOf(event));
529
+ if (isWorkerSession(sessionId) && typeof event.seq === 'number') {
530
+ const attempt = book.attemptForChild(sessionId);
531
+ if (attempt && (attempt.status === 'started' || attempt.status === 'enqueued')) {
532
+ book.touchLease(attempt.id, new Date(now().getTime() + limits.leaseMs).toISOString(), event.seq);
533
+ }
534
+ }
535
+ }
536
+ /**
537
+ * @param {string} sessionId
538
+ * @param {string} messageId
539
+ * @param {number | null} turn
540
+ */
541
+ function observeClaimed(sessionId, messageId, turn) {
542
+ if (book.inputByNative(messageId))
543
+ turns.set(sessionId, { messageId, turn, seq: null });
544
+ book.setNoticeObserve(messageId, 'claimed');
545
+ }
546
+ /**
547
+ * @param {Record<string, any>} ticket
548
+ */
549
+ async function ensureChild(ticket) {
550
+ if (ticket.child_session_id)
551
+ return { ticket };
552
+ if (!options.createChild)
553
+ return { error: publicDispatch(ticket, { flush: 'pending' }) };
554
+ const sessionId = `worker-${ticket.id}`;
555
+ try {
556
+ const created = await options.createChild({
557
+ sessionId,
558
+ ownerSessionId: ticket.owner_session_id,
559
+ ticketId: ticket.id,
560
+ fencingToken: book.attempt(ticket.active_attempt_id)?.fencing_token ?? 1,
561
+ });
562
+ const child = typeof created === 'string' && created !== '' ? created : sessionId;
563
+ engine.ensureSession(child);
564
+ const saved = await store.write('work', () => book.setChildIfEmpty(ticket.id, child));
565
+ return { ticket: saved };
566
+ }
567
+ catch {
568
+ return {
569
+ error: publicDispatch(book.ticket(ticket.id), { flush: 'pending', childSessionId: null, nativeMessageId: null }),
570
+ };
571
+ }
572
+ }
573
+ /**
574
+ * @param {string} owner
575
+ * @param {unknown} ticketId
576
+ * @param {string[] | null} statuses
577
+ */
578
+ function resolveTicket(owner, ticketId, statuses) {
579
+ if (typeof ticketId === 'string' && ticketId !== '') {
580
+ const ticket = book.ticket(ticketId);
581
+ if (!ticket || ticket.owner_session_id !== owner)
582
+ return { error: toolError('NOT_FOUND', 'No such ticket.') };
583
+ return { ticket };
584
+ }
585
+ const rows = store.db.prepare(`
586
+ SELECT * FROM work_tickets WHERE owner_session_id = ?
587
+ ${statuses ? `AND status IN (${statuses.map(() => '?').join(',')})` : ''}
588
+ ORDER BY updated_at DESC
589
+ `).all(owner, ...(statuses ?? []));
590
+ if (rows.length !== 1)
591
+ return { error: toolError('VALIDATION', 'Name the ticket.') };
592
+ return { ticket: rows[0] };
593
+ }
594
+ /**
595
+ * @param {unknown} value
596
+ */
597
+ function revisionOf(value) {
598
+ return Number.isInteger(value) ? value : null;
599
+ }
600
+ /**
601
+ * @param {string} owner
602
+ * @param {unknown} value
603
+ */
604
+ function correlationOf(owner, value) {
605
+ if (typeof value !== 'string' || value === '')
606
+ return '';
607
+ const found = store.db.prepare(`
608
+ SELECT 1 AS ok FROM deliveries WHERE id = ? AND (sender_session_id = ? OR target_session_id = ?)
609
+ `).get(value, owner, owner);
610
+ return found ? value : '';
611
+ }
612
+ /**
613
+ * @param {Record<string, any>} ticket
614
+ * @param {{ replayed?: boolean, flush?: string, nativeMessageId?: string | null, childSessionId?: string | null }} [extra]
615
+ */
616
+ function publicDispatch(ticket, extra = {}) {
617
+ const fresh = book.ticket(ticket.id) ?? ticket;
618
+ const attempt = fresh.active_attempt_id ? book.attempt(fresh.active_attempt_id) : null;
619
+ 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'));
623
+ const dispatched = flush === 'accepted' || (fresh.status !== 'accepted' && fresh.status !== 'failed' && fresh.status !== 'cancelled');
624
+ return {
625
+ ok: true,
626
+ ticketId: fresh.id,
627
+ attemptId: attempt?.id ?? fresh.active_attempt_id,
628
+ briefingRevision: fresh.briefing_revision,
629
+ status: dispatched && flush === 'accepted' ? 'enqueued' : 'accepted',
630
+ ticketStatus: fresh.status,
631
+ childSessionId: extra.childSessionId === null ? null : fresh.child_session_id,
632
+ fencingToken: attempt?.fencing_token ?? null,
633
+ nativeMessageId: extra.nativeMessageId === undefined ? (input?.native_message_id ?? null) : extra.nativeMessageId,
634
+ flush,
635
+ replayed: extra.replayed === true,
636
+ };
637
+ }
638
+ function project(ticket) {
639
+ return publicDispatch(ticket);
640
+ }
641
+ /**
642
+ * @param {{ status?: string }} flushed
643
+ */
644
+ function flushWord(flushed) {
645
+ if (flushed?.status === 'accepted')
646
+ return 'accepted';
647
+ if (flushed?.status === 'ambiguous')
648
+ return 'ambiguous';
649
+ return 'pending';
650
+ }
651
+ /**
652
+ * @param {string} sessionId
653
+ * @param {number | null} turn
654
+ * @param {string} reason
655
+ */
656
+ function applyTurnEnd(sessionId, turn, reason) {
657
+ const bound = turns.get(sessionId);
658
+ if (engine.isBot(sessionId) && turn != null) {
659
+ const nativeId = wakeTurns.get(`${sessionId}:${turn}`);
660
+ if (nativeId)
661
+ book.setNoticeObserve(nativeId, 'completed');
662
+ }
663
+ clearBudget(sessionId);
664
+ if (!bound)
665
+ return;
666
+ if (turn != null && bound.turn != null && bound.turn !== turn)
667
+ return;
668
+ const input = book.inputByNative(bound.messageId);
669
+ if (!input)
670
+ return;
671
+ const found = book.detail(input.ticket_id);
672
+ if (!found)
673
+ return;
674
+ for (const event of found.events) {
675
+ if (event.attempt_id !== input.attempt_id)
676
+ continue;
677
+ if (event.briefing_revision !== input.briefing_revision)
678
+ continue;
679
+ if (event.apply_status !== 'pending_completion')
680
+ continue;
681
+ book.applyTerminal(event.event_id, reason);
682
+ }
683
+ }
684
+ /**
685
+ * @param {string} sessionId
686
+ */
687
+ async function reconcileChild(sessionId) {
688
+ if (!options.snapshot)
689
+ return;
690
+ const events = await options.snapshot(sessionId);
691
+ /** @type {Map<number, string>} */
692
+ const byTurn = new Map();
693
+ for (const event of events) {
694
+ const nativeId = messageIdOf(event);
695
+ if (event.type === 'user/message' && nativeId && book.inputByNative(nativeId)) {
696
+ const input = book.inputByNative(nativeId);
697
+ book.markStarted(input.ticket_id, nativeId);
698
+ turns.set(sessionId, {
699
+ messageId: nativeId,
700
+ turn: event.data?.turn ?? null,
701
+ seq: typeof event.seq === 'number' ? event.seq : null,
702
+ });
703
+ if (event.data?.turn != null)
704
+ byTurn.set(event.data.turn, nativeId);
705
+ }
706
+ }
707
+ for (const event of events) {
708
+ if (event.type !== 'turn/end')
709
+ continue;
710
+ const nativeId = byTurn.get(event.data?.turn);
711
+ if (!nativeId)
712
+ continue;
713
+ turns.set(sessionId, { messageId: nativeId, turn: event.data?.turn ?? null, seq: null });
714
+ const input = book.inputByNative(nativeId);
715
+ if (!input)
716
+ continue;
717
+ const found = book.detail(input.ticket_id);
718
+ for (const item of found?.events ?? []) {
719
+ if (item.apply_status === 'pending_completion' && item.briefing_revision === input.briefing_revision) {
720
+ book.applyTerminal(item.event_id, reasonKindOf(event));
721
+ }
722
+ }
723
+ }
724
+ }
725
+ /**
726
+ * @param {string} owner
727
+ */
728
+ async function reconcileOwner(owner) {
729
+ if (!options.snapshot)
730
+ return;
731
+ const events = await options.snapshot(owner);
732
+ const notices = book.noticeIds(owner);
733
+ /** @type {string | null} */
734
+ let waiting = null;
735
+ for (const event of events) {
736
+ const name = event.data?.name ?? event.data?.toolName;
737
+ 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') {
739
+ waiting = args.resultEventId;
740
+ }
741
+ if (event.type === 'user/message' && notices.has(messageIdOf(event)))
742
+ continue;
743
+ if (event.type === 'assistant/message' && waiting && typeof event.seq === 'number') {
744
+ const ticketRows = book.ownerIds().includes(owner) ? store.db.prepare(`
745
+ SELECT * FROM user_deliveries WHERE owner_session_id = ? AND result_event_id = ? AND status = 'intent'
746
+ `).get(owner, waiting) : null;
747
+ if (ticketRows)
748
+ book.bindDelivery(ticketRows.publish_id, event.seq);
749
+ waiting = null;
750
+ }
751
+ }
752
+ }
753
+ /**
754
+ * @param {string} nativeId
755
+ */
756
+ function noticeText(nativeId) {
757
+ const rows = store.db.prepare(`SELECT * FROM work_notices WHERE native_message_id = ?`).all(nativeId);
758
+ const lines = rows.map(row => {
759
+ const ticket = book.ticket(row.ticket_id);
760
+ return `${row.ticket_id} ${ticket?.status ?? ''} rev ${ticket?.briefing_revision ?? ''} ${row.event_id}`;
761
+ });
762
+ return renderNotice(lines);
763
+ }
764
+ /**
765
+ * @param {string} owner
766
+ * @param {string} ticketId
767
+ */
768
+ async function removeUnclaimed(owner, ticketId) {
769
+ const rows = store.db.prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`).all(ticketId);
770
+ const seen = new Set();
771
+ for (const row of rows) {
772
+ if (seen.has(row.native_message_id))
773
+ continue;
774
+ seen.add(row.native_message_id);
775
+ if (row.flush_status === 'accepted' && options.remove) {
776
+ await options.remove(owner, row.native_message_id);
777
+ }
778
+ else if (row.flush_status !== 'accepted') {
779
+ book.markNoticeGroup(row.native_message_id, 'dead', row.flush_pid ?? null, 'cancelled', null, false);
780
+ }
781
+ }
782
+ }
783
+ /**
784
+ * @param {string} sessionId
785
+ * @param {Record<string, any>} event
786
+ */
787
+ function noteBudget(sessionId, event) {
788
+ const role = budgetRole(sessionId);
789
+ if (!role)
790
+ return;
791
+ if (role === 'main' && (event.type === 'tool/call' || event.type === 'tool/result')) {
792
+ const name = event.data?.name ?? event.data?.toolName;
793
+ if (name === 'foundations_dispatch' || (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
794
+ tightenMain(sessionId);
795
+ }
796
+ }
797
+ if (event.type === 'turn/start') {
798
+ arm(sessionId, event.data?.turn ?? 0, role);
799
+ return;
800
+ }
801
+ const state = arms.get(sessionId);
802
+ if (event.type === 'assistant/message' && role === 'worker' && state) {
803
+ const seq = typeof event.seq === 'number' ? event.seq : null;
804
+ if (seq != null && state.lastSeq != null && seq <= state.lastSeq)
805
+ return;
806
+ const total = event.data?.usage?.totalTokens;
807
+ if (typeof total === 'number' && total > 0) {
808
+ state.tokens += total;
809
+ if (seq != null)
810
+ state.lastSeq = seq;
811
+ consider(sessionId, state, false);
812
+ }
813
+ return;
814
+ }
815
+ if (event.type !== 'step/end')
816
+ return;
817
+ const live = state ?? arm(sessionId, event.data?.turn ?? 0, role);
818
+ const step = Number(event.data?.step);
819
+ live.steps = Number.isFinite(step) ? Math.max(live.steps, step) : live.steps + 1;
820
+ if (role === 'main')
821
+ consider(sessionId, live, false);
822
+ }
823
+ /**
824
+ * @param {string} sessionId
825
+ */
826
+ function budgetRole(sessionId) {
827
+ if (book.attemptForChild(sessionId))
828
+ return 'worker';
829
+ if (engine.isBot(sessionId))
830
+ return 'main';
831
+ return null;
832
+ }
833
+ /**
834
+ * Keep ticket notices out of the inbox until the interrupting user message
835
+ * arrives, or until the hold expires.
836
+ * @param {string} sessionId
837
+ */
838
+ function holdNotices(sessionId) {
839
+ if (!engine.isBot(sessionId))
840
+ return toolError('FORBIDDEN', 'Only a bot main session holds ticket notices.');
841
+ const until = now().getTime() + limits.holdMs;
842
+ holds.set(sessionId, until);
843
+ return { ok: true, until };
844
+ }
845
+ /**
846
+ * @param {string} sessionId
847
+ */
848
+ function releaseHold(sessionId) {
849
+ holds.delete(sessionId);
850
+ return { ok: true };
851
+ }
852
+ /**
853
+ * A dispatch or a host tool leaves the chat budget and uses the short cap.
854
+ * @param {string} sessionId
855
+ */
856
+ function tightenMain(sessionId) {
857
+ const state = arms.get(sessionId);
858
+ if (!state || state.role !== 'main' || state.tight || state.closing || state.tripped)
859
+ return;
860
+ state.tight = true;
861
+ state.limits = {
862
+ ...state.limits,
863
+ maxSteps: limits.mainMaxSteps,
864
+ wallMs: limits.mainWallMs,
865
+ ceilingWall: limits.mainWallMs,
866
+ };
867
+ state.clear?.();
868
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
869
+ state.clear = schedule(() => {
870
+ const live = arms.get(sessionId);
871
+ if (!live || live !== state || live.closing)
872
+ return;
873
+ consider(sessionId, live, true);
874
+ }, Math.max(1, state.limits.wallMs - elapsed));
875
+ consider(sessionId, state, false);
876
+ }
877
+ /**
878
+ * @param {string} sessionId
879
+ * @param {number} turn
880
+ * @param {'main' | 'worker'} role
881
+ */
882
+ function arm(sessionId, turn, role) {
883
+ const previous = arms.get(sessionId);
884
+ clearBudget(sessionId);
885
+ const caps = role === 'main'
886
+ ? { maxSteps: limits.chatMaxSteps, wallMs: limits.chatWallMs, maxTokens: Number.POSITIVE_INFINITY, ceilingWall: limits.chatWallMs, ceilingTokens: Number.POSITIVE_INFINITY, extensionOpen: false }
887
+ : workerCaps(sessionId);
888
+ const state = {
889
+ turn,
890
+ startedAt: previous?.startedAt ?? now().getTime(),
891
+ steps: 0,
892
+ tokens: previous?.tokens ?? 0,
893
+ lastSeq: previous?.lastSeq ?? null,
894
+ role,
895
+ tight: false,
896
+ limits: caps,
897
+ tripped: false,
898
+ extensionOpen: false,
899
+ closing: false,
900
+ clear: () => { },
901
+ };
902
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
903
+ state.extensionOpen = previous?.extensionOpen === true || caps.extensionOpen === true;
904
+ const target = state.extensionOpen ? caps.ceilingWall : caps.wallMs;
905
+ state.clear = schedule(() => {
906
+ const live = arms.get(sessionId);
907
+ if (!live || live !== state || live.closing)
908
+ return;
909
+ consider(sessionId, live, true);
910
+ }, Math.max(1, target - elapsed));
911
+ arms.set(sessionId, state);
912
+ return state;
913
+ }
914
+ /**
915
+ * @param {string} sessionId
916
+ */
917
+ function workerCaps(sessionId) {
918
+ const attempt = book.attemptForChild(sessionId);
919
+ const ticket = attempt ? book.ticket(attempt.ticket_id) : null;
920
+ let wallMs = limits.workerWallMs;
921
+ let maxTokens = limits.workerMaxTokens;
922
+ let extensionOpen = false;
923
+ if (ticket) {
924
+ try {
925
+ const parsed = JSON.parse(ticket.budget_json);
926
+ if (Number.isFinite(parsed.wallMs))
927
+ wallMs = Math.min(limits.workerWallMs, Math.max(1000, parsed.wallMs));
928
+ if (Number.isFinite(parsed.maxTokens))
929
+ maxTokens = Math.min(limits.workerMaxTokens, Math.max(1000, parsed.maxTokens));
930
+ extensionOpen = parsed.extension === 'open';
931
+ }
932
+ catch { /* host ceiling */ }
933
+ }
934
+ return {
935
+ maxSteps: Number.POSITIVE_INFINITY,
936
+ wallMs,
937
+ maxTokens,
938
+ ceilingWall: limits.workerWallMs,
939
+ ceilingTokens: limits.workerMaxTokens,
940
+ extensionOpen,
941
+ };
942
+ }
943
+ /**
944
+ * @param {string} sessionId
945
+ * @param {{ steps: number, startedAt: number, limits: { maxSteps: number, wallMs: number }, tripped: boolean, role: 'main' | 'worker' }} state
946
+ * @param {boolean} fromTimer
947
+ */
948
+ function consider(sessionId, state, fromTimer) {
949
+ if (state.closing)
950
+ return;
951
+ 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)
960
+ return;
961
+ state.tripped = true;
962
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: true })).catch(() => { });
963
+ return;
964
+ }
965
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
966
+ if (state.tokens >= state.limits.ceilingTokens || elapsed >= state.limits.ceilingWall) {
967
+ finishWorker(sessionId, state, state.tokens >= state.limits.ceilingTokens && elapsed < state.limits.ceilingWall ? 'tokens' : 'wall');
968
+ return;
969
+ }
970
+ if (state.extensionOpen)
971
+ return;
972
+ const overWall = fromTimer || elapsed >= state.limits.wallMs;
973
+ const overTokens = state.tokens >= state.limits.maxTokens;
974
+ if (!overWall && !overTokens)
975
+ return;
976
+ if (overWall && state.limits.wallMs < state.limits.ceilingWall) {
977
+ askForQuota(sessionId, state, 'wall', elapsed);
978
+ return;
979
+ }
980
+ if (overTokens && state.limits.maxTokens < state.limits.ceilingTokens) {
981
+ askForQuota(sessionId, state, 'tokens', elapsed);
982
+ return;
983
+ }
984
+ finishWorker(sessionId, state, overTokens ? 'tokens' : 'wall');
985
+ }
986
+ /**
987
+ * @param {string} sessionId
988
+ * @param {{ limits: { wallMs: number, maxTokens: number, ceilingWall: number }, tokens: number, startedAt: number, extensionOpen: boolean, closing: boolean, clear: () => void }} state
989
+ * @param {'wall' | 'tokens'} reason
990
+ * @param {number} elapsed
991
+ */
992
+ function askForQuota(sessionId, state, reason, elapsed) {
993
+ state.extensionOpen = true;
994
+ state.clear?.();
995
+ watchHostCeiling(sessionId, state);
996
+ const attempt = book.attemptForChild(sessionId);
997
+ if (!attempt)
998
+ return;
999
+ const ticket = book.ticket(attempt.ticket_id);
1000
+ if (!ticket || ticket.status === 'failed' || ticket.status === 'cancelled' || ticket.status === 'delivered') {
1001
+ finishWorker(sessionId, state, reason);
1002
+ return;
1003
+ }
1004
+ const marked = book.markExtensionOpen(ticket.id);
1005
+ if (!marked || marked.already)
1006
+ return;
1007
+ const text = [
1008
+ '[foundations:extension]',
1009
+ reason === 'tokens' ? 'The token budget is used up.' : 'The runtime is used up.',
1010
+ `elapsed ms: ${elapsed}`,
1011
+ `granted wall ms: ${state.limits.wallMs}`,
1012
+ `tokens used: ${state.tokens}`,
1013
+ `granted tokens: ${state.limits.maxTokens}`,
1014
+ 'Do not mark the ticket failed. Call foundations_grant to add budget. wallMs and maxTokens are amounts to add. Pass deny=true to refuse the grant.',
1015
+ ].join('\n');
1016
+ book.insertEvent({
1017
+ ticketId: ticket.id,
1018
+ attemptId: attempt.id,
1019
+ fencingToken: attempt.fencing_token,
1020
+ briefingRevision: ticket.briefing_revision,
1021
+ kind: 'progress',
1022
+ text,
1023
+ applyStatus: 'applied',
1024
+ });
1025
+ }
1026
+ /**
1027
+ * After a quota request, the worker keeps running until the host ceiling.
1028
+ * An early timer is rearmed. It does not fail the ticket by itself.
1029
+ * @param {string} sessionId
1030
+ * @param {{ startedAt: number, limits: { ceilingWall: number }, closing: boolean, clear: () => void }} state
1031
+ */
1032
+ function watchHostCeiling(sessionId, state) {
1033
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
1034
+ state.clear = schedule(() => {
1035
+ const live = arms.get(sessionId);
1036
+ if (!live || live !== state || live.closing)
1037
+ return;
1038
+ const at = Math.max(0, now().getTime() - live.startedAt);
1039
+ if (at >= live.limits.ceilingWall) {
1040
+ finishWorker(sessionId, live, 'wall');
1041
+ return;
1042
+ }
1043
+ watchHostCeiling(sessionId, live);
1044
+ }, Math.max(1000, state.limits.ceilingWall - elapsed));
1045
+ }
1046
+ /**
1047
+ * @param {string} sessionId
1048
+ * @param {{ closing: boolean, clear: () => void }} state
1049
+ * @param {string} reason
1050
+ */
1051
+ function finishWorker(sessionId, state, reason) {
1052
+ if (state.closing)
1053
+ return;
1054
+ state.closing = true;
1055
+ state.clear?.();
1056
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: false })).catch(() => { });
1057
+ const attempt = book.attemptForChild(sessionId);
1058
+ if (attempt)
1059
+ book.failRunning(attempt.ticket_id, reason);
1060
+ }
1061
+ /**
1062
+ * @param {string} sessionId
1063
+ * @param {{ wallMs: number, maxTokens: number }} budget
1064
+ */
1065
+ function releaseArm(sessionId, budget) {
1066
+ const state = arms.get(sessionId);
1067
+ if (!state || state.role !== 'worker' || state.closing)
1068
+ return;
1069
+ state.extensionOpen = false;
1070
+ state.limits.wallMs = budget.wallMs;
1071
+ state.limits.maxTokens = budget.maxTokens;
1072
+ state.clear?.();
1073
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
1074
+ state.clear = schedule(() => {
1075
+ const live = arms.get(sessionId);
1076
+ if (!live || live !== state || live.closing)
1077
+ return;
1078
+ consider(sessionId, live, true);
1079
+ }, Math.max(1, budget.wallMs - elapsed));
1080
+ if (state.tokens >= budget.maxTokens || elapsed >= budget.wallMs)
1081
+ consider(sessionId, state, false);
1082
+ }
1083
+ /**
1084
+ * @param {string} sessionId
1085
+ */
1086
+ function clearBudget(sessionId) {
1087
+ const state = arms.get(sessionId);
1088
+ if (!state)
1089
+ return;
1090
+ state.clear?.();
1091
+ arms.delete(sessionId);
1092
+ }
1093
+ }
1094
+ /**
1095
+ * @param {unknown} value
1096
+ */
1097
+ function parseArgs(value) {
1098
+ if (value && typeof value === 'object')
1099
+ return value;
1100
+ if (typeof value !== 'string' || value === '')
1101
+ return null;
1102
+ try {
1103
+ return JSON.parse(value);
1104
+ }
1105
+ catch {
1106
+ return null;
1107
+ }
1108
+ }