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

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