@parcha/agentrun-kernel 0.0.0-stage → 0.1.0-beta.30

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 (84) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +63 -2
  5. package/dist/booking.d.ts +50 -0
  6. package/dist/booking.js +52 -0
  7. package/dist/delegate.d.ts +87 -0
  8. package/dist/delegate.js +143 -0
  9. package/dist/errors.d.ts +36 -0
  10. package/dist/errors.js +37 -0
  11. package/dist/host/alive.d.ts +2 -0
  12. package/dist/host/alive.js +28 -0
  13. package/dist/host/box-slot.d.ts +26 -0
  14. package/dist/host/box-slot.js +112 -0
  15. package/dist/host/box.d.ts +104 -0
  16. package/dist/host/box.js +16 -0
  17. package/dist/host/egress-proxy.d.ts +45 -0
  18. package/dist/host/egress-proxy.js +416 -0
  19. package/dist/host/egress-table.d.ts +24 -0
  20. package/dist/host/egress-table.js +165 -0
  21. package/dist/host/index.d.ts +16 -0
  22. package/dist/host/index.js +12 -0
  23. package/dist/host/overhead.d.ts +53 -0
  24. package/dist/host/overhead.js +75 -0
  25. package/dist/host/parent-death.d.ts +15 -0
  26. package/dist/host/parent-death.js +42 -0
  27. package/dist/host/parent-watch.d.ts +1 -0
  28. package/dist/host/parent-watch.js +38 -0
  29. package/dist/host/pinned-binary.d.ts +6 -0
  30. package/dist/host/pinned-binary.js +48 -0
  31. package/dist/host/proxy.d.ts +212 -0
  32. package/dist/host/proxy.js +808 -0
  33. package/dist/host/serial.d.ts +3 -0
  34. package/dist/host/serial.js +10 -0
  35. package/dist/index.d.ts +13 -0
  36. package/dist/index.js +7 -0
  37. package/dist/kernel/blobs.d.ts +16 -0
  38. package/dist/kernel/blobs.js +59 -0
  39. package/dist/kernel/drive.d.ts +40 -0
  40. package/dist/kernel/drive.js +239 -0
  41. package/dist/kernel/errors.d.ts +27 -0
  42. package/dist/kernel/errors.js +42 -0
  43. package/dist/kernel/follow-up.d.ts +67 -0
  44. package/dist/kernel/follow-up.js +146 -0
  45. package/dist/kernel/halt.d.ts +11 -0
  46. package/dist/kernel/halt.js +17 -0
  47. package/dist/kernel/index.d.ts +8 -0
  48. package/dist/kernel/index.js +5 -0
  49. package/dist/kernel/types.d.ts +129 -0
  50. package/dist/kernel/types.js +1 -0
  51. package/dist/process/builtins.d.ts +142 -0
  52. package/dist/process/builtins.js +207 -0
  53. package/dist/process/inbox.d.ts +29 -0
  54. package/dist/process/inbox.js +52 -0
  55. package/dist/process/index.d.ts +9 -0
  56. package/dist/process/index.js +11 -0
  57. package/dist/process/journal.d.ts +111 -0
  58. package/dist/process/journal.js +232 -0
  59. package/dist/process/records.d.ts +143 -0
  60. package/dist/process/records.js +142 -0
  61. package/dist/process/recovery.d.ts +76 -0
  62. package/dist/process/recovery.js +139 -0
  63. package/dist/process/settle.d.ts +22 -0
  64. package/dist/process/settle.js +38 -0
  65. package/dist/process/tail.d.ts +20 -0
  66. package/dist/process/tail.js +53 -0
  67. package/dist/process/tools.d.ts +105 -0
  68. package/dist/process/tools.js +120 -0
  69. package/dist/process/zod.d.ts +32 -0
  70. package/dist/process/zod.js +109 -0
  71. package/dist/runner.d.ts +154 -0
  72. package/dist/runner.js +559 -0
  73. package/dist/schema-check-cases.d.ts +7 -0
  74. package/dist/schema-check-cases.js +73 -0
  75. package/dist/schema-check.d.ts +3 -0
  76. package/dist/schema-check.js +88 -0
  77. package/dist/skill-files.d.ts +23 -0
  78. package/dist/skill-files.js +136 -0
  79. package/dist/testing.d.ts +91 -0
  80. package/dist/testing.js +196 -0
  81. package/dist/types.d.ts +256 -0
  82. package/dist/types.js +17 -0
  83. package/package.json +74 -4
  84. package/vendor/durable-harness/UPSTREAM.json +67 -0
@@ -0,0 +1,808 @@
1
+ // A session's model proxy, written for AgentRun: the provider a harness is pointed at, on the loopback interface. The
2
+ // harness holds only the session's own key; the provider's credential never reaches it. The proxy is provider-neutral,
3
+ // and a `ProviderPolicy` says what one provider's API may carry (its routes, how its client sends a key, the body it may
4
+ // forward, where a response reports its usage). The core:
5
+ // - admits a request only with the session's key (compared in constant time), on a route the policy lists, by exact
6
+ // path text, with no query or one the route lists exactly: an absolute URL, `..`, `//` or `%` escapes never match. A
7
+ // route may be answered here with a status alone, with no key (a client's connectivity check), or be free (a token
8
+ // count, which the runner never pays);
9
+ // - parses the body strictly (one JSON value, no duplicate key at any depth, so a check on one `model` cannot pass while
10
+ // the provider reads another), then has the policy shape it (or refuse it);
11
+ // - asks the runner before every paid request (`beforeRequest`, where a turn cap or the host's budget refuses it) and
12
+ // answers a refusal with a status the client does not retry, adds the provider's credential, forwards to the
13
+ // provider's origin and the route's own path (never text from the request), streams the answer back, and reports the
14
+ // response's usage once it completes (`afterRequest`). Every paid request forwarded is booked exactly once: a response
15
+ // cut short, or one that says no usage, is booked at an unknown cost.
16
+ // Model spend is accounted only there, by the runner: the proxy keeps no ledger of its own.
17
+ import { createHash, timingSafeEqual } from "node:crypto";
18
+ import { createServer } from "node:http";
19
+ import { CONTENT_FILTERED } from "../types.js";
20
+ import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
21
+ /** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
22
+ * not a stream of events, read whole as one). */
23
+ const EVENT_MAX_CHARS = 1 << 22;
24
+ /** What of a response reached its client, event by event: each whole server-sent event (up to a blank line) read by
25
+ * each of `readers`, its bytes added to that reader's sum; a reader the policy does not have counts none. */
26
+ function eventCounter(readers) {
27
+ const keys = Object.keys(readers).filter((key) => readers[key] !== undefined);
28
+ const sums = Object.fromEntries(keys.map((key) => [key, 0]));
29
+ let pending = "";
30
+ /** A "\r" the last piece ended on: the first half of a "\r\n" the next piece ends. */
31
+ let cr = "";
32
+ return {
33
+ push(text) {
34
+ if (!keys.length)
35
+ return;
36
+ // A line end split between pieces ("\r" here, "\n" in the next) is joined before "\r\n" becomes "\n", or the two
37
+ // events around a split blank line would read as one, which no policy can parse.
38
+ let piece = cr + text;
39
+ cr = piece.endsWith("\r") ? "\r" : "";
40
+ if (cr)
41
+ piece = piece.slice(0, -1);
42
+ pending += piece.replace(/\r\n/g, "\n");
43
+ for (let at = pending.indexOf("\n\n"); at >= 0; at = pending.indexOf("\n\n")) {
44
+ const event = pending.slice(0, at);
45
+ pending = pending.slice(at + 2);
46
+ for (const key of keys) {
47
+ try {
48
+ const n = readers[key](event);
49
+ if (typeof n === "number" && Number.isFinite(n) && n > 0)
50
+ sums[key] += n;
51
+ }
52
+ catch {
53
+ // An event the policy cannot read carries nothing it counts.
54
+ }
55
+ }
56
+ }
57
+ if (pending.length > EVENT_MAX_CHARS)
58
+ pending = "";
59
+ },
60
+ bytes: (of) => sums[of] ?? 0,
61
+ };
62
+ }
63
+ /** A header a host may not set on forwarded requests: the credential's, the transport's, and the provider's protocol. */
64
+ const RESERVED_HEADER = /^(?:authorization|proxy-authorization|x-api-key|host|content-length|content-type|transfer-encoding|connection|cookie|anthropic-.*)$/i;
65
+ const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
66
+ /** What is wrong with headers a host would add to forwarded requests: a name that is not a token or is reserved, a value
67
+ * an HTTP header cannot carry (a line break or other control character, or a character beyond Latin-1, which the fetch
68
+ * the proxy forwards with refuses) or over 1 KiB. Empty when they are fine. */
69
+ export function hostHeaderProblems(headers) {
70
+ const problems = [];
71
+ for (const [name, value] of Object.entries(headers ?? {})) {
72
+ if (!HEADER_NAME.test(name))
73
+ problems.push(`the header name ${JSON.stringify(name.slice(0, 80))} is not a token`);
74
+ else if (RESERVED_HEADER.test(name))
75
+ problems.push(`the header ${name} is the proxy's own (credential, transport or protocol), not a host's`);
76
+ if (typeof value !== "string" || /[^\t\x20-\x7e\x80-\xff]/.test(value) || value.length > 1024)
77
+ problems.push(`the header ${name.slice(0, 80)}'s value must be one line of text an HTTP header can carry (Latin-1, no control characters), at most 1024 characters`);
78
+ }
79
+ return problems;
80
+ }
81
+ const UNSAFE_PATH = /[^A-Za-z0-9/_.\-?=&]|\.\.|\/\/|^[^/]|\?.*\?/;
82
+ const MAX_BODY = 32 * 1024 * 1024;
83
+ /** How much of a response's start and end the proxy keeps to read its usage from. */
84
+ const USAGE_WINDOW = 64 * 1024;
85
+ /** How long an answer the provider stopped on its content filter is still read after its client left, or the proxy began
86
+ * to close, so the request is booked at the usage its end reports; past it, it is cut off as any other. */
87
+ const FILTERED_DRAIN_MS = 5_000;
88
+ /** How much of the start of each line of an answer the proxy keeps, for its last LINE_STARTS whole lines: an event's name
89
+ * and the first fields of its data, which a stop can be read from when the event's line is longer than either window. */
90
+ const LINE_START = 16 * 1024;
91
+ const LINE_STARTS = 4;
92
+ /** A response header that names the request: the provider's `request-id` (`x-request-id`), or a gateway's own call id
93
+ * (LiteLLM's `x-litellm-call-id`, the id its spend log records; `llm_provider-request-id`, the provider's passed on). */
94
+ const ID_HEADER = /^(?:[a-z0-9]+[-_])*(?:request|call)[-_]id$/;
95
+ /** What an id looks like: nothing else (a cookie, a token, prose) is ever kept. */
96
+ const ID_VALUE = /^[A-Za-z0-9_.:-]{1,200}$/;
97
+ /** The ids a response's headers give its request, by header name, so a run's books can be joined to the provider's (or
98
+ * a gateway's) request by request; undefined when there are none. Only id-named headers with id-shaped values. */
99
+ export function providerIdsOf(headers) {
100
+ const ids = {};
101
+ headers.forEach((value, name) => {
102
+ if (ID_HEADER.test(name) && ID_VALUE.test(value))
103
+ ids[name] = value;
104
+ });
105
+ return Object.keys(ids).length ? ids : undefined;
106
+ }
107
+ /** LiteLLM's figures for what a response cost: its own (`x-litellm-response-cost`), and the figure before its discount
108
+ * and margin (`-original`), which is the same only when both are reported 0. */
109
+ const COST_HEADER = "x-litellm-response-cost";
110
+ const COST_PARTS = ["x-litellm-response-cost-discount-amount", "x-litellm-response-cost-margin-amount"];
111
+ /** A cost as a gateway writes it: a decimal number, an exponent allowed (`3.7e-06`); nothing else is read as one. */
112
+ const COST_VALUE = /^\d{1,9}(?:\.\d{1,30})?(?:[eE][-+]?\d{1,3})?$/;
113
+ /** No one request costs this much: a figure above it is not believed. */
114
+ const MAX_REQUEST_USD = 1000;
115
+ const costOf = (value) => {
116
+ if (value === null || !COST_VALUE.test(value.trim()))
117
+ return undefined;
118
+ const usd = Number(value.trim());
119
+ return Number.isFinite(usd) && usd > 0 && usd <= MAX_REQUEST_USD ? usd : undefined;
120
+ };
121
+ /** What a response's headers say it cost, when they say so: LiteLLM's `x-litellm-response-cost`, or its `-original` when
122
+ * the discount and margin it reports are both exactly 0. Only a positive number counts. A missing, malformed or zero
123
+ * figure is unknown, never $0: a streamed answer's headers leave before it is priced, and LiteLLM writes 0.0 there. */
124
+ export function reportedCostOf(headers) {
125
+ const own = costOf(headers.get(COST_HEADER));
126
+ if (own !== undefined)
127
+ return own;
128
+ if (!COST_PARTS.every((name) => /^0(?:\.0+)?$/.test(headers.get(name)?.trim() ?? "")))
129
+ return undefined;
130
+ return costOf(headers.get(`${COST_HEADER}-original`));
131
+ }
132
+ export class ProxyRefusal extends Error {
133
+ status;
134
+ constructor(status, message) {
135
+ super(message);
136
+ this.status = status;
137
+ this.name = "ProxyRefusal";
138
+ }
139
+ }
140
+ /** Match a request's method and path text against the routes, never parsing the path as a URL: the route, and the
141
+ * query it carried, which is one the route lists exactly, or none. */
142
+ export function matchRoute(routes, method, path) {
143
+ if (typeof path !== "string" || path.length === 0 || path.length > 2048 || UNSAFE_PATH.test(path))
144
+ throw new ProxyRefusal(403, "the path is not one the table can match");
145
+ const at = path.indexOf("?");
146
+ const pathname = at < 0 ? path : path.slice(0, at);
147
+ const query = at < 0 ? "" : path.slice(at + 1);
148
+ const route = routes.find((r) => r.method === method && r.path === pathname);
149
+ if (!route)
150
+ throw new ProxyRefusal(403, `${method.slice(0, 16)} ${pathname.slice(0, 128)} is not in the table`);
151
+ if (at >= 0 && !route.query?.includes(query))
152
+ throw new ProxyRefusal(403, `the query on ${pathname.slice(0, 128)} is not in the table`);
153
+ return { route, query };
154
+ }
155
+ /** Parse one JSON value, refusing a duplicate key at any depth and nesting past 64 levels. */
156
+ export function parseStrict(text) {
157
+ let i = 0;
158
+ const fail = (why) => { throw new ProxyRefusal(400, `the body is not strict JSON: ${why}`); };
159
+ const ws = () => { while (i < text.length && /[ \t\n\r]/.test(text[i]))
160
+ i++; };
161
+ const str = () => {
162
+ const start = i;
163
+ i++;
164
+ while (i < text.length && text[i] !== '"') {
165
+ if (text[i] === "\\")
166
+ i++;
167
+ i++;
168
+ }
169
+ if (text[i] !== '"')
170
+ fail("an unterminated string");
171
+ i++;
172
+ return JSON.parse(text.slice(start, i));
173
+ };
174
+ const value = (depth) => {
175
+ if (depth > 64)
176
+ fail("nested too deep");
177
+ ws();
178
+ const c = text[i];
179
+ if (c === "{") {
180
+ i++;
181
+ const out = {};
182
+ const seen = new Set();
183
+ ws();
184
+ if (text[i] === "}") {
185
+ i++;
186
+ return out;
187
+ }
188
+ for (;;) {
189
+ ws();
190
+ if (text[i] !== '"')
191
+ fail("an object key");
192
+ const key = str();
193
+ if (seen.has(key))
194
+ fail(`the key ${JSON.stringify(key).slice(0, 40)} appears twice`);
195
+ seen.add(key);
196
+ ws();
197
+ if (text[i] !== ":")
198
+ fail("a colon");
199
+ i++;
200
+ // Defined, never assigned: a "__proto__" key is an own field like any other, and the prototype stays put.
201
+ Object.defineProperty(out, key, { value: value(depth + 1), enumerable: true, writable: true, configurable: true });
202
+ ws();
203
+ if (text[i] === ",") {
204
+ i++;
205
+ continue;
206
+ }
207
+ if (text[i] === "}") {
208
+ i++;
209
+ return out;
210
+ }
211
+ fail("an object");
212
+ }
213
+ }
214
+ if (c === "[") {
215
+ i++;
216
+ const out = [];
217
+ ws();
218
+ if (text[i] === "]") {
219
+ i++;
220
+ return out;
221
+ }
222
+ for (;;) {
223
+ out.push(value(depth + 1));
224
+ ws();
225
+ if (text[i] === ",") {
226
+ i++;
227
+ continue;
228
+ }
229
+ if (text[i] === "]") {
230
+ i++;
231
+ return out;
232
+ }
233
+ fail("an array");
234
+ }
235
+ }
236
+ if (c === '"')
237
+ return str();
238
+ const m = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
239
+ if (!m)
240
+ fail("a value");
241
+ i += m[0].length;
242
+ return JSON.parse(m[0]);
243
+ };
244
+ const out = value(0);
245
+ ws();
246
+ if (i !== text.length)
247
+ fail("more than one value");
248
+ return out;
249
+ }
250
+ /** Whether `given` is `key`, in time that does not depend on where they differ. */
251
+ export const sameKey = (given, key) => {
252
+ const a = createHash("sha256").update(given).digest();
253
+ const b = createHash("sha256").update(key).digest();
254
+ return timingSafeEqual(a, b);
255
+ };
256
+ /** `base` as the proxy joins a route's path to it: its origin and its path, without a trailing slash. */
257
+ function baseOf(base) {
258
+ const url = new URL(base);
259
+ // A backslash is a path separator to the URL parser, so it could move the base to a path the text does not read as.
260
+ if (url.username || url.password || url.search || url.hash || base.includes("\\"))
261
+ throw new Error("agentrun-kernel: a model proxy's base is an origin and a path, with no userinfo, query, fragment or backslash");
262
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
263
+ }
264
+ /** Start a session's model proxy on the loopback interface, admitting `key`. */
265
+ /**
266
+ * The most input tokens a request with body `sent` (the body `apply` returned, as it is sent) can be billed for: its UTF-8
267
+ * byte count, plus the input the policy says the provider adds that the body does not carry. A provider's tokenizer is a
268
+ * byte-level BPE, whose every token covers at least one byte of what it encodes, so the text the body carries can never
269
+ * be more tokens than bytes, however dense (CJK, emoji, base64). It is not an average of characters per token, which
270
+ * undercounts dense text. Undefined, never 0, when the policy says the body has no bound (its undefined) or its figure
271
+ * cannot be read (a throw, or no count, which is reported): the input is then unmeasured.
272
+ */
273
+ export function inputTokensMaxOf(policy, body, sent, say = () => { }) {
274
+ try {
275
+ // Only a policy with no hook adds nothing. A hook's undefined is its word that the body has no bound: unmeasured,
276
+ // never 0, and no failure to report. Anything else that is not a count (null, a throw) is reported, and unmeasured too.
277
+ const overhead = policy.serverInputOverhead ? policy.serverInputOverhead(body) : 0;
278
+ if (overhead === undefined)
279
+ return undefined;
280
+ if (typeof overhead !== "number" || !Number.isSafeInteger(overhead) || overhead < 0)
281
+ throw new Error(`not a token count: ${String(overhead).slice(0, 40)}`);
282
+ return Buffer.byteLength(sent, "utf8") + overhead;
283
+ }
284
+ catch (error) {
285
+ say(`model proxy (${policy.id}): the policy could not say what the provider adds to the body's input; its input is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
286
+ return undefined;
287
+ }
288
+ }
289
+ export async function startModelProxy(options, key) {
290
+ const { policy, hooks, model } = options;
291
+ if (!key)
292
+ throw new Error("agentrun-kernel: a model proxy needs the session's key");
293
+ const wrongHeaders = hostHeaderProblems(options.headers);
294
+ if (wrongHeaders.length)
295
+ throw new Error(`agentrun-kernel: ${wrongHeaders.join("; ")}`);
296
+ const hostHeaders = { ...options.headers };
297
+ const forward = options.fetch ?? fetch;
298
+ const origin = baseOf(options.origin);
299
+ const refusedStatus = policy.refusedStatus ?? 400;
300
+ const inflight = new Set();
301
+ /** The requests whose answer the provider stopped on its content filter, read on for their usage, each until booked. */
302
+ const draining = new Map();
303
+ /** Set by close(): nothing is admitted or sent after it. */
304
+ let closing = false;
305
+ /** The host's log, which must never break a request (a throw from it is dropped). */
306
+ const say = (message, detail) => {
307
+ try {
308
+ options.log?.(message, detail);
309
+ }
310
+ catch { /* the host's log failed; the request goes on */ }
311
+ };
312
+ const refuse = (res, status, message, req) => {
313
+ // Every refusal is reported, so a client that calls something the table does not hold is seen, not silently refused.
314
+ // The client's user-agent names who called: the session's own harness, or another local process that found the port.
315
+ const agent = req?.headers["user-agent"];
316
+ say(`model proxy (${policy.id}): refused`, {
317
+ status, method: String(req?.method ?? "").slice(0, 16), path: String(req?.url ?? "").slice(0, 200), reason: message.slice(0, 200),
318
+ ...(typeof agent === "string" && agent ? { userAgent: agent.slice(0, 120) } : {}),
319
+ });
320
+ res.writeHead(status, { "content-type": "application/json", connection: "close" });
321
+ res.end(JSON.stringify({ error: { message, type: "agentrun_proxy" } }));
322
+ };
323
+ const serve = async (req, res) => {
324
+ // A request refused before its body is read is drained, so its client gets the answer instead of a reset.
325
+ res.once("finish", () => { if (!req.complete)
326
+ req.resume(); });
327
+ let route;
328
+ let query;
329
+ try {
330
+ ({ route, query } = matchRoute(policy.routes, req.method ?? "", req.url ?? ""));
331
+ }
332
+ catch (error) {
333
+ // Without the key every request that is not a local route gets the same answer, so the table can't be mapped.
334
+ if (!sameKey(policy.keyOf(req.headers), key))
335
+ return refuse(res, 401, "this session's key is required", req);
336
+ const e = error;
337
+ return refuse(res, e.status ?? 403, e.message, req);
338
+ }
339
+ // A local route forwards nothing and answers only a status, so it needs no key: a client's connectivity check
340
+ // (the Claude Agent CLI's `HEAD /api/hello`) is sent without one.
341
+ if (route.local !== undefined) {
342
+ res.writeHead(route.local, { "content-length": "0" });
343
+ return res.end();
344
+ }
345
+ if (!sameKey(policy.keyOf(req.headers), key))
346
+ return refuse(res, 401, "this session's key is required", req);
347
+ const chunks = [];
348
+ let size = 0;
349
+ for await (const chunk of req) {
350
+ size += chunk.length;
351
+ if (size > MAX_BODY)
352
+ return refuse(res, 413, "the body is too large", req);
353
+ chunks.push(chunk);
354
+ }
355
+ let body;
356
+ const headers = { "content-type": "application/json" };
357
+ try {
358
+ body = policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route);
359
+ // The listed headers, as the policy keeps them (or refuses them), before the runner is asked.
360
+ for (const name of route.headers ?? []) {
361
+ const value = req.headers[name.toLowerCase()];
362
+ const kept = typeof value === "string" ? (policy.header ? policy.header(name, value) : value) : undefined;
363
+ if (kept !== undefined)
364
+ headers[name] = kept;
365
+ }
366
+ }
367
+ catch (error) {
368
+ const e = error;
369
+ return refuse(res, e instanceof ProxyRefusal ? e.status : 400, e instanceof ProxyRefusal ? e.message : "the body was refused", req);
370
+ }
371
+ // The model this request is for, as the policy read it from the body it checked: the runner is asked about it, and
372
+ // it is priced at its rate.
373
+ let asked = model;
374
+ try {
375
+ const named = policy.modelOf?.(body);
376
+ if (typeof named === "string" && named)
377
+ asked = named;
378
+ }
379
+ catch (error) {
380
+ say(`model proxy (${policy.id}): the policy could not name the request's model; it is booked as the session's`, { error: String(error?.message ?? error).slice(0, 200) });
381
+ }
382
+ // The body as it is sent, and the most input tokens it can be billed for, measured before the runner is asked.
383
+ let sent;
384
+ try {
385
+ sent = JSON.stringify(body);
386
+ }
387
+ catch (error) {
388
+ say(`model proxy (${policy.id}): the body could not be serialized`, { error: String(error?.message ?? error).slice(0, 200) });
389
+ return refuse(res, 500, "the body could not be serialized", req);
390
+ }
391
+ let inputTokensMax = inputTokensMaxOf(policy, body, sent, say);
392
+ // What the body asks for at most, and the least it may be limited to, as the policy reads them. One the policy cannot
393
+ // read leaves the request's worst case unknown: its input is unmeasured.
394
+ const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
395
+ let outputTokensAsked;
396
+ let outputTokensLeast;
397
+ /** The reasoning a stop of this request leaves unseen (the policy's `reasoningHidden`), in tokens. */
398
+ let hiddenTokens = 0;
399
+ /** The content and the reasoning the client was sent, by the policy's reading of each event (content: text,
400
+ * reasoning and tool arguments; reasoning: what of its reasoning streamed). */
401
+ const sentOf = eventCounter({ content: policy.contentBytesOf?.bind(policy), reasoning: policy.reasoningBytesOf?.bind(policy) });
402
+ try {
403
+ outputTokensAsked = figure(policy.outputAsked?.(body));
404
+ outputTokensLeast = figure(policy.outputLeast?.(body));
405
+ hiddenTokens = figure(policy.reasoningHidden?.(body)) ?? 0;
406
+ }
407
+ catch (error) {
408
+ say(`model proxy (${policy.id}): the policy could not read the body's output; its worst case is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
409
+ inputTokensMax = undefined;
410
+ }
411
+ // The provider's credential and its headers come before the runner is asked: a request that could not be sent is
412
+ // refused without being admitted, so it is never booked and spends no turn.
413
+ let credential = "";
414
+ try {
415
+ credential = await options.credential();
416
+ }
417
+ catch (error) {
418
+ say(`model proxy (${policy.id}): the provider credential could not be read`, { error: String(error?.message ?? error).slice(0, 200) });
419
+ }
420
+ if (!credential)
421
+ return refuse(res, 500, "the session has no provider credential", req);
422
+ try {
423
+ // The host's own headers, over any the client sent by those names; then the credential's, over everything. A name
424
+ // replaces any other spelling of it, so no two headers of one name reach the provider combined.
425
+ const set = (name, value) => {
426
+ for (const sent of Object.keys(headers))
427
+ if (sent.toLowerCase() === name.toLowerCase())
428
+ delete headers[sent];
429
+ headers[name] = value;
430
+ };
431
+ for (const [name, value] of Object.entries(hostHeaders))
432
+ set(name, value);
433
+ for (const [name, value] of Object.entries(policy.authHeaders(credential)))
434
+ set(name, value);
435
+ }
436
+ catch (error) {
437
+ say(`model proxy (${policy.id}): the policy could not build the provider's credential headers`, { error: String(error?.message ?? error).slice(0, 200) });
438
+ return refuse(res, 500, "the provider's credential headers could not be built", req);
439
+ }
440
+ if (closing)
441
+ return refuse(res, 503, "the model proxy is closing", req);
442
+ // This request's own admission, handed back to its booking (requests may be in flight together).
443
+ let ticket;
444
+ try {
445
+ if (!route.free)
446
+ ticket = await hooks.beforeRequest({
447
+ model: asked, inputTokensMax,
448
+ ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
449
+ ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
450
+ });
451
+ }
452
+ catch (error) {
453
+ // Not 429: clients retry that, and the runner already refused this request (a turn cap, the host's budget).
454
+ return refuse(res, refusedStatus, `refused before it was sent: ${String(error?.message ?? error).slice(0, 300)}`, req);
455
+ }
456
+ /** An admitted request that is not sent after all: refused to its client, and released, booked at nothing, so the
457
+ * runner's count agrees. */
458
+ const release = async (status, message) => {
459
+ refuse(res, status, message, req);
460
+ if (!route.free) {
461
+ try {
462
+ await hooks.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket);
463
+ }
464
+ catch (error) {
465
+ say(`model proxy (${policy.id}): afterRequest threw; the request was not sent and not booked`, { error: String(error?.message ?? error).slice(0, 200) });
466
+ }
467
+ }
468
+ };
469
+ // Admitted while the proxy was closing, and never sent.
470
+ if (closing)
471
+ return release(503, "the model proxy is closing");
472
+ // Admitted with an output limit (what is left of a spend cap can buy): written into the body, which is never sent
473
+ // unlimited, nor longer than the body its input bound was measured on.
474
+ const limit = typeof ticket === "object" && ticket !== null ? ticket.outputTokensMax : undefined;
475
+ if (limit !== undefined) {
476
+ if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || !policy.limitOutput)
477
+ return release(500, "the request's output could not be limited to what its spend cap leaves");
478
+ let limited;
479
+ try {
480
+ limited = JSON.stringify(policy.limitOutput(body, limit));
481
+ }
482
+ catch (error) {
483
+ say(`model proxy (${policy.id}): the policy could not limit the body's output`, { error: String(error?.message ?? error).slice(0, 200) });
484
+ return release(500, "the request's output could not be limited to what its spend cap leaves");
485
+ }
486
+ if (Buffer.byteLength(limited, "utf8") > Buffer.byteLength(sent, "utf8"))
487
+ return release(500, "the request's limited body is longer than the one its input was measured on");
488
+ sent = limited;
489
+ }
490
+ const controller = new AbortController();
491
+ inflight.add(controller);
492
+ /** Set once the provider's content-filter stop was told: the answer is read on to its end for its usage, though the
493
+ * client (whose turn the harness ends) goes away. */
494
+ let keepReading = false;
495
+ /** That the client left before the answer reached it whole (the harness stopped the request). */
496
+ let clientLeft = false;
497
+ /** The bytes of the answer the client was sent (and, for one read on after its content-filter stop, read after its
498
+ * client left: what the provider streamed). */
499
+ let sentBytes = 0;
500
+ /** That the answer ended because its client left part way, not because the provider or this proxy ended it. */
501
+ let stoppedByClient = false;
502
+ res.on("close", () => {
503
+ if (!answered)
504
+ clientLeft = true;
505
+ if (!keepReading)
506
+ controller.abort();
507
+ });
508
+ let head = "";
509
+ let tail = "";
510
+ let length = 0;
511
+ /** The provider's answer, once it reached the client whole. */
512
+ let answered;
513
+ /** That the provider's answer began, with its status: what a client that left before the end had of it. */
514
+ let began;
515
+ /** The code of the provider's fetch failing before any response (rejectionCode): a connect-phase one never left. */
516
+ let failedCode;
517
+ let watchEnd;
518
+ /** The ids its headers gave it. */
519
+ let ids;
520
+ let reported;
521
+ /** Whether the provider's content-filter stop was read (once an answer). */
522
+ let filteredTold = false;
523
+ /** Whether this request is the turn's answer request (`ProviderPolicy.answers`): a side call's stop ends nothing. */
524
+ let answering = true;
525
+ try {
526
+ answering = policy.answers ? policy.answers(body) : true;
527
+ }
528
+ catch (error) {
529
+ say(`model proxy (${policy.id}): whether the request is the turn's could not be read; taken as the turn's`, { error: String(error?.message ?? error).slice(0, 200) });
530
+ }
531
+ /** Called once the request is booked, when its answer was read on after its stop (the proxy's close waits for it). */
532
+ let drained;
533
+ const settled = () => {
534
+ if (!drained)
535
+ return;
536
+ draining.delete(controller);
537
+ drained();
538
+ };
539
+ /** The start of the line being read (LINE_START) and of the last whole lines (LINE_STARTS). */
540
+ let lineStart = "";
541
+ let lineLength = 0;
542
+ const starts = [];
543
+ /** Tells the harness the provider stopped this answer on its content filter, when `text` (the answer so far, or the
544
+ * kept window of it) says so: once, and never failing the answer. */
545
+ const tellFiltered = (text) => {
546
+ if (filteredTold || !policy.filtered)
547
+ return;
548
+ let stopped = false;
549
+ try {
550
+ stopped = policy.filtered(text, starts);
551
+ }
552
+ catch (error) {
553
+ say(`model proxy (${policy.id}): whether the provider's content filter stopped the answer could not be read`, { error: String(error?.message ?? error).slice(0, 200) });
554
+ }
555
+ if (!stopped)
556
+ return;
557
+ filteredTold = true;
558
+ if (!answering) {
559
+ say(`model proxy (${policy.id}): the provider stopped a side call on its content filter; left to the client`);
560
+ return;
561
+ }
562
+ say(`model proxy (${policy.id}): the provider stopped the answer on its content filter`);
563
+ // Read on to the answer's end for its usage, though the client goes; the proxy's close waits for it, bounded.
564
+ keepReading = true;
565
+ draining.set(controller, new Promise((resolve) => (drained = resolve)));
566
+ try {
567
+ options.onFiltered?.(CONTENT_FILTERED);
568
+ }
569
+ catch (error) {
570
+ say(`model proxy (${policy.id}): onFiltered threw`, { error: String(error?.message ?? error).slice(0, 200) });
571
+ }
572
+ };
573
+ try {
574
+ // From here a paid request may be paid, so every way out below books it exactly once.
575
+ const upstream = await forward(`${origin}${route.path}${query ? `?${query}` : ""}`, { method: route.method, headers, body: sent, signal: controller.signal });
576
+ // The provider answered (and a paid request was paid): a host callback that throws must not lose the answer or
577
+ // its booking.
578
+ try {
579
+ options.onResponse?.({ method: route.method, path: route.path, free: route.free === true, status: upstream.status });
580
+ }
581
+ catch (error) {
582
+ say(`model proxy (${policy.id}): onResponse threw`, { error: String(error?.message ?? error).slice(0, 200) });
583
+ }
584
+ // Its ids are kept before its body is read: from here the provider has seen it, whatever cuts it off.
585
+ ids = route.free ? undefined : providerIdsOf(upstream.headers);
586
+ reported = route.free ? undefined : reportedCostOf(upstream.headers);
587
+ if (ids && hooks.responded) {
588
+ try {
589
+ await hooks.responded(ids, ticket);
590
+ }
591
+ catch (error) {
592
+ say(`model proxy (${policy.id}): responded threw; the request's ids are kept with its booking only`, { error: String(error?.message ?? error).slice(0, 200) });
593
+ }
594
+ }
595
+ began = { ok: upstream.ok, status: upstream.status };
596
+ res.writeHead(upstream.status, { "content-type": upstream.headers.get("content-type") ?? "application/json" });
597
+ const decoder = new TextDecoder();
598
+ let watcher;
599
+ try {
600
+ watcher = policy.watch?.();
601
+ watchEnd = watcher?.end?.bind(watcher);
602
+ }
603
+ catch (error) {
604
+ say(`model proxy (${policy.id}): the response watcher could not start`, { error: String(error?.message ?? error).slice(0, 200) });
605
+ try {
606
+ policy.unwatched?.();
607
+ }
608
+ catch { }
609
+ }
610
+ if (upstream.body) {
611
+ for await (const chunk of upstream.body) {
612
+ // What the watcher reads of a piece, it reads before the client has the piece.
613
+ const text = decoder.decode(chunk, { stream: true });
614
+ if (watcher) {
615
+ try {
616
+ watcher.chunk(text);
617
+ }
618
+ catch (error) {
619
+ say(`model proxy (${policy.id}): the response watcher failed`, { error: String(error?.message ?? error).slice(0, 200) });
620
+ try {
621
+ watcher.failed?.();
622
+ }
623
+ catch { }
624
+ watcher = undefined;
625
+ }
626
+ }
627
+ // The provider's content-filter stop, read before the client has the piece that carries it: the harness ends the
628
+ // turn before its client acts on the stop (asks for the refused answer again, or ends the turn its own way).
629
+ // A line longer than the window is read as it ends, from its start, while the lines just before it (an event's
630
+ // name) are still the last starts kept: a piece may carry the lines after it too.
631
+ const window = (tail + text).slice(-USAGE_WINDOW);
632
+ const lines = text.split("\n");
633
+ for (let at = 0; at < lines.length; at++) {
634
+ if (lineStart.length < LINE_START)
635
+ lineStart += lines[at].slice(0, LINE_START - lineStart.length);
636
+ lineLength += lines[at].length;
637
+ if (at < lines.length - 1) {
638
+ starts.push(lineStart);
639
+ if (starts.length > LINE_STARTS)
640
+ starts.shift();
641
+ if (upstream.ok && lineLength > USAGE_WINDOW)
642
+ tellFiltered(window);
643
+ lineStart = "";
644
+ lineLength = 0;
645
+ }
646
+ }
647
+ if (upstream.ok && lines.length > 1)
648
+ tellFiltered(window);
649
+ // A client that reads slowly holds the provider back: nothing more is read until what was written drains. A
650
+ // client gone after the stop was told is written nothing more: the answer is read on for its usage alone.
651
+ if (!res.destroyed && !res.write(chunk)) {
652
+ // One wait, and nothing left behind: whichever comes first takes both listeners off.
653
+ await new Promise((resolve) => {
654
+ const done = () => { res.off("drain", done); res.off("close", done); resolve(); };
655
+ res.on("drain", done);
656
+ res.on("close", done);
657
+ });
658
+ }
659
+ // The usage is at the start, the end, or both: keep those, not the whole answer.
660
+ length += text.length;
661
+ sentBytes += chunk.byteLength;
662
+ sentOf.push(text);
663
+ if (head.length < USAGE_WINDOW)
664
+ head += text.slice(0, USAGE_WINDOW - head.length);
665
+ tail = (tail + text).slice(-USAGE_WINDOW);
666
+ }
667
+ }
668
+ res.end();
669
+ answered = { ok: upstream.ok };
670
+ }
671
+ catch (error) {
672
+ // Its client had left before this (a stop): read now, as the proxy's own end below closes the response too.
673
+ // Before any header too: the request left, and the provider may have begun it, as a stop part way. Only this proxy's
674
+ // abort ends a stop: an answer read on after its client left (its content-filter stop) that the provider ends with
675
+ // an error is no stop.
676
+ stoppedByClient = clientLeft && (began === undefined || began.ok) && controller.signal.aborted;
677
+ if (!began)
678
+ failedCode = rejectionCode(error);
679
+ say(`model proxy (${policy.id}): the request did not complete`, { error: String(error?.message ?? error).slice(0, 200) });
680
+ if (!res.headersSent)
681
+ refuse(res, 502, "the provider did not answer", req);
682
+ else
683
+ res.destroy();
684
+ }
685
+ finally {
686
+ inflight.delete(controller);
687
+ try {
688
+ watchEnd?.();
689
+ }
690
+ catch { }
691
+ }
692
+ // Every paid request the proxy forwarded is booked exactly once, after the client has its answer (or lost it):
693
+ // nothing here can turn an answer into an error the client sees and might pay again for. Its usage and price
694
+ // when the answer is whole and says them; nothing for a provider's error answer; an unknown cost for an answer
695
+ // cut short, one that said no usage, or a usage or a price that could not be read. A booking that fails is
696
+ // reported (the runner stops the node on it).
697
+ if (route.free)
698
+ return settled();
699
+ let usage;
700
+ let usd = null;
701
+ // Whether `usd` is a figure the provider gave (an error answer's nothing included), not one this proxy made up.
702
+ let own = false;
703
+ let tableUsd;
704
+ // A client may leave once it has read the response's usage (Codex does, at the completion event) while the provider
705
+ // still holds the stream open: what was read of a successful answer is read for its usage as a whole one is. With none
706
+ // in it, the cost is unknown, as for any answer cut short.
707
+ // An error answer cut part way is still an error answer: its status says it was not paid.
708
+ const seen = answered ?? began;
709
+ if (!seen) {
710
+ usage = { input: 0, output: 0, cacheRead: 0 };
711
+ // A request refused at connect never left: it costs nothing. Anything else may have reached the provider.
712
+ if (isConnectCode(failedCode)) {
713
+ usd = 0;
714
+ own = true;
715
+ }
716
+ }
717
+ else if (!seen.ok) {
718
+ // A provider's error answer was not a paid response: it costs nothing. But a gateway's 504 or 524 says only that
719
+ // the gateway gave up: the provider was still at work, and bills it.
720
+ usage = { input: 0, output: 0, cacheRead: 0 };
721
+ if (!isGatewayTimeout(began?.status ?? 0)) {
722
+ usd = 0;
723
+ own = true;
724
+ }
725
+ }
726
+ else {
727
+ let unread = false;
728
+ try {
729
+ usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${tail}`);
730
+ }
731
+ catch (error) {
732
+ say(`model proxy (${policy.id}): the usage could not be read; the request is booked at an unknown cost`, { error: String(error?.message ?? error).slice(0, 200) });
733
+ usage = { input: 0, output: 0, cacheRead: 0 };
734
+ unread = true;
735
+ }
736
+ if (!usage) {
737
+ usage = { input: 0, output: 0, cacheRead: 0 };
738
+ unread = true;
739
+ }
740
+ try {
741
+ usd = unread ? null : options.price?.(asked, usage) ?? null;
742
+ }
743
+ catch (error) {
744
+ say(`model proxy (${policy.id}): the price could not be computed; the request is booked at an unknown cost`, { error: String(error?.message ?? error).slice(0, 200) });
745
+ usd = null;
746
+ }
747
+ // What the gateway says it cost is what was paid; the table's figure stays beside it, to audit the table.
748
+ if (reported !== undefined) {
749
+ tableUsd = usd;
750
+ usd = reported;
751
+ own = true;
752
+ }
753
+ }
754
+ try {
755
+ // A response its client stopped and whose cost is unknown says what streamed of it, for the host to count it by.
756
+ // With the reasoning it never streamed, which the provider can have billed too.
757
+ // What it streamed: its content where the policy reads it, never the provider's framing; else the bytes as sent.
758
+ const streamed = policy.contentBytesOf ? sentOf.bytes("content") : sentBytes;
759
+ const stopped = stoppedByClient && usd === null ? { stoppedAfterBytes: streamed, ...(hiddenTokens > 0 ? { stoppedHiddenTokens: hiddenTokens, stoppedReasoningBytes: sentOf.bytes("reasoning") } : {}) } : {};
760
+ // How it ended, for the runner to book it by (booking.ts). A stop counts what the stop fields above say of it: its
761
+ // content, and the part of its hidden reasoning budget that did not stream, max(0, budget - the reasoning sent).
762
+ const ended = stoppedByClient && usd === null ? { end: "stopped", streamedTokens: streamed + Math.max(0, hiddenTokens - sentOf.bytes("reasoning")) }
763
+ : !seen ? (isConnectCode(failedCode) ? { end: "nothing", label: "never_left" } : { end: "lost", label: "error_before" })
764
+ : !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
765
+ : !answered && usd === null ? { end: "lost", label: "error_after", began: true }
766
+ : { end: "answered", usd, ...(filteredTold ? { label: "filtered" } : {}) };
767
+ await hooks.afterRequest({ ...usage, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
768
+ }
769
+ catch (error) {
770
+ say(`model proxy (${policy.id}): afterRequest threw; the request was answered and not booked`, { error: String(error?.message ?? error).slice(0, 200) });
771
+ }
772
+ // An answer whose stop no piece showed before it ended (a whole JSON body): read whole once it is booked.
773
+ if (seen?.ok)
774
+ tellFiltered(length <= USAGE_WINDOW ? tail : `${head}\n${tail}`);
775
+ settled();
776
+ };
777
+ const server = createServer((req, res) => { void serve(req, res).catch(() => { if (!res.headersSent)
778
+ refuse(res, 500, "the proxy failed", req);
779
+ else
780
+ res.destroy(); }); });
781
+ await new Promise((resolve, reject) => {
782
+ server.once("error", reject);
783
+ server.listen(0, "127.0.0.1", () => resolve());
784
+ });
785
+ const address = server.address();
786
+ if (!address || typeof address === "string")
787
+ throw new Error("agentrun-kernel: the model proxy has no port");
788
+ return {
789
+ url: `http://127.0.0.1:${address.port}`,
790
+ key,
791
+ close: async () => {
792
+ closing = true;
793
+ for (const c of inflight)
794
+ if (!draining.has(c))
795
+ c.abort();
796
+ // An answer the provider stopped on its content filter is read on to its end and booked first, for FILTERED_DRAIN_MS.
797
+ if (draining.size) {
798
+ let timer;
799
+ await Promise.race([Promise.all(draining.values()), new Promise((resolve) => (timer = setTimeout(resolve, FILTERED_DRAIN_MS)))]);
800
+ clearTimeout(timer);
801
+ for (const c of inflight)
802
+ c.abort();
803
+ }
804
+ server.closeAllConnections();
805
+ await new Promise((resolve) => server.close(() => resolve()));
806
+ },
807
+ };
808
+ }