@parcha/agentrun-kernel 0.1.0-beta.38 → 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.
- package/CHANGELOG.md +83 -0
- package/NOTICE +2 -0
- package/dist/booking.d.ts +25 -6
- package/dist/booking.js +15 -4
- package/dist/host/index.d.ts +4 -3
- package/dist/host/index.js +3 -2
- package/dist/host/o200k.d.ts +11 -0
- package/dist/host/o200k.js +185 -0
- package/dist/host/overhead.d.ts +72 -12
- package/dist/host/overhead.js +220 -38
- package/dist/host/proxy.d.ts +85 -7
- package/dist/host/proxy.js +374 -87
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/kernel/cap/admit.d.ts +5 -8
- package/dist/kernel/cap/admit.js +13 -19
- package/dist/kernel/cap/free.d.ts +43 -0
- package/dist/kernel/cap/free.js +71 -0
- package/dist/kernel/cap/index.d.ts +6 -5
- package/dist/kernel/cap/index.js +5 -4
- package/dist/kernel/cap/marks.d.ts +2 -3
- package/dist/kernel/cap/park.d.ts +3 -4
- package/dist/kernel/cap/park.js +4 -5
- package/dist/kernel/cap/port.d.ts +8 -13
- package/dist/kernel/cap/port.js +10 -18
- package/dist/kernel/cap/price.d.ts +10 -49
- package/dist/kernel/cap/price.js +15 -68
- package/dist/kernel/cap/recover.d.ts +1 -2
- package/dist/kernel/cap/recover.js +2 -4
- package/dist/kernel/cap/rule.d.ts +8 -16
- package/dist/kernel/cap/rule.js +35 -35
- package/dist/kernel/cap/run-cap.d.ts +21 -13
- package/dist/kernel/cap/run-cap.js +74 -36
- package/dist/kernel/cap/types.d.ts +11 -31
- package/dist/kernel/cap/words.d.ts +13 -8
- package/dist/kernel/cap/words.js +23 -14
- package/dist/kernel/cap/wrap-up.d.ts +4 -0
- package/dist/kernel/cap/wrap-up.js +5 -1
- package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
- package/dist/kernel/registry/computer-surface.generated.js +9 -25
- package/dist/kernel/registry/computer.d.ts +14 -7
- package/dist/kernel/registry/computer.js +52 -12
- package/dist/kernel/registry/gate.d.ts +2 -2
- package/dist/kernel/registry/gate.js +4 -7
- package/dist/kernel/registry/hands.d.ts +3 -4
- package/dist/kernel/registry/index.d.ts +1 -1
- package/dist/kernel/registry/index.js +1 -1
- package/dist/kernel/registry/registry.js +6 -9
- package/dist/process/recovery.d.ts +4 -1
- package/dist/process/recovery.js +15 -3
- package/dist/process/resume.d.ts +5 -2
- package/dist/process/resume.js +15 -3
- package/dist/process/tools.d.ts +26 -1
- package/dist/process/tools.js +47 -4
- package/dist/run-booking.d.ts +21 -2
- package/dist/run-booking.js +215 -18
- package/dist/runner.d.ts +82 -21
- package/dist/runner.js +176 -59
- package/dist/testing.d.ts +4 -2
- package/dist/testing.js +2 -2
- package/dist/tool-deferral.d.ts +3 -3
- package/dist/tool-deferral.js +4 -4
- package/dist/types.d.ts +70 -14
- package/dist/types.js +8 -0
- package/package.json +5 -3
- package/vendor/o200k/LICENSE +61 -0
- package/vendor/o200k/o200k_base.tiktoken +199998 -0
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
|
-
|
|
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)
|
|
72
|
-
//
|
|
73
|
-
|
|
74
|
-
|
|
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),
|
|
82
|
-
// the
|
|
83
|
-
|
|
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
|
|
92
|
-
|
|
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.
|
|
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
|
|
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
|
-
//
|
|
108
|
-
//
|
|
109
|
-
const own =
|
|
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
|
-
|
|
110
|
+
known += own.usd;
|
|
114
111
|
}
|
|
115
112
|
const openHolds = new Set();
|
|
116
113
|
for (const turn of turns) {
|
|
@@ -124,15 +121,62 @@ export function sessionSpendOf(records) {
|
|
|
124
121
|
figures.push({ turn, usd: worst(turn) ?? null });
|
|
125
122
|
unpriced++;
|
|
126
123
|
}
|
|
127
|
-
return { turns, held,
|
|
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:"));
|
|
136
180
|
/** The bookings of each session scope (SessionWriter.scope) in this process, across its claims: each request a booking
|
|
137
181
|
* admitted and has not seen answer (`flying`, settled once its afterRequest has written or failed to), and each answered
|
|
138
182
|
* request whose runner.turn the store refused (`refused`: a claim lost as the request answered). The scope's next
|
|
@@ -175,12 +219,14 @@ function bookingFor(writer, options) {
|
|
|
175
219
|
const hosts = read.hosts;
|
|
176
220
|
let turns = inherited.length;
|
|
177
221
|
const held = read.held;
|
|
178
|
-
/** What a cache miss adds to each request's hold (Admission.boundUsd): a request booked lost counts at both. */
|
|
179
|
-
const bounds = read.bounds;
|
|
180
222
|
/** What the host counts each request of this process at if its client stops it part way (Admission.stoppedUsd). */
|
|
181
223
|
const stoppedAt = new Map();
|
|
182
224
|
/** The host's record of a note each request of this process carries (Admission.note), for its runner.turn. */
|
|
183
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();
|
|
184
230
|
const answered = read.answered;
|
|
185
231
|
let spentUsd = read.spentUsd;
|
|
186
232
|
// The ids each request's response gave it, kept as its headers arrived: a request cut off after them reached the provider.
|
|
@@ -234,7 +280,7 @@ function bookingFor(writer, options) {
|
|
|
234
280
|
// A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
|
|
235
281
|
let failed;
|
|
236
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 }) });
|
|
237
|
-
const admit = async ({ model, inputTokensMax: measured,
|
|
283
|
+
const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, unanswered, noted, inputTokensMaxWithoutNote, host, route, signal }) => {
|
|
238
284
|
let inputTokensMax = measured;
|
|
239
285
|
const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
|
|
240
286
|
if (stopped)
|
|
@@ -244,13 +290,13 @@ function bookingFor(writer, options) {
|
|
|
244
290
|
throw pausing;
|
|
245
291
|
if (limit !== null && turns >= limit)
|
|
246
292
|
throw end("turn_limit");
|
|
247
|
-
|
|
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,
|
|
248
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 }) });
|
|
249
297
|
if (verdict && "refuse" in verdict)
|
|
250
298
|
throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
|
|
251
299
|
const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
|
|
252
|
-
// What a cache miss adds to the hold: kept beside it, so a request that never answers counts at both (sessionSpendOf).
|
|
253
|
-
const bound = hold !== undefined && verdict && "boundUsd" in verdict ? heldFigure(verdict.boundUsd) : undefined;
|
|
254
300
|
// Admitted only without the note: it goes as its client sent it, measured so.
|
|
255
301
|
const withoutNote = noted === true && !!verdict && "withoutNote" in verdict && verdict.withoutNote === true;
|
|
256
302
|
if (withoutNote)
|
|
@@ -269,20 +315,28 @@ function bookingFor(writer, options) {
|
|
|
269
315
|
// Durable before the request leaves: admitted, then sent. It counts as a turn once its record is written (admissions
|
|
270
316
|
// run one at a time), so a write that fails refuses the request and costs no turn.
|
|
271
317
|
const turn = turns + 1;
|
|
272
|
-
|
|
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 }) } }]);
|
|
273
325
|
turns = turn;
|
|
274
326
|
if (host !== undefined)
|
|
275
327
|
hosts.set(turn, host);
|
|
276
328
|
if (hold !== undefined)
|
|
277
329
|
held.set(turn, hold);
|
|
278
|
-
if (bound)
|
|
279
|
-
bounds.set(turn, bound);
|
|
280
330
|
const stoppedUsd = verdict && "stoppedUsd" in verdict && typeof verdict.stoppedUsd === "function" ? verdict.stoppedUsd : undefined;
|
|
281
331
|
if (stoppedUsd)
|
|
282
332
|
stoppedAt.set(turn, stoppedUsd);
|
|
283
333
|
const note = verdict && "note" in verdict && verdict.note && typeof verdict.note === "object" && !withoutNote ? verdict.note : undefined;
|
|
284
334
|
if (note)
|
|
285
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);
|
|
286
340
|
// A stop that came while the record was written: the request has not left. It is booked withdrawn, at $0, so no
|
|
287
341
|
// later process books it as cut at an unknown price; if that write fails, it is booked cut, which is never less.
|
|
288
342
|
// Its record is written, so it costs a turn of the cap, never money.
|
|
@@ -312,7 +366,7 @@ function bookingFor(writer, options) {
|
|
|
312
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" } });
|
|
313
367
|
throw stoppedLate;
|
|
314
368
|
}
|
|
315
|
-
open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(
|
|
369
|
+
open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }), ...(paid?.hold ? { stays: true } : {}) });
|
|
316
370
|
fly(turn);
|
|
317
371
|
return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
|
|
318
372
|
};
|
|
@@ -348,6 +402,17 @@ function bookingFor(writer, options) {
|
|
|
348
402
|
stoppedAt.delete(turn);
|
|
349
403
|
const note = notes.get(turn);
|
|
350
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 };
|
|
351
416
|
// Its hidden reasoning counts beside all it sent, less the reasoning it sent: max(0, budget - reasoning bytes), so
|
|
352
417
|
// reasoning that streamed is not counted twice and answer text never stands in for it.
|
|
353
418
|
const figure0 = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
|
|
@@ -357,14 +422,14 @@ function bookingFor(writer, options) {
|
|
|
357
422
|
const stopped = usage.usd === null && hold !== undefined && stoppedUsd && sent !== undefined ? heldFigure(stoppedUsd(sent + Math.max(0, hidden - reasoned))) : undefined;
|
|
358
423
|
// How its path saw it end, booked by the one rule (booking.ts); a host from before that says nothing of it: as
|
|
359
424
|
// before, its own cost, else what streamed of a stop, else the hold.
|
|
360
|
-
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;
|
|
361
426
|
const figure = booking ? booking.usd : usage.usd !== null ? usage.usd : stopped === undefined ? hold : Math.min(hold, stopped);
|
|
362
|
-
|
|
363
|
-
// sessionSpendOf reads it on the next claim.
|
|
364
|
-
const capped = booking && bookedLost(booking.rule) && hold !== undefined ? hold + (bounds.get(turn) ?? 0) : figure;
|
|
365
|
-
spentUsd = spent(spentUsd, capped ?? undefined);
|
|
427
|
+
spentUsd = spent(spentUsd, figure ?? undefined);
|
|
366
428
|
const settle = settles.get(turn);
|
|
367
|
-
const 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 } : {}) };
|
|
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;
|
|
368
433
|
try {
|
|
369
434
|
// A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
|
|
370
435
|
// stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
|
|
@@ -414,6 +479,14 @@ function bookingFor(writer, options) {
|
|
|
414
479
|
clearTimeout(timer);
|
|
415
480
|
}
|
|
416
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
|
+
};
|
|
417
490
|
const bookedSince = sessionSpendOf(now).answered;
|
|
418
491
|
for (const t of inherited)
|
|
419
492
|
if (bookedSince.has(t))
|
|
@@ -431,16 +504,15 @@ function bookingFor(writer, options) {
|
|
|
431
504
|
return one ? [{ turn, ...one }] : [];
|
|
432
505
|
});
|
|
433
506
|
if (taken.length) {
|
|
434
|
-
|
|
435
|
-
await append(records);
|
|
507
|
+
await book(taken.map((one) => ({ kind: RUNNER_RECORDS.turn, data: one.data })));
|
|
436
508
|
for (const one of taken) {
|
|
437
509
|
handed.refused.delete(one.turn);
|
|
438
510
|
answered.add(one.turn);
|
|
439
511
|
}
|
|
440
|
-
// Its spend read the request at its hold
|
|
512
|
+
// Its spend read the request at its hold (or unknown); booked, it reads at what it was booked at. Only
|
|
441
513
|
// before this booking's own requests: the spend is the session's records then.
|
|
442
514
|
if (turns === inherited.length && open.length === 0)
|
|
443
|
-
spentUsd = sessionSpendOf([...now, ...
|
|
515
|
+
spentUsd = sessionSpendOf([...now, ...booked]).spentUsd;
|
|
444
516
|
for (const one of taken) {
|
|
445
517
|
const hosted = hosts.get(one.turn);
|
|
446
518
|
await emit({ type: "request_end", turn: one.turn, usage: one.usage, ...(hosted === undefined ? {} : { host: hosted }), ...(one.ended ? { ended: one.ended } : {}) });
|
|
@@ -462,36 +534,82 @@ function bookingFor(writer, options) {
|
|
|
462
534
|
return data.owed === true && data.hold !== true ? [inherited[i]] : [];
|
|
463
535
|
}));
|
|
464
536
|
const owed = left.filter((t) => !read.openHolds.has(t) && owedTurns.has(t) && (held.get(t) ?? 0) > 0);
|
|
465
|
-
|
|
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));
|
|
466
546
|
if (givenBack.length) {
|
|
467
|
-
await
|
|
547
|
+
await book(givenBack.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, givenBack: true } })));
|
|
468
548
|
for (const turn of givenBack)
|
|
469
549
|
answered.add(turn);
|
|
470
550
|
}
|
|
471
551
|
if (owed.length) {
|
|
472
|
-
await
|
|
552
|
+
await book(owed.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: { turn, usd: held.get(turn), bookedUsd: held.get(turn), rule: "owed" } })));
|
|
473
553
|
for (const turn of owed) {
|
|
474
554
|
answered.add(turn);
|
|
475
555
|
const hosted = hosts.get(turn);
|
|
476
556
|
emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: held.get(turn), estimated: true }, ...(hosted === undefined ? {} : { host: hosted }) });
|
|
477
557
|
}
|
|
478
558
|
}
|
|
479
|
-
if (numbers.length === 0)
|
|
480
|
-
return;
|
|
481
559
|
// A cut request whose response had begun carries the ids it gave: the provider saw it, under them. One with none may
|
|
482
|
-
// still have reached the provider before any answer
|
|
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
|
+
};
|
|
483
578
|
const cutOf = (turn) => {
|
|
484
579
|
const providerIds = responses.get(turn);
|
|
485
|
-
|
|
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 } : {}) };
|
|
486
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;
|
|
487
604
|
await append(numbers.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: cutOf(turn) })));
|
|
488
605
|
for (const turn of numbers)
|
|
489
606
|
answered.add(turn);
|
|
490
|
-
// The spend already counts each of them, at its hold
|
|
607
|
+
// The spend already counts each of them, at its hold or as unknown: booking them adds nothing.
|
|
491
608
|
for (const turn of numbers) {
|
|
492
609
|
const providerIds = responses.get(turn);
|
|
493
610
|
const hosted = hosts.get(turn);
|
|
494
|
-
|
|
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" } });
|
|
495
613
|
}
|
|
496
614
|
};
|
|
497
615
|
return {
|
|
@@ -499,7 +617,6 @@ function bookingFor(writer, options) {
|
|
|
499
617
|
turns: () => turns,
|
|
500
618
|
spentUsd: () => spentUsd,
|
|
501
619
|
heldUsd: () => open.reduce((sum, flight) => (sum === null || flight.holdUsd === undefined ? null : sum + flight.holdUsd), 0),
|
|
502
|
-
boundUsd: () => open.reduce((sum, flight) => sum + (flight.boundUsd ?? 0), 0),
|
|
503
620
|
bookCut() {
|
|
504
621
|
cutting ??= bookCut().catch((error) => {
|
|
505
622
|
cutting = undefined;
|
package/dist/testing.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ 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
8
|
* counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
|
|
9
9
|
* in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
|
|
@@ -26,7 +26,8 @@ export declare function memorySessionStore(options?: {
|
|
|
26
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
|
|
27
27
|
* side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists). */
|
|
28
28
|
/** `onRefused: "next"`: a request its host refuses (its admission throws) is not the turn's end: the client goes on to its
|
|
29
|
-
* 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). */
|
|
30
31
|
export type FauxRequest = {
|
|
31
32
|
onRefused?: "next";
|
|
32
33
|
tokens?: {
|
|
@@ -38,6 +39,7 @@ export type FauxRequest = {
|
|
|
38
39
|
inputTokensMax?: number;
|
|
39
40
|
outputTokensAsked?: number;
|
|
40
41
|
outputTokensLeast?: number;
|
|
42
|
+
effort?: string;
|
|
41
43
|
until?: string;
|
|
42
44
|
bookWhen?: string;
|
|
43
45
|
sideAfterNote?: {
|
package/dist/testing.js
CHANGED
|
@@ -12,7 +12,7 @@ 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
17
|
* counts one more holder at once, and a writer appends only while its count is the newest. `scope`: the run's identity
|
|
18
18
|
* in this process, for a test that plays a claim lost and taken again in one process (SessionWriter.scope); without it,
|
|
@@ -205,7 +205,7 @@ export function fauxAdapter(options) {
|
|
|
205
205
|
io.onEvent({ type: "text", delta: say });
|
|
206
206
|
}
|
|
207
207
|
// The output it asks for at most (a CLI's max_tokens), as a real adapter's proxy reads it from the body.
|
|
208
|
-
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 } : {}) };
|
|
209
209
|
const admit = () => io.models.beforeRequest({ model: own, inputTokensMax: note ? measured + Buffer.byteLength(note, "utf8") : measured, ...asked, ...(note ? { noted: true, inputTokensMaxWithoutNote: measured } : {}) });
|
|
210
210
|
let ticket;
|
|
211
211
|
try {
|
package/dist/tool-deferral.d.ts
CHANGED
|
@@ -5,8 +5,8 @@ export declare const CODEMODE = "codemode";
|
|
|
5
5
|
export declare const META_TOOLS: ReadonlySet<string>;
|
|
6
6
|
/** A run with more catalog tools than this is deferred them. */
|
|
7
7
|
export declare const DEFER_CATALOG_OVER = 20;
|
|
8
|
-
/** Whether a tool is a catalog tool, by the name a harness gives it: an MCP tool (`mcp__<server>__<tool>`)
|
|
9
|
-
* endpoint (`monid__<provider>__<endpoint>`). */
|
|
10
|
-
export declare const
|
|
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
11
|
/** Whether a run whose host tools are `names` has its catalog tools deferred: more than DEFER_CATALOG_OVER of them. */
|
|
12
12
|
export declare const defersCatalog: (names: readonly string[]) => boolean;
|
package/dist/tool-deferral.js
CHANGED
|
@@ -10,8 +10,8 @@ export const CODEMODE = "codemode";
|
|
|
10
10
|
export const META_TOOLS = new Set([TOOLS_SEARCH, TOOLS_CALL, CODEMODE]);
|
|
11
11
|
/** A run with more catalog tools than this is deferred them. */
|
|
12
12
|
export const DEFER_CATALOG_OVER = 20;
|
|
13
|
-
/** Whether a tool is a catalog tool, by the name a harness gives it: an MCP tool (`mcp__<server>__<tool>`)
|
|
14
|
-
* endpoint (`monid__<provider>__<endpoint>`). */
|
|
15
|
-
export const
|
|
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
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(
|
|
17
|
+
export const defersCatalog = (names) => names.filter(isCatalogWire).length > DEFER_CATALOG_OVER;
|