@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.10

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.
Files changed (144) hide show
  1. package/README.md +109 -1
  2. package/client.js +646 -621
  3. package/dist/approvals.js +160 -0
  4. package/dist/authorization.js +225 -0
  5. package/dist/cli.js +32 -12
  6. package/dist/context.js +59 -17
  7. package/dist/cron.js +1 -1
  8. package/dist/cua-access.js +79 -0
  9. package/dist/desk.js +314 -37
  10. package/dist/engine.js +178 -84
  11. package/dist/fs-safe.js +1 -1
  12. package/dist/host.js +1 -0
  13. package/dist/http-plugin.js +14 -4
  14. package/dist/http.js +383 -85
  15. package/dist/inbox.js +51 -40
  16. package/dist/index.js +190 -47
  17. package/dist/live-diff.js +3 -1
  18. package/dist/live-snapshot.js +2 -13
  19. package/dist/log/canonical.js +37 -0
  20. package/dist/log/plan.js +62 -0
  21. package/dist/log/routes.js +144 -0
  22. package/dist/log/snapshot-service.js +76 -0
  23. package/dist/log/source.js +173 -0
  24. package/dist/memory-catalog.js +798 -0
  25. package/dist/permissions.js +86 -0
  26. package/dist/provision.js +2 -0
  27. package/dist/questions.js +407 -0
  28. package/dist/runtime-registry.js +4 -4
  29. package/dist/session-files.js +2 -2
  30. package/dist/session-previews.js +5 -1
  31. package/dist/store.js +20 -5
  32. package/dist/tools.js +150 -32
  33. package/dist/triggers.js +83 -39
  34. package/dist/work-admit.js +222 -25
  35. package/dist/work-child.js +17 -9
  36. package/dist/work-http.js +33 -2
  37. package/dist/work-ledger.js +256 -16
  38. package/dist/work-mock-host.js +9 -6
  39. package/dist/work-mock.js +29 -19
  40. package/dist/work-tickets.js +423 -96
  41. package/dist/work-tools.js +43 -6
  42. package/dist/work-worker.js +1028 -207
  43. package/dist/workspace-files.js +319 -0
  44. package/dist/workspace-image.js +91 -0
  45. package/fixtures/mock-llm.mjs +17 -2
  46. package/package.json +15 -5
  47. package/public/assets/SourceEditor-BEQaScgR.js +669 -0
  48. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  49. package/public/assets/abap-CRCWOmpq.js +1 -0
  50. package/public/assets/apex-DnsZk_dE.js +1 -0
  51. package/public/assets/azcli-1IWB1ccx.js +1 -0
  52. package/public/assets/bat-DPkNLes8.js +1 -0
  53. package/public/assets/bicep-Corcdgou.js +2 -0
  54. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  55. package/public/assets/clojure-D9WOWImG.js +1 -0
  56. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  57. package/public/assets/coffee-B7EJu28W.js +1 -0
  58. package/public/assets/cpp-SEyurbux.js +1 -0
  59. package/public/assets/csharp-BoL64M5l.js +1 -0
  60. package/public/assets/csp-C46ZqvIl.js +1 -0
  61. package/public/assets/css-DQU6DXDx.js +3 -0
  62. package/public/assets/css.worker-DYpkewsP.js +79 -0
  63. package/public/assets/cssMode-gpcjCFFS.js +4 -0
  64. package/public/assets/cypher-D84EuPTj.js +1 -0
  65. package/public/assets/dart-D8lhlL1r.js +1 -0
  66. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  67. package/public/assets/ecl-BO6FnfXk.js +1 -0
  68. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  69. package/public/assets/elixir-BRjLKONM.js +1 -0
  70. package/public/assets/flow9-Cac8vKd7.js +1 -0
  71. package/public/assets/freemarker2-C1qemGIt.js +3 -0
  72. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  73. package/public/assets/go-O9LJTZXk.js +1 -0
  74. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  75. package/public/assets/handlebars-sZqIfAlP.js +1 -0
  76. package/public/assets/hcl-DxDQ3s82.js +1 -0
  77. package/public/assets/html-Bn1WXB8L.js +1 -0
  78. package/public/assets/html.worker-tnXziJOq.js +456 -0
  79. package/public/assets/htmlMode-CvQyXnaW.js +4 -0
  80. package/public/assets/index-DRNkUrer.css +1 -0
  81. package/public/assets/index-DhL5Kdlz.js +63 -0
  82. package/public/assets/ini-BvajGCUy.js +1 -0
  83. package/public/assets/java-SYsfObOQ.js +1 -0
  84. package/public/assets/javascript-Ox4Jg12j.js +1 -0
  85. package/public/assets/json.worker-aFakAbRR.js +44 -0
  86. package/public/assets/jsonMode-DMR7R2dQ.js +10 -0
  87. package/public/assets/julia-DQXNmw_w.js +1 -0
  88. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  89. package/public/assets/less-GGFNNJHn.js +2 -0
  90. package/public/assets/lexon-Canl7DCW.js +1 -0
  91. package/public/assets/liquid-B6HxtpBd.js +1 -0
  92. package/public/assets/lua-D28Ae8-K.js +1 -0
  93. package/public/assets/m3-DPitgjJI.js +1 -0
  94. package/public/assets/markdown-B811l8j2.js +1 -0
  95. package/public/assets/mdx--jDhmrXq.js +1 -0
  96. package/public/assets/mips-CdjsipkG.js +1 -0
  97. package/public/assets/msdax-CYqgjx_P.js +1 -0
  98. package/public/assets/mysql-BHd6q0vd.js +1 -0
  99. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  100. package/public/assets/pascal-BhNW15KB.js +1 -0
  101. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  102. package/public/assets/perl-DlYyT36c.js +1 -0
  103. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  104. package/public/assets/php-120yhfDK.js +1 -0
  105. package/public/assets/pla-CjnFlu4u.js +1 -0
  106. package/public/assets/postiats-CQpG440k.js +1 -0
  107. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  108. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  109. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  110. package/public/assets/pug-kFxLfcjb.js +1 -0
  111. package/public/assets/python-YjG50skX.js +1 -0
  112. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  113. package/public/assets/r-BIFz-_sK.js +1 -0
  114. package/public/assets/razor-CEcFE3UK.js +1 -0
  115. package/public/assets/redis-CHOsPHWR.js +1 -0
  116. package/public/assets/redshift-CBifECDb.js +1 -0
  117. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  118. package/public/assets/ruby-CYWGW-b1.js +1 -0
  119. package/public/assets/rust-DMDD0SHb.js +1 -0
  120. package/public/assets/sb-BYAiYHFx.js +1 -0
  121. package/public/assets/scala-Bqvq8jcR.js +1 -0
  122. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  123. package/public/assets/scss-CTwUZ5N7.js +3 -0
  124. package/public/assets/shell-CsDZo4DB.js +1 -0
  125. package/public/assets/solidity-CME5AdoB.js +1 -0
  126. package/public/assets/sophia-RYC1BQQz.js +1 -0
  127. package/public/assets/sparql-KEyrF7De.js +1 -0
  128. package/public/assets/sql-BdTr02Mf.js +1 -0
  129. package/public/assets/st-C7iG7M4S.js +1 -0
  130. package/public/assets/swift-D7IUmUK8.js +1 -0
  131. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  132. package/public/assets/tcl-PloMZuKG.js +1 -0
  133. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  134. package/public/assets/tsMode-g4kTQl09.js +11 -0
  135. package/public/assets/twig-BfRIq3la.js +1 -0
  136. package/public/assets/typescript-CnHeFmPW.js +1 -0
  137. package/public/assets/typespec-CzxlYoT_.js +1 -0
  138. package/public/assets/vb-BwAE3J76.js +1 -0
  139. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  140. package/public/assets/xml-BFXMY9nb.js +1 -0
  141. package/public/assets/yaml-DNm87nSf.js +1 -0
  142. package/public/index.html +2 -2
  143. package/public/assets/index-Be82iGwe.css +0 -1
  144. package/public/assets/index-ByU9a3Lh.js +0 -61
@@ -2,9 +2,10 @@ import { randomUUID } from 'node:crypto';
2
2
  import { sha256 } from "./fs-safe.js";
3
3
  import { toolError } from "./errors.js";
4
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";
5
+ import { decideAdmission, budgetTrip, estimateWorkerBudget, DEFAULT_WORK_BUDGET, effectiveWorkLimits, } from "./work-admit.js";
6
+ import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderMainHistory, renderNotice, renderWorkerHistory, } from "./work-ledger.js";
7
7
  const KINDS = new Set(['progress', 'question', 'artifact', 'result', 'failure']);
8
+ const OPEN_TICKET_STATUSES = ['accepted', 'enqueued', 'started', 'needs_user', 'ready'];
8
9
  const LABEL = {
9
10
  accepted: 'accepted',
10
11
  enqueued: 'enqueued',
@@ -15,6 +16,8 @@ const LABEL = {
15
16
  cancelled: 'cancelled',
16
17
  failed: 'failed',
17
18
  };
19
+ /** Message id prefix of the inbox notice sent after a main-session budget trip. */
20
+ export const BUDGET_NOTICE_PREFIX = 'foundations-budget:';
18
21
  /**
19
22
  * Host-side ticket protocol. The model is not called from here.
20
23
  * Native inbox delivery stays in `options.push` / `options.pendingIds`.
@@ -24,10 +27,15 @@ const LABEL = {
24
27
  export function createWorkRuntime(store, engine, options = {}) {
25
28
  const now = options.now ?? (() => new Date());
26
29
  const limits = { ...DEFAULT_WORK_BUDGET, ...options.budget };
30
+ const slots = effectiveWorkLimits(limits);
27
31
  const pid = options.pid ?? process.pid;
28
32
  const resident = options.resident !== false;
29
33
  const book = createTicketBook(store.db, store.root, now);
30
34
  const inflight = new Set();
35
+ /** Ticket ids currently in ensureChild / flush, so a tick cannot start the same ticket twice. */
36
+ const starting = new Set();
37
+ /** In-flight startReserved promises, so a later promoteQueued can join them. */
38
+ const startingPromises = new Map();
31
39
  /** @type {Map<string, { messageId: string, turn: number | null, seq: number | null }>} */
32
40
  const turns = new Map();
33
41
  /** @type {Map<string, string>} */
@@ -36,11 +44,14 @@ export function createWorkRuntime(store, engine, options = {}) {
36
44
  const arms = new Map();
37
45
  /** @type {Map<string, number>} */
38
46
  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
- });
47
+ const admitting = new Set();
48
+ const budgetWaiters = new Map();
49
+ const schedule = options.schedule ??
50
+ ((fn, ms) => {
51
+ const timer = setTimeout(fn, ms);
52
+ timer.unref?.();
53
+ return () => clearTimeout(timer);
54
+ });
44
55
  const deps = {
45
56
  pid,
46
57
  inflight,
@@ -55,6 +66,7 @@ export function createWorkRuntime(store, engine, options = {}) {
55
66
  return options.push(sessionId, messageId, text);
56
67
  },
57
68
  noticeText: (nativeId) => noticeText(nativeId),
69
+ mainHistory: (ownerSessionId) => readMainHistory(ownerSessionId),
58
70
  };
59
71
  return {
60
72
  limits,
@@ -68,13 +80,19 @@ export function createWorkRuntime(store, engine, options = {}) {
68
80
  publish,
69
81
  reject,
70
82
  report,
83
+ mainHistory,
84
+ workerHistory,
71
85
  holdNotices,
72
86
  releaseHold,
73
87
  tick,
74
88
  admit,
89
+ promoteQueued,
75
90
  observeSession,
76
91
  observeClaimed,
92
+ gateStep,
93
+ waitForBudget,
77
94
  isWorkerSession,
95
+ ownerOf,
78
96
  summaries: (owner) => book.summaries(owner),
79
97
  detail: (id) => book.detail(id),
80
98
  liveStamp: () => book.liveStamp(),
@@ -88,6 +106,284 @@ export function createWorkRuntime(store, engine, options = {}) {
88
106
  function isWorkerSession(sessionId) {
89
107
  return book.attemptForChild(sessionId) != null;
90
108
  }
109
+ /**
110
+ * Main bot that owns this worker session. Empty when the id is not a ticket child.
111
+ * @param {string} sessionId
112
+ */
113
+ function ownerOf(sessionId) {
114
+ const attempt = book.attemptForChild(sessionId);
115
+ if (!attempt)
116
+ return null;
117
+ const owner = book.ticket(attempt.ticket_id)?.owner_session_id;
118
+ return typeof owner === 'string' && owner !== '' ? owner : null;
119
+ }
120
+ /**
121
+ * Direct read of the main session that owns this worker. No authorization prompt.
122
+ * @param {string} sessionId
123
+ * @param {{ maxChars?: number }} [limits]
124
+ */
125
+ async function mainHistory(sessionId, limits) {
126
+ const attempt = book.attemptForChild(sessionId);
127
+ if (!attempt)
128
+ return toolError('FORBIDDEN', 'Only the worker for a ticket can read the main session.');
129
+ const owner = book.ticket(attempt.ticket_id)?.owner_session_id;
130
+ if (typeof owner !== 'string' || owner === '')
131
+ return toolError('NOT_FOUND', 'This ticket has no main session.');
132
+ if (!options.snapshot)
133
+ return toolError('UNAVAILABLE', 'The host cannot read the main session log.');
134
+ const events = await options.snapshot(owner);
135
+ return {
136
+ ok: true,
137
+ direct: true,
138
+ ownerSessionId: owner,
139
+ text: renderMainHistory(events, limits),
140
+ };
141
+ }
142
+ /**
143
+ * Transcript excerpt attached to a briefing. A missing log is an empty excerpt.
144
+ * @param {string} ownerSessionId
145
+ */
146
+ async function readMainHistory(ownerSessionId) {
147
+ if (!options.snapshot)
148
+ return '';
149
+ const events = await options.snapshot(ownerSessionId);
150
+ return renderMainHistory(events);
151
+ }
152
+ /**
153
+ * Direct read of a worker session owned by this main bot. No inbox write,
154
+ * and the worker is not notified.
155
+ * @param {string} sessionId
156
+ * @param {{ ticketId?: unknown, maxChars?: number }} [args]
157
+ */
158
+ async function workerHistory(sessionId, args = {}) {
159
+ if (!engine.isBot(sessionId))
160
+ return toolError('FORBIDDEN', 'Only the main session that owns the ticket can read the worker log.');
161
+ const requested = typeof args.ticketId === 'string' ? args.ticketId.trim() : '';
162
+ let ticket = null;
163
+ if (requested !== '') {
164
+ ticket = book.ticket(requested);
165
+ if (!ticket)
166
+ return toolError('NOT_FOUND', 'No such ticket.');
167
+ if (ticket.owner_session_id !== sessionId)
168
+ return toolError('FORBIDDEN', 'Only the main session that owns the ticket can read the worker log.');
169
+ }
170
+ else {
171
+ const rows = openTickets(sessionId);
172
+ if (rows.length === 0)
173
+ return toolError('NOT_FOUND', 'No unfinished ticket.');
174
+ if (rows.length > 1) {
175
+ return {
176
+ ok: true,
177
+ direct: true,
178
+ tickets: rows.map(row => ({ ticketId: row.id, status: row.status })),
179
+ text: '',
180
+ };
181
+ }
182
+ ticket = rows[0] ?? null;
183
+ }
184
+ if (!ticket)
185
+ return toolError('NOT_FOUND', 'No such ticket.');
186
+ const child = typeof ticket.child_session_id === 'string' ? ticket.child_session_id : '';
187
+ if (child === '') {
188
+ return {
189
+ ok: true,
190
+ direct: true,
191
+ ticketId: ticket.id,
192
+ status: ticket.status,
193
+ childSessionId: null,
194
+ text: '',
195
+ };
196
+ }
197
+ if (!options.snapshot)
198
+ return toolError('UNAVAILABLE', 'The host cannot read the worker session log.');
199
+ const events = await options.snapshot(child);
200
+ const limits = Number.isFinite(args.maxChars) ? { maxChars: args.maxChars } : undefined;
201
+ return {
202
+ ok: true,
203
+ direct: true,
204
+ ticketId: ticket.id,
205
+ status: ticket.status,
206
+ childSessionId: child,
207
+ text: renderWorkerHistory(events, limits),
208
+ };
209
+ }
210
+ /**
211
+ * @param {string} owner
212
+ */
213
+ function openTickets(owner) {
214
+ return store.db
215
+ .prepare(`
216
+ SELECT * FROM work_tickets
217
+ WHERE owner_session_id = ? AND status IN (${OPEN_TICKET_STATUSES.map(() => '?').join(',')})
218
+ ORDER BY updated_at DESC
219
+ `)
220
+ .all(owner, ...OPEN_TICKET_STATUSES);
221
+ }
222
+ /**
223
+ * A running slot is free when both the per-bot and global running caps have room.
224
+ * needs_user does not occupy a running slot.
225
+ * @param {string} owner
226
+ */
227
+ function hasSlot(owner) {
228
+ return book.countSlots(owner) < slots.perBot && book.countGlobalSlots() < slots.global;
229
+ }
230
+ /**
231
+ * Queue room is separate from running slots. The combined unfinished cap is
232
+ * slots + queue, so parked needs_user tickets cannot grow without bound.
233
+ * @param {string} owner
234
+ */
235
+ function canQueue(owner) {
236
+ return (book.countQueued(owner) < slots.perBotQueue &&
237
+ book.countGlobalQueued() < slots.globalQueue &&
238
+ book.countActive(owner) < slots.perBot + slots.perBotQueue &&
239
+ book.countGlobal() < slots.global + slots.globalQueue);
240
+ }
241
+ /**
242
+ * @param {string} owner
243
+ * @returns {'start' | 'queue' | 'refuse'}
244
+ */
245
+ function underCombinedCap(owner) {
246
+ return (book.countActive(owner) < slots.perBot + slots.perBotQueue &&
247
+ book.countGlobal() < slots.global + slots.globalQueue);
248
+ }
249
+ /**
250
+ * @param {string} owner
251
+ * @returns {'start' | 'queue' | 'refuse'}
252
+ */
253
+ function decideDispatch(owner) {
254
+ // needs_user does not occupy a running slot, but it still counts as unfinished.
255
+ // A free slot must not admit a new ticket once the combined cap is full.
256
+ if (!underCombinedCap(owner))
257
+ return 'refuse';
258
+ if (hasSlot(owner))
259
+ return 'start';
260
+ if (canQueue(owner))
261
+ return 'queue';
262
+ return 'refuse';
263
+ }
264
+ /**
265
+ * Create the child if needed and flush the current briefing or supply.
266
+ * @param {Record<string, any>} ticket
267
+ */
268
+ async function startReserved(ticket) {
269
+ if (!resident) {
270
+ return { ...publicDispatch(ticket), flush: 'pending', resident: false, message: 'Only a resident host continues' };
271
+ }
272
+ if (starting.has(ticket.id)) {
273
+ return startingPromises.get(ticket.id) ?? publicDispatch(book.ticket(ticket.id) ?? ticket, { flush: 'pending' });
274
+ }
275
+ starting.add(ticket.id);
276
+ const run = (async () => {
277
+ const current = book.ticket(ticket.id);
278
+ if (!current)
279
+ return toolError('NOT_FOUND', 'No such ticket.');
280
+ if (current.status === 'cancelled' || current.status === 'failed' || current.status === 'delivered') {
281
+ return publicDispatch(current);
282
+ }
283
+ const created = await ensureChild(current);
284
+ if (created.error)
285
+ return created.error;
286
+ if (created.rejected)
287
+ return publicDispatch(created.ticket ?? book.ticket(ticket.id) ?? current);
288
+ const liveAfterStart = book.ticket(ticket.id);
289
+ if (!liveAfterStart ||
290
+ liveAfterStart.status === 'cancelled' ||
291
+ liveAfterStart.status === 'failed' ||
292
+ liveAfterStart.status === 'delivered') {
293
+ return publicDispatch(liveAfterStart ?? current);
294
+ }
295
+ const input = await store.write('work', () => {
296
+ const live = book.ticket(ticket.id);
297
+ const liveAttempt = book.attempt(live.active_attempt_id);
298
+ if (liveAttempt?.current_input_id) {
299
+ const existing = book.input(liveAttempt.current_input_id);
300
+ if (existing)
301
+ return existing;
302
+ }
303
+ const text = book.readBriefing(live.briefing_hash);
304
+ return book.insertInput({
305
+ ticketId: live.id,
306
+ attemptId: liveAttempt.id,
307
+ revision: live.briefing_revision,
308
+ kind: 'briefing',
309
+ text,
310
+ });
311
+ });
312
+ if (input.flush_status === 'accepted') {
313
+ return publicDispatch(book.ticket(ticket.id), { flush: 'accepted', nativeMessageId: input.native_message_id });
314
+ }
315
+ const flushed = await pushInput(book, input, deps);
316
+ return publicDispatch(book.ticket(ticket.id), {
317
+ flush: flushWord(flushed),
318
+ nativeMessageId: input.native_message_id,
319
+ });
320
+ })();
321
+ startingPromises.set(ticket.id, run);
322
+ try {
323
+ return await run;
324
+ }
325
+ finally {
326
+ starting.delete(ticket.id);
327
+ startingPromises.delete(ticket.id);
328
+ }
329
+ }
330
+ /**
331
+ * Start waiting tickets that now fit a slot. Awaits only starts this call
332
+ * launched, so a hung createChild from an earlier call cannot deadlock
333
+ * later ticks or cancel. The earlier promise stays owned until it finishes
334
+ * and is then attached or cleaned up.
335
+ */
336
+ async function promoteQueued() {
337
+ if (!resident)
338
+ return { started: [] };
339
+ const started = [];
340
+ const launched = [];
341
+ const launch = (ticket) => {
342
+ if (!ticket?.id || starting.has(ticket.id))
343
+ return;
344
+ started.push(ticket.id);
345
+ launched.push(startReserved(ticket).catch(error => {
346
+ options.log?.('warn', `session-foundations: startReserved failed ticket=${ticket.id} ${error instanceof Error ? error.message : String(error)}`);
347
+ return error;
348
+ }));
349
+ };
350
+ for (const ticket of book.heldStarts())
351
+ launch(ticket);
352
+ for (;;) {
353
+ const claimed = await store.write('work', () => {
354
+ for (const ticket of book.nextPromotable()) {
355
+ if (book.slotHeld(ticket))
356
+ continue;
357
+ if (ticket.status !== 'accepted' && ticket.status !== 'needs_user')
358
+ continue;
359
+ if (!hasSlot(ticket.owner_session_id))
360
+ continue;
361
+ return book.reserveSlot(ticket.id);
362
+ }
363
+ return null;
364
+ });
365
+ if (!claimed)
366
+ break;
367
+ launch(claimed);
368
+ }
369
+ await Promise.all(launched);
370
+ // Join in-flight starts that are still allowed to attach. Do not join a
371
+ // hung createChild after the ticket has already been cancelled, failed, or
372
+ // expired, so a later tick can free the slot and start the next waiter.
373
+ const pending = [...startingPromises.entries()]
374
+ .filter(([id]) => {
375
+ const ticket = book.ticket(id);
376
+ return (ticket != null && ticket.status !== 'failed' && ticket.status !== 'cancelled' && ticket.status !== 'delivered');
377
+ })
378
+ .map(([, promise]) => promise);
379
+ await Promise.all(pending);
380
+ return { started };
381
+ }
382
+ function schedulePromote() {
383
+ void promoteQueued().catch(error => {
384
+ options.log?.('warn', `session-foundations: promoteQueued failed ${error instanceof Error ? error.message : String(error)}`);
385
+ });
386
+ }
91
387
  /**
92
388
  * @param {string} owner
93
389
  * @param {Record<string, unknown>} args
@@ -109,49 +405,46 @@ export function createWorkRuntime(store, engine, options = {}) {
109
405
  const existing = book.byIdempotency(owner, key);
110
406
  if (existing) {
111
407
  if (existing.briefing_hash !== sha256(briefing))
112
- return { error: toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for a different task.') };
408
+ return {
409
+ error: toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for a different task.'),
410
+ };
113
411
  return { replay: existing };
114
412
  }
115
413
  }
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.') };
414
+ const decision = decideDispatch(owner);
415
+ if (decision === 'refuse') {
416
+ return {
417
+ error: toolError('BUDGET', 'Unfinished tickets already hit the host slot and queue limits, so no row was created.'),
418
+ };
118
419
  }
119
- return {
120
- created: book.insertAccepted({
121
- owner,
122
- briefing,
123
- idempotencyKey: key,
124
- correlationId: correlationOf(owner, args.correlationId),
125
- budget,
126
- }),
127
- };
420
+ const created = book.insertAccepted({
421
+ owner,
422
+ briefing,
423
+ idempotencyKey: key,
424
+ correlationId: correlationOf(owner, args.correlationId),
425
+ budget,
426
+ });
427
+ if (decision === 'start')
428
+ book.reserveSlot(created.ticket.id);
429
+ return { created, start: decision === 'start' };
128
430
  });
129
431
  if (prepared.error)
130
432
  return prepared.error;
131
433
  if (prepared.replay)
132
434
  return publicDispatch(prepared.replay, { replayed: true });
133
435
  const ticket = prepared.created.ticket;
436
+ if (!prepared.start) {
437
+ return publicDispatch(book.ticket(ticket.id), {
438
+ flush: 'pending',
439
+ queued: true,
440
+ childSessionId: null,
441
+ nativeMessageId: null,
442
+ });
443
+ }
134
444
  if (!resident) {
135
445
  return { ...publicDispatch(ticket), flush: 'pending', resident: false, message: 'Only a resident host continues' };
136
446
  }
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 });
447
+ return startReserved(ticket);
155
448
  }
156
449
  /**
157
450
  * @param {string} owner
@@ -182,13 +475,35 @@ export function createWorkRuntime(store, engine, options = {}) {
182
475
  if (found.error)
183
476
  return found.error;
184
477
  const expected = revisionOf(args.expectedRevision);
185
- const advanced = await store.write('work', () => book.advanceGeneration(found.ticket.id, expected, kind, text));
478
+ const advanced = await store.write('work', () => {
479
+ const result = book.advanceGeneration(found.ticket.id, expected, kind, text);
480
+ if (result.error)
481
+ return result;
482
+ // A supply into needs_user must take a running slot. If none is free, keep
483
+ // the input durable and start it when promoteQueued reserves one.
484
+ if (kind === 'supply' && result.ticket.status === 'needs_user' && !hasSlot(owner)) {
485
+ return { ...result, queued: true };
486
+ }
487
+ if (kind === 'supply' && result.ticket.status === 'needs_user')
488
+ book.reserveSlot(result.ticket.id);
489
+ return result;
490
+ });
186
491
  if (advanced.error)
187
492
  return toolError(advanced.error, advanced.message ?? 'Changing the generation failed.');
493
+ if (advanced.queued) {
494
+ return publicDispatch(book.ticket(found.ticket.id), {
495
+ flush: 'pending',
496
+ queued: true,
497
+ nativeMessageId: advanced.input.native_message_id,
498
+ });
499
+ }
188
500
  if (!resident)
189
501
  return { ...publicDispatch(advanced.ticket), flush: 'pending', message: 'Only a resident host continues' };
190
502
  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 });
503
+ return publicDispatch(book.ticket(found.ticket.id), {
504
+ flush: flushWord(flushed),
505
+ nativeMessageId: advanced.input.native_message_id,
506
+ });
192
507
  }
193
508
  /**
194
509
  * @param {string} owner
@@ -206,13 +521,21 @@ export function createWorkRuntime(store, engine, options = {}) {
206
521
  if (cancelled.error)
207
522
  return toolError(cancelled.error, cancelled.message ?? 'Cancel failed.');
208
523
  const child = cancelled.ticket.child_session_id;
524
+ if (child)
525
+ closeBudgetWait(child);
209
526
  if (resident && child && options.cancel) {
210
- await options.cancel(child, { keepInbox: note !== '' });
527
+ await options.cancel(child, { keepInbox: note !== '', reason: 'ticket-cancel' });
211
528
  }
212
529
  if (resident && note !== '' && cancelled.input)
213
530
  await pushInput(book, cancelled.input, deps);
214
531
  await removeUnclaimed(owner, cancelled.ticket.id);
215
- return { ok: true, ticketId: cancelled.ticket.id, ticketStatus: cancelled.ticket.status, already: cancelled.already === true };
532
+ schedulePromote();
533
+ return {
534
+ ok: true,
535
+ ticketId: cancelled.ticket.id,
536
+ ticketStatus: cancelled.ticket.status,
537
+ already: cancelled.already === true,
538
+ };
216
539
  }
217
540
  /**
218
541
  * @param {string} owner
@@ -224,33 +547,99 @@ export function createWorkRuntime(store, engine, options = {}) {
224
547
  const found = resolveTicket(owner, args.ticketId, null);
225
548
  if (found.error)
226
549
  return found.error;
550
+ // The model cannot kill a worker by refusing budget. A deny adds another
551
+ // full slice. Grant count is not a reason to stop.
552
+ let refusalIgnored = false;
227
553
  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 };
554
+ refusalIgnored = true;
555
+ args = {
556
+ ticketId: found.ticket.id,
557
+ maxTokens: limits.workerMaxTokens,
558
+ wallMs: limits.workerWallMs,
559
+ };
238
560
  }
561
+ const live = found.ticket.child_session_id ? arms.get(found.ticket.child_session_id) : null;
562
+ if (live?.role === 'worker')
563
+ saveQuota(found.ticket.child_session_id, live);
239
564
  const added = await store.write('work', () => book.extendBudget(found.ticket.id, {
240
565
  wallMs: typeof args.wallMs === 'number' ? args.wallMs : undefined,
241
566
  maxTokens: typeof args.maxTokens === 'number' ? args.maxTokens : undefined,
242
567
  }, { wallMs: limits.workerWallMs, maxTokens: limits.workerMaxTokens }));
243
- if (added.error)
244
- return toolError(added.error, added.message ?? 'No budget was added.');
568
+ if (added.error) {
569
+ return {
570
+ ...toolError(added.error, added.message ?? 'No budget was added.'),
571
+ ...quotaFeedback(found.ticket.id),
572
+ ...(refusalIgnored ? { denied: false } : {}),
573
+ };
574
+ }
245
575
  const child = added.ticket.child_session_id;
246
576
  if (child)
247
577
  releaseArm(child, added.budget);
578
+ let resumedInput = null;
579
+ const quota = quotaOf(added.ticket.id);
580
+ if (child &&
581
+ !arms.has(child) &&
582
+ quota?.waiting &&
583
+ options.resumePaused &&
584
+ resident &&
585
+ options.push &&
586
+ ['started', 'enqueued'].includes(added.ticket.status) &&
587
+ added.budget.maxTokens > quota.tokens &&
588
+ added.budget.wallMs > quota.activeMs &&
589
+ !(await isChildLive(child))) {
590
+ resumedInput = await store.write('work', () => {
591
+ const fresh = book.ticket(added.ticket.id);
592
+ if (!fresh ||
593
+ !['started', 'enqueued'].includes(fresh.status) ||
594
+ fresh.active_attempt_id !== added.ticket.active_attempt_id)
595
+ return null;
596
+ const current = quotaOf(fresh.id);
597
+ if (!current?.waiting)
598
+ return null;
599
+ if (current.resumeInputId)
600
+ return book.input(current.resumeInputId);
601
+ // A detached native turn ended (possibly disposed). Advance only the
602
+ // input generation, not the attempt/fence/session, so replay of that
603
+ // old turn/end cannot finalize a new pending result.
604
+ store.db
605
+ .prepare('UPDATE work_tickets SET revision = revision + 1, briefing_revision = briefing_revision + 1, updated_at = ? WHERE id = ?')
606
+ .run(now().toISOString(), fresh.id);
607
+ const input = book.insertInput({
608
+ ticketId: fresh.id,
609
+ attemptId: fresh.active_attempt_id,
610
+ revision: fresh.briefing_revision + 1,
611
+ kind: 'supply',
612
+ text: '[foundations:budget-resume] Budget was explicitly granted. Continue the SAME ticket from durable history; do not repeat completed effects. Inspect current state before continuing. This is a new host turn after detachment, not a new task.',
613
+ });
614
+ writeQuota(fresh.id, { ...current, resumeInputId: input.id });
615
+ return input;
616
+ });
617
+ if (resumedInput)
618
+ await pushInput(book, resumedInput, deps);
619
+ }
620
+ const feedback = quotaFeedback(added.ticket.id);
248
621
  return {
249
622
  ok: true,
250
623
  ticketId: added.ticket.id,
251
- ticketStatus: added.ticket.status,
624
+ ticketStatus: book.ticket(added.ticket.id)?.status ?? added.ticket.status,
625
+ briefingRevision: book.ticket(added.ticket.id)?.briefing_revision,
252
626
  wallMs: added.budget.wallMs,
253
627
  maxTokens: added.budget.maxTokens,
628
+ ...feedback,
629
+ ...(refusalIgnored
630
+ ? {
631
+ denied: false,
632
+ refusalIgnored: true,
633
+ message: feedback.waitingBudget
634
+ ? 'Budget refusal was not applied. Another full slice was granted, and the worker is still paused because usage is past that grant. Grant another slice. Do not cancel unless the user asks to stop. Do not take over the task.'
635
+ : 'Budget refusal was not applied. Another full slice was granted and the worker continues. Do not take over the task.',
636
+ }
637
+ : {}),
638
+ continuation: resumedInput
639
+ ? 'same-session-new-turn'
640
+ : child && arms.has(child)
641
+ ? 'same-turn'
642
+ : 'awaiting-host-turn',
254
643
  };
255
644
  }
256
645
  async function retry(owner, args) {
@@ -260,16 +649,27 @@ export function createWorkRuntime(store, engine, options = {}) {
260
649
  if (found.error)
261
650
  return found.error;
262
651
  const expected = revisionOf(args.expectedRevision);
263
- const retried = await store.write('work', () => book.insertRetry(found.ticket.id, expected));
652
+ const retried = await store.write('work', () => {
653
+ const result = book.insertRetry(found.ticket.id, expected);
654
+ if (result.error)
655
+ return result;
656
+ if (!hasSlot(owner))
657
+ return { ...result, queued: true };
658
+ book.reserveSlot(result.ticket.id);
659
+ return result;
660
+ });
264
661
  if (retried.error)
265
662
  return toolError(retried.error, retried.message ?? 'Retry failed.');
663
+ if (retried.queued) {
664
+ return publicDispatch(book.ticket(retried.ticket.id), {
665
+ flush: 'pending',
666
+ queued: true,
667
+ nativeMessageId: retried.input?.native_message_id ?? null,
668
+ });
669
+ }
266
670
  if (!resident)
267
671
  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 });
672
+ return startReserved(book.ticket(retried.ticket.id));
273
673
  }
274
674
  /**
275
675
  * @param {string} owner
@@ -278,13 +678,15 @@ export function createWorkRuntime(store, engine, options = {}) {
278
678
  async function publish(owner, args) {
279
679
  if (!engine.isBot(owner))
280
680
  return toolError('FORBIDDEN', 'An ordinary session cannot publish.');
281
- if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
681
+ const resultEventId = args.resultEventId;
682
+ if (typeof resultEventId !== 'string' || resultEventId === '')
282
683
  return toolError('VALIDATION', 'resultEventId is required.');
283
- if (typeof args.text !== 'string' || args.text.trim() === '' || args.text.length > 16000)
684
+ const text = args.text;
685
+ if (typeof text !== 'string' || text.trim() === '' || text.length > 16000)
284
686
  return toolError('VALIDATION', 'text is empty or too long.');
285
687
  const turn = args.turn == null ? null : String(args.turn);
286
688
  const saved = await store.write('work', () => {
287
- const event = book.event(args.resultEventId);
689
+ const event = book.event(resultEventId);
288
690
  if (!event)
289
691
  return toolError('NOT_FOUND', 'No such result.');
290
692
  const ticket = book.ticket(event.ticket_id);
@@ -309,14 +711,14 @@ export function createWorkRuntime(store, engine, options = {}) {
309
711
  attemptId: attempt.id,
310
712
  fencingToken: attempt.fencing_token,
311
713
  briefingRevision: event.briefing_revision,
312
- text: args.text,
714
+ text,
313
715
  turn,
314
716
  });
315
717
  return {
316
718
  ok: true,
317
719
  publishId: delivery.row.publish_id,
318
720
  already: delivery.already,
319
- text: args.text,
721
+ text,
320
722
  status: delivery.row.status,
321
723
  ticketId: ticket.id,
322
724
  };
@@ -330,10 +732,11 @@ export function createWorkRuntime(store, engine, options = {}) {
330
732
  async function reject(owner, args) {
331
733
  if (!engine.isBot(owner))
332
734
  return toolError('FORBIDDEN', 'An ordinary session cannot reject a candidate.');
333
- if (typeof args.resultEventId !== 'string' || args.resultEventId === '')
735
+ const resultEventId = args.resultEventId;
736
+ if (typeof resultEventId !== 'string' || resultEventId === '')
334
737
  return toolError('VALIDATION', 'resultEventId is required.');
335
738
  return store.write('work', () => {
336
- const event = book.event(args.resultEventId);
739
+ const event = book.event(resultEventId);
337
740
  if (!event)
338
741
  return toolError('NOT_FOUND', 'No such result.');
339
742
  const ticket = book.ticket(event.ticket_id);
@@ -342,10 +745,12 @@ export function createWorkRuntime(store, engine, options = {}) {
342
745
  if (event.kind !== 'result' || event.apply_status !== 'applied')
343
746
  return toolError('VALIDATION', 'There is no candidate to reject yet.');
344
747
  book.setReview(ticket.id, 'rejected');
345
- store.db.prepare(`
748
+ store.db
749
+ .prepare(`
346
750
  UPDATE user_deliveries SET status = 'abandoned'
347
751
  WHERE result_event_id = ? AND status = 'intent'
348
- `).run(event.event_id);
752
+ `)
753
+ .run(event.event_id);
349
754
  return { ok: true, reviewStatus: 'rejected', ticketId: ticket.id };
350
755
  });
351
756
  }
@@ -364,20 +769,20 @@ export function createWorkRuntime(store, engine, options = {}) {
364
769
  if (!attempt)
365
770
  return toolError('FORBIDDEN', 'This session is not a worker, so it cannot report.');
366
771
  const bound = turns.get(sessionId);
367
- const input = bound ? book.inputByNative(bound.messageId) : null;
772
+ if (!bound)
773
+ return toolError('NOT_FOUND', 'This round has no matching briefing.');
774
+ const input = book.inputByNative(bound.messageId);
368
775
  if (!input || input.attempt_id !== attempt.id)
369
776
  return toolError('NOT_FOUND', 'This round has no matching briefing.');
370
777
  const ticket = book.ticket(input.ticket_id);
371
778
  if (!ticket)
372
779
  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');
780
+ const current = ticket.active_attempt_id === attempt.id &&
781
+ ticket.briefing_revision === input.briefing_revision &&
782
+ ticket.status !== 'cancelled' &&
783
+ ticket.status !== 'failed' &&
784
+ ticket.status !== 'delivered';
785
+ const applyStatus = current && (kind === 'progress' || kind === 'artifact') ? 'applied' : current ? 'pending_completion' : 'stale';
381
786
  const saved = await store.write('work', () => book.insertEvent({
382
787
  ticketId: ticket.id,
383
788
  attemptId: attempt.id,
@@ -401,20 +806,148 @@ export function createWorkRuntime(store, engine, options = {}) {
401
806
  async function tick() {
402
807
  await reconcileInputs(book, deps);
403
808
  await reconcileNotices(book, deps);
404
- await store.write('work', () => { book.expireQuiet(); });
809
+ await renewLiveLeases();
810
+ const expired = await store.write('work', () => book.expireQuiet());
811
+ await stopExpiredChildren(expired);
405
812
  for (const owner of book.ownerIds()) {
406
813
  if (engine.isBot(owner))
407
814
  await admit(owner);
408
815
  }
409
- for (const child of book.childIds())
816
+ for (const child of book.childIdsForReconcile())
410
817
  await reconcileChild(child);
411
- for (const owner of book.ownerIds())
818
+ for (const owner of book.ownerIdsForReconcile())
412
819
  await reconcileOwner(owner);
820
+ await promoteQueued();
821
+ }
822
+ /**
823
+ * Renew the lease of a started worker that is still alive, so a silent
824
+ * model or tool turn longer than leaseMs does not false-expire it.
825
+ */
826
+ async function renewLiveLeases() {
827
+ const renewals = [];
828
+ for (const child of book.childIdsForReconcile()) {
829
+ const attempt = book.attemptForChild(child);
830
+ if (!attempt || (attempt.status !== 'started' && attempt.status !== 'enqueued'))
831
+ continue;
832
+ if (!(await isChildLive(child)))
833
+ continue;
834
+ renewals.push(attempt.id);
835
+ }
836
+ if (renewals.length === 0)
837
+ return;
838
+ await store.write('work', () => {
839
+ const until = new Date(now().getTime() + limits.leaseMs).toISOString();
840
+ for (const id of renewals) {
841
+ const attempt = book.attempt(id);
842
+ if (!attempt || (attempt.status !== 'started' && attempt.status !== 'enqueued'))
843
+ continue;
844
+ book.touchLease(id, until, typeof attempt.lease_observed_seq === 'number' ? attempt.lease_observed_seq : null);
845
+ }
846
+ });
847
+ }
848
+ /**
849
+ * @param {string} sessionId
850
+ */
851
+ async function isChildLive(sessionId) {
852
+ if (options.childPresent) {
853
+ try {
854
+ if (!(await options.childPresent(sessionId)))
855
+ return false;
856
+ }
857
+ catch {
858
+ return false;
859
+ }
860
+ }
861
+ else if (!options.snapshot) {
862
+ return false;
863
+ }
864
+ if (!options.snapshot)
865
+ return true;
866
+ try {
867
+ const events = await options.snapshot(sessionId);
868
+ return !latestTurnEnded(events);
869
+ }
870
+ catch {
871
+ return false;
872
+ }
873
+ }
874
+ /**
875
+ * @param {Array<{ ticketId: string, reason: string, childSessionId?: string | null }>} expired
876
+ */
877
+ async function stopExpiredChildren(expired) {
878
+ if (!Array.isArray(expired) || expired.length === 0)
879
+ return;
880
+ for (const item of expired) {
881
+ const child = item.childSessionId;
882
+ if (!child || !options.cancel)
883
+ continue;
884
+ const state = arms.get(child);
885
+ if (state) {
886
+ state.closing = true;
887
+ state.clear?.();
888
+ }
889
+ try {
890
+ await options.cancel(child, { keepInbox: false, reason: `worker-expire:${item.reason}` });
891
+ }
892
+ catch {
893
+ /* best-effort stop; the ledger already failed the ticket */
894
+ }
895
+ }
896
+ }
897
+ /**
898
+ * @param {Record<string, any>} event
899
+ */
900
+ function eventText(event) {
901
+ if (typeof event.text === 'string' && event.text !== '')
902
+ return event.text;
903
+ return book.detail(event.ticket_id)?.events?.find(item => item.event_id === event.event_id)?.text ?? '';
904
+ }
905
+ /**
906
+ * @param {Record<string, any>} event
907
+ */
908
+ function isExtensionAsk(event) {
909
+ return event.kind === 'progress' && eventText(event).startsWith('[foundations:extension]');
910
+ }
911
+ /**
912
+ * Extension asks are decision-required: they may starve-bypass notice-open,
913
+ * user-pending, and delivery-open. Ordinary progress does not.
914
+ * @param {Record<string, any>} event
915
+ */
916
+ function isDecisionRequiredEvent(event) {
917
+ return event.kind === 'question' || event.kind === 'result' || event.kind === 'failure' || isExtensionAsk(event);
918
+ }
919
+ /**
920
+ * @param {Record<string, any>} ticket
921
+ */
922
+ function isFinishedTicket(ticket) {
923
+ const status = String(ticket.status);
924
+ return status === 'failed' || status === 'cancelled' || status === 'delivered';
413
925
  }
414
926
  /**
415
927
  * @param {string} owner
416
928
  */
417
929
  async function admit(owner) {
930
+ if (admitting.has(owner))
931
+ return { admitted: false, reason: 'admission-inflight' };
932
+ admitting.add(owner);
933
+ try {
934
+ return await admitOnce(owner);
935
+ }
936
+ finally {
937
+ admitting.delete(owner);
938
+ }
939
+ }
940
+ function currentExtension(event) {
941
+ const ticket = book.ticket(event.ticket_id);
942
+ if (!ticket || !['started', 'enqueued'].includes(ticket.status))
943
+ return false;
944
+ const budget = JSON.parse(ticket.budget_json);
945
+ if (budget.extension !== 'open')
946
+ return false;
947
+ const latest = book.detail(ticket.id)?.events.filter(isExtensionAsk).at(-1);
948
+ return latest?.event_id === event.event_id;
949
+ }
950
+ async function admitOnce(owner) {
418
951
  const wake = book.pendingWake(owner);
419
952
  if (wake.events.length === 0 && wake.cancels.length === 0)
420
953
  return { admitted: false, reason: 'empty' };
@@ -427,14 +960,17 @@ export function createWorkRuntime(store, engine, options = {}) {
427
960
  }
428
961
  const terminalTimes = [];
429
962
  for (const event of wake.events) {
430
- if ((event.kind === 'question' || event.kind === 'result' || event.kind === 'failure') && event.apply_status === 'applied') {
963
+ if (event.apply_status === 'applied' &&
964
+ isDecisionRequiredEvent(event) &&
965
+ (!isExtensionAsk(event) || currentExtension(event))) {
431
966
  terminalTimes.push(Date.parse(event.created_at));
432
967
  }
433
968
  }
434
969
  for (const ticket of wake.cancels)
435
970
  terminalTimes.push(Date.parse(ticket.updated_at));
971
+ const urgent = wake.events.filter(event => isExtensionAsk(event) && currentExtension(event));
436
972
  const heldUntil = holds.get(owner);
437
- if (heldUntil != null && now().getTime() < heldUntil)
973
+ if (!urgent.length && heldUntil != null && now().getTime() < heldUntil)
438
974
  return { admitted: false, reason: 'interrupt-hold' };
439
975
  if (heldUntil != null)
440
976
  holds.delete(owner);
@@ -449,21 +985,24 @@ export function createWorkRuntime(store, engine, options = {}) {
449
985
  terminalSince: terminalTimes.length === 0 ? null : Math.min(...terminalTimes),
450
986
  starveMs: limits.starveMs,
451
987
  });
452
- if (!decision.admit)
988
+ if (!urgent.length && !decision.admit)
453
989
  return { admitted: false, ...decision };
454
990
  const nativeId = randomUUID();
455
991
  const items = [];
456
- for (const event of wake.events) {
992
+ for (const event of urgent.length ? urgent : wake.events) {
457
993
  const ticket = book.ticket(event.ticket_id);
458
994
  if (!ticket)
459
995
  continue;
996
+ // A grant cannot revive a finished ticket, so drop a stale extension ask.
997
+ if (isExtensionAsk(event) && !currentExtension(event))
998
+ continue;
460
999
  items.push({
461
1000
  ticketId: ticket.id,
462
1001
  eventId: event.event_id,
463
1002
  line: noticeLine(ticket, event),
464
1003
  });
465
1004
  }
466
- for (const ticket of wake.cancels) {
1005
+ for (const ticket of urgent.length ? [] : wake.cancels) {
467
1006
  items.push({
468
1007
  ticketId: ticket.id,
469
1008
  eventId: `cancel:${ticket.cancel_requested_revision}`,
@@ -472,9 +1011,25 @@ export function createWorkRuntime(store, engine, options = {}) {
472
1011
  }
473
1012
  if (items.length === 0)
474
1013
  return { admitted: false, reason: 'empty' };
475
- await store.write('work', () => { book.insertNotices(nativeId, owner, items); });
1014
+ await store.write('work', () => {
1015
+ // Revalidate after the write queue: a grant/cancel may have raced admission.
1016
+ const valid = items.filter(item => item.eventId.startsWith('cancel:') ||
1017
+ (!book.event(item.eventId)?.notice_id &&
1018
+ (!isExtensionAsk(book.event(item.eventId) ?? {}) || currentExtension(book.event(item.eventId)))));
1019
+ items.splice(0, items.length, ...valid);
1020
+ if (items.length)
1021
+ book.insertNotices(nativeId, owner, items);
1022
+ });
1023
+ if (!items.length)
1024
+ return { admitted: false, reason: 'superseded' };
476
1025
  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 };
1026
+ return {
1027
+ ...decision,
1028
+ admitted: true,
1029
+ reason: urgent.length ? 'budget-decision' : decision.reason,
1030
+ nativeMessageId: nativeId,
1031
+ flush: flushWord(flushed),
1032
+ };
478
1033
  }
479
1034
  /**
480
1035
  * Progress stays a status line. Result and failure carry the body so the
@@ -483,9 +1038,12 @@ export function createWorkRuntime(store, engine, options = {}) {
483
1038
  * @param {Record<string, any>} event
484
1039
  */
485
1040
  function noticeLine(ticket, event) {
486
- const head = `${ticket.id} ${ticket.status} (${LABEL[ticket.status] ?? ticket.status}) rev ${ticket.briefing_revision} ${event.kind}`;
1041
+ const status = String(ticket.status);
1042
+ const head = `${ticket.id} ${status} (${LABEL[status] ?? status}) rev ${ticket.briefing_revision} ${event.kind}`;
487
1043
  const text = book.detail(ticket.id)?.events?.find(item => item.event_id === event.event_id)?.text ?? '';
488
1044
  if (text.startsWith('[foundations:extension]')) {
1045
+ if (isFinishedTicket(ticket))
1046
+ return head;
489
1047
  return [head, `eventId: ${event.event_id}`, text].join('\n');
490
1048
  }
491
1049
  if (event.kind !== 'result' && event.kind !== 'failure')
@@ -493,7 +1051,7 @@ export function createWorkRuntime(store, engine, options = {}) {
493
1051
  const body = text.length > 8000 ? `${text.slice(0, 8000)}\n…` : text;
494
1052
  const ask = event.kind === 'result'
495
1053
  ? '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.';
1054
+ : 'This is a failed result. Tell the user the reason in your own words, then stop. Do not only restate the status, and do not ask the user to paste the body back. Do not take over the task, and do not dispatch a replacement unless the user explicitly asks.';
497
1055
  return [head, `eventId: ${event.event_id}`, ask, '---', body].join('\n');
498
1056
  }
499
1057
  /**
@@ -505,8 +1063,14 @@ export function createWorkRuntime(store, engine, options = {}) {
505
1063
  return;
506
1064
  noteBudget(sessionId, event);
507
1065
  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 });
1066
+ if ((event.type === 'user/message' || event.type === 'agent/inbox/claimed') &&
1067
+ nativeId &&
1068
+ book.inputByNative(nativeId)) {
1069
+ turns.set(sessionId, {
1070
+ messageId: nativeId,
1071
+ turn: event.data?.turn ?? null,
1072
+ seq: typeof event.seq === 'number' ? event.seq : null,
1073
+ });
510
1074
  }
511
1075
  if (event.type === 'user/message' && engine.isBot(sessionId))
512
1076
  holds.delete(sessionId);
@@ -524,8 +1088,15 @@ export function createWorkRuntime(store, engine, options = {}) {
524
1088
  wakeTurns.set(`${sessionId}:${event.data.turn}`, nativeId);
525
1089
  }
526
1090
  }
527
- if (event.type === 'turn/end')
1091
+ if (event.type === 'turn/end') {
1092
+ if (isWorkerSession(sessionId) && event.data?.reason?.reason?.kind === 'user') {
1093
+ const attempt = book.attemptForChild(sessionId);
1094
+ if (attempt)
1095
+ book.markCancelled(attempt.ticket_id, null, 'Worker cancelled by user.');
1096
+ closeBudgetWait(sessionId);
1097
+ }
528
1098
  applyTurnEnd(sessionId, event.data?.turn ?? null, reasonKindOf(event));
1099
+ }
529
1100
  if (isWorkerSession(sessionId) && typeof event.seq === 'number') {
530
1101
  const attempt = book.attemptForChild(sessionId);
531
1102
  if (attempt && (attempt.status === 'started' || attempt.status === 'enqueued')) {
@@ -542,6 +1113,8 @@ export function createWorkRuntime(store, engine, options = {}) {
542
1113
  if (book.inputByNative(messageId))
543
1114
  turns.set(sessionId, { messageId, turn, seq: null });
544
1115
  book.setNoticeObserve(messageId, 'claimed');
1116
+ if (turn != null && book.noticeIds(sessionId).has(messageId))
1117
+ wakeTurns.set(`${sessionId}:${turn}`, messageId);
545
1118
  }
546
1119
  /**
547
1120
  * @param {Record<string, any>} ticket
@@ -552,21 +1125,39 @@ export function createWorkRuntime(store, engine, options = {}) {
552
1125
  if (!options.createChild)
553
1126
  return { error: publicDispatch(ticket, { flush: 'pending' }) };
554
1127
  const sessionId = `worker-${ticket.id}`;
1128
+ const attemptId = ticket.active_attempt_id;
1129
+ const fencingToken = book.attempt(attemptId)?.fencing_token ?? 1;
555
1130
  try {
556
1131
  const created = await options.createChild({
557
1132
  sessionId,
558
1133
  ownerSessionId: ticket.owner_session_id,
559
1134
  ticketId: ticket.id,
560
- fencingToken: book.attempt(ticket.active_attempt_id)?.fencing_token ?? 1,
1135
+ fencingToken,
561
1136
  });
562
1137
  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 };
1138
+ const saved = await store.write('work', () => book.setChildIfEmpty(ticket.id, child, { attemptId, fencingToken }));
1139
+ if (!saved?.attached) {
1140
+ try {
1141
+ if (options.cancel)
1142
+ await options.cancel(child, { keepInbox: false, reason: 'stale-start' });
1143
+ }
1144
+ catch {
1145
+ /* best-effort cleanup of a late or fenced child */
1146
+ }
1147
+ return { rejected: true, ticket: saved?.ticket ?? book.ticket(ticket.id) ?? ticket };
1148
+ }
1149
+ engine.ensureSession(child, {
1150
+ parentSessionId: typeof ticket.owner_session_id === 'string' ? ticket.owner_session_id : null,
1151
+ });
1152
+ return { ticket: saved.ticket };
566
1153
  }
567
1154
  catch {
568
1155
  return {
569
- error: publicDispatch(book.ticket(ticket.id), { flush: 'pending', childSessionId: null, nativeMessageId: null }),
1156
+ error: publicDispatch(book.ticket(ticket.id), {
1157
+ flush: 'pending',
1158
+ childSessionId: null,
1159
+ nativeMessageId: null,
1160
+ }),
570
1161
  };
571
1162
  }
572
1163
  }
@@ -582,11 +1173,13 @@ export function createWorkRuntime(store, engine, options = {}) {
582
1173
  return { error: toolError('NOT_FOUND', 'No such ticket.') };
583
1174
  return { ticket };
584
1175
  }
585
- const rows = store.db.prepare(`
1176
+ const rows = store.db
1177
+ .prepare(`
586
1178
  SELECT * FROM work_tickets WHERE owner_session_id = ?
587
1179
  ${statuses ? `AND status IN (${statuses.map(() => '?').join(',')})` : ''}
588
1180
  ORDER BY updated_at DESC
589
- `).all(owner, ...(statuses ?? []));
1181
+ `)
1182
+ .all(owner, ...(statuses ?? []));
590
1183
  if (rows.length !== 1)
591
1184
  return { error: toolError('VALIDATION', 'Name the ticket.') };
592
1185
  return { ticket: rows[0] };
@@ -595,7 +1188,7 @@ export function createWorkRuntime(store, engine, options = {}) {
595
1188
  * @param {unknown} value
596
1189
  */
597
1190
  function revisionOf(value) {
598
- return Number.isInteger(value) ? value : null;
1191
+ return typeof value === 'number' && Number.isInteger(value) ? value : null;
599
1192
  }
600
1193
  /**
601
1194
  * @param {string} owner
@@ -604,9 +1197,11 @@ export function createWorkRuntime(store, engine, options = {}) {
604
1197
  function correlationOf(owner, value) {
605
1198
  if (typeof value !== 'string' || value === '')
606
1199
  return '';
607
- const found = store.db.prepare(`
1200
+ const found = store.db
1201
+ .prepare(`
608
1202
  SELECT 1 AS ok FROM deliveries WHERE id = ? AND (sender_session_id = ? OR target_session_id = ?)
609
- `).get(value, owner, owner);
1203
+ `)
1204
+ .get(value, owner, owner);
610
1205
  return found ? value : '';
611
1206
  }
612
1207
  /**
@@ -617,9 +1212,12 @@ export function createWorkRuntime(store, engine, options = {}) {
617
1212
  const fresh = book.ticket(ticket.id) ?? ticket;
618
1213
  const attempt = fresh.active_attempt_id ? book.attempt(fresh.active_attempt_id) : null;
619
1214
  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'));
1215
+ const flush = extra.flush ??
1216
+ (input?.flush_status === 'accepted'
1217
+ ? 'accepted'
1218
+ : input?.flush_status === 'ambiguous' || input?.flush_status === 'flushing'
1219
+ ? 'ambiguous'
1220
+ : 'pending');
623
1221
  const dispatched = flush === 'accepted' || (fresh.status !== 'accepted' && fresh.status !== 'failed' && fresh.status !== 'cancelled');
624
1222
  return {
625
1223
  ok: true,
@@ -628,11 +1226,13 @@ export function createWorkRuntime(store, engine, options = {}) {
628
1226
  briefingRevision: fresh.briefing_revision,
629
1227
  status: dispatched && flush === 'accepted' ? 'enqueued' : 'accepted',
630
1228
  ticketStatus: fresh.status,
1229
+ ...quotaFeedback(fresh.id),
631
1230
  childSessionId: extra.childSessionId === null ? null : fresh.child_session_id,
632
1231
  fencingToken: attempt?.fencing_token ?? null,
633
1232
  nativeMessageId: extra.nativeMessageId === undefined ? (input?.native_message_id ?? null) : extra.nativeMessageId,
634
1233
  flush,
635
1234
  replayed: extra.replayed === true,
1235
+ queued: extra.queued === true || (fresh.status === 'accepted' && !book.slotHeld(fresh)),
636
1236
  };
637
1237
  }
638
1238
  function project(ticket) {
@@ -671,6 +1271,7 @@ export function createWorkRuntime(store, engine, options = {}) {
671
1271
  const found = book.detail(input.ticket_id);
672
1272
  if (!found)
673
1273
  return;
1274
+ let released = false;
674
1275
  for (const event of found.events) {
675
1276
  if (event.attempt_id !== input.attempt_id)
676
1277
  continue;
@@ -679,7 +1280,10 @@ export function createWorkRuntime(store, engine, options = {}) {
679
1280
  if (event.apply_status !== 'pending_completion')
680
1281
  continue;
681
1282
  book.applyTerminal(event.event_id, reason);
1283
+ released = true;
682
1284
  }
1285
+ if (released)
1286
+ void promoteQueued().catch(() => { });
683
1287
  }
684
1288
  /**
685
1289
  * @param {string} sessionId
@@ -710,7 +1314,7 @@ export function createWorkRuntime(store, engine, options = {}) {
710
1314
  const nativeId = byTurn.get(event.data?.turn);
711
1315
  if (!nativeId)
712
1316
  continue;
713
- turns.set(sessionId, { messageId: nativeId, turn: event.data?.turn ?? null, seq: null });
1317
+ // Historical turn endings must not overwrite the latest live input binding.
714
1318
  const input = book.inputByNative(nativeId);
715
1319
  if (!input)
716
1320
  continue;
@@ -735,15 +1339,21 @@ export function createWorkRuntime(store, engine, options = {}) {
735
1339
  for (const event of events) {
736
1340
  const name = event.data?.name ?? event.data?.toolName;
737
1341
  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') {
1342
+ if ((event.type === 'tool/call' || event.type === 'tool/result') &&
1343
+ name === 'foundations_publish' &&
1344
+ typeof args?.resultEventId === 'string') {
739
1345
  waiting = args.resultEventId;
740
1346
  }
741
1347
  if (event.type === 'user/message' && notices.has(messageIdOf(event)))
742
1348
  continue;
743
1349
  if (event.type === 'assistant/message' && waiting && typeof event.seq === 'number') {
744
- const ticketRows = book.ownerIds().includes(owner) ? store.db.prepare(`
1350
+ const ticketRows = book.ownerIds().includes(owner)
1351
+ ? store.db
1352
+ .prepare(`
745
1353
  SELECT * FROM user_deliveries WHERE owner_session_id = ? AND result_event_id = ? AND status = 'intent'
746
- `).get(owner, waiting) : null;
1354
+ `)
1355
+ .get(owner, waiting)
1356
+ : null;
747
1357
  if (ticketRows)
748
1358
  book.bindDelivery(ticketRows.publish_id, event.seq);
749
1359
  waiting = null;
@@ -766,7 +1376,9 @@ export function createWorkRuntime(store, engine, options = {}) {
766
1376
  * @param {string} ticketId
767
1377
  */
768
1378
  async function removeUnclaimed(owner, ticketId) {
769
- const rows = store.db.prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`).all(ticketId);
1379
+ const rows = store.db
1380
+ .prepare(`SELECT * FROM work_notices WHERE ticket_id = ? AND observe_status = 'none'`)
1381
+ .all(ticketId);
770
1382
  const seen = new Set();
771
1383
  for (const row of rows) {
772
1384
  if (seen.has(row.native_message_id))
@@ -790,7 +1402,8 @@ export function createWorkRuntime(store, engine, options = {}) {
790
1402
  return;
791
1403
  if (role === 'main' && (event.type === 'tool/call' || event.type === 'tool/result')) {
792
1404
  const name = event.data?.name ?? event.data?.toolName;
793
- if (name === 'foundations_dispatch' || (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
1405
+ if (name === 'foundations_dispatch' ||
1406
+ (typeof name === 'string' && name !== '' && !name.startsWith('foundations_'))) {
794
1407
  tightenMain(sessionId);
795
1408
  }
796
1409
  }
@@ -799,6 +1412,13 @@ export function createWorkRuntime(store, engine, options = {}) {
799
1412
  return;
800
1413
  }
801
1414
  const state = arms.get(sessionId);
1415
+ if (role === 'main' &&
1416
+ state &&
1417
+ (event.type === 'user/message' || event.type === 'agent/inbox/claimed') &&
1418
+ (messageIdOf(event) ?? '').startsWith(BUDGET_NOTICE_PREFIX)) {
1419
+ state.budgetNotice = true;
1420
+ return;
1421
+ }
802
1422
  if (event.type === 'assistant/message' && role === 'worker' && state) {
803
1423
  const seq = typeof event.seq === 'number' ? event.seq : null;
804
1424
  if (seq != null && state.lastSeq != null && seq <= state.lastSeq)
@@ -808,6 +1428,7 @@ export function createWorkRuntime(store, engine, options = {}) {
808
1428
  state.tokens += total;
809
1429
  if (seq != null)
810
1430
  state.lastSeq = seq;
1431
+ saveQuota(sessionId, state);
811
1432
  consider(sessionId, state, false);
812
1433
  }
813
1434
  return;
@@ -817,8 +1438,72 @@ export function createWorkRuntime(store, engine, options = {}) {
817
1438
  const live = state ?? arm(sessionId, event.data?.turn ?? 0, role);
818
1439
  const step = Number(event.data?.step);
819
1440
  live.steps = Number.isFinite(step) ? Math.max(live.steps, step) : live.steps + 1;
820
- if (role === 'main')
821
- consider(sessionId, live, false);
1441
+ // The main step cap is enforced in gateStep (agent/pre-step), before the next
1442
+ // step starts. Cancelling here would abort a turn whose last step already
1443
+ // ended naturally and record it as aborted.
1444
+ }
1445
+ /**
1446
+ * `agent/pre-step` gate for a bot main session. Refuses the next step once the
1447
+ * turn has used its step or wall budget. A turn whose last step ended without
1448
+ * a tool call never reaches this gate, so it still ends `completed`.
1449
+ * Messages claimed for this step (a user steer) always enter: dropping them on
1450
+ * a refusal would lose user input.
1451
+ * @param {string} sessionId
1452
+ * @param {{ turn?: number, step?: number, claimed?: number }} position
1453
+ */
1454
+ function gateStep(sessionId, position = {}) {
1455
+ if (budgetRole(sessionId) !== 'main')
1456
+ return { kind: 'enter' };
1457
+ const state = arms.get(sessionId);
1458
+ if (!state || state.role !== 'main' || state.closing)
1459
+ return { kind: 'enter' };
1460
+ if ((position.claimed ?? 0) > 0)
1461
+ return { kind: 'enter' };
1462
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
1463
+ const reason = budgetTrip({
1464
+ steps: state.steps,
1465
+ elapsedMs: elapsed,
1466
+ maxSteps: state.limits.maxSteps,
1467
+ wallMs: state.limits.wallMs,
1468
+ });
1469
+ if (reason !== 'steps' && reason !== 'wall')
1470
+ return { kind: 'enter' };
1471
+ const trip = tripMain(sessionId, state, reason, elapsed, 'pre-step');
1472
+ return { kind: 'reject', trip };
1473
+ }
1474
+ /**
1475
+ * Record, log, and announce one main-session budget trip.
1476
+ * @param {string} sessionId
1477
+ * @param {BudgetArm} state
1478
+ * @param {'steps' | 'wall'} reason
1479
+ * @param {number} elapsed
1480
+ * @param {'pre-step' | 'timer'} via
1481
+ */
1482
+ function tripMain(sessionId, state, reason, elapsed, via) {
1483
+ const trip = {
1484
+ reason,
1485
+ cause: `main-budget:${reason}`,
1486
+ turn: state.turn,
1487
+ steps: state.steps,
1488
+ elapsedMs: elapsed,
1489
+ maxSteps: state.limits.maxSteps,
1490
+ wallMs: state.limits.wallMs,
1491
+ via,
1492
+ notify: !state.budgetNotice,
1493
+ };
1494
+ if (state.tripped)
1495
+ return { ...trip, notify: false };
1496
+ state.tripped = true;
1497
+ 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 });
1498
+ if (trip.notify) {
1499
+ try {
1500
+ options.onMainBudget?.(sessionId, trip);
1501
+ }
1502
+ catch {
1503
+ /* the notice is best effort; the log line above stays */
1504
+ }
1505
+ }
1506
+ return trip;
822
1507
  }
823
1508
  /**
824
1509
  * @param {string} sessionId
@@ -850,7 +1535,8 @@ export function createWorkRuntime(store, engine, options = {}) {
850
1535
  return { ok: true };
851
1536
  }
852
1537
  /**
853
- * A dispatch or a host tool leaves the chat budget and uses the short cap.
1538
+ * A dispatch or a host tool moves the turn onto the `main*` cap. The cap can
1539
+ * only tighten: with the defaults (main == chat) this changes nothing.
854
1540
  * @param {string} sessionId
855
1541
  */
856
1542
  function tightenMain(sessionId) {
@@ -858,11 +1544,15 @@ export function createWorkRuntime(store, engine, options = {}) {
858
1544
  if (!state || state.role !== 'main' || state.tight || state.closing || state.tripped)
859
1545
  return;
860
1546
  state.tight = true;
1547
+ const maxSteps = Math.min(state.limits.maxSteps, limits.mainMaxSteps);
1548
+ const wallMs = Math.min(state.limits.wallMs, limits.mainWallMs);
1549
+ if (maxSteps === state.limits.maxSteps && wallMs === state.limits.wallMs)
1550
+ return;
861
1551
  state.limits = {
862
1552
  ...state.limits,
863
- maxSteps: limits.mainMaxSteps,
864
- wallMs: limits.mainWallMs,
865
- ceilingWall: limits.mainWallMs,
1553
+ maxSteps,
1554
+ wallMs,
1555
+ ceilingWall: wallMs,
866
1556
  };
867
1557
  state.clear?.();
868
1558
  const elapsed = Math.max(0, now().getTime() - state.startedAt);
@@ -883,32 +1573,60 @@ export function createWorkRuntime(store, engine, options = {}) {
883
1573
  const previous = arms.get(sessionId);
884
1574
  clearBudget(sessionId);
885
1575
  const caps = role === 'main'
886
- ? { maxSteps: limits.chatMaxSteps, wallMs: limits.chatWallMs, maxTokens: Number.POSITIVE_INFINITY, ceilingWall: limits.chatWallMs, ceilingTokens: Number.POSITIVE_INFINITY, extensionOpen: false }
1576
+ ? {
1577
+ maxSteps: limits.chatMaxSteps,
1578
+ wallMs: limits.chatWallMs,
1579
+ maxTokens: Number.POSITIVE_INFINITY,
1580
+ ceilingWall: limits.chatWallMs,
1581
+ ceilingTokens: Number.POSITIVE_INFINITY,
1582
+ extensionOpen: false,
1583
+ }
887
1584
  : workerCaps(sessionId);
888
1585
  const state = {
1586
+ attemptId: role === 'worker' ? (book.attemptForChild(sessionId)?.id ?? null) : null,
889
1587
  turn,
890
- startedAt: previous?.startedAt ?? now().getTime(),
1588
+ startedAt: role === 'worker' ? now().getTime() : (previous?.startedAt ?? now().getTime()),
891
1589
  steps: 0,
892
- tokens: previous?.tokens ?? 0,
893
- lastSeq: previous?.lastSeq ?? null,
1590
+ tokens: role === 'worker' ? 0 : (previous?.tokens ?? 0),
1591
+ lastSeq: role === 'worker' ? null : (previous?.lastSeq ?? null),
894
1592
  role,
895
1593
  tight: false,
896
1594
  limits: caps,
897
1595
  tripped: false,
1596
+ budgetNotice: false,
898
1597
  extensionOpen: false,
899
1598
  closing: false,
1599
+ pausedAt: null,
1600
+ atBoundary: false,
900
1601
  clear: () => { },
901
1602
  };
902
- const elapsed = Math.max(0, now().getTime() - state.startedAt);
1603
+ if (role === 'worker') {
1604
+ const attempt = book.attemptForChild(sessionId);
1605
+ const quota = attempt ? quotaOf(attempt.ticket_id) : null;
1606
+ if (quota) {
1607
+ state.tokens = quota.tokens ?? 0;
1608
+ state.lastSeq = quota.lastSeq ?? null;
1609
+ const elapsed = (quota.activeMs ?? 0) + (quota.runningSince == null ? 0 : Math.max(0, now().getTime() - quota.runningSince));
1610
+ state.startedAt = now().getTime() - elapsed;
1611
+ if (quota.waiting) {
1612
+ state.pausedAt = now().getTime();
1613
+ state.atBoundary = true;
1614
+ }
1615
+ }
1616
+ }
1617
+ const elapsed = Math.max(0, (state.pausedAt != null && state.atBoundary ? state.pausedAt : now().getTime()) - state.startedAt);
903
1618
  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));
1619
+ const target = caps.wallMs;
1620
+ if (state.pausedAt == null)
1621
+ state.clear = schedule(() => {
1622
+ const live = arms.get(sessionId);
1623
+ if (!live || live !== state || live.closing)
1624
+ return;
1625
+ consider(sessionId, live, true);
1626
+ }, Math.max(1, target - elapsed));
911
1627
  arms.set(sessionId, state);
1628
+ if (role === 'worker')
1629
+ saveQuota(sessionId, state);
912
1630
  return state;
913
1631
  }
914
1632
  /**
@@ -924,19 +1642,21 @@ export function createWorkRuntime(store, engine, options = {}) {
924
1642
  try {
925
1643
  const parsed = JSON.parse(ticket.budget_json);
926
1644
  if (Number.isFinite(parsed.wallMs))
927
- wallMs = Math.min(limits.workerWallMs, Math.max(1000, parsed.wallMs));
1645
+ wallMs = Math.max(1000, parsed.wallMs);
928
1646
  if (Number.isFinite(parsed.maxTokens))
929
- maxTokens = Math.min(limits.workerMaxTokens, Math.max(1000, parsed.maxTokens));
1647
+ maxTokens = Math.max(1000, parsed.maxTokens);
930
1648
  extensionOpen = parsed.extension === 'open';
931
1649
  }
932
- catch { /* host ceiling */ }
1650
+ catch {
1651
+ /* ticket budget */
1652
+ }
933
1653
  }
934
1654
  return {
935
1655
  maxSteps: Number.POSITIVE_INFINITY,
936
1656
  wallMs,
937
1657
  maxTokens,
938
- ceilingWall: limits.workerWallMs,
939
- ceilingTokens: limits.workerMaxTokens,
1658
+ ceilingWall: Number.POSITIVE_INFINITY,
1659
+ ceilingTokens: Number.POSITIVE_INFINITY,
940
1660
  extensionOpen,
941
1661
  };
942
1662
  }
@@ -949,39 +1669,24 @@ export function createWorkRuntime(store, engine, options = {}) {
949
1669
  if (state.closing)
950
1670
  return;
951
1671
  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)
1672
+ // Step caps are enforced by gateStep before the next step. Only the wall
1673
+ // timer stops a step that is still running; the arm is cleared on
1674
+ // turn/end, so a finished turn is never cancelled here.
1675
+ if (!fromTimer || state.tripped)
960
1676
  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');
1677
+ const elapsed = Math.max(state.limits.wallMs, now().getTime() - state.startedAt);
1678
+ const trip = tripMain(sessionId, state, 'wall', elapsed, 'timer');
1679
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: true, reason: trip.cause })).catch(() => { });
968
1680
  return;
969
1681
  }
970
- if (state.extensionOpen)
1682
+ if (state.pausedAt != null)
971
1683
  return;
1684
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
972
1685
  const overWall = fromTimer || elapsed >= state.limits.wallMs;
973
1686
  const overTokens = state.tokens >= state.limits.maxTokens;
974
1687
  if (!overWall && !overTokens)
975
1688
  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');
1689
+ askForQuota(sessionId, state, overTokens ? 'tokens' : 'wall', elapsed);
985
1690
  }
986
1691
  /**
987
1692
  * @param {string} sessionId
@@ -992,13 +1697,15 @@ export function createWorkRuntime(store, engine, options = {}) {
992
1697
  function askForQuota(sessionId, state, reason, elapsed) {
993
1698
  state.extensionOpen = true;
994
1699
  state.clear?.();
995
- watchHostCeiling(sessionId, state);
1700
+ state.pausedAt = now().getTime();
1701
+ state.atBoundary = false;
1702
+ saveQuota(sessionId, state, reason);
996
1703
  const attempt = book.attemptForChild(sessionId);
997
1704
  if (!attempt)
998
1705
  return;
999
1706
  const ticket = book.ticket(attempt.ticket_id);
1000
1707
  if (!ticket || ticket.status === 'failed' || ticket.status === 'cancelled' || ticket.status === 'delivered') {
1001
- finishWorker(sessionId, state, reason);
1708
+ closeBudgetWait(sessionId);
1002
1709
  return;
1003
1710
  }
1004
1711
  const marked = book.markExtensionOpen(ticket.id);
@@ -1011,7 +1718,10 @@ export function createWorkRuntime(store, engine, options = {}) {
1011
1718
  `granted wall ms: ${state.limits.wallMs}`,
1012
1719
  `tokens used: ${state.tokens}`,
1013
1720
  `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.',
1721
+ `required total tokens: ${state.tokens + 1}; required total active wall ms: ${elapsed + 1}`,
1722
+ `standard slice tokens: ${limits.workerMaxTokens}; standard slice wall ms: ${limits.workerWallMs}`,
1723
+ 'Worker is waiting for budget at the next safe loop boundary. It will not dispatch another step until sufficient budget is granted. Budget wait does not expire.',
1724
+ "Call foundations_grant with amounts to ADD. Add at least one standard slice, and more if current usage is already past granted plus that slice. There is no limit on how many times you grant and no cumulative ceiling. Do not refuse because this ticket has already been extended. deny does not stop the worker. Do not cancel unless the user asks to stop. Do not redispatch a replacement ticket. Do not take over the task: do not inspect, edit, or build the worker's files, and do not run its commands.",
1015
1725
  ].join('\n');
1016
1726
  book.insertEvent({
1017
1727
  ticketId: ticket.id,
@@ -1023,74 +1733,185 @@ export function createWorkRuntime(store, engine, options = {}) {
1023
1733
  applyStatus: 'applied',
1024
1734
  });
1025
1735
  }
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
1736
  /**
1062
1737
  * @param {string} sessionId
1063
1738
  * @param {{ wallMs: number, maxTokens: number }} budget
1064
1739
  */
1065
1740
  function releaseArm(sessionId, budget) {
1066
1741
  const state = arms.get(sessionId);
1067
- if (!state || state.role !== 'worker' || state.closing)
1742
+ const attempt = book.attemptForChild(sessionId);
1743
+ if (!attempt)
1068
1744
  return;
1069
- state.extensionOpen = false;
1745
+ const quota = quotaOf(attempt.ticket_id);
1746
+ if (!state || state.role !== 'worker' || state.closing) {
1747
+ // A detached turn stays parked until the grant path queues a durable continuation.
1748
+ if (quota)
1749
+ writeQuota(attempt.ticket_id, { ...quota, waiting: true, runningSince: null });
1750
+ return;
1751
+ }
1070
1752
  state.limits.wallMs = budget.wallMs;
1071
1753
  state.limits.maxTokens = budget.maxTokens;
1754
+ const elapsed = Math.max(0, (state.pausedAt != null && state.atBoundary ? state.pausedAt : now().getTime()) - state.startedAt);
1755
+ if (state.tokens >= budget.maxTokens || elapsed >= budget.wallMs) {
1756
+ state.extensionOpen = true;
1757
+ if (state.pausedAt == null)
1758
+ state.pausedAt = now().getTime();
1759
+ state.clear();
1760
+ saveQuota(sessionId, state);
1761
+ book.markExtensionOpen(attempt.ticket_id);
1762
+ return;
1763
+ }
1764
+ state.extensionOpen = false;
1765
+ state.startedAt = now().getTime() - elapsed;
1766
+ state.pausedAt = null;
1767
+ state.atBoundary = false;
1072
1768
  state.clear?.();
1073
- const elapsed = Math.max(0, now().getTime() - state.startedAt);
1769
+ saveQuota(sessionId, state);
1074
1770
  state.clear = schedule(() => {
1075
- const live = arms.get(sessionId);
1076
- if (!live || live !== state || live.closing)
1077
- return;
1078
- consider(sessionId, live, true);
1771
+ if (arms.get(sessionId) === state && !state.closing)
1772
+ consider(sessionId, state, true);
1079
1773
  }, Math.max(1, budget.wallMs - elapsed));
1080
- if (state.tokens >= budget.maxTokens || elapsed >= budget.wallMs)
1081
- consider(sessionId, state, false);
1774
+ for (const resolve of budgetWaiters.get(sessionId) ?? [])
1775
+ resolve(true);
1776
+ budgetWaiters.delete(sessionId);
1777
+ }
1778
+ function quotaOf(ticketId) {
1779
+ try {
1780
+ return JSON.parse(book.ticket(ticketId)?.budget_json ?? '{}').quota ?? null;
1781
+ }
1782
+ catch {
1783
+ return null;
1784
+ }
1785
+ }
1786
+ function writeQuota(ticketId, quota) {
1787
+ const ticket = book.ticket(ticketId);
1788
+ if (!ticket)
1789
+ return;
1790
+ const budget = JSON.parse(ticket.budget_json);
1791
+ budget.quota = quota;
1792
+ store.db
1793
+ .prepare('UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?')
1794
+ .run(JSON.stringify(budget), now().toISOString(), ticketId);
1795
+ }
1796
+ function saveQuota(sessionId, state, reason) {
1797
+ const attempt = book.attemptForChild(sessionId);
1798
+ if (!attempt || attempt.id !== state.attemptId)
1799
+ return;
1800
+ const activeMs = Math.max(0, (state.pausedAt != null && state.atBoundary ? state.pausedAt : now().getTime()) - state.startedAt);
1801
+ writeQuota(attempt.ticket_id, {
1802
+ tokens: state.tokens,
1803
+ lastSeq: state.lastSeq,
1804
+ activeMs,
1805
+ runningSince: state.pausedAt == null ? now().getTime() : null,
1806
+ waiting: state.pausedAt != null,
1807
+ phase: state.atBoundary ? 'waiting' : 'requested',
1808
+ reason: state.pausedAt == null ? undefined : (reason ?? quotaOf(attempt.ticket_id)?.reason),
1809
+ });
1810
+ }
1811
+ function quotaFeedback(ticketId) {
1812
+ const quota = quotaOf(ticketId);
1813
+ const budget = JSON.parse(book.ticket(ticketId)?.budget_json ?? '{}');
1814
+ return {
1815
+ waitingBudget: quota?.waiting === true,
1816
+ budgetReason: quota?.reason ?? null,
1817
+ usedTokens: quota?.tokens ?? 0,
1818
+ activeElapsedMs: quota?.activeMs ?? 0,
1819
+ requiredMaxTokens: (quota?.tokens ?? 0) + 1,
1820
+ requiredWallMs: (quota?.activeMs ?? 0) + 1,
1821
+ minimumAdditionalTokens: Math.max(0, (quota?.tokens ?? 0) + 1 - (budget.maxTokens ?? 0)),
1822
+ minimumAdditionalWallMs: Math.max(0, (quota?.activeMs ?? 0) + 1 - (budget.wallMs ?? 0)),
1823
+ sliceTokens: limits.workerMaxTokens,
1824
+ sliceWallMs: limits.workerWallMs,
1825
+ };
1826
+ }
1827
+ function closeBudgetWait(sessionId) {
1828
+ const state = arms.get(sessionId);
1829
+ if (state) {
1830
+ state.closing = true;
1831
+ state.clear();
1832
+ }
1833
+ for (const resolve of budgetWaiters.get(sessionId) ?? [])
1834
+ resolve(false);
1835
+ budgetWaiters.delete(sessionId);
1836
+ }
1837
+ /** Awaiting this official pre-step waterfall suspends admission, not the turn. */
1838
+ async function waitForBudget(sessionId, signal) {
1839
+ if (!isWorkerSession(sessionId))
1840
+ return true;
1841
+ const attempt = book.attemptForChild(sessionId);
1842
+ const ticket = attempt ? book.ticket(attempt.ticket_id) : null;
1843
+ if (!ticket || isFinishedTicket(ticket) || signal?.aborted)
1844
+ return false;
1845
+ const state = arms.get(sessionId) ?? arm(sessionId, 0, 'worker');
1846
+ if (state.closing)
1847
+ return false;
1848
+ consider(sessionId, state, false);
1849
+ if (state.pausedAt == null)
1850
+ return true;
1851
+ if (!state.atBoundary) {
1852
+ // The already-admitted request/tool batch may finish; account for that
1853
+ // active time before freezing the clock at this safe loop boundary.
1854
+ state.pausedAt = now().getTime();
1855
+ state.atBoundary = true;
1856
+ saveQuota(sessionId, state);
1857
+ }
1858
+ const caps = workerCaps(sessionId);
1859
+ releaseArm(sessionId, caps);
1860
+ if (state.pausedAt == null)
1861
+ return true;
1862
+ return new Promise(resolve => {
1863
+ const waiters = budgetWaiters.get(sessionId) ?? new Set();
1864
+ const done = (allowed) => {
1865
+ signal?.removeEventListener('abort', aborted);
1866
+ waiters.delete(done);
1867
+ if (!waiters.size)
1868
+ budgetWaiters.delete(sessionId);
1869
+ resolve(allowed);
1870
+ };
1871
+ const aborted = () => done(false);
1872
+ waiters.add(done);
1873
+ budgetWaiters.set(sessionId, waiters);
1874
+ signal?.addEventListener('abort', aborted, { once: true });
1875
+ if (signal?.aborted)
1876
+ done(false);
1877
+ });
1082
1878
  }
1083
1879
  /**
1084
1880
  * @param {string} sessionId
1085
1881
  */
1086
1882
  function clearBudget(sessionId) {
1087
1883
  const state = arms.get(sessionId);
1884
+ if (state?.role === 'worker')
1885
+ saveQuota(sessionId, state);
1088
1886
  if (!state)
1089
1887
  return;
1090
1888
  state.clear?.();
1091
1889
  arms.delete(sessionId);
1092
1890
  }
1093
1891
  }
1892
+ /**
1893
+ * A later turn/end for every started turn means the child is idle.
1894
+ * No turn at all, or an open turn, means it may still be running.
1895
+ * @param {Array<Record<string, any>>} events
1896
+ */
1897
+ function latestTurnEnded(events) {
1898
+ const open = new Set();
1899
+ let sawTurn = false;
1900
+ for (const event of events) {
1901
+ const turn = event.data?.turn;
1902
+ if (turn == null)
1903
+ continue;
1904
+ if (event.type === 'turn/start' || event.type === 'user/message') {
1905
+ sawTurn = true;
1906
+ open.add(turn);
1907
+ }
1908
+ else if (event.type === 'turn/end') {
1909
+ sawTurn = true;
1910
+ open.delete(turn);
1911
+ }
1912
+ }
1913
+ return sawTurn && open.size === 0;
1914
+ }
1094
1915
  /**
1095
1916
  * @param {unknown} value
1096
1917
  */