@parcha/agentrun-kernel 0.1.0-beta.37 → 0.1.0-beta.39

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 (70) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/NOTICE +2 -0
  3. package/dist/booking.d.ts +25 -6
  4. package/dist/booking.js +15 -4
  5. package/dist/host/index.d.ts +4 -5
  6. package/dist/host/index.js +3 -3
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +105 -3
  10. package/dist/host/overhead.js +276 -20
  11. package/dist/host/proxy.d.ts +97 -16
  12. package/dist/host/proxy.js +420 -108
  13. package/dist/index.d.ts +6 -5
  14. package/dist/index.js +4 -3
  15. package/dist/kernel/cap/admit.d.ts +5 -8
  16. package/dist/kernel/cap/admit.js +13 -19
  17. package/dist/kernel/cap/free.d.ts +43 -0
  18. package/dist/kernel/cap/free.js +71 -0
  19. package/dist/kernel/cap/index.d.ts +7 -6
  20. package/dist/kernel/cap/index.js +6 -5
  21. package/dist/kernel/cap/marks.d.ts +2 -3
  22. package/dist/kernel/cap/park.d.ts +3 -4
  23. package/dist/kernel/cap/park.js +4 -5
  24. package/dist/kernel/cap/port.d.ts +11 -5
  25. package/dist/kernel/cap/port.js +26 -24
  26. package/dist/kernel/cap/price.d.ts +10 -30
  27. package/dist/kernel/cap/price.js +15 -48
  28. package/dist/kernel/cap/recover.d.ts +1 -2
  29. package/dist/kernel/cap/recover.js +2 -4
  30. package/dist/kernel/cap/rule.d.ts +11 -17
  31. package/dist/kernel/cap/rule.js +37 -19
  32. package/dist/kernel/cap/run-cap.d.ts +25 -10
  33. package/dist/kernel/cap/run-cap.js +78 -35
  34. package/dist/kernel/cap/types.d.ts +11 -27
  35. package/dist/kernel/cap/words.d.ts +13 -8
  36. package/dist/kernel/cap/words.js +23 -14
  37. package/dist/kernel/cap/wrap-up.d.ts +4 -0
  38. package/dist/kernel/cap/wrap-up.js +5 -1
  39. package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
  40. package/dist/kernel/registry/computer-surface.generated.js +18 -27
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +64 -16
  43. package/dist/kernel/registry/gate.d.ts +2 -2
  44. package/dist/kernel/registry/gate.js +4 -7
  45. package/dist/kernel/registry/hands.d.ts +4 -5
  46. package/dist/kernel/registry/index.d.ts +1 -1
  47. package/dist/kernel/registry/index.js +1 -1
  48. package/dist/kernel/registry/registry.js +6 -9
  49. package/dist/kernel/types.d.ts +8 -1
  50. package/dist/process/recovery.d.ts +4 -1
  51. package/dist/process/recovery.js +15 -3
  52. package/dist/process/resume.d.ts +5 -2
  53. package/dist/process/resume.js +15 -3
  54. package/dist/process/tools.d.ts +28 -1
  55. package/dist/process/tools.js +102 -5
  56. package/dist/run-booking.d.ts +21 -2
  57. package/dist/run-booking.js +215 -18
  58. package/dist/runner.d.ts +82 -21
  59. package/dist/runner.js +271 -56
  60. package/dist/testing.d.ts +10 -4
  61. package/dist/testing.js +7 -5
  62. package/dist/tool-deferral.d.ts +12 -0
  63. package/dist/tool-deferral.js +17 -0
  64. package/dist/types.d.ts +133 -48
  65. package/dist/types.js +8 -0
  66. package/package.json +5 -3
  67. package/vendor/o200k/LICENSE +61 -0
  68. package/vendor/o200k/o200k_base.tiktoken +199998 -0
  69. package/dist/host/mcp-route.d.ts +0 -14
  70. package/dist/host/mcp-route.js +0 -125
package/dist/runner.js CHANGED
@@ -59,58 +59,55 @@ export function sessionSpendOf(records) {
59
59
  requests.forEach((data, i) => { if (typeof data.host === "string")
60
60
  hosts.set(turns[i], data.host); });
61
61
  const held = new Map();
62
- const bounds = new Map();
63
62
  requests.forEach((data, i) => {
64
- const figure = heldFigure(data.heldUsd);
63
+ // One billed to a person's plan (Admitted.plan) costs the run $0 however it ends: its figure, held or not.
64
+ const figure = data.plan === true ? 0 : heldFigure(data.heldUsd);
65
65
  if (figure !== undefined)
66
66
  held.set(turns[i], figure);
67
- const bound = heldFigure(data.boundUsd);
68
- if (bound !== undefined)
69
- bounds.set(turns[i], bound);
70
67
  });
71
- // A request that never answered (a crash or a lost claim cut it; booked cut or not yet) may have been billed at a cache
72
- // miss: for the cap it counts at its hold plus its bound, the worst case, never less. Unknown with no hold.
73
- const worst = (turn) => {
74
- const hold = held.get(turn);
75
- return hold === undefined ? undefined : hold + (bounds.get(turn) ?? 0);
76
- };
68
+ // A request that never answered (a crash or a lost claim cut it; booked cut or not yet) counts for the cap at its hold,
69
+ // its worst case: its whole input uncached and the output it was sent with, so no cache miss bills it more. Unknown with
70
+ // no hold.
71
+ const worst = (turn) => held.get(turn);
77
72
  // Which of them were answered: each runner.turn names its own turn (one written before turns were named answers the
78
73
  // earliest still open, as answers then came in order).
79
74
  const answered = new Set();
80
75
  let spentUsd = 0;
81
- // The run's cost: what is known (each booked or reported figure), and how many requests have none. A held figure is
82
- // the cap's, never a cost: a request without its own figure makes the cost unknown, the known part kept beside it.
83
- let soFarUsd = 0;
76
+ // The run's cost (costOfParts): what is known (each booked or reported figure), each cut request booked at its hold
77
+ // apart (`bounded`, the most it can have cost), and how many requests have none. A held figure is the cap's, never a
78
+ // cost: a request without its own figure makes the cost unknown, the known part kept beside it.
79
+ let known = 0;
80
+ let bounded = 0;
84
81
  let unpriced = 0;
82
+ let atMost = 0;
85
83
  // Each request's figure for the cap, in the order its spend is summed (`spentUsd` is their sum; null: no figure).
86
84
  const figures = [];
87
85
  for (const r of records) {
88
86
  if (r.kind !== RUNNER_RECORDS.turn)
89
87
  continue;
90
88
  const data = r.data;
91
- // A request is booked once: a second runner.turn of a turn already answered (two bookings of one session that each
92
- // read it open, a cut written twice) counts no money and no request again.
93
- if (typeof data.turn === "number" && answered.has(data.turn))
89
+ // A request is booked once (rebooked): a second runner.turn of a turn already answered counts no money and no request.
90
+ if (rebooked(answered, typeof data.turn === "number" ? data.turn : undefined))
94
91
  continue;
95
92
  const turn = data.turn ?? turns.find((t) => !answered.has(t)) ?? 0;
96
93
  answered.add(turn);
97
94
  // The figure it was booked at (bookRequest), as written. A record from before that has none: a request cut off with
98
95
  // no answer at its worst case; a cost that never came in at the figure its answer was booked at (a stopped request's),
99
- // else what was held for it. One booked lost (at its hold) may have been billed at a cache miss like one with no
100
- // answer: for the cap, its worst case.
96
+ // else what was held for it.
101
97
  const booked = data.bookedUsd === null ? null : heldFigure(data.bookedUsd);
102
98
  const cut = data.cut === true && booked === undefined;
103
- const capped = booked !== undefined && bookedLost(data.rule) ? (worst(turn) ?? booked) : booked;
104
- const figure = capped !== undefined ? (capped ?? undefined) : cut ? worst(turn) : data.usd === null ? (heldFigure(data.heldUsd) ?? held.get(turn)) : (data.usd ?? 0);
99
+ const figure = booked !== undefined ? (booked ?? undefined) : cut ? worst(turn) : data.usd === null ? (heldFigure(data.heldUsd) ?? held.get(turn)) : (data.usd ?? 0);
105
100
  spentUsd = spent(spentUsd, figure);
106
101
  figures.push({ turn, usd: figure ?? null });
107
- // An answer with no price of its own (usd null) was booked at its hold for the cap: as a cost it is unknown, never
108
- // the hold (0 with no cap), as main read an unpriced answer.
109
- const own = answeredUnpriced(data) ? null : booked !== undefined ? booked : cut || data.usd === null ? null : data.usd === undefined ? 0 : (heldFigure(data.usd) ?? null);
110
- if (own === null)
102
+ // Its own cost (turnCostOf): an answer with no price of its own is unknown, never the hold it counts at for the cap; a
103
+ // request cut with no answer and booked at its hold is that figure, the most it can have cost.
104
+ const own = turnCostOf(data);
105
+ if (own.usd === null)
111
106
  unpriced++;
107
+ else if (own.atMost)
108
+ (bounded += own.usd), atMost++;
112
109
  else
113
- soFarUsd += own;
110
+ known += own.usd;
114
111
  }
115
112
  const openHolds = new Set();
116
113
  for (const turn of turns) {
@@ -124,15 +121,93 @@ export function sessionSpendOf(records) {
124
121
  figures.push({ turn, usd: worst(turn) ?? null });
125
122
  unpriced++;
126
123
  }
127
- return { turns, held, bounds, hosts, answered, openHolds, spentUsd, figures, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
124
+ return { turns, held, hosts, answered, openHolds, spentUsd, figures, cost: costOfParts([{ known, bounded, atMost, unpriced }]) };
125
+ }
126
+ /** The one rule for a cost made of parts, as every reader of a run's cost says it (the session's, the run's stored cost,
127
+ * its view and its usage row). Every charge counted: `usd` is their sum, holds included, and `atMost` how many of them are
128
+ * a hold, so the cost is at most `usd`. Any charge with no figure: `usd` is null, `soFarUsd` the charges' own figures
129
+ * alone, and `unpriced` counts the held ones with those of no figure. A hold is a ceiling, never spend: beside a cost no
130
+ * one knows it bounds nothing, so it joins no known sum, where it would read as money spent. */
131
+ export function costOfParts(parts) {
132
+ let known = 0;
133
+ let bounded = 0;
134
+ let atMost = 0;
135
+ let unpriced = 0;
136
+ for (const part of parts)
137
+ (known += part.known), (bounded += part.bounded), (atMost += part.atMost), (unpriced += part.unpriced);
138
+ if (unpriced > 0)
139
+ return { usd: null, soFarUsd: known, unpriced: unpriced + atMost };
140
+ return { usd: known + bounded, soFarUsd: known + bounded, unpriced: 0, ...(atMost > 0 ? { atMost } : {}) };
141
+ }
142
+ /** Whether a runner.turn books a request already booked: its turn (`key`, as the reader names it) is in `seen`, which it
143
+ * joins otherwise. Every reader of a booking (sessionSpendOf, serve's bookedSpend) skips such a record, so a request is
144
+ * counted once: two bookings of one session that each read it open, or a cut written twice, wrote it twice. A record
145
+ * with no turn (written before turns were named) is never a repeat. */
146
+ export function rebooked(seen, key) {
147
+ if (key === undefined)
148
+ return false;
149
+ if (seen.has(key))
150
+ return true;
151
+ seen.add(key);
152
+ return false;
153
+ }
154
+ /** The rule (runner.turn `rule`) of a request cut with no answer that bookCut booked at what its host held for it: the
155
+ * most it can have cost (its whole input uncached and the output it was sent with), marked `atMost`. */
156
+ export const CUT_AT_HOLD = "cut";
157
+ /** A booked request's own cost, from its runner.turn, as every reader of a run's cost reads it (the session's cost, the
158
+ * run's stored cost and its views): what it was booked at, else its `usd`; null when no one knows it (an answer with no
159
+ * price of its own booked at its hold for the cap, answeredUnpriced; a request cut with no hold). `atMost`: a request cut
160
+ * with no answer, booked at its hold (CUT_AT_HOLD), so the figure is the most it can have cost, never less. One billed to
161
+ * a person's plan (`billing: "plan"`) is $0 to the run however it ended: the plan pays for it, never the run. */
162
+ export function turnCostOf(data) {
163
+ // Billed to a person's plan (Admitted.plan): no dollars to the run however it ended, answered, stopped or cut.
164
+ if (data.billing === "plan")
165
+ return { usd: 0, atMost: false };
166
+ if (answeredUnpriced(data))
167
+ return { usd: null, atMost: false };
168
+ const booked = data.bookedUsd === null ? null : heldFigure(data.bookedUsd);
169
+ if (booked !== undefined)
170
+ return { usd: booked, atMost: booked !== null && data.rule === CUT_AT_HOLD && data.atMost === true };
171
+ if (data.cut === true || data.usd === null)
172
+ return { usd: null, atMost: false };
173
+ return { usd: data.usd === undefined ? 0 : (heldFigure(data.usd) ?? null), atMost: false };
128
174
  }
129
175
  /** Whether a request ended with no price of its own (usd null) under a rule that books it at a figure of the host's: an
130
176
  * answer with no cost (bookRequest's rule `answered`, or `answered:<label>`: its hold), or one our side stopped
131
177
  * (`stopped`: what streamed, an estimate) or lost (`lost`, `lost:<label>`: its hold). Each counts for the cap at that
132
178
  * figure, but as a cost it is unknown, never an estimate stored as a known charge (the provider may bill otherwise). */
133
179
  export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:") || data.rule === "stopped" || data.rule === "lost" || data.rule.startsWith("lost:"));
134
- /** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
135
- const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
180
+ /** The bookings of each session scope (SessionWriter.scope) in this process, across its claims: each request a booking
181
+ * admitted and has not seen answer (`flying`, settled once its afterRequest has written or failed to), and each answered
182
+ * request whose runner.turn the store refused (`refused`: a claim lost as the request answered). The scope's next
183
+ * booking waits for the first and writes the second at its bookCut: a request that answered is booked at what it
184
+ * reported, once, never cut at an unknown cost because the claim that sent it could no longer write. */
185
+ const handoffs = new Map();
186
+ /** How long a bookCut waits for an earlier booking's request still in flight in this process (its claim lost, its loop
187
+ * stopping, which ends its requests): past it, the request is booked cut as one a dead process left. */
188
+ const HANDOFF_WAIT_MS = 10_000;
189
+ /** The most scopes kept: past it, the oldest with nothing in flight is dropped (a run resumed in another process, or not
190
+ * at all, never takes what it left here; its next booking anywhere books those requests cut, as before). */
191
+ const HANDOFF_SCOPES_MAX = 1024;
192
+ const handoffOf = (scope) => {
193
+ let at = handoffs.get(scope);
194
+ if (!at) {
195
+ at = { flying: new Map(), refused: new Map() };
196
+ handoffs.set(scope, at);
197
+ if (handoffs.size > HANDOFF_SCOPES_MAX)
198
+ for (const [key, old] of handoffs)
199
+ if (old.flying.size === 0 && key !== scope) {
200
+ handoffs.delete(key);
201
+ break;
202
+ }
203
+ }
204
+ return at;
205
+ };
206
+ const handoffDone = (scope) => {
207
+ const at = handoffs.get(scope);
208
+ if (at && at.flying.size === 0 && at.refused.size === 0)
209
+ handoffs.delete(scope);
210
+ };
136
211
  function bookingFor(writer, options) {
137
212
  const node = { key: options.key, label: options.label ?? options.key, ...(options.executionPath === undefined ? {} : { executionPath: options.executionPath }) };
138
213
  const limit = options.maxTurns ?? null;
@@ -144,12 +219,14 @@ function bookingFor(writer, options) {
144
219
  const hosts = read.hosts;
145
220
  let turns = inherited.length;
146
221
  const held = read.held;
147
- /** What a cache miss adds to each request's hold (Admission.boundUsd): a request booked lost counts at both. */
148
- const bounds = read.bounds;
149
222
  /** What the host counts each request of this process at if its client stops it part way (Admission.stoppedUsd). */
150
223
  const stoppedAt = new Map();
151
224
  /** The host's record of a note each request of this process carries (Admission.note), for its runner.turn. */
152
225
  const notes = new Map();
226
+ /** The requests of this process on a free model (Admitted.free): each booked a known $0 however it ends. */
227
+ const freeTurns = new Set();
228
+ /** The requests of this process billed to a plan (Admitted.plan): each booked $0 to the run however it ends. */
229
+ const planTurns = new Set();
153
230
  const answered = read.answered;
154
231
  let spentUsd = read.spentUsd;
155
232
  // The ids each request's response gave it, kept as its headers arrived: a request cut off after them reached the provider.
@@ -163,6 +240,24 @@ function bookingFor(writer, options) {
163
240
  }
164
241
  // This process's requests in flight, oldest first: the turn each was admitted as, and its model.
165
242
  const open = [];
243
+ // Each of them as the session's scope knows it in flight (handoffs), settled once its afterRequest has written or not.
244
+ const scope = writer.scope;
245
+ const settles = new Map();
246
+ const fly = (turn) => {
247
+ if (scope === undefined)
248
+ return;
249
+ let settle;
250
+ const flying = handoffOf(scope).flying;
251
+ const done = new Promise((resolve) => (settle = resolve));
252
+ flying.set(turn, done);
253
+ settles.set(turn, () => {
254
+ settles.delete(turn);
255
+ if (flying.get(turn) === done)
256
+ flying.delete(turn);
257
+ settle();
258
+ handoffDone(scope);
259
+ });
260
+ };
166
261
  // Response ids whose own write was refused, marked `late`: the booking's next write of its own (the next runner.request,
167
262
  // or a runner.turn) carries them first, so a request this process cuts by dying after that still keeps its ids. One a
168
263
  // runner.turn writes with the ids is dropped, never written twice. A process that dies before writing for its booking
@@ -185,7 +280,7 @@ function bookingFor(writer, options) {
185
280
  // A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
186
281
  let failed;
187
282
  const end = (reason, message, code) => options.stop ? options.stop(reason, message, code) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }), ...(code === undefined ? {} : { refusal: code }) });
188
- const admit = async ({ model, inputTokensMax: measured, inputTokensCounted, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, unanswered, noted, inputTokensMaxWithoutNote, host, route }) => {
283
+ const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, unanswered, noted, inputTokensMaxWithoutNote, host, route, signal }) => {
189
284
  let inputTokensMax = measured;
190
285
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
191
286
  if (stopped)
@@ -195,13 +290,13 @@ function bookingFor(writer, options) {
195
290
  throw pausing;
196
291
  if (limit !== null && turns >= limit)
197
292
  throw end("turn_limit");
198
- const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax, ...(inputTokensCounted ? { inputTokensCounted } : {}),
293
+ // A host that makes the request wait for room (runBooking) lets it go at its client's abort or the booking's own stop.
294
+ const halted = () => options.stopped?.(host === undefined ? {} : { host }) ?? failed ?? options.draining?.();
295
+ const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax, ...(signal ? { signal } : {}), halted,
199
296
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(unanswered ? { unanswered } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
200
297
  if (verdict && "refuse" in verdict)
201
298
  throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
202
299
  const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
203
- // What a cache miss adds to the hold: kept beside it, so a request that never answers counts at both (sessionSpendOf).
204
- const bound = hold !== undefined && verdict && "boundUsd" in verdict ? heldFigure(verdict.boundUsd) : undefined;
205
300
  // Admitted only without the note: it goes as its client sent it, measured so.
206
301
  const withoutNote = noted === true && !!verdict && "withoutNote" in verdict && verdict.withoutNote === true;
207
302
  if (withoutNote)
@@ -220,20 +315,28 @@ function bookingFor(writer, options) {
220
315
  // Durable before the request leaves: admitted, then sent. It counts as a turn once its record is written (admissions
221
316
  // run one at a time), so a write that fails refuses the request and costs no turn.
222
317
  const turn = turns + 1;
223
- await write([{ kind: RUNNER_RECORDS.request, data: { turn, model, ...(hold === undefined ? {} : { heldUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(side ? { side } : {}), ...(host === undefined ? {} : { host }), ...(paid?.call === undefined ? {} : { call: paid.call }), ...(paid?.charged_by === undefined ? {} : { charged_by: paid.charged_by }), ...(paid?.tool === undefined ? {} : { tool: paid.tool }), ...(paid?.tag === undefined ? {} : { tag: paid.tag }), ...(paid?.owed ? { owed: true } : {}), ...(paid?.hold ? { hold: true } : {}), ...(paid?.ref === undefined ? {} : { ref: paid.ref }) } }]);
318
+ // Billed to a plan (Admitted.plan), or counted toward the run's free-model limit (Admitted.freeRequest): said on its
319
+ // record, so a later process that books it cut books it so, and the next count holds it. Never both (runCap).
320
+ const onPlan = !!verdict && "plan" in verdict && verdict.plan === true;
321
+ const freeRequest = !!verdict && "freeRequest" in verdict && verdict.freeRequest === true;
322
+ // A paid tool call (ModelRequest.paid) says so on its record (`paid`), so a later process that books it cut knows its
323
+ // hold is its fee as admitted, never a bound on what its provider charged (bookCut).
324
+ await write([{ kind: RUNNER_RECORDS.request, data: { turn, model, ...(paid ? { paid: true } : {}), ...(hold === undefined ? {} : { heldUsd: hold }), ...(onPlan ? { plan: true } : {}), ...(freeRequest ? { freeRequest: true } : {}), ...(side ? { side } : {}), ...(host === undefined ? {} : { host }), ...(paid?.call === undefined ? {} : { call: paid.call }), ...(paid?.charged_by === undefined ? {} : { charged_by: paid.charged_by }), ...(paid?.tool === undefined ? {} : { tool: paid.tool }), ...(paid?.tag === undefined ? {} : { tag: paid.tag }), ...(paid?.owed ? { owed: true } : {}), ...(paid?.hold ? { hold: true } : {}), ...(paid?.ref === undefined ? {} : { ref: paid.ref }) } }]);
224
325
  turns = turn;
225
326
  if (host !== undefined)
226
327
  hosts.set(turn, host);
227
328
  if (hold !== undefined)
228
329
  held.set(turn, hold);
229
- if (bound)
230
- bounds.set(turn, bound);
231
330
  const stoppedUsd = verdict && "stoppedUsd" in verdict && typeof verdict.stoppedUsd === "function" ? verdict.stoppedUsd : undefined;
232
331
  if (stoppedUsd)
233
332
  stoppedAt.set(turn, stoppedUsd);
234
333
  const note = verdict && "note" in verdict && verdict.note && typeof verdict.note === "object" && !withoutNote ? verdict.note : undefined;
235
334
  if (note)
236
335
  notes.set(turn, note);
336
+ if (verdict && "free" in verdict && verdict.free === true)
337
+ freeTurns.add(turn);
338
+ if (onPlan)
339
+ planTurns.add(turn);
237
340
  // A stop that came while the record was written: the request has not left. It is booked withdrawn, at $0, so no
238
341
  // later process books it as cut at an unknown price; if that write fails, it is booked cut, which is never less.
239
342
  // Its record is written, so it costs a turn of the cap, never money.
@@ -263,7 +366,8 @@ function bookingFor(writer, options) {
263
366
  await emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
264
367
  throw stoppedLate;
265
368
  }
266
- open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
369
+ open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }), ...(paid?.hold ? { stays: true } : {}) });
370
+ fly(turn);
267
371
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
268
372
  };
269
373
  const models = {
@@ -298,6 +402,17 @@ function bookingFor(writer, options) {
298
402
  stoppedAt.delete(turn);
299
403
  const note = notes.get(turn);
300
404
  notes.delete(turn);
405
+ // Billed to a plan: so booked however it ended (a cut or a stop reports no usage that says so), at $0 for the cap
406
+ // as its hold is, and $0 to the run (turnCostOf).
407
+ const plan = planTurns.delete(turn);
408
+ if (plan && usage.billing === undefined)
409
+ usage = { ...usage, billing: "plan" };
410
+ // On a free model nothing it was billed for costs anything: its own cost is a known $0, never unknown. A cost its
411
+ // provider reported above $0 is a cost all the same: booked as it is, never free. A request billed to a plan is the
412
+ // plan's, at no price here, whatever its listing says: never free.
413
+ const free = freeTurns.delete(turn) && usage.billing === undefined && (usage.usd === null || usage.usd === 0);
414
+ if (free)
415
+ usage = { ...usage, usd: 0, free };
301
416
  // Its hidden reasoning counts beside all it sent, less the reasoning it sent: max(0, budget - reasoning bytes), so
302
417
  // reasoning that streamed is not counted twice and answer text never stands in for it.
303
418
  const figure0 = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
@@ -307,19 +422,27 @@ function bookingFor(writer, options) {
307
422
  const stopped = usage.usd === null && hold !== undefined && stoppedUsd && sent !== undefined ? heldFigure(stoppedUsd(sent + Math.max(0, hidden - reasoned))) : undefined;
308
423
  // How its path saw it end, booked by the one rule (booking.ts); a host from before that says nothing of it: as
309
424
  // before, its own cost, else what streamed of a stop, else the hold.
310
- const booking = ended ? bookRequest(ended, { ...(hold === undefined ? {} : { hold }), ...(stoppedUsd ? { stoppedPrice: stoppedUsd } : {}) }) : undefined;
425
+ const booking = ended ? bookRequest(ended, { ...(hold === undefined ? (plan ? { hold: 0 } : {}) : { hold }), ...(stoppedUsd ? { stoppedPrice: stoppedUsd } : {}), ...(free ? { free } : {}) }) : undefined;
311
426
  const figure = booking ? booking.usd : usage.usd !== null ? usage.usd : stopped === undefined ? hold : Math.min(hold, stopped);
312
- // Booked lost (at its hold), it may have been billed at a cache miss: for the cap, its hold plus its bound, as
313
- // sessionSpendOf reads it on the next claim.
314
- const capped = booking && bookedLost(booking.rule) && hold !== undefined ? hold + (bounds.get(turn) ?? 0) : figure;
315
- spentUsd = spent(spentUsd, capped ?? undefined);
427
+ spentUsd = spent(spentUsd, figure ?? undefined);
428
+ const settle = settles.get(turn);
429
+ const data = { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.givenBack ? { givenBack: true } : {}), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.billing ? { billing: usage.billing } : {}), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}), ...(ended?.end === "nothing" && ended.label === "refused" && ended.reason ? { refusal: ended.reason } : {}), ...(ended?.end === "answered" && ended.label === "error" && ended.reason ? { providerError: ended.reason } : {}), ...(note ? { note } : {}) };
430
+ // Marked so, for a reader to say why it cost nothing (a run on free models: "$0 · free model").
431
+ if (free)
432
+ data.free = true;
316
433
  try {
317
434
  // A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
318
435
  // stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
319
436
  const covers = (r) => usage.providerIds !== undefined && r.data.turn === turn;
320
- await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.givenBack ? { givenBack: true } : {}), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}), ...(note ? { note } : {}) } }], covers);
437
+ await write([{ kind: RUNNER_RECORDS.turn, data }], covers);
438
+ settle?.();
321
439
  }
322
440
  catch (error) {
441
+ // Refused (its claim lost as it answered, say): the booking is handed to the session's next booking in this
442
+ // process, which writes it at its bookCut, never cutting a request that answered (handoffs).
443
+ if (scope !== undefined)
444
+ handoffOf(scope).refused.set(turn, { data, usage, ...(ended ? { ended } : {}) });
445
+ settle?.();
323
446
  // A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted. Asked
324
447
  // with the request's own host label, as its admission was: a stop that holds only the harness's own requests (a
325
448
  // parked turn's) never hides the failure from the host's. A turn parked on a call (TurnParked) is no stop of the
@@ -346,10 +469,57 @@ function bookingFor(writer, options) {
346
469
  // Only requests an earlier process admitted: one this process has in flight is not cut. Read again here, just before
347
470
  // the cut is written: another booking of this session (an earlier pass of this claim, or one racing it) may have
348
471
  // booked it since this one opened, and a request is booked once.
349
- const bookedSince = sessionSpendOf(await writer.read().catch(() => options.records)).answered;
472
+ // An earlier booking of this session in this process (a claim lost, then taken again here) may still have one of them
473
+ // in flight: its end is waited for, bounded, so a request that answers meanwhile is booked by what it reported.
474
+ const before = scope === undefined ? undefined : handoffs.get(scope);
475
+ const flying = before ? inherited.filter((t) => !answered.has(t)).flatMap((t) => before.flying.get(t) ?? []) : [];
476
+ if (flying.length) {
477
+ let timer;
478
+ await Promise.race([Promise.all(flying), new Promise((resolve) => (timer = setTimeout(resolve, HANDOFF_WAIT_MS)))]);
479
+ clearTimeout(timer);
480
+ }
481
+ const now = await writer.read().catch(() => options.records);
482
+ // Every record this pass appends after that read (a handed-on answer, a given-back hold, an owed step, a free cut), in
483
+ // order: a spend rebuilt from the session's records reads `now` and these, so a request booked earlier in the pass
484
+ // counts at what it was booked at, never at the hold `now` still has it open at.
485
+ const booked = [];
486
+ const book = async (records) => {
487
+ await append(records);
488
+ booked.push(...records);
489
+ };
490
+ const bookedSince = sessionSpendOf(now).answered;
350
491
  for (const t of inherited)
351
492
  if (bookedSince.has(t))
352
493
  answered.add(t);
494
+ // A request an earlier booking in this process saw answer, whose runner.turn its store refused: written now as that
495
+ // booking would have written it, and told as it would have told it, at what it reported. One the session booked since
496
+ // is dropped: a request is booked once.
497
+ const handed = scope === undefined ? undefined : handoffs.get(scope);
498
+ if (scope !== undefined && handed) {
499
+ for (const t of inherited)
500
+ if (answered.has(t))
501
+ handed.refused.delete(t);
502
+ const taken = inherited.flatMap((turn) => {
503
+ const one = handed.refused.get(turn);
504
+ return one ? [{ turn, ...one }] : [];
505
+ });
506
+ if (taken.length) {
507
+ await book(taken.map((one) => ({ kind: RUNNER_RECORDS.turn, data: one.data })));
508
+ for (const one of taken) {
509
+ handed.refused.delete(one.turn);
510
+ answered.add(one.turn);
511
+ }
512
+ // Its spend read the request at its hold (or unknown); booked, it reads at what it was booked at. Only
513
+ // before this booking's own requests: the spend is the session's records then.
514
+ if (turns === inherited.length && open.length === 0)
515
+ spentUsd = sessionSpendOf([...now, ...booked]).spentUsd;
516
+ for (const one of taken) {
517
+ const hosted = hosts.get(one.turn);
518
+ await emit({ type: "request_end", turn: one.turn, usage: one.usage, ...(hosted === undefined ? {} : { host: hosted }), ...(one.ended ? { ended: one.ended } : {}) });
519
+ }
520
+ }
521
+ handoffDone(scope);
522
+ }
353
523
  const left = inherited.filter((t) => !answered.has(t));
354
524
  if (left.length === 0)
355
525
  return;
@@ -364,36 +534,82 @@ function bookingFor(writer, options) {
364
534
  return data.owed === true && data.hold !== true ? [inherited[i]] : [];
365
535
  }));
366
536
  const owed = left.filter((t) => !read.openHolds.has(t) && owedTurns.has(t) && (held.get(t) ?? 0) > 0);
367
- const numbers = left.filter((t) => !read.openHolds.has(t) && !owed.includes(t));
537
+ // A request on a free model (its runner.request says `freeRequest`, as the run's cap admitted it) an earlier process
538
+ // left open costs nothing whatever reached the provider: booked cut at a known $0 and marked `free`, as this process
539
+ // books its own (bookRequest's free), never unknown. Any other keeps the rule below.
540
+ const freeTurns = new Set(options.records.filter((r) => r.kind === RUNNER_RECORDS.request).flatMap((r, i) => {
541
+ const data = (r.data ?? {});
542
+ return data.freeRequest === true ? [typeof data.turn === "number" ? data.turn : i + 1] : [];
543
+ }));
544
+ const free = left.filter((t) => !read.openHolds.has(t) && !owed.includes(t) && freeTurns.has(t));
545
+ const numbers = left.filter((t) => !read.openHolds.has(t) && !owed.includes(t) && !free.includes(t));
368
546
  if (givenBack.length) {
369
- await append(givenBack.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, givenBack: true } })));
547
+ await book(givenBack.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, givenBack: true } })));
370
548
  for (const turn of givenBack)
371
549
  answered.add(turn);
372
550
  }
373
551
  if (owed.length) {
374
- await append(owed.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: held.get(turn), bookedUsd: held.get(turn), rule: "owed" } })));
552
+ await book(owed.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: held.get(turn), bookedUsd: held.get(turn), rule: "owed" } })));
375
553
  for (const turn of owed) {
376
554
  answered.add(turn);
377
555
  const hosted = hosts.get(turn);
378
556
  emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: held.get(turn), estimated: true }, ...(hosted === undefined ? {} : { host: hosted }) });
379
557
  }
380
558
  }
381
- if (numbers.length === 0)
382
- return;
383
559
  // A cut request whose response had begun carries the ids it gave: the provider saw it, under them. One with none may
384
- // still have reached the provider before any answer; both are booked at an unknown price.
560
+ // still have reached the provider before any answer. Neither left a figure of its own (the process that would have
561
+ // read what it reported is gone): one its host held a figure for is booked at that hold, the most it can have cost
562
+ // (CUT_AT_HOLD, `atMost`), so the run's cost stays known and says it is an upper bound; one with no hold (no cap) is
563
+ // booked at an unknown price, as no one can bound it. A hold of $0 (no cap's) bounds nothing, and a paid tool call's
564
+ // (its runner.request's `paid`) is its fee as admitted, not what its provider may have charged: both stay unknown.
565
+ // One billed to a person's plan (its runner.request's `plan`) costs the run $0 however it ended: booked cut at $0,
566
+ // marked as the plan's (`billing`), a known figure, never an unknown that blanks the run's cost.
567
+ // Each request left open is in exactly one class, taken in this order: given back (an open hold-only step), owed (its
568
+ // figure settled at admission), free (`freeRequest`: a known $0, `free`), then `numbers`, where a plan request books $0
569
+ // billing "plan" and any other at its hold (`atMost`) or unknown. A request is never both free and plan: the cap marks
570
+ // a plan request `plan` before it looks at free, and freeModel refuses a plan model, so no plan request is admitted
571
+ // `freeRequest`.
572
+ const modelTurns = new Set(options.records.filter((r) => r.kind === RUNNER_RECORDS.request).flatMap((r, i) => (r.data?.paid === true ? [] : [inherited[i]])));
573
+ const onPlan = new Set(options.records.filter((r) => r.kind === RUNNER_RECORDS.request).flatMap((r, i) => (r.data?.plan === true ? [inherited[i]] : [])));
574
+ const boundOf = (turn) => {
575
+ const hold = held.get(turn);
576
+ return hold !== undefined && hold > 0 && modelTurns.has(turn) ? hold : undefined;
577
+ };
385
578
  const cutOf = (turn) => {
386
579
  const providerIds = responses.get(turn);
387
- return providerIds ? { usd: null, cut: true, turn, providerIds } : { usd: null, cut: true, turn };
580
+ if (onPlan.has(turn))
581
+ return { usd: null, cut: true, turn, bookedUsd: 0, rule: CUT_AT_HOLD, billing: "plan", ...(providerIds ? { providerIds } : {}) };
582
+ const hold = boundOf(turn);
583
+ return { usd: null, cut: true, turn, ...(hold === undefined ? {} : { bookedUsd: hold, rule: CUT_AT_HOLD, atMost: true }), ...(providerIds ? { providerIds } : {}) };
388
584
  };
585
+ if (free.length) {
586
+ await book(free.map((turn) => {
587
+ const providerIds = responses.get(turn);
588
+ return { kind: RUNNER_RECORDS.turn, data: { usd: 0, cut: true, turn, ...(providerIds ? { providerIds } : {}), bookedUsd: 0, rule: "lost:cut", free: true } };
589
+ }));
590
+ for (const turn of free) {
591
+ answered.add(turn);
592
+ const providerIds = responses.get(turn);
593
+ const hosted = hosts.get(turn);
594
+ emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0, cut: true, free: true, ...(providerIds ? { providerIds } : {}) }, ...(hosted === undefined ? {} : { host: hosted }), ended: { end: "lost", label: "cut" } });
595
+ }
596
+ // Its spend read the request at its hold (or unknown); booked, it reads at $0. Only before this booking's own
597
+ // requests: the spend is the session's records then, every one this pass booked above included (a handed-on answer
598
+ // at what it reported, an owed step at its booked figure).
599
+ if (turns === inherited.length && open.length === 0)
600
+ spentUsd = sessionSpendOf([...now, ...booked]).spentUsd;
601
+ }
602
+ if (numbers.length === 0)
603
+ return;
389
604
  await append(numbers.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: cutOf(turn) })));
390
605
  for (const turn of numbers)
391
606
  answered.add(turn);
392
- // The spend already counts each of them, at its hold plus its bound or as unknown: booking them adds nothing.
607
+ // The spend already counts each of them, at its hold or as unknown: booking them adds nothing.
393
608
  for (const turn of numbers) {
394
609
  const providerIds = responses.get(turn);
395
610
  const hosted = hosts.get(turn);
396
- emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: null, estimated: true, cut: true, ...(providerIds ? { providerIds } : {}) }, ...(hosted === undefined ? {} : { host: hosted }), ended: { end: "lost", label: "cut" } });
611
+ const hold = onPlan.has(turn) ? undefined : boundOf(turn);
612
+ emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: null, estimated: true, cut: true, ...(hold === undefined ? {} : { atMostUsd: hold }), ...(onPlan.has(turn) ? { billing: "plan" } : {}), ...(providerIds ? { providerIds } : {}) }, ...(hosted === undefined ? {} : { host: hosted }), ended: { end: "lost", label: "cut" } });
397
613
  }
398
614
  };
399
615
  return {
@@ -401,7 +617,6 @@ function bookingFor(writer, options) {
401
617
  turns: () => turns,
402
618
  spentUsd: () => spentUsd,
403
619
  heldUsd: () => open.reduce((sum, flight) => (sum === null || flight.holdUsd === undefined ? null : sum + flight.holdUsd), 0),
404
- boundUsd: () => open.reduce((sum, flight) => sum + (flight.boundUsd ?? 0), 0),
405
620
  bookCut() {
406
621
  cutting ??= bookCut().catch((error) => {
407
622
  cutting = undefined;
package/dist/testing.d.ts CHANGED
@@ -3,10 +3,14 @@ import { type ModelProxyOptions } from "./host/proxy.js";
3
3
  export { SCHEMA_CHECK_CASES, type SchemaCheckCase } from "./schema-check-cases.js";
4
4
  /** The model proxy's own parts, for tests of a provider policy and of the proxy: the host API (./host) keeps only what a
5
5
  * harness runs. */
6
- export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
6
+ export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf, streamErrorOf, usageCostOf } from "./host/proxy.js";
7
7
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
8
- * counts one more holder at once, and a writer appends only while its count is the newest. */
9
- export declare function memorySessionStore(): SessionStore & {
8
+ * counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
9
+ * in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
10
+ * each open plays a process of its own, which hands nothing on. */
11
+ export declare function memorySessionStore(options?: {
12
+ scope?: string;
13
+ }): SessionStore & {
10
14
  keys(): string[];
11
15
  };
12
16
  /** What a scripted request reports beside its cost, as a real adapter's proxy reads a response, and how it is measured:
@@ -22,7 +26,8 @@ export declare function memorySessionStore(): SessionStore & {
22
26
  * session's (a resumed turn's, say) with no request of this process's own yet, and a side call's the only one open. The
23
27
  * side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists). */
24
28
  /** `onRefused: "next"`: a request its host refuses (its admission throws) is not the turn's end: the client goes on to its
25
- * next action, as a CLI whose request the proxy refused sends another. */
29
+ * next action, as a CLI whose request the proxy refused sends another. `effort`: the reasoning effort its body names, as
30
+ * the proxy tells it beside its least (ProviderPolicy.effortOf). */
26
31
  export type FauxRequest = {
27
32
  onRefused?: "next";
28
33
  tokens?: {
@@ -34,6 +39,7 @@ export type FauxRequest = {
34
39
  inputTokensMax?: number;
35
40
  outputTokensAsked?: number;
36
41
  outputTokensLeast?: number;
42
+ effort?: string;
37
43
  until?: string;
38
44
  bookWhen?: string;
39
45
  sideAfterNote?: {
package/dist/testing.js CHANGED
@@ -12,10 +12,12 @@ import { randomBytes } from "node:crypto";
12
12
  export { SCHEMA_CHECK_CASES } from "./schema-check-cases.js";
13
13
  /** The model proxy's own parts, for tests of a provider policy and of the proxy: the host API (./host) keeps only what a
14
14
  * harness runs. */
15
- export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
15
+ export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf, streamErrorOf, usageCostOf } from "./host/proxy.js";
16
16
  /** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
17
- * counts one more holder at once, and a writer appends only while its count is the newest. */
18
- export function memorySessionStore() {
17
+ * counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
18
+ * in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
19
+ * each open plays a process of its own, which hands nothing on. */
20
+ export function memorySessionStore(options = {}) {
19
21
  const sessions = new Map();
20
22
  const holders = new Map();
21
23
  const read = async (key) => structuredClone(sessions.get(key) ?? []);
@@ -26,6 +28,7 @@ export function memorySessionStore() {
26
28
  holders.set(key, holder);
27
29
  return {
28
30
  key,
31
+ ...(options.scope === undefined ? {} : { scope: `${options.scope}\n${key}` }),
29
32
  read: () => read(key),
30
33
  async append(records) {
31
34
  if (holders.get(key) !== holder)
@@ -53,7 +56,6 @@ export function fauxAdapter(options) {
53
56
  get calls() { return stats.calls; },
54
57
  get opened() { return stats.opened; },
55
58
  get closed() { return stats.closed; },
56
- capabilities: () => ({}),
57
59
  check: (spec) => [
58
60
  ...(spec.context === "fork" ? ["the faux harness cannot fork a session"] : []),
59
61
  ...(options.refuse?.(spec) ?? []),
@@ -203,7 +205,7 @@ export function fauxAdapter(options) {
203
205
  io.onEvent({ type: "text", delta: say });
204
206
  }
205
207
  // The output it asks for at most (a CLI's max_tokens), as a real adapter's proxy reads it from the body.
206
- const asked = { ...("outputTokensAsked" in action && typeof action.outputTokensAsked === "number" ? { outputTokensAsked: action.outputTokensAsked } : {}), ...("outputTokensLeast" in action && typeof action.outputTokensLeast === "number" ? { outputTokensLeast: action.outputTokensLeast } : {}) };
208
+ const asked = { ...("outputTokensAsked" in action && typeof action.outputTokensAsked === "number" ? { outputTokensAsked: action.outputTokensAsked } : {}), ...("outputTokensLeast" in action && typeof action.outputTokensLeast === "number" ? { outputTokensLeast: action.outputTokensLeast } : {}), ...("effort" in action && typeof action.effort === "string" ? { effort: action.effort } : {}) };
207
209
  const admit = () => io.models.beforeRequest({ model: own, inputTokensMax: note ? measured + Buffer.byteLength(note, "utf8") : measured, ...asked, ...(note ? { noted: true, inputTokensMaxWithoutNote: measured } : {}) });
208
210
  let ticket;
209
211
  try {
@@ -0,0 +1,12 @@
1
+ export declare const TOOLS_SEARCH = "tools_search";
2
+ export declare const TOOLS_CALL = "tools_call";
3
+ export declare const CODEMODE = "codemode";
4
+ /** The three, by name: none of them can be called through another, and none is searched for. */
5
+ export declare const META_TOOLS: ReadonlySet<string>;
6
+ /** A run with more catalog tools than this is deferred them. */
7
+ export declare const DEFER_CATALOG_OVER = 20;
8
+ /** Whether a tool is a catalog tool, by its wire name (the name a harness gives it): an MCP tool (`mcp__<server>__<tool>`)
9
+ * or a monid endpoint (`monid__<provider>__<endpoint>`). */
10
+ export declare const isCatalogWire: (name: string) => boolean;
11
+ /** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
12
+ export declare const defersCatalog: (names: readonly string[]) => boolean;
@@ -0,0 +1,17 @@
1
+ // One discovery system. A run lists every tool to the model in full until its catalog tools (an MCP server's, a monid
2
+ // one) pass DEFER_CATALOG_OVER: then they are deferred, not listed, and the model finds them with tools_search and runs
3
+ // them with tools_call. Claude Code defers MCP tools itself (its ToolSearch), on under the same test, so it is offered
4
+ // neither of ours. Built-ins and a harness's own tools are always listed. A run under the threshold has no search or call:
5
+ // they would find tools the model already has, at about 640 tokens on every request.
6
+ export const TOOLS_SEARCH = "tools_search";
7
+ export const TOOLS_CALL = "tools_call";
8
+ export const CODEMODE = "codemode";
9
+ /** The three, by name: none of them can be called through another, and none is searched for. */
10
+ export const META_TOOLS = new Set([TOOLS_SEARCH, TOOLS_CALL, CODEMODE]);
11
+ /** A run with more catalog tools than this is deferred them. */
12
+ export const DEFER_CATALOG_OVER = 20;
13
+ /** Whether a tool is a catalog tool, by its wire name (the name a harness gives it): an MCP tool (`mcp__<server>__<tool>`)
14
+ * or a monid endpoint (`monid__<provider>__<endpoint>`). */
15
+ export const isCatalogWire = (name) => name.startsWith("mcp__") || name.startsWith("monid__");
16
+ /** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
17
+ export const defersCatalog = (names) => names.filter(isCatalogWire).length > DEFER_CATALOG_OVER;