@thready-web/dsh-bot-plugin 0.1.0-beta.3 → 0.1.0-beta.5

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.
@@ -1,5 +1,6 @@
1
1
  import { durableFollowup } from "./work-durable.js";
2
2
  import { sha256 } from "./fs-safe.js";
3
+ import { DEFAULT_WORK_BUDGET } from "./work-admit.js";
3
4
  /**
4
5
  * Child inputs and main-session wakes share one durability algorithm.
5
6
  * They are not rows in `deliveries`.
@@ -136,7 +137,14 @@ export async function pushInput(book, input, deps) {
136
137
  const ticket = book.ticket(input.ticket_id);
137
138
  if (!attempt?.child_session_id || !ticket)
138
139
  return { ok: false, status: 'pending' };
139
- let budget = { wallMs: 600_000, maxTokens: 400_000 };
140
+ if (input.kind !== 'cancel_note' &&
141
+ (['failed', 'cancelled', 'delivered'].includes(ticket.status) ||
142
+ ticket.active_attempt_id !== input.attempt_id ||
143
+ ticket.briefing_revision !== input.briefing_revision)) {
144
+ book.markInputFlush(input.id, 'dead', deps.pid, 'ticket-finished-or-superseded', null, false);
145
+ return { ok: false, status: 'dead' };
146
+ }
147
+ let budget = { wallMs: DEFAULT_WORK_BUDGET.workerWallMs, maxTokens: DEFAULT_WORK_BUDGET.workerMaxTokens };
140
148
  try {
141
149
  budget = { ...budget, ...JSON.parse(ticket.budget_json) };
142
150
  }
@@ -23,6 +23,7 @@ export async function startWorkMock(options) {
23
23
  pendingIds: sessionId => world.pendingIds(sessionId),
24
24
  cancel: (sessionId, cancelOptions) => world.cancel(sessionId, cancelOptions),
25
25
  snapshot: sessionId => world.snapshot(sessionId),
26
+ childPresent: sessionId => world.hasSession(sessionId),
26
27
  now,
27
28
  pid: process.pid,
28
29
  });
package/dist/work-mock.js CHANGED
@@ -106,6 +106,12 @@ export function createMockWorld() {
106
106
  async snapshot(sessionId) {
107
107
  return session(sessionId).events.map(event => ({ ...event, data: event.data }));
108
108
  },
109
+ hasSession(sessionId) {
110
+ return sessions.has(sessionId);
111
+ },
112
+ dropChild(sessionId) {
113
+ sessions.delete(sessionId);
114
+ },
109
115
  };
110
116
  /**
111
117
  * @param {string} sessionId
@@ -3,6 +3,10 @@ import { join } from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { sha256 } from "./fs-safe.js";
5
5
  export const ACTIVE_TICKET = Object.freeze(['accepted', 'enqueued', 'started', 'needs_user']);
6
+ /** Tickets that occupy a running execution slot, plus reserved starts stored as slot=held. */
7
+ export const SLOT_TICKET = Object.freeze(['enqueued', 'started']);
8
+ /** Cap on how long an accepted/needs_user ticket may occupy a reserved start slot. */
9
+ export const RESERVE_WALL_MS = 10 * 60 * 1000;
6
10
  const TERMINAL_KIND = new Set(['question', 'result', 'failure']);
7
11
  const OPEN_NOTICE_FLUSH = new Set(['intent', 'flushing', 'ambiguous']);
8
12
  /**
@@ -14,10 +18,23 @@ const OPEN_NOTICE_FLUSH = new Set(['intent', 'flushing', 'ambiguous']);
14
18
  */
15
19
  export function createTicketBook(db, root, now = () => new Date()) {
16
20
  const iso = () => now().toISOString();
21
+ const SLOT_SQL = `status IN ('enqueued','started')
22
+ OR (status IN ('accepted','needs_user') AND json_extract(budget_json, '$.slot') = 'held')`;
23
+ const QUEUE_SQL = `status = 'accepted'
24
+ AND (json_extract(budget_json, '$.slot') IS NULL OR json_extract(budget_json, '$.slot') != 'held')`;
17
25
  return {
18
26
  iso,
19
27
  countActive,
20
28
  countGlobal,
29
+ countSlots,
30
+ countGlobalSlots,
31
+ countQueued,
32
+ countGlobalQueued,
33
+ slotHeld,
34
+ reserveSlot,
35
+ releaseSlot,
36
+ nextPromotable,
37
+ heldStarts,
21
38
  ticket: (id) => row('SELECT * FROM work_tickets WHERE id = ?', id),
22
39
  attempt: (id) => row('SELECT * FROM work_attempts WHERE id = ?', id),
23
40
  byIdempotency,
@@ -98,6 +115,98 @@ export function createTicketBook(db, root, now = () => new Date()) {
98
115
  `)
99
116
  .get().n;
100
117
  }
118
+ /**
119
+ * Running execution slots for one bot. needs_user does not count unless a
120
+ * resume has already reserved a slot.
121
+ * @param {string} owner
122
+ */
123
+ function countSlots(owner) {
124
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE owner_session_id = ? AND (${SLOT_SQL})`).get(owner)
125
+ .n;
126
+ }
127
+ function countGlobalSlots() {
128
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE ${SLOT_SQL}`).get().n;
129
+ }
130
+ /**
131
+ * Accepted tickets waiting for a slot. A reserved start is not queued.
132
+ * @param {string} owner
133
+ */
134
+ function countQueued(owner) {
135
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE owner_session_id = ? AND ${QUEUE_SQL}`).get(owner).n;
136
+ }
137
+ function countGlobalQueued() {
138
+ return db.prepare(`SELECT COUNT(*) AS n FROM work_tickets WHERE ${QUEUE_SQL}`).get().n;
139
+ }
140
+ /**
141
+ * @param {{ budget_json?: string } | null | undefined} ticket
142
+ */
143
+ function slotHeld(ticket) {
144
+ return budgetObject(ticket ?? {}).slot === 'held';
145
+ }
146
+ /**
147
+ * Reserve a running slot on an accepted or needs_user ticket. Returns null
148
+ * when the ticket is missing or already terminal.
149
+ * @param {string} ticketId
150
+ */
151
+ function reserveSlot(ticketId) {
152
+ const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
153
+ if (!ticket)
154
+ return null;
155
+ if (ticket.status === 'cancelled' || ticket.status === 'failed' || ticket.status === 'delivered')
156
+ return ticket;
157
+ if (ticket.status === 'enqueued' || ticket.status === 'started' || slotHeld(ticket))
158
+ return ticket;
159
+ const budget = { ...budgetObject(ticket), slot: 'held' };
160
+ db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), iso(), ticketId);
161
+ return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
162
+ }
163
+ /**
164
+ * @param {string} ticketId
165
+ */
166
+ function releaseSlot(ticketId) {
167
+ const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
168
+ if (!ticket || !slotHeld(ticket))
169
+ return ticket;
170
+ const budget = budgetObject(ticket);
171
+ delete budget.slot;
172
+ db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), iso(), ticketId);
173
+ return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
174
+ }
175
+ /**
176
+ * Oldest ticket that can take a newly freed slot: a queued accept, a reserved
177
+ * start that has not reached enqueued, or a needs_user resume with unflushed input.
178
+ * FIFO is created_at, then SQLite rowid (insertion order), not ticket id.
179
+ * The caller still checks per-bot and global slot caps before reserveSlot.
180
+ */
181
+ function nextPromotable() {
182
+ return db
183
+ .prepare(`
184
+ SELECT t.* FROM work_tickets t
185
+ LEFT JOIN work_attempts a ON a.id = t.active_attempt_id
186
+ LEFT JOIN work_inputs i ON i.id = a.current_input_id
187
+ WHERE t.status = 'accepted'
188
+ OR (t.status IN ('accepted','needs_user') AND json_extract(t.budget_json, '$.slot') = 'held')
189
+ OR (
190
+ t.status = 'needs_user'
191
+ AND t.child_session_id IS NOT NULL
192
+ AND i.flush_status IN ('intent','ambiguous')
193
+ )
194
+ ORDER BY t.created_at ASC, t.rowid ASC
195
+ `)
196
+ .all();
197
+ }
198
+ /**
199
+ * Reserved starts that still need create/flush after a crash or a mid-start return.
200
+ */
201
+ function heldStarts() {
202
+ return db
203
+ .prepare(`
204
+ SELECT * FROM work_tickets
205
+ WHERE status IN ('accepted','needs_user') AND json_extract(budget_json, '$.slot') = 'held'
206
+ ORDER BY created_at ASC, rowid ASC
207
+ `)
208
+ .all();
209
+ }
101
210
  /**
102
211
  * @param {string} owner
103
212
  * @param {string | null} key
@@ -192,17 +301,34 @@ export function createTicketBook(db, root, now = () => new Date()) {
192
301
  * @param {string} ticketId
193
302
  * @param {string} childSessionId
194
303
  */
195
- function setChildIfEmpty(ticketId, childSessionId) {
304
+ function setChildIfEmpty(ticketId, childSessionId, expected) {
196
305
  const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
197
- if (!ticket || ticket.child_session_id)
198
- return ticket;
306
+ if (!ticket)
307
+ return { ticket: null, attached: false };
308
+ if (ticket.status === 'cancelled' || ticket.status === 'failed' || ticket.status === 'delivered') {
309
+ return { ticket, attached: false };
310
+ }
311
+ if (ticket.child_session_id) {
312
+ return { ticket, attached: ticket.child_session_id === childSessionId };
313
+ }
314
+ const attempt = ticket.active_attempt_id
315
+ ? row('SELECT * FROM work_attempts WHERE id = ?', ticket.active_attempt_id)
316
+ : null;
317
+ if (expected?.attemptId && attempt?.id !== expected.attemptId)
318
+ return { ticket, attached: false };
319
+ if (expected?.fencingToken != null && attempt && attempt.fencing_token !== expected.fencingToken) {
320
+ return { ticket, attached: false };
321
+ }
199
322
  db.prepare(`
200
323
  UPDATE work_tickets SET child_session_id = ?, updated_at = ? WHERE id = ? AND child_session_id IS NULL
201
324
  `).run(childSessionId, iso(), ticketId);
202
- db.prepare(`
203
- UPDATE work_attempts SET child_session_id = ? WHERE id = ? AND child_session_id IS NULL
204
- `).run(childSessionId, ticket.active_attempt_id);
205
- return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
325
+ if (ticket.active_attempt_id) {
326
+ db.prepare(`
327
+ UPDATE work_attempts SET child_session_id = ? WHERE id = ? AND child_session_id IS NULL
328
+ `).run(childSessionId, ticket.active_attempt_id);
329
+ }
330
+ const fresh = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
331
+ return { ticket: fresh, attached: fresh?.child_session_id === childSessionId };
206
332
  }
207
333
  /**
208
334
  * @param {{
@@ -396,14 +522,17 @@ export function createTicketBook(db, root, now = () => new Date()) {
396
522
  const token = (previous?.fencing_token ?? 0) + 1;
397
523
  const attemptId = randomUUID();
398
524
  const next = ticket.revision + 1;
525
+ const retryBudget = budgetObject(ticket);
526
+ delete retryBudget.quota;
527
+ delete retryBudget.extension;
399
528
  const info = db
400
529
  .prepare(`
401
530
  UPDATE work_tickets
402
- SET revision = ?, briefing_revision = 1, status = 'accepted', review_status = 'none',
531
+ SET budget_json = ?, revision = ?, briefing_revision = 1, status = 'accepted', review_status = 'none',
403
532
  active_attempt_id = ?, cancel_requested_revision = NULL, updated_at = ?
404
533
  WHERE id = ? AND revision = ?
405
534
  `)
406
- .run(next, attemptId, iso(), ticketId, expected);
535
+ .run(JSON.stringify(retryBudget), next, attemptId, iso(), ticketId, expected);
407
536
  if (info.changes !== 1)
408
537
  return { error: 'CAS_CONFLICT' };
409
538
  if (previous) {
@@ -488,7 +617,9 @@ export function createTicketBook(db, root, now = () => new Date()) {
488
617
  db.prepare(`UPDATE work_events SET apply_status = 'applied', turn_end_reason = ? WHERE event_id = ?`).run(reasonKind, eventId);
489
618
  const stamp = iso();
490
619
  if (found.kind === 'question') {
491
- db.prepare(`UPDATE work_tickets SET status = 'needs_user', updated_at = ? WHERE id = ?`).run(stamp, ticket.id);
620
+ const budget = budgetObject(ticket);
621
+ delete budget.slot;
622
+ db.prepare(`UPDATE work_tickets SET status = 'needs_user', budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), stamp, ticket.id);
492
623
  }
493
624
  else if (found.kind === 'result') {
494
625
  const review = ticket.review_status === 'rejected' ? 'rejected' : 'candidate';
@@ -531,12 +662,13 @@ export function createTicketBook(db, root, now = () => new Date()) {
531
662
  return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), already: false };
532
663
  }
533
664
  /**
534
- * Add granted runtime or tokens, capped by the host ceiling, and close the request.
665
+ * Add granted runtime or tokens and close the request when the new totals
666
+ * exceed current usage. There is no cumulative ceiling and no grant-count cap.
535
667
  * @param {string} ticketId
536
668
  * @param {{ wallMs?: number, maxTokens?: number }} add
537
- * @param {{ wallMs: number, maxTokens: number }} ceilings
669
+ * @param {{ wallMs: number, maxTokens: number }} [baseline]
538
670
  */
539
- function extendBudget(ticketId, add, ceilings) {
671
+ function extendBudget(ticketId, add, baseline) {
540
672
  const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
541
673
  if (!ticket)
542
674
  return { error: 'NOT_FOUND', message: 'No such ticket.' };
@@ -544,18 +676,25 @@ export function createTicketBook(db, root, now = () => new Date()) {
544
676
  return { error: 'VALIDATION', message: 'This ticket has finished and cannot be granted more budget.' };
545
677
  }
546
678
  const budget = budgetObject(ticket);
547
- const beforeWall = Number(budget.wallMs) || ceilings.wallMs;
548
- const beforeTokens = Number(budget.maxTokens) || ceilings.maxTokens;
679
+ const beforeWall = Number(budget.wallMs) || baseline?.wallMs || 0;
680
+ const beforeTokens = Number(budget.maxTokens) || baseline?.maxTokens || 0;
549
681
  const wallAdd = Number(add.wallMs);
550
682
  const tokenAdd = Number(add.maxTokens);
551
- const wallMs = Number.isFinite(wallAdd) && wallAdd > 0 ? Math.min(ceilings.wallMs, beforeWall + Math.floor(wallAdd)) : beforeWall;
552
- const maxTokens = Number.isFinite(tokenAdd) && tokenAdd > 0
553
- ? Math.min(ceilings.maxTokens, beforeTokens + Math.floor(tokenAdd))
554
- : beforeTokens;
683
+ const wallMs = Number.isFinite(wallAdd) && wallAdd > 0 ? beforeWall + Math.floor(wallAdd) : beforeWall;
684
+ const maxTokens = Number.isFinite(tokenAdd) && tokenAdd > 0 ? beforeTokens + Math.floor(tokenAdd) : beforeTokens;
555
685
  if (wallMs === beforeWall && maxTokens === beforeTokens) {
556
- return { error: 'VALIDATION', message: 'Nothing more can be granted. The host ceiling is already used.' };
686
+ return { error: 'VALIDATION', message: 'Pass wallMs or maxTokens to add.' };
557
687
  }
558
- const next = { ...budget, wallMs, maxTokens, extension: null };
688
+ const quota = budget.quota;
689
+ const enough = !quota?.waiting || (maxTokens > quota.tokens && wallMs > quota.activeMs);
690
+ const next = {
691
+ ...budget,
692
+ wallMs,
693
+ maxTokens,
694
+ extension: enough ? null : 'open',
695
+ // Only actual loop admission clears durable waiting. A crash after this
696
+ // grant transaction must not remove expiry protection before resumption.
697
+ };
559
698
  db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(next), iso(), ticketId);
560
699
  return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), budget: next };
561
700
  }
@@ -605,11 +744,20 @@ export function createTicketBook(db, root, now = () => new Date()) {
605
744
  }
606
745
  return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
607
746
  }
747
+ function extensionIsOpen(budgetJson) {
748
+ try {
749
+ return JSON.parse(budgetJson ?? '')?.extension === 'open';
750
+ }
751
+ catch {
752
+ return false;
753
+ }
754
+ }
608
755
  function expireQuiet() {
609
756
  const failed = [];
610
757
  const running = db
611
758
  .prepare(`
612
- SELECT t.id AS ticket_id, t.budget_json, t.status AS ticket_status, a.id AS attempt_id, a.status AS attempt_status,
759
+ SELECT t.id AS ticket_id, t.budget_json, t.status AS ticket_status, t.child_session_id,
760
+ a.id AS attempt_id, a.status AS attempt_status,
613
761
  a.lease_until, a.current_input_id
614
762
  FROM work_tickets t
615
763
  JOIN work_attempts a ON a.id = t.active_attempt_id
@@ -617,12 +765,17 @@ export function createTicketBook(db, root, now = () => new Date()) {
617
765
  `)
618
766
  .all();
619
767
  for (const item of running) {
768
+ if (budgetObject(item).quota?.waiting)
769
+ continue;
620
770
  if (item.ticket_status === 'started' &&
621
771
  item.attempt_status === 'started' &&
622
772
  item.lease_until &&
623
773
  Date.parse(item.lease_until) <= now().getTime()) {
774
+ // The host already asked main to grant, not to mark the ticket failed.
775
+ if (extensionIsOpen(item.budget_json))
776
+ continue;
624
777
  failRunning(item.ticket_id, 'lease');
625
- failed.push(item.ticket_id);
778
+ failed.push({ ticketId: item.ticket_id, reason: 'lease', childSessionId: item.child_session_id ?? null });
626
779
  continue;
627
780
  }
628
781
  if (item.ticket_status === 'enqueued' && item.attempt_status === 'enqueued' && item.current_input_id) {
@@ -636,10 +789,42 @@ export function createTicketBook(db, root, now = () => new Date()) {
636
789
  }
637
790
  if (input && input.flush_status === 'accepted' && Date.parse(input.updated_at) + wall <= now().getTime()) {
638
791
  failRunning(item.ticket_id, 'enqueue-wall');
639
- failed.push(item.ticket_id);
792
+ failed.push({
793
+ ticketId: item.ticket_id,
794
+ reason: 'enqueue-wall',
795
+ childSessionId: item.child_session_id ?? null,
796
+ });
640
797
  }
641
798
  }
642
799
  }
800
+ const reserved = db
801
+ .prepare(`
802
+ SELECT t.id AS ticket_id, t.budget_json, t.updated_at, t.child_session_id
803
+ FROM work_tickets t
804
+ WHERE t.status IN ('accepted','needs_user')
805
+ AND json_extract(t.budget_json, '$.slot') = 'held'
806
+ `)
807
+ .all();
808
+ for (const item of reserved) {
809
+ let wall = RESERVE_WALL_MS;
810
+ try {
811
+ const parsed = JSON.parse(item.budget_json);
812
+ const ticketWall = Number(parsed?.wallMs);
813
+ if (Number.isFinite(ticketWall) && ticketWall > 0)
814
+ wall = Math.min(ticketWall, RESERVE_WALL_MS);
815
+ }
816
+ catch {
817
+ /* host default */
818
+ }
819
+ if (Date.parse(item.updated_at) + wall <= now().getTime()) {
820
+ failRunning(item.ticket_id, 'reserve-wall');
821
+ failed.push({
822
+ ticketId: item.ticket_id,
823
+ reason: 'reserve-wall',
824
+ childSessionId: item.child_session_id ?? null,
825
+ });
826
+ }
827
+ }
643
828
  return failed;
644
829
  }
645
830
  /**
@@ -737,6 +922,7 @@ export function createTicketBook(db, root, now = () => new Date()) {
737
922
  return visibleTickets(owner).map(item => ({
738
923
  id: item.id,
739
924
  status: item.status,
925
+ waiting_budget: (item.status === 'started' || item.status === 'enqueued') && budgetObject(item).quota?.waiting === true,
740
926
  briefing_revision: item.briefing_revision,
741
927
  child_session_id: item.child_session_id,
742
928
  summary: readBriefing(item.briefing_hash).replace(/\s+/g, ' ').trim().slice(0, 80),
@@ -767,7 +953,7 @@ export function createTicketBook(db, root, now = () => new Date()) {
767
953
  function signalMap() {
768
954
  const rows = db
769
955
  .prepare(`
770
- SELECT owner_session_id, status FROM work_tickets
956
+ SELECT owner_session_id, status, budget_json FROM work_tickets
771
957
  WHERE status != 'delivered' AND status != 'cancelled'
772
958
  ORDER BY updated_at DESC
773
959
  `)
@@ -777,7 +963,9 @@ export function createTicketBook(db, root, now = () => new Date()) {
777
963
  for (const item of rows) {
778
964
  const owner = item.owner_session_id;
779
965
  const list = signals[owner] ?? [];
780
- list.push(item.status);
966
+ list.push((item.status === 'started' || item.status === 'enqueued') && budgetObject(item).quota?.waiting
967
+ ? 'waiting_budget'
968
+ : item.status);
781
969
  signals[owner] = list;
782
970
  }
783
971
  return signals;
@@ -849,6 +1037,7 @@ export function createTicketBook(db, root, now = () => new Date()) {
849
1037
  ticket: {
850
1038
  id: item.id,
851
1039
  status: item.status,
1040
+ waiting_budget: (item.status === 'started' || item.status === 'enqueued') && budgetObject(item).quota?.waiting === true,
852
1041
  briefing_revision: item.briefing_revision,
853
1042
  child_session_id: item.child_session_id,
854
1043
  active_attempt_id: item.active_attempt_id,
@@ -1120,6 +1309,8 @@ function hostFailureText(reason) {
1120
1309
  return 'The worker lease expired and this round has stopped.';
1121
1310
  if (reason === 'enqueue-wall')
1122
1311
  return 'The task entered the queue and did not start before the time limit.';
1312
+ if (reason === 'reserve-wall')
1313
+ return 'The reserved start did not create a worker before the time limit, so the slot was released.';
1123
1314
  if (reason === 'steps')
1124
1315
  return 'The worker hit its step limit and this round has stopped.';
1125
1316
  return 'The worker has stopped.';
@@ -1,4 +1,6 @@
1
1
  import { toolError } from "./errors.js";
2
+ import { DEFAULT_WORK_BUDGET } from "./work-admit.js";
3
+ const SLICE = `${DEFAULT_WORK_BUDGET.workerWallMs} ms and ${DEFAULT_WORK_BUDGET.workerMaxTokens} tokens`;
2
4
  const OUTPUT = {
3
5
  schema: {
4
6
  type: 'object',
@@ -17,14 +19,14 @@ const OUTPUT = {
17
19
  */
18
20
  export function workToolDefinitions(work, engine) {
19
21
  return [
20
- tool('foundations_dispatch', 'Hand a long job to a worker session. Available only on a bot. status=accepted means received, not yet dispatched. status=enqueued means it entered the execution queue, not that it has started. The return value is never started. ownerSessionId is ignored.', {
22
+ tool('foundations_dispatch', 'Hand a non-trivial job to a worker session. Prefer this over doing the work with bash, write, edit, or an official subagent in the main session. Available only on a bot. status=accepted means received, and may wait for an execution slot. status=enqueued means it entered the execution queue, not that it has started. queued=true means it is waiting for a slot and will start automatically when one is free. The return value is never started. A BUDGET error means both the slot cap and the queue cap are full; do not start the job in the main session. ownerSessionId is ignored.', {
21
23
  type: 'object',
22
24
  properties: {
23
25
  briefing: { type: 'string' },
24
26
  idempotencyKey: { type: 'string' },
25
27
  budget: {
26
28
  type: 'object',
27
- description: 'Time and token estimate for this ticket. When omitted, the host estimates from the task text. It cannot exceed the host ceiling.',
29
+ description: `Time and token budget for this ticket. When omitted, the host uses one standard slice (${SLICE}). Pass that slice. Do not estimate a smaller budget. Later grants add more slices with no cumulative ceiling.`,
28
30
  properties: {
29
31
  wallMs: { type: 'integer', description: 'Expected maximum runtime in milliseconds.' },
30
32
  maxTokens: { type: 'integer', description: 'Expected maximum tokens.' },
@@ -65,13 +67,16 @@ export function workToolDefinitions(work, engine) {
65
67
  ownerSessionId: { type: 'string', description: 'Ignored.' },
66
68
  },
67
69
  }, (args, hostId) => work.cancelTicket(hostId, args), 'bot'),
68
- tool('foundations_grant', 'Grant more time or tokens to an unfinished ticket. wallMs and maxTokens are amounts to add, not a new total. A budget-exhausted notice is not a failure. deny=true refuses the grant and stops this round.', {
70
+ tool('foundations_grant', `Grant more active runtime or tokens to an unfinished ticket. wallMs and maxTokens are amounts to ADD, not totals. Add at least one standard slice (${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 earlier grants were many or large. Exhausted workers wait at the next safe loop boundary without expiry. An insufficient grant leaves the worker paused. The main session cannot refuse. deny=true does not stop the worker; another full slice is granted. Tell the user and end the turn. Do not take over the task and do not redispatch a replacement.`, {
69
71
  type: 'object',
70
72
  properties: {
71
73
  ticketId: { type: 'string' },
72
74
  wallMs: { type: 'integer', description: 'Milliseconds to add.' },
73
75
  maxTokens: { type: 'integer', description: 'Tokens to add.' },
74
- deny: { type: 'boolean', description: 'Refuse the grant and stop.' },
76
+ deny: {
77
+ type: 'boolean',
78
+ description: 'Ignored as a refusal. Does not stop the worker.',
79
+ },
75
80
  ownerSessionId: { type: 'string', description: 'Ignored.' },
76
81
  },
77
82
  required: ['ticketId'],