@parcha/agentrun-kernel 0.1.0-beta.30 → 0.1.0-beta.32
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 +68 -0
- package/README.md +5 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/host/box.d.ts +0 -58
- package/dist/host/box.js +7 -0
- package/dist/host/index.d.ts +5 -9
- package/dist/host/index.js +2 -4
- package/dist/host/mcp-route.d.ts +14 -0
- package/dist/host/mcp-route.js +125 -0
- package/dist/host/proxy.d.ts +96 -2
- package/dist/host/proxy.js +533 -41
- package/dist/host/serial.js +2 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.js +3 -2
- package/dist/kernel/cap/admit.d.ts +35 -0
- package/dist/kernel/cap/admit.js +186 -0
- package/dist/kernel/cap/errors.d.ts +20 -0
- package/dist/kernel/cap/errors.js +25 -0
- package/dist/kernel/cap/index.d.ts +14 -0
- package/dist/kernel/cap/index.js +15 -0
- package/dist/kernel/cap/ledger.d.ts +37 -0
- package/dist/kernel/cap/ledger.js +83 -0
- package/dist/kernel/cap/marks.d.ts +50 -0
- package/dist/kernel/cap/marks.js +28 -0
- package/dist/kernel/cap/park.d.ts +80 -0
- package/dist/kernel/cap/park.js +57 -0
- package/dist/kernel/cap/port.d.ts +21 -0
- package/dist/kernel/cap/port.js +95 -0
- package/dist/kernel/cap/price.d.ts +54 -0
- package/dist/kernel/cap/price.js +117 -0
- package/dist/kernel/cap/recover.d.ts +18 -0
- package/dist/kernel/cap/recover.js +71 -0
- package/dist/kernel/cap/rule.d.ts +55 -0
- package/dist/kernel/cap/rule.js +93 -0
- package/dist/kernel/cap/run-cap.d.ts +80 -0
- package/dist/kernel/cap/run-cap.js +132 -0
- package/dist/kernel/cap/steps.d.ts +36 -0
- package/dist/kernel/cap/steps.js +64 -0
- package/dist/kernel/cap/stopped.d.ts +17 -0
- package/dist/kernel/cap/stopped.js +34 -0
- package/dist/kernel/cap/types.d.ts +151 -0
- package/dist/kernel/cap/types.js +1 -0
- package/dist/kernel/cap/words.d.ts +39 -0
- package/dist/kernel/cap/words.js +75 -0
- package/dist/kernel/cap/wrap-up.d.ts +17 -0
- package/dist/kernel/cap/wrap-up.js +37 -0
- package/dist/kernel/drive.d.ts +0 -1
- package/dist/kernel/drive.js +9 -2
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/registry/background.d.ts +12 -0
- package/dist/kernel/registry/background.js +342 -0
- package/dist/kernel/registry/bash.d.ts +3 -0
- package/dist/kernel/registry/bash.js +23 -0
- package/dist/kernel/registry/browser.d.ts +11 -0
- package/dist/kernel/registry/browser.js +14 -0
- package/dist/kernel/registry/defs.d.ts +42 -0
- package/dist/kernel/registry/defs.js +153 -0
- package/dist/kernel/registry/desktop.d.ts +11 -0
- package/dist/kernel/registry/desktop.js +90 -0
- package/dist/kernel/registry/gate.d.ts +20 -0
- package/dist/kernel/registry/gate.js +32 -0
- package/dist/kernel/registry/handoff.d.ts +11 -0
- package/dist/kernel/registry/handoff.js +51 -0
- package/dist/kernel/registry/hands.d.ts +280 -0
- package/dist/kernel/registry/hands.js +28 -0
- package/dist/kernel/registry/index.d.ts +17 -0
- package/dist/kernel/registry/index.js +14 -0
- package/dist/kernel/registry/limits.d.ts +27 -0
- package/dist/kernel/registry/limits.js +29 -0
- package/dist/kernel/registry/phone.d.ts +15 -0
- package/dist/kernel/registry/phone.js +135 -0
- package/dist/kernel/registry/registry.d.ts +22 -0
- package/dist/kernel/registry/registry.js +75 -0
- package/dist/kernel/types.d.ts +0 -7
- package/dist/process/builtins.js +1 -1
- package/dist/process/index.d.ts +1 -0
- package/dist/process/index.js +1 -0
- package/dist/process/journal.js +1 -1
- package/dist/process/recovery.js +1 -1
- package/dist/process/resume.d.ts +20 -0
- package/dist/process/resume.js +16 -0
- package/dist/process/tail.js +1 -1
- package/dist/process/tools.d.ts +8 -1
- package/dist/process/tools.js +20 -3
- package/dist/process/zod.js +1 -1
- package/dist/run-booking.d.ts +9 -0
- package/dist/run-booking.js +50 -0
- package/dist/runner.d.ts +91 -17
- package/dist/runner.js +132 -41
- package/dist/testing.d.ts +79 -12
- package/dist/testing.js +106 -13
- package/dist/types.d.ts +235 -10
- package/package.json +8 -4
- package/vendor/durable-harness/UPSTREAM.json +0 -9
- package/dist/host/box-slot.d.ts +0 -26
- package/dist/host/box-slot.js +0 -112
- package/dist/host/egress-proxy.d.ts +0 -45
- package/dist/host/egress-proxy.js +0 -416
- package/dist/host/egress-table.d.ts +0 -24
- package/dist/host/egress-table.js +0 -165
package/dist/runner.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { randomUUID } from "node:crypto";
|
|
9
9
|
import { Compile } from "typebox/compile";
|
|
10
10
|
import { submitParameters } from "@parcha/agentrun-dsl";
|
|
11
|
-
import { HarnessRunError, SessionFenced } from "./errors.js";
|
|
11
|
+
import { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
|
|
12
12
|
import { bookRequest } from "./booking.js";
|
|
13
13
|
/** The tool the runner injects; a host tool may not take its name. */
|
|
14
14
|
export const SUBMIT_TOOL = "submit";
|
|
@@ -42,44 +42,90 @@ export const NO_PROGRESS_TURNS = 3;
|
|
|
42
42
|
export async function modelPortFor(writer, options) {
|
|
43
43
|
return bookingFor(writer, { ...options, records: options.records ?? (await writer.read()) });
|
|
44
44
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
/** What the host held for each request, by turn: what it counts at when its own cost never comes in. */
|
|
45
|
+
/** What a session's runner records say: the turn of each paid request that left, in order (`turns`), what its host held
|
|
46
|
+
* for each (`held`), the label of each the host sent beside the harness's own (`hosts`), which were answered, and the
|
|
47
|
+
* session's spend (null: unknown). A turn is a paid request that left: counted from the records written before each one
|
|
48
|
+
* left, so a request a crash cut off (or one still in flight, read from another process or session) counts at the
|
|
49
|
+
* figure its host held for it, and leaves the spend unknown when there is none. */
|
|
50
|
+
export function sessionSpendOf(records) {
|
|
51
|
+
const requests = records.filter((r) => r.kind === RUNNER_RECORDS.request).map((r) => (r.data ?? {}));
|
|
52
|
+
const turns = requests.map((data, i) => data.turn ?? i + 1);
|
|
53
|
+
const hosts = new Map();
|
|
54
|
+
requests.forEach((data, i) => { if (typeof data.host === "string")
|
|
55
|
+
hosts.set(turns[i], data.host); });
|
|
57
56
|
const held = new Map();
|
|
58
|
-
|
|
59
|
-
const stoppedAt = new Map();
|
|
57
|
+
const bounds = new Map();
|
|
60
58
|
requests.forEach((data, i) => {
|
|
61
59
|
const figure = heldFigure(data.heldUsd);
|
|
62
60
|
if (figure !== undefined)
|
|
63
|
-
held.set(
|
|
61
|
+
held.set(turns[i], figure);
|
|
62
|
+
const bound = heldFigure(data.boundUsd);
|
|
63
|
+
if (bound !== undefined)
|
|
64
|
+
bounds.set(turns[i], bound);
|
|
64
65
|
});
|
|
66
|
+
// 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
|
|
67
|
+
// miss: for the cap it counts at its hold plus its bound, the worst case, never less. Unknown with no hold.
|
|
68
|
+
const worst = (turn) => {
|
|
69
|
+
const hold = held.get(turn);
|
|
70
|
+
return hold === undefined ? undefined : hold + (bounds.get(turn) ?? 0);
|
|
71
|
+
};
|
|
65
72
|
// Which of them were answered: each runner.turn names its own turn (one written before turns were named answers the
|
|
66
73
|
// earliest still open, as answers then came in order).
|
|
67
74
|
const answered = new Set();
|
|
68
75
|
let spentUsd = 0;
|
|
69
|
-
|
|
76
|
+
// The run's cost: what is known (each booked or reported figure), and how many requests have none. A held figure is
|
|
77
|
+
// the cap's, never a cost: a request without its own figure makes the cost unknown, the known part kept beside it.
|
|
78
|
+
let soFarUsd = 0;
|
|
79
|
+
let unpriced = 0;
|
|
80
|
+
for (const r of records) {
|
|
70
81
|
if (r.kind !== RUNNER_RECORDS.turn)
|
|
71
82
|
continue;
|
|
72
83
|
const data = r.data;
|
|
73
|
-
const turn = data.turn ??
|
|
84
|
+
const turn = data.turn ?? turns.find((t) => !answered.has(t)) ?? 0;
|
|
74
85
|
answered.add(turn);
|
|
75
|
-
// The figure it was booked at (bookRequest), as written. A record from before that has none: a
|
|
76
|
-
// in at the figure its answer was booked at (a stopped request's),
|
|
86
|
+
// The figure it was booked at (bookRequest), as written. A record from before that has none: a request cut off with
|
|
87
|
+
// no answer at its worst case; a cost that never came in at the figure its answer was booked at (a stopped request's),
|
|
88
|
+
// else what was held for it. One booked lost (at its hold) may have been billed at a cache miss like one with no
|
|
89
|
+
// answer: for the cap, its worst case.
|
|
77
90
|
const booked = data.bookedUsd === null ? null : heldFigure(data.bookedUsd);
|
|
78
|
-
|
|
91
|
+
const cut = data.cut === true && booked === undefined;
|
|
92
|
+
const capped = booked !== undefined && bookedLost(data.rule) ? (worst(turn) ?? booked) : booked;
|
|
93
|
+
spentUsd = spent(spentUsd, capped !== undefined ? (capped ?? undefined) : cut ? worst(turn) : data.usd === null ? (heldFigure(data.heldUsd) ?? held.get(turn)) : (data.usd ?? 0));
|
|
94
|
+
const own = booked !== undefined ? booked : cut || data.usd === null ? null : data.usd === undefined ? 0 : (heldFigure(data.usd) ?? null);
|
|
95
|
+
if (own === null)
|
|
96
|
+
unpriced++;
|
|
97
|
+
else
|
|
98
|
+
soFarUsd += own;
|
|
99
|
+
}
|
|
100
|
+
for (const turn of turns) {
|
|
101
|
+
if (answered.has(turn))
|
|
102
|
+
continue;
|
|
103
|
+
spentUsd = spent(spentUsd, worst(turn));
|
|
104
|
+
unpriced++;
|
|
79
105
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
106
|
+
return { turns, held, bounds, hosts, answered, spentUsd, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
|
|
107
|
+
}
|
|
108
|
+
/** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
|
|
109
|
+
const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
|
|
110
|
+
function bookingFor(writer, options) {
|
|
111
|
+
const node = { key: options.key, label: options.label ?? options.key, ...(options.executionPath === undefined ? {} : { executionPath: options.executionPath }) };
|
|
112
|
+
const limit = options.maxTurns ?? null;
|
|
113
|
+
const append = options.append ?? ((records) => writer.append(records));
|
|
114
|
+
const emit = (event) => options.onEvent?.({ ...event, ...node });
|
|
115
|
+
// What this session's records say when it opens (sessionSpendOf).
|
|
116
|
+
const read = sessionSpendOf(options.records);
|
|
117
|
+
const inherited = read.turns;
|
|
118
|
+
const hosts = read.hosts;
|
|
119
|
+
let turns = inherited.length;
|
|
120
|
+
const held = read.held;
|
|
121
|
+
/** What a cache miss adds to each request's hold (Admission.boundUsd): a request booked lost counts at both. */
|
|
122
|
+
const bounds = read.bounds;
|
|
123
|
+
/** What the host counts each request of this process at if its client stops it part way (Admission.stoppedUsd). */
|
|
124
|
+
const stoppedAt = new Map();
|
|
125
|
+
/** The host's record of a note each request of this process carries (Admission.note), for its runner.turn. */
|
|
126
|
+
const notes = new Map();
|
|
127
|
+
const answered = read.answered;
|
|
128
|
+
let spentUsd = read.spentUsd;
|
|
83
129
|
// The ids each request's response gave it, kept as its headers arrived: a request cut off after them reached the provider.
|
|
84
130
|
const responses = new Map();
|
|
85
131
|
for (const r of options.records) {
|
|
@@ -113,8 +159,9 @@ function bookingFor(writer, options) {
|
|
|
113
159
|
// A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
|
|
114
160
|
let failed;
|
|
115
161
|
const end = (reason, message) => options.stop ? options.stop(reason, message) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }) });
|
|
116
|
-
const admit = async ({ model, inputTokensMax, outputTokensAsked, outputTokensLeast }) => {
|
|
117
|
-
|
|
162
|
+
const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host }) => {
|
|
163
|
+
let inputTokensMax = measured;
|
|
164
|
+
const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
|
|
118
165
|
if (stopped)
|
|
119
166
|
throw stopped;
|
|
120
167
|
const pausing = options.draining?.();
|
|
@@ -123,10 +170,16 @@ function bookingFor(writer, options) {
|
|
|
123
170
|
if (limit !== null && turns >= limit)
|
|
124
171
|
throw end("turn_limit");
|
|
125
172
|
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,
|
|
126
|
-
...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }) });
|
|
173
|
+
...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }) });
|
|
127
174
|
if (verdict && "refuse" in verdict)
|
|
128
175
|
throw end("refused", verdict.refuse);
|
|
129
176
|
const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
|
|
177
|
+
// What a cache miss adds to the hold: kept beside it, so a request that never answers counts at both (sessionSpendOf).
|
|
178
|
+
const bound = hold !== undefined && verdict && "boundUsd" in verdict ? heldFigure(verdict.boundUsd) : undefined;
|
|
179
|
+
// Admitted only without the note: it goes as its client sent it, measured so.
|
|
180
|
+
const withoutNote = noted === true && !!verdict && "withoutNote" in verdict && verdict.withoutNote === true;
|
|
181
|
+
if (withoutNote)
|
|
182
|
+
inputTokensMax = inputTokensMaxWithoutNote;
|
|
130
183
|
// The output limit the host admits it with goes into its body. A limit that is no whole number of tokens above 0 (a
|
|
131
184
|
// fraction, 0, a negative, NaN) can't be sent, so the request is refused before anything is written: dropping it would
|
|
132
185
|
// send the request with no limit at all. Only a verdict with no limit sends the request with none.
|
|
@@ -135,34 +188,60 @@ function bookingFor(writer, options) {
|
|
|
135
188
|
throw end("refused", `the request was not sent: its output limit (${String(limited)}) is not a whole number of tokens above 0`);
|
|
136
189
|
// A stop or a pause that came while the host was checking: nothing was written for this request, so it is refused, not
|
|
137
190
|
// sent. After the write below it is committed (refusing it then would leave a recorded request that was never sent).
|
|
138
|
-
const late = options.stopped?.() ?? failed ?? options.draining?.();
|
|
191
|
+
const late = options.stopped?.(host === undefined ? {} : { host }) ?? failed ?? options.draining?.();
|
|
139
192
|
if (late)
|
|
140
193
|
throw late;
|
|
141
194
|
// Durable before the request leaves: admitted, then sent. It counts as a turn once its record is written (admissions
|
|
142
195
|
// run one at a time), so a write that fails refuses the request and costs no turn.
|
|
143
196
|
const turn = turns + 1;
|
|
144
|
-
await write([{ kind: RUNNER_RECORDS.request, data: { turn, model, ...(hold === undefined ? {} : { heldUsd: hold }) } }]);
|
|
197
|
+
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 }) } }]);
|
|
145
198
|
turns = turn;
|
|
199
|
+
if (host !== undefined)
|
|
200
|
+
hosts.set(turn, host);
|
|
146
201
|
if (hold !== undefined)
|
|
147
202
|
held.set(turn, hold);
|
|
203
|
+
if (bound)
|
|
204
|
+
bounds.set(turn, bound);
|
|
148
205
|
const stoppedUsd = verdict && "stoppedUsd" in verdict && typeof verdict.stoppedUsd === "function" ? verdict.stoppedUsd : undefined;
|
|
149
206
|
if (stoppedUsd)
|
|
150
207
|
stoppedAt.set(turn, stoppedUsd);
|
|
208
|
+
const note = verdict && "note" in verdict && verdict.note && typeof verdict.note === "object" && !withoutNote ? verdict.note : undefined;
|
|
209
|
+
if (note)
|
|
210
|
+
notes.set(turn, note);
|
|
151
211
|
// A stop that came while the record was written: the request has not left. It is booked withdrawn, at $0, so no
|
|
152
212
|
// later process books it as cut at an unknown price; if that write fails, it is booked cut, which is never less.
|
|
153
213
|
// Its record is written, so it costs a turn of the cap, never money.
|
|
154
|
-
const stoppedNow = options.stopped?.();
|
|
214
|
+
const stoppedNow = options.stopped?.(host === undefined ? {} : { host });
|
|
155
215
|
if (stoppedNow) {
|
|
156
216
|
answered.add(turn);
|
|
157
217
|
// Through the booking's own write: a response's ids still waiting to be carried go with the withdrawal.
|
|
158
218
|
await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, unsent: true } }]).catch(() => undefined);
|
|
159
219
|
throw stoppedNow;
|
|
160
220
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
221
|
+
// The host's start mark, awaited before the request leaves (its handler commits and syncs it). One it refuses is
|
|
222
|
+
// booked as a stop is, withdrawn at $0, and the request never joins the open ones, which a ticketless answer reads.
|
|
223
|
+
try {
|
|
224
|
+
await emit({ type: "request_start", turn, model, ...(host === undefined ? {} : { host }) });
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
answered.add(turn);
|
|
228
|
+
await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, unsent: true } }]).catch(() => undefined);
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
// A stop that came while the mark was made: the request has not left either. Booked withdrawn as above, and its end
|
|
232
|
+
// told to the host, whose mark has it started: at $0, so the host never reads it cut at an unknown price.
|
|
233
|
+
const stoppedLate = options.stopped?.(host === undefined ? {} : { host });
|
|
234
|
+
if (stoppedLate) {
|
|
235
|
+
answered.add(turn);
|
|
236
|
+
await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, unsent: true } }]).catch(() => undefined);
|
|
237
|
+
emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
|
|
238
|
+
throw stoppedLate;
|
|
239
|
+
}
|
|
240
|
+
open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }) });
|
|
241
|
+
return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
|
|
164
242
|
};
|
|
165
243
|
const models = {
|
|
244
|
+
...(options.note ? { note: options.note } : {}),
|
|
166
245
|
beforeRequest: (request) => {
|
|
167
246
|
const admitted = admitting.then(() => admit(request));
|
|
168
247
|
admitting = admitted.catch(() => { });
|
|
@@ -190,6 +269,8 @@ function bookingFor(writer, options) {
|
|
|
190
269
|
const hold = held.get(turn);
|
|
191
270
|
const stoppedUsd = stoppedAt.get(turn);
|
|
192
271
|
stoppedAt.delete(turn);
|
|
272
|
+
const note = notes.get(turn);
|
|
273
|
+
notes.delete(turn);
|
|
193
274
|
// Its hidden reasoning counts beside all it sent, less the reasoning it sent: max(0, budget - reasoning bytes), so
|
|
194
275
|
// reasoning that streamed is not counted twice and answer text never stands in for it.
|
|
195
276
|
const figure0 = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
|
|
@@ -201,21 +282,30 @@ function bookingFor(writer, options) {
|
|
|
201
282
|
// before, its own cost, else what streamed of a stop, else the hold.
|
|
202
283
|
const booking = ended ? bookRequest(ended, { ...(hold === undefined ? {} : { hold }), ...(stoppedUsd ? { stoppedPrice: stoppedUsd } : {}) }) : undefined;
|
|
203
284
|
const figure = booking ? booking.usd : usage.usd !== null ? usage.usd : stopped === undefined ? hold : Math.min(hold, stopped);
|
|
204
|
-
|
|
285
|
+
// Booked lost (at its hold), it may have been billed at a cache miss: for the cap, its hold plus its bound, as
|
|
286
|
+
// sessionSpendOf reads it on the next claim.
|
|
287
|
+
const capped = booking && bookedLost(booking.rule) && hold !== undefined ? hold + (bounds.get(turn) ?? 0) : figure;
|
|
288
|
+
spentUsd = spent(spentUsd, capped ?? undefined);
|
|
205
289
|
try {
|
|
206
290
|
// A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
|
|
207
291
|
// stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
|
|
208
292
|
const covers = (r) => usage.providerIds !== undefined && r.data.turn === turn;
|
|
209
|
-
await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: usage.usd, ...tokensOf(usage), ...(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 } : {}) } }], covers);
|
|
293
|
+
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);
|
|
210
294
|
}
|
|
211
295
|
catch (error) {
|
|
212
|
-
// A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted.
|
|
213
|
-
|
|
296
|
+
// A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted. Asked
|
|
297
|
+
// with the request's own host label, as its admission was: a stop that holds only the harness's own requests (a
|
|
298
|
+
// parked turn's) never hides the failure from the host's. A turn parked on a call (TurnParked) is no stop of the
|
|
299
|
+
// booking, so it stops here too; a stop that ended it already wins.
|
|
300
|
+
const host = hosts.get(turn);
|
|
301
|
+
const stop = options.stopped?.(host === undefined ? {} : { host });
|
|
302
|
+
if (!stop || stop instanceof TurnParked)
|
|
214
303
|
failed ??= end("model_error", `harness node stopped: the cost of a paid request could not be recorded: ${String(error?.message ?? error).slice(0, 200)}`);
|
|
215
304
|
throw error;
|
|
216
305
|
}
|
|
217
306
|
answered.add(turn);
|
|
218
|
-
|
|
307
|
+
const hosted = hosts.get(turn);
|
|
308
|
+
emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
|
|
219
309
|
},
|
|
220
310
|
};
|
|
221
311
|
// One booking of the cut requests at a time: a call made while one is writing waits for it, never books them again.
|
|
@@ -237,10 +327,11 @@ function bookingFor(writer, options) {
|
|
|
237
327
|
await append(numbers.map((turn) => ({ kind: RUNNER_RECORDS.turn, data: cutOf(turn) })));
|
|
238
328
|
for (const turn of numbers)
|
|
239
329
|
answered.add(turn);
|
|
240
|
-
// The spend already counts each of them, at its
|
|
330
|
+
// The spend already counts each of them, at its hold plus its bound or as unknown: booking them adds nothing.
|
|
241
331
|
for (const turn of numbers) {
|
|
242
332
|
const providerIds = responses.get(turn);
|
|
243
|
-
|
|
333
|
+
const hosted = hosts.get(turn);
|
|
334
|
+
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" } });
|
|
244
335
|
}
|
|
245
336
|
};
|
|
246
337
|
return {
|
|
@@ -422,7 +513,7 @@ export function createHarnessRunner(adapter, options) {
|
|
|
422
513
|
};
|
|
423
514
|
// Refused at create time, before anything is spent: a fork the adapter cannot make, or anything the adapter refuses.
|
|
424
515
|
const problems = [
|
|
425
|
-
...(spec.context === "fork"
|
|
516
|
+
...(spec.context === "fork" ? [`Node "${request.label}" asks for context: "fork", but ${adapter.id} has no caller transcript to fork. Declare context: "fresh".`] : []),
|
|
426
517
|
...adapter.check(spec),
|
|
427
518
|
];
|
|
428
519
|
if (problems.length)
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,30 +1,76 @@
|
|
|
1
|
-
import type { AgentAdapter, SessionSpec, SessionState, SessionStore, TurnStatus } from "./types.js";
|
|
1
|
+
import type { AgentAdapter, SessionPort, SessionSpec, SessionState, SessionStore, TurnStatus } from "./types.js";
|
|
2
|
+
import { type ModelProxyOptions } from "./host/proxy.js";
|
|
2
3
|
export { SCHEMA_CHECK_CASES, type SchemaCheckCase } from "./schema-check-cases.js";
|
|
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
|
+
* harness runs. */
|
|
6
|
+
export { inputTokensMaxOf, matchRoute, parseStrict, reportedCostOf } from "./host/proxy.js";
|
|
3
7
|
/** A session store in memory: what one run's store holds, across the processes a test plays. Each `open` of a key
|
|
4
8
|
* counts one more holder at once, and a writer appends only while its count is the newest. */
|
|
5
9
|
export declare function memorySessionStore(): SessionStore & {
|
|
6
10
|
keys(): string[];
|
|
7
11
|
};
|
|
12
|
+
/** What a scripted request reports beside its cost, as a real adapter's proxy reads a response, and how it is measured:
|
|
13
|
+
* its tokens (`tokens`, in pi's shape: `input` excludes the cache's reads and writes; default 10 in, 5 out), the input
|
|
14
|
+
* bound its body was measured at (`inputTokensMax`; default the prompt's UTF-8 bytes), and a file it waits for once it
|
|
15
|
+
* is admitted, before it answers (`until`): a request held in flight until a test lets it go. `bookWhen`: its reply is
|
|
16
|
+
* shown at once and its cost booked only once that file exists, as a provider's usage can come after its answer. */
|
|
17
|
+
/** `sideAfterNote`: a client's side call on another model (a title, a summary: ModelRequest.side) admitted and answered
|
|
18
|
+
* at `usd` after this request took its host's note and before this request is admitted, as a Claude Code side call can
|
|
19
|
+
* be while the model proxy reads the credential between the two. `sideDuring`: one admitted and answered at `usd` while
|
|
20
|
+
* this request still streams (after its first call's text, before that call), so two of its requests are in flight.
|
|
21
|
+
* `sideFirst`: one admitted before this request, then `say` streamed before this request is admitted: text of the
|
|
22
|
+
* 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
|
+
* side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists). `resultWhen`: a call's
|
|
24
|
+
* result is told (its tool_end) only once this file exists, as a harness still recording it would. */
|
|
25
|
+
/** `onRefused: "next"`: a request its host refuses (its admission throws) is not the turn's end: the client goes on to its
|
|
26
|
+
* next action, as a CLI whose request the proxy refused sends another. */
|
|
27
|
+
export type FauxRequest = {
|
|
28
|
+
onRefused?: "next";
|
|
29
|
+
tokens?: {
|
|
30
|
+
input: number;
|
|
31
|
+
output: number;
|
|
32
|
+
cacheRead?: number;
|
|
33
|
+
cacheWrite?: number;
|
|
34
|
+
};
|
|
35
|
+
inputTokensMax?: number;
|
|
36
|
+
outputTokensAsked?: number;
|
|
37
|
+
outputTokensLeast?: number;
|
|
38
|
+
until?: string;
|
|
39
|
+
bookWhen?: string;
|
|
40
|
+
sideAfterNote?: {
|
|
41
|
+
usd: number;
|
|
42
|
+
};
|
|
43
|
+
sideDuring?: {
|
|
44
|
+
usd: number;
|
|
45
|
+
};
|
|
46
|
+
sideFirst?: {
|
|
47
|
+
usd: number;
|
|
48
|
+
say: string;
|
|
49
|
+
};
|
|
50
|
+
resultWhen?: string;
|
|
51
|
+
};
|
|
8
52
|
/** One model request of the faux harness, and what its reply does. */
|
|
9
|
-
export type FauxAction = {
|
|
53
|
+
export type FauxAction = ({
|
|
10
54
|
say: string;
|
|
11
55
|
usd?: number | null;
|
|
12
|
-
} | {
|
|
56
|
+
} & FauxRequest) | ({
|
|
13
57
|
call: string;
|
|
14
58
|
args?: unknown;
|
|
15
59
|
usd?: number | null;
|
|
16
|
-
}
|
|
60
|
+
} & FauxRequest)
|
|
17
61
|
/** One answer that asks for several tools, run one after another, as Claude Code and Codex run a response's calls.
|
|
18
62
|
* `bookAfter`: the calls run before the answer's cost is booked, as with Claude Code, whose cost comes in after its
|
|
19
|
-
* response, so a call can end before the request that asked for it is paid.
|
|
20
|
-
|
|
63
|
+
* response, so a call can end before the request that asked for it is paid. A call's `say` streams that text first,
|
|
64
|
+
* as a model writes between the calls of one answer. */
|
|
65
|
+
| ({
|
|
21
66
|
calls: {
|
|
22
67
|
call: string;
|
|
23
68
|
args?: unknown;
|
|
69
|
+
say?: string;
|
|
24
70
|
}[];
|
|
25
71
|
usd?: number | null;
|
|
26
72
|
bookAfter?: boolean;
|
|
27
|
-
} | {
|
|
73
|
+
} & FauxRequest) | {
|
|
28
74
|
submit: unknown;
|
|
29
75
|
usd?: number | null;
|
|
30
76
|
}
|
|
@@ -35,10 +81,16 @@ export type FauxAction = {
|
|
|
35
81
|
usd?: number | null;
|
|
36
82
|
turn?: TurnStatus;
|
|
37
83
|
}
|
|
38
|
-
/** The request fails: the turn ends failed. */
|
|
84
|
+
/** The request fails: the provider answers an error status before any event (booked so), and the turn ends failed. */
|
|
39
85
|
| {
|
|
40
86
|
fail: string;
|
|
41
87
|
}
|
|
88
|
+
/** The provider does not answer this request: an error status before any event (`status`), our stop after part of it
|
|
89
|
+
* streamed (`stopped`), or the connection lost once it left (`lost`). It is booked as such, and the client goes on to
|
|
90
|
+
* its next action, as a CLI sends a request again. */
|
|
91
|
+
| ({
|
|
92
|
+
unanswered: "status" | "stopped" | "lost";
|
|
93
|
+
} & FauxRequest)
|
|
42
94
|
/** The process stops here: nothing resolves until the session's signal aborts. */
|
|
43
95
|
| {
|
|
44
96
|
hang: true;
|
|
@@ -48,15 +100,17 @@ export type FauxAction = {
|
|
|
48
100
|
halt: string;
|
|
49
101
|
}
|
|
50
102
|
/** A paid request leaves (its beforeRequest passes) and the process dies before it answers: nothing more resolves. */
|
|
51
|
-
| {
|
|
103
|
+
| ({
|
|
52
104
|
cut: true;
|
|
53
|
-
}
|
|
105
|
+
} & FauxRequest)
|
|
54
106
|
/** A paid request leaves and holds unanswered until the turn is stopped: the stop cuts it, and its cost (what had
|
|
55
107
|
* streamed) is still booked, as a provider bills a response cut short. */
|
|
56
108
|
| {
|
|
57
109
|
cutBooked: true;
|
|
58
110
|
usd?: number | null;
|
|
59
111
|
};
|
|
112
|
+
/** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
|
|
113
|
+
* would add it to the body: filed with its text, for a test to see. */
|
|
60
114
|
export declare const FAUX_RECORDS: {
|
|
61
115
|
readonly request: "faux.request";
|
|
62
116
|
readonly user: "faux.user";
|
|
@@ -64,16 +118,29 @@ export declare const FAUX_RECORDS: {
|
|
|
64
118
|
readonly turnEnd: "faux.turn_end";
|
|
65
119
|
readonly call: "faux.call";
|
|
66
120
|
readonly result: "faux.result";
|
|
121
|
+
readonly note: "faux.note";
|
|
67
122
|
};
|
|
68
123
|
export interface FauxOptions {
|
|
69
124
|
/** The session's model replies, in order, by its spec: one action per paid request. */
|
|
70
125
|
script: (spec: SessionSpec) => FauxAction[];
|
|
71
|
-
/** Whether the faux harness can fork (default false). */
|
|
72
|
-
fork?: boolean;
|
|
73
126
|
/** Problems `check` reports for a spec. */
|
|
74
127
|
refuse?: (spec: SessionSpec) => string[];
|
|
75
128
|
/** How long `open` takes, ignoring the session's signal, as a slow harness start does (default 0). */
|
|
76
129
|
openDelayMs?: number;
|
|
130
|
+
/** Told each session closed, by its key. */
|
|
131
|
+
onClose?: (key: string) => void;
|
|
132
|
+
/** How long a session's close takes before it is told closed, as a slow harness stop does (default 0). */
|
|
133
|
+
closeDelayMs?: number;
|
|
134
|
+
/** A close that fails, after its delay, with these words (default none). */
|
|
135
|
+
closeError?: string;
|
|
136
|
+
/** A real model proxy for each session, as a real adapter's machine starts one (its hooks the session's booking,
|
|
137
|
+
* io.models), whose side keys the session's `port` hands the host: the host's own requests then go through the same
|
|
138
|
+
* policy, origin and credential as a real harness's. The faux harness's own scripted requests stay booked directly.
|
|
139
|
+
* `api`: what the proxy serves. */
|
|
140
|
+
proxy?: {
|
|
141
|
+
options: Omit<ModelProxyOptions, "hooks">;
|
|
142
|
+
api: SessionPort["api"];
|
|
143
|
+
};
|
|
77
144
|
}
|
|
78
145
|
export interface FauxAdapter extends AgentAdapter {
|
|
79
146
|
/** Paid requests made, across every session and process of this adapter. */
|