@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.
Files changed (102) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +5 -0
  3. package/dist/errors.d.ts +7 -0
  4. package/dist/errors.js +10 -0
  5. package/dist/host/box.d.ts +0 -58
  6. package/dist/host/box.js +7 -0
  7. package/dist/host/index.d.ts +5 -9
  8. package/dist/host/index.js +2 -4
  9. package/dist/host/mcp-route.d.ts +14 -0
  10. package/dist/host/mcp-route.js +125 -0
  11. package/dist/host/proxy.d.ts +96 -2
  12. package/dist/host/proxy.js +533 -41
  13. package/dist/host/serial.js +2 -1
  14. package/dist/index.d.ts +5 -4
  15. package/dist/index.js +3 -2
  16. package/dist/kernel/cap/admit.d.ts +35 -0
  17. package/dist/kernel/cap/admit.js +186 -0
  18. package/dist/kernel/cap/errors.d.ts +20 -0
  19. package/dist/kernel/cap/errors.js +25 -0
  20. package/dist/kernel/cap/index.d.ts +14 -0
  21. package/dist/kernel/cap/index.js +15 -0
  22. package/dist/kernel/cap/ledger.d.ts +37 -0
  23. package/dist/kernel/cap/ledger.js +83 -0
  24. package/dist/kernel/cap/marks.d.ts +50 -0
  25. package/dist/kernel/cap/marks.js +28 -0
  26. package/dist/kernel/cap/park.d.ts +80 -0
  27. package/dist/kernel/cap/park.js +57 -0
  28. package/dist/kernel/cap/port.d.ts +21 -0
  29. package/dist/kernel/cap/port.js +95 -0
  30. package/dist/kernel/cap/price.d.ts +54 -0
  31. package/dist/kernel/cap/price.js +117 -0
  32. package/dist/kernel/cap/recover.d.ts +18 -0
  33. package/dist/kernel/cap/recover.js +71 -0
  34. package/dist/kernel/cap/rule.d.ts +55 -0
  35. package/dist/kernel/cap/rule.js +93 -0
  36. package/dist/kernel/cap/run-cap.d.ts +80 -0
  37. package/dist/kernel/cap/run-cap.js +132 -0
  38. package/dist/kernel/cap/steps.d.ts +36 -0
  39. package/dist/kernel/cap/steps.js +64 -0
  40. package/dist/kernel/cap/stopped.d.ts +17 -0
  41. package/dist/kernel/cap/stopped.js +34 -0
  42. package/dist/kernel/cap/types.d.ts +151 -0
  43. package/dist/kernel/cap/types.js +1 -0
  44. package/dist/kernel/cap/words.d.ts +39 -0
  45. package/dist/kernel/cap/words.js +75 -0
  46. package/dist/kernel/cap/wrap-up.d.ts +17 -0
  47. package/dist/kernel/cap/wrap-up.js +37 -0
  48. package/dist/kernel/drive.d.ts +0 -1
  49. package/dist/kernel/drive.js +9 -2
  50. package/dist/kernel/index.d.ts +1 -0
  51. package/dist/kernel/index.js +1 -0
  52. package/dist/kernel/registry/background.d.ts +12 -0
  53. package/dist/kernel/registry/background.js +342 -0
  54. package/dist/kernel/registry/bash.d.ts +3 -0
  55. package/dist/kernel/registry/bash.js +23 -0
  56. package/dist/kernel/registry/browser.d.ts +11 -0
  57. package/dist/kernel/registry/browser.js +14 -0
  58. package/dist/kernel/registry/defs.d.ts +42 -0
  59. package/dist/kernel/registry/defs.js +153 -0
  60. package/dist/kernel/registry/desktop.d.ts +11 -0
  61. package/dist/kernel/registry/desktop.js +90 -0
  62. package/dist/kernel/registry/gate.d.ts +20 -0
  63. package/dist/kernel/registry/gate.js +32 -0
  64. package/dist/kernel/registry/handoff.d.ts +11 -0
  65. package/dist/kernel/registry/handoff.js +51 -0
  66. package/dist/kernel/registry/hands.d.ts +280 -0
  67. package/dist/kernel/registry/hands.js +28 -0
  68. package/dist/kernel/registry/index.d.ts +17 -0
  69. package/dist/kernel/registry/index.js +14 -0
  70. package/dist/kernel/registry/limits.d.ts +27 -0
  71. package/dist/kernel/registry/limits.js +29 -0
  72. package/dist/kernel/registry/phone.d.ts +15 -0
  73. package/dist/kernel/registry/phone.js +135 -0
  74. package/dist/kernel/registry/registry.d.ts +22 -0
  75. package/dist/kernel/registry/registry.js +75 -0
  76. package/dist/kernel/types.d.ts +0 -7
  77. package/dist/process/builtins.js +1 -1
  78. package/dist/process/index.d.ts +1 -0
  79. package/dist/process/index.js +1 -0
  80. package/dist/process/journal.js +1 -1
  81. package/dist/process/recovery.js +1 -1
  82. package/dist/process/resume.d.ts +20 -0
  83. package/dist/process/resume.js +16 -0
  84. package/dist/process/tail.js +1 -1
  85. package/dist/process/tools.d.ts +8 -1
  86. package/dist/process/tools.js +20 -3
  87. package/dist/process/zod.js +1 -1
  88. package/dist/run-booking.d.ts +9 -0
  89. package/dist/run-booking.js +50 -0
  90. package/dist/runner.d.ts +91 -17
  91. package/dist/runner.js +132 -41
  92. package/dist/testing.d.ts +79 -12
  93. package/dist/testing.js +106 -13
  94. package/dist/types.d.ts +235 -10
  95. package/package.json +8 -4
  96. package/vendor/durable-harness/UPSTREAM.json +0 -9
  97. package/dist/host/box-slot.d.ts +0 -26
  98. package/dist/host/box-slot.js +0 -112
  99. package/dist/host/egress-proxy.d.ts +0 -45
  100. package/dist/host/egress-proxy.js +0 -416
  101. package/dist/host/egress-table.d.ts +0 -24
  102. package/dist/host/egress-table.js +0 -165
@@ -14,8 +14,9 @@
14
14
  // response's usage once it completes (`afterRequest`). Every paid request forwarded is booked exactly once: a response
15
15
  // cut short, or one that says no usage, is booked at an unknown cost.
16
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";
17
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
18
18
  import { createServer } from "node:http";
19
+ import { mcpRoute } from "./mcp-route.js";
19
20
  import { CONTENT_FILTERED } from "../types.js";
20
21
  import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
21
22
  /** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
@@ -23,6 +24,314 @@ import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
23
24
  const EVENT_MAX_CHARS = 1 << 22;
24
25
  /** What of a response reached its client, event by event: each whole server-sent event (up to a blank line) read by
25
26
  * each of `readers`, its bytes added to that reader's sum; a reader the policy does not have counts none. */
27
+ /** What a secret this proxy sent reads as in a provider's error the harness gets. */
28
+ export const REDACTED = "[redacted]";
29
+ /** The forms a provider may echo `secrets` in: as sent, JSON-escaped, with "/" escaped as "\/" (some JSON encoders do), and
30
+ * both at once, the longest first, so a form that holds a shorter one is cut whole. */
31
+ export function echoForms(secrets) {
32
+ const slashed = (text) => text.replaceAll("/", "\\/");
33
+ const forms = secrets.filter((secret) => secret.length > 0).flatMap((secret) => {
34
+ const escaped = JSON.stringify(secret).slice(1, -1);
35
+ return [secret, escaped, slashed(secret), slashed(escaped)];
36
+ });
37
+ return [...new Set(forms)].sort((a, b) => b.length - a.length);
38
+ }
39
+ /** The most of an error the cut holds back while the host's redactor may still be reading a value it knows across the
40
+ * pieces: no secret it holds is longer. */
41
+ export const REDACT_WINDOW = 4096;
42
+ /** The most of an event the relay holds while it cannot yet tell whether the event is an error's: past it, the event is
43
+ * told from what came of it, and nothing of it is held whole. */
44
+ export const EVENT_HOLD = 64 * 1024;
45
+ /** The names, and data types, an error event has: Messages' and Responses' `error`, Responses' `response.failed`. */
46
+ const ERROR_TYPES = new Set(["error", "response.failed"]);
47
+ /** A data line's JSON whose type comes first, as most providers write it: its type, readable before the line ends. */
48
+ const TYPE_FIRST = /^\s*\{\s*"type"\s*:\s*"([^"]*)"/;
49
+ /** Whether a UTF-16 code unit is the second half of a character written as two. */
50
+ const isLowSurrogate = (unit) => unit >= 0xdc00 && unit <= 0xdfff;
51
+ /** The shortest form a healthy event is cut of: a shorter one (a test's one-letter credential) matches its text by chance,
52
+ * and cutting it there breaks the answer. An error is cut of every form. */
53
+ const MIN_ECHO = 8;
54
+ /** What may stand beside a short value inside a token of its own: past one of these, it is part of a longer word. */
55
+ const WORD_CHAR = /[A-Za-z0-9_-]/;
56
+ /** A line's end in an event stream: LF, CRLF or a bare CR, as the format has them. */
57
+ const LINE_END = /\r\n|\r|\n/;
58
+ /** The next line end of a piece, searched from `lastIndex`. */
59
+ const LINE_BREAK = /\r\n|\r|\n/g;
60
+ /**
61
+ * What the harness gets of a provider's answer: as it came, but for the provider's own words in an error, where a secret
62
+ * this proxy sent (`forms`, echoForms) is cut out and then the host's `redact` runs.
63
+ * - `error` (an answer with an error status): cut as it comes. What goes out is what can no longer change: the end that
64
+ * could still begin a form is held, and, with a host redactor, the last REDACT_WINDOW characters too, so a value it
65
+ * knows is never split between two of its readings. An error body the provider never finishes still reaches the
66
+ * client as it comes, past what is held. The body's end is cut, and a start of a form it ends on is cut too.
67
+ * - `events` (a successful streamed answer): each event is told from its fields, whatever their order: an `event:` name
68
+ * of an error, or its data's JSON (a type of `error` or `response.failed`, or an `error`), an `id:`, `retry:` or
69
+ * comment line read past; a healthy name exempts nothing, its data is still read. An error event is cut as an error
70
+ * answer is, as it comes; every other event has the credential's forms of MIN_ECHO characters or more cut and passes
71
+ * otherwise byte for byte, only
72
+ * the start of a form held back (never past a line end). An event is held only until it can be told (an error's
73
+ * name, or its data line whole), and at most EVENT_HOLD of it: past that it is told from what came (a data line whose
74
+ * type comes first), and one that still cannot be is cut as an error's. Nothing a healthy event sent is kept.
75
+ * - `as-is`: every piece as it came.
76
+ * `tokens` (the forms of values too short to tell from text by chance) are cut in an error alone, and only as a whole
77
+ * token: in an error body anywhere, in an error event only inside a data line's value, never a field's name.
78
+ * A `redact` that throws leaves the cut, and is said.
79
+ */
80
+ export function errorCut(mode, forms, redact, say, tokens = []) {
81
+ /** `text` with every one of `of` cut out. */
82
+ const cutOf = (of, text) => of.reduce((out, form) => out.split(form).join(REDACTED), text);
83
+ /** `text` with each of `tokens` (short values' forms, longest first) cut where it stands as a whole token: no letter,
84
+ * digit, "_" or "-" beside it, and, in an event stream, inside a data line's value, never a field's name or another
85
+ * line. `before` is the character just before `text`, `lineHead` the start of its line that came before it; a token
86
+ * the text ends on is cut only when `final` (more may follow it), and is otherwise left for the caller to hold. */
87
+ const cutTokens = (text, before, lineHead, final) => {
88
+ if (!tokens.some((token) => text.includes(token)))
89
+ return text;
90
+ let out = "";
91
+ for (let i = 0; i < text.length;) {
92
+ const hit = tokens.find((token) => {
93
+ if (!text.startsWith(token, i))
94
+ return false;
95
+ const end = i + token.length;
96
+ if (end === text.length && !final)
97
+ return false;
98
+ if (WORD_CHAR.test(i > 0 ? text[i - 1] : before) || WORD_CHAR.test(text[end] ?? ""))
99
+ return false;
100
+ if (mode !== "events")
101
+ return true;
102
+ const lineAt = Math.max(text.lastIndexOf("\n", i - 1), text.lastIndexOf("\r", i - 1));
103
+ return (i > 0 && lineAt >= 0 ? text.slice(lineAt + 1, i) : lineHead + text.slice(0, i)).startsWith("data:");
104
+ });
105
+ if (hit) {
106
+ out += REDACTED;
107
+ i += hit.length;
108
+ }
109
+ else {
110
+ out += text[i];
111
+ i += 1;
112
+ }
113
+ }
114
+ return out;
115
+ };
116
+ const cut = (text) => cutOf(forms, text);
117
+ /** The forms a healthy event is cut of: those long enough not to match its text by chance. */
118
+ const healthyForms = forms.filter((form) => form.length >= MIN_ECHO);
119
+ const redacted = (text) => {
120
+ if (!text || !redact)
121
+ return text;
122
+ try {
123
+ return redact(text);
124
+ }
125
+ catch (error) {
126
+ say(`the host's redactor threw (${String(error?.message ?? error).slice(0, 200)}): the error is sent with the proxy's own cut only`);
127
+ return text;
128
+ }
129
+ };
130
+ if (mode === "as-is" || !forms.length && !tokens.length && !redact)
131
+ return { push: (text) => text, end: () => "" };
132
+ /** The length of the longest end of `text` that is a proper start of one of `of` (default every form). */
133
+ const startOfForm = (text, of = forms) => {
134
+ let longest = 0;
135
+ for (const form of of)
136
+ for (let n = Math.min(form.length - 1, text.length); n > longest; n--)
137
+ if (text.endsWith(form.slice(0, n)))
138
+ longest = n;
139
+ return longest;
140
+ };
141
+ /** An error's text cut as it comes: all that came, cut and redacted again each time (both leave cut text as it is), less
142
+ * the end that could still change: the start of a form, and with a host redactor the last REDACT_WINDOW characters.
143
+ * `host` false: a healthy event's, cut of healthyForms alone, holding back only the start of one. */
144
+ const cutter = (host = true) => {
145
+ const of = host ? forms : healthyForms;
146
+ const startOf = (text) => startOfForm(text, of);
147
+ /** The longest end of `text` that is a short value's token, or the start of one, not yet told whole (host only). */
148
+ const tokenEnd = (text) => {
149
+ if (!host)
150
+ return 0;
151
+ let longest = 0;
152
+ for (const token of tokens)
153
+ for (let n = Math.min(token.length, text.length); n > longest; n--)
154
+ if (text.endsWith(token.slice(0, n)))
155
+ longest = n;
156
+ return longest;
157
+ };
158
+ let held = "";
159
+ // What came out before `held`: its last character, and the start of the line it ends on (a data line's "data:").
160
+ let before = "";
161
+ let lineHead = "";
162
+ const sent = (out) => {
163
+ if (!out)
164
+ return out;
165
+ before = out.at(-1);
166
+ const lineAt = Math.max(out.lastIndexOf("\n"), out.lastIndexOf("\r"));
167
+ lineHead = (lineAt >= 0 ? out.slice(lineAt + 1) : lineHead + out).slice(0, 8);
168
+ return out;
169
+ };
170
+ return {
171
+ push(text) {
172
+ const all = host ? redacted(cutTokens(cut(held + text), before, lineHead, false)) : cutOf(of, held + text);
173
+ let at = all.length - Math.min(all.length, Math.max(startOf(all), tokenEnd(all), host && redact ? REDACT_WINDOW : 0));
174
+ // Never between the two UTF-16 halves of a character: each half written alone is two U+FFFD to the client.
175
+ if (at > 0 && at < all.length && isLowSurrogate(all.charCodeAt(at)))
176
+ at -= 1;
177
+ held = all.slice(at);
178
+ return sent(all.slice(0, at));
179
+ },
180
+ end() {
181
+ const rest = host ? cutTokens(held, before, lineHead, true) : held;
182
+ held = "";
183
+ // Text that ends on the start of a form ends on part of a secret: cut too.
184
+ const part = startOf(rest);
185
+ return part ? `${rest.slice(0, rest.length - part)}${REDACTED}` : rest;
186
+ },
187
+ };
188
+ };
189
+ if (mode === "error")
190
+ return cutter();
191
+ /** An event's field lines, `id:`, `retry:`, comments and unknown fields read past: its name, and its data's lines. */
192
+ const fieldsOf = (lines) => {
193
+ const out = { data: [] };
194
+ for (const line of lines) {
195
+ if (!line || line.startsWith(":"))
196
+ continue;
197
+ const at = line.indexOf(":");
198
+ const field = at === -1 ? line : line.slice(0, at);
199
+ const value = at === -1 ? "" : line.slice(at + 1).replace(/^ /, "");
200
+ if (field === "event")
201
+ out.name = value.trim();
202
+ else if (field === "data")
203
+ out.data.push(value);
204
+ }
205
+ return out;
206
+ };
207
+ /** Whether a data payload is an error's: its JSON's type is one, or it carries an `error`. Undefined when it does not
208
+ * read as JSON (yet). */
209
+ const dataSays = (data) => {
210
+ let value;
211
+ try {
212
+ value = JSON.parse(data);
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
217
+ if (typeof value !== "object" || value === null || Array.isArray(value))
218
+ return "raw";
219
+ const json = value;
220
+ return (typeof json.type === "string" && ERROR_TYPES.has(json.type)) || (json.error !== undefined && json.error !== null) ? "error" : "raw";
221
+ };
222
+ /** What an event not yet whole is, from its whole lines (`whole`) and the line still coming (`part`), if it can be told:
223
+ * an error's name, else its first data line once that reads (a healthy name exempts nothing: its data may still be an
224
+ * error's); past EVENT_HOLD, from a data line whose type comes first, else an error's (a data line that cannot be told
225
+ * is cut) or a healthy event's (no data yet). */
226
+ const verdict = (whole, part, held) => {
227
+ const fields = fieldsOf(whole);
228
+ if (fields.name !== undefined && ERROR_TYPES.has(fields.name))
229
+ return "error";
230
+ for (const data of fields.data) {
231
+ const said = dataSays(data);
232
+ if (said)
233
+ return said;
234
+ }
235
+ if (held <= EVENT_HOLD)
236
+ return undefined;
237
+ const coming = part;
238
+ if (coming.startsWith("data:")) {
239
+ const type = TYPE_FIRST.exec(coming.slice(5))?.[1];
240
+ return type === undefined ? "error" : ERROR_TYPES.has(type) ? "error" : "raw";
241
+ }
242
+ return fields.data.length ? "error" : "raw";
243
+ };
244
+ /** A whole event that was never told: an error's when its name or its data says so, or it holds a form long enough to
245
+ * be told from its text. */
246
+ const wholeIsError = (event) => {
247
+ const fields = fieldsOf(event.split(LINE_END));
248
+ if (fields.name !== undefined && ERROR_TYPES.has(fields.name))
249
+ return true;
250
+ if (fields.data.length && dataSays(fields.data.join("\n")) === "error")
251
+ return true;
252
+ return healthyForms.some((form) => event.includes(form));
253
+ };
254
+ /** The event's state: `hold` until it can be told (its text so far in `held`, at most EVENT_HOLD and a piece), then
255
+ * `raw` (passed as it comes with the credential's forms cut, only the start of a form held back) or `error` (cut as it
256
+ * comes, the host's redactor too). `lineChars`: the characters of the line coming, for telling a blank line, which ends
257
+ * the event; nothing a raw event sent is kept. */
258
+ let state = "hold";
259
+ let held = "";
260
+ let lineChars = 0;
261
+ let eventCutter;
262
+ const decide = (to) => {
263
+ const text = held;
264
+ held = "";
265
+ state = to;
266
+ eventCutter = cutter(to === "error");
267
+ return eventCutter.push(text);
268
+ };
269
+ const eventEnds = () => {
270
+ const out = state === "hold" ? (wholeIsError(held) ? redacted(cutTokens(cut(held), "", "", true)) : cutOf(healthyForms, held)) : eventCutter.end();
271
+ state = "hold";
272
+ held = "";
273
+ eventCutter = undefined;
274
+ return out;
275
+ };
276
+ /** Whether the last piece ended on a CR: its line ended there, and a LF that begins the next piece is that CR's (a CRLF
277
+ * split between pieces), not a line of its own. */
278
+ let afterCr = false;
279
+ const feed = (piece) => {
280
+ if (state !== "hold")
281
+ return eventCutter.push(piece);
282
+ held += piece;
283
+ return "";
284
+ };
285
+ return {
286
+ push(text) {
287
+ let out = "";
288
+ let at = 0;
289
+ if (afterCr && text.startsWith("\n")) {
290
+ // The rest of a line end that came already: a blank line's goes out with the event it ended; any other's is the
291
+ // event's, as it is now.
292
+ out += state === "hold" && !held ? "\n" : feed("\n");
293
+ at = 1;
294
+ }
295
+ afterCr = false;
296
+ while (at < text.length) {
297
+ // A line ends at LF, CRLF or a bare CR, as the format has them; a CR that ends the piece ends its line now.
298
+ LINE_BREAK.lastIndex = at;
299
+ const found = LINE_BREAK.exec(text);
300
+ let end = -1;
301
+ let content = text.length - at;
302
+ if (found) {
303
+ content = found.index - at;
304
+ end = found.index + found[0].length;
305
+ if (found[0] === "\r" && end === text.length)
306
+ afterCr = true;
307
+ }
308
+ const piece = end === -1 ? text.slice(at) : text.slice(at, end);
309
+ at += piece.length;
310
+ lineChars += content;
311
+ out += feed(piece);
312
+ if (end !== -1) {
313
+ const blank = lineChars === 0;
314
+ lineChars = 0;
315
+ if (blank) {
316
+ out += eventEnds();
317
+ continue;
318
+ }
319
+ }
320
+ if (state === "hold" && (end !== -1 || held.length > EVENT_HOLD)) {
321
+ const lines = held.split(LINE_END);
322
+ const part = lines.pop() ?? "";
323
+ const told = verdict(lines, part, held.length);
324
+ if (told)
325
+ out += decide(told);
326
+ }
327
+ }
328
+ return out;
329
+ },
330
+ end() {
331
+ return eventEnds();
332
+ },
333
+ };
334
+ }
26
335
  function eventCounter(readers) {
27
336
  const keys = Object.keys(readers).filter((key) => readers[key] !== undefined);
28
337
  const sums = Object.fromEntries(keys.map((key) => [key, 0]));
@@ -78,6 +387,10 @@ export function hostHeaderProblems(headers) {
78
387
  }
79
388
  return problems;
80
389
  }
390
+ /** A server's endpoint, `/mcp/<server>`, with no query. */
391
+ const MCP_PATH = /^\/mcp\/([a-z][a-z0-9-]{0,31})$/;
392
+ /** Where an MCP client looks for OAuth after a 401: never served here, so it never starts a sign-in against the proxy. */
393
+ const OAUTH_PATH = /^\/(?:\.well-known\/|register(?:$|[/?]))/;
81
394
  const UNSAFE_PATH = /[^A-Za-z0-9/_.\-?=&]|\.\.|\/\/|^[^/]|\?.*\?/;
82
395
  const MAX_BODY = 32 * 1024 * 1024;
83
396
  /** How much of a response's start and end the proxy keeps to read its usage from. */
@@ -297,11 +610,25 @@ export async function startModelProxy(options, key) {
297
610
  const forward = options.fetch ?? fetch;
298
611
  const origin = baseOf(options.origin);
299
612
  const refusedStatus = policy.refusedStatus ?? 400;
613
+ /** Why the turn's answer stopped, once the harness was told (onCut, onFiltered): the session's answer requests are
614
+ * refused, unsent and unbooked, until it opens its next turn (openTurn). A client that asks again (Codex retries an
615
+ * incomplete stream) is never paid for, whether or not the harness's own stop beat it. */
616
+ let stopTold;
300
617
  const inflight = new Set();
301
618
  /** The requests whose answer the provider stopped on its content filter, read on for their usage, each until booked. */
302
619
  const draining = new Map();
303
620
  /** Set by close(): nothing is admitted or sent after it. */
304
621
  let closing = false;
622
+ /** The side keys minted (sideKey), each with its label. */
623
+ const sideKeys = new Map();
624
+ /** The label of the side key `sent`, compared in constant time against each minted one; undefined for any other. */
625
+ const sideOf = (sent) => {
626
+ let found;
627
+ for (const [label, minted] of sideKeys)
628
+ if (sameKey(sent, minted))
629
+ found = label;
630
+ return found;
631
+ };
305
632
  /** The host's log, which must never break a request (a throw from it is dropped). */
306
633
  const say = (message, detail) => {
307
634
  try {
@@ -320,10 +647,25 @@ export async function startModelProxy(options, key) {
320
647
  res.writeHead(status, { "content-type": "application/json", connection: "close" });
321
648
  res.end(JSON.stringify({ error: { message, type: "agentrun_proxy" } }));
322
649
  };
650
+ // The session's MCP door, mounted once here for whichever harness's client calls it (the call id from its fact).
651
+ const mcpDoor = options.mcp && mcpRoute(options.mcp.session, { callIdMeta: options.mcp.client.callIdMeta, ...(options.mcp.keepaliveMs !== undefined ? { keepaliveMs: options.mcp.keepaliveMs } : {}) });
323
652
  const serve = async (req, res) => {
324
653
  // A request refused before its body is read is drained, so its client gets the answer instead of a reset.
325
654
  res.once("finish", () => { if (!req.complete)
326
655
  req.resume(); });
656
+ const path = req.url ?? "";
657
+ if (options.mcp && OAUTH_PATH.test(path)) {
658
+ res.writeHead(404, { "content-length": "0" });
659
+ return res.end();
660
+ }
661
+ const mcp = mcpDoor ? MCP_PATH.exec(path) : null;
662
+ if (mcp) {
663
+ if (!sameKey(policy.keyOf(req.headers), key))
664
+ return refuse(res, 401, "this session's key is required", req);
665
+ if (closing)
666
+ return refuse(res, 503, "the model proxy is closing", req);
667
+ return mcpDoor(mcp[1], req, res);
668
+ }
327
669
  let route;
328
670
  let query;
329
671
  try {
@@ -342,7 +684,10 @@ export async function startModelProxy(options, key) {
342
684
  res.writeHead(route.local, { "content-length": "0" });
343
685
  return res.end();
344
686
  }
345
- if (!sameKey(policy.keyOf(req.headers), key))
687
+ // The session's key (the harness's requests), or a side key the host holds (its own, labelled).
688
+ const sentKey = policy.keyOf(req.headers);
689
+ const host = sameKey(sentKey, key) ? undefined : sideOf(sentKey);
690
+ if (host === undefined && !sameKey(sentKey, key))
346
691
  return refuse(res, 401, "this session's key is required", req);
347
692
  const chunks = [];
348
693
  let size = 0;
@@ -355,7 +700,7 @@ export async function startModelProxy(options, key) {
355
700
  let body;
356
701
  const headers = { "content-type": "application/json" };
357
702
  try {
358
- body = policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route);
703
+ body = policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route, host === undefined ? {} : { host });
359
704
  // The listed headers, as the policy keeps them (or refuses them), before the runner is asked.
360
705
  for (const name of route.headers ?? []) {
361
706
  const value = req.headers[name.toLowerCase()];
@@ -379,6 +724,42 @@ export async function startModelProxy(options, key) {
379
724
  catch (error) {
380
725
  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
726
  }
727
+ // A note the host has for the session's next main-model request (the spend cap's wrap-up): a paid request on the
728
+ // session's model whose policy can place it takes it, once, before the body is measured, so the cap admits its bytes.
729
+ // Only the turn's own request (ProviderPolicy.answers): a side call on the session's model (a title, a summary, when
730
+ // the client has no small model) takes none. One the policy fails to place is dropped, said once; the request goes as
731
+ // the client sent it. The body as the client sent it is kept (`plain`): a request the cap admits only without the
732
+ // note's bytes goes as that (ModelTicket.noteDropped).
733
+ let noted = false;
734
+ let plain;
735
+ // Never on the host's own request (`host`): the note is for the harness's model, in its own conversation, so a host
736
+ // request is neither measured for it nor noted.
737
+ if (!route.free && asked === model && host === undefined && (policy.answers ? policy.answers(body) : true) && policy.addNote && hooks.note) {
738
+ // The request as its client sent it, measured first, so the host prices it as its admission will (the wrap-up's least).
739
+ let request = {};
740
+ try {
741
+ const measured = inputTokensMaxOf(policy, body, JSON.stringify(body), say);
742
+ const askedOut = policy.outputAsked?.(body);
743
+ const leastOut = policy.outputLeast?.(body);
744
+ const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
745
+ request = { ...(count(measured) === undefined ? {} : { inputTokensMax: measured }), ...(count(askedOut) === undefined ? {} : { outputTokensAsked: askedOut }), ...(count(leastOut) === undefined ? {} : { outputTokensLeast: leastOut }) };
746
+ }
747
+ catch {
748
+ request = {};
749
+ }
750
+ const note = hooks.note(asked, request);
751
+ if (note) {
752
+ try {
753
+ const without = body;
754
+ body = policy.addNote(body, note);
755
+ plain = without;
756
+ noted = true;
757
+ }
758
+ catch (error) {
759
+ say(`model proxy (${policy.id}): the host's note could not be placed; the request goes without it`, { error: String(error?.message ?? error).slice(0, 200) });
760
+ }
761
+ }
762
+ }
382
763
  // The body as it is sent, and the most input tokens it can be billed for, measured before the runner is asked.
383
764
  let sent;
384
765
  try {
@@ -389,6 +770,18 @@ export async function startModelProxy(options, key) {
389
770
  return refuse(res, 500, "the body could not be serialized", req);
390
771
  }
391
772
  let inputTokensMax = inputTokensMaxOf(policy, body, sent, say);
773
+ // The same, of the body as the client sent it, when a note was placed: the cap checks the request without the note.
774
+ let plainSent;
775
+ let inputTokensMaxWithoutNote;
776
+ if (plain) {
777
+ try {
778
+ plainSent = JSON.stringify(plain);
779
+ inputTokensMaxWithoutNote = inputTokensMaxOf(policy, plain, plainSent, say);
780
+ }
781
+ catch {
782
+ plainSent = undefined;
783
+ }
784
+ }
392
785
  // 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
786
  // read leaves the request's worst case unknown: its input is unmeasured.
394
787
  const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
@@ -439,14 +832,31 @@ export async function startModelProxy(options, key) {
439
832
  }
440
833
  if (closing)
441
834
  return refuse(res, 503, "the model proxy is closing", req);
835
+ /** Whether this request is the turn's answer request (`ProviderPolicy.answers`): a side call's stop ends nothing, and
836
+ * a side call is never refused for the turn's. */
837
+ let answering = host === undefined;
838
+ try {
839
+ if (host === undefined)
840
+ answering = policy.answers ? policy.answers(body) : true;
841
+ }
842
+ catch (error) {
843
+ 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) });
844
+ }
845
+ // The turn's answer stopped and the harness was told: its client asking again is refused (no retry), never sent, never
846
+ // admitted or booked, until the harness opens its next turn.
847
+ if (answering && !route.free && stopTold !== undefined)
848
+ return refuse(res, refusedStatus, `refused: the turn's answer was ${stopTold}, and the turn ends there`, req);
442
849
  // This request's own admission, handed back to its booking (requests may be in flight together).
443
850
  let ticket;
444
851
  try {
445
852
  if (!route.free)
446
853
  ticket = await hooks.beforeRequest({
447
- model: asked, inputTokensMax,
854
+ // A side call: on another model than the session's, or the host's own (it counts toward no typical request).
855
+ model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}),
856
+ ...(noted ? { noted: true, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}),
448
857
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
449
858
  ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
859
+ ...(host === undefined ? {} : { host }),
450
860
  });
451
861
  }
452
862
  catch (error) {
@@ -459,7 +869,7 @@ export async function startModelProxy(options, key) {
459
869
  refuse(res, status, message, req);
460
870
  if (!route.free) {
461
871
  try {
462
- await hooks.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket);
872
+ await hooks.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket, { end: "nothing", label: "never_left" });
463
873
  }
464
874
  catch (error) {
465
875
  say(`model proxy (${policy.id}): afterRequest threw; the request was not sent and not booked`, { error: String(error?.message ?? error).slice(0, 200) });
@@ -469,6 +879,13 @@ export async function startModelProxy(options, key) {
469
879
  // Admitted while the proxy was closing, and never sent.
470
880
  if (closing)
471
881
  return release(503, "the model proxy is closing");
882
+ // Admitted only without the note (its bytes did not fit what is left of the cap): the body as the client sent it.
883
+ if (typeof ticket === "object" && ticket !== null && ticket.noteDropped === true) {
884
+ if (!plain || plainSent === undefined)
885
+ return release(500, "the request was admitted without its note, which this proxy cannot take back out");
886
+ body = plain;
887
+ sent = plainSent;
888
+ }
472
889
  // Admitted with an output limit (what is left of a spend cap can buy): written into the body, which is never sent
473
890
  // unlimited, nor longer than the body its input bound was measured on.
474
891
  const limit = typeof ticket === "object" && ticket !== null ? ticket.outputTokensMax : undefined;
@@ -506,7 +923,10 @@ export async function startModelProxy(options, key) {
506
923
  controller.abort();
507
924
  });
508
925
  let head = "";
926
+ /** At least the answer's last USAGE_WINDOW characters, at most twice that: cut back only once it doubles, so keeping
927
+ * it costs each piece its own length, never a copy of the window (`lastOf` reads the window from it). */
509
928
  let tail = "";
929
+ const lastOf = (text) => (text.length > USAGE_WINDOW ? text.slice(-USAGE_WINDOW) : text);
510
930
  let length = 0;
511
931
  /** The provider's answer, once it reached the client whole. */
512
932
  let answered;
@@ -520,14 +940,6 @@ export async function startModelProxy(options, key) {
520
940
  let reported;
521
941
  /** Whether the provider's content-filter stop was read (once an answer). */
522
942
  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
943
  /** Called once the request is booked, when its answer was read on after its stop (the proxy's close waits for it). */
532
944
  let drained;
533
945
  const settled = () => {
@@ -539,6 +951,10 @@ export async function startModelProxy(options, key) {
539
951
  /** The start of the line being read (LINE_START) and of the last whole lines (LINE_STARTS). */
540
952
  let lineStart = "";
541
953
  let lineLength = 0;
954
+ /** The line being read, whole while it is no longer than the window (a longer one is read from the window as it ends). */
955
+ let line = "";
956
+ /** Whether the answer is a whole JSON body rather than an event stream, once its first character says so. */
957
+ let wholeBody;
542
958
  const starts = [];
543
959
  /** Tells the harness the provider stopped this answer on its content filter, when `text` (the answer so far, or the
544
960
  * kept window of it) says so: once, and never failing the answer. */
@@ -560,6 +976,9 @@ export async function startModelProxy(options, key) {
560
976
  return;
561
977
  }
562
978
  say(`model proxy (${policy.id}): the provider stopped the answer on its content filter`);
979
+ // The harness ends the turn: until it opens its next, the session's answer requests are refused.
980
+ if (options.onFiltered)
981
+ stopTold = "stopped on the provider's content filter";
563
982
  // Read on to the answer's end for its usage, though the client goes; the proxy's close waits for it, bounded.
564
983
  keepReading = true;
565
984
  draining.set(controller, new Promise((resolve) => (drained = resolve)));
@@ -570,6 +989,38 @@ export async function startModelProxy(options, key) {
570
989
  say(`model proxy (${policy.id}): onFiltered threw`, { error: String(error?.message ?? error).slice(0, 200) });
571
990
  }
572
991
  };
992
+ /** Whether the provider's cut at its output limit was read (once an answer). */
993
+ let cutTold = false;
994
+ /** Tells the harness the provider cut this answer at its output limit, when `text` says so: once, an answer request's
995
+ * only, and never failing the answer (it is passed and booked as any answer). */
996
+ const tellCut = (text) => {
997
+ if (cutTold || !answering || !policy.cut || !options.onCut)
998
+ return;
999
+ let stop;
1000
+ try {
1001
+ stop = policy.cut(text, starts);
1002
+ }
1003
+ catch (error) {
1004
+ say(`model proxy (${policy.id}): whether the provider cut the answer at its output limit could not be read`, { error: String(error?.message ?? error).slice(0, 200) });
1005
+ }
1006
+ if (!stop)
1007
+ return;
1008
+ cutTold = true;
1009
+ say(`model proxy (${policy.id}): the provider cut the answer at its output limit`);
1010
+ // The harness ends the turn: until it opens its next, the session's answer requests are refused.
1011
+ stopTold = "cut at the model's output limit";
1012
+ try {
1013
+ options.onCut(stop);
1014
+ }
1015
+ catch (error) {
1016
+ say(`model proxy (${policy.id}): onCut threw`, { error: String(error?.message ?? error).slice(0, 200) });
1017
+ }
1018
+ };
1019
+ /** The answer's stops, read from what has come of it so far: its content-filter stop, and its cut. */
1020
+ const tellStops = (text) => {
1021
+ tellFiltered(text);
1022
+ tellCut(text);
1023
+ };
573
1024
  try {
574
1025
  // From here a paid request may be paid, so every way out below books it exactly once.
575
1026
  const upstream = await forward(`${origin}${route.path}${query ? `?${query}` : ""}`, { method: route.method, headers, body: sent, signal: controller.signal });
@@ -593,11 +1044,34 @@ export async function startModelProxy(options, key) {
593
1044
  }
594
1045
  }
595
1046
  began = { ok: upstream.ok, status: upstream.status };
596
- res.writeHead(upstream.status, { "content-type": upstream.headers.get("content-type") ?? "application/json" });
1047
+ const contentType = upstream.headers.get("content-type") ?? "application/json";
1048
+ res.writeHead(upstream.status, { "content-type": contentType });
597
1049
  const decoder = new TextDecoder();
1050
+ // The provider's own words in an error reach the harness with the credential this proxy sent, and the values of the
1051
+ // headers it added, cut out, then the host's redactor (errorCut): an error answer, or an error event in a stream. The
1052
+ // credential and a header value of MIN_ECHO or more are cut wherever they stand; a shorter header value only in an
1053
+ // error's payload, and only as a whole token, so "1" never cuts "401" and "data" never cuts a data: field.
1054
+ const hostValues = Object.values(hostHeaders);
1055
+ const relay = errorCut(!upstream.ok ? "error" : /^text\/event-stream\b/i.test(contentType) ? "events" : "as-is", echoForms([credential, ...hostValues.filter((value) => value.length >= MIN_ECHO)]), options.redact, (message) => say(`model proxy (${policy.id}): ${message}`), echoForms(hostValues.filter((value) => value.length < MIN_ECHO)));
1056
+ const write = async (out) => {
1057
+ if (!out || res.destroyed)
1058
+ return;
1059
+ const bytes = Buffer.from(out, "utf8");
1060
+ sentBytes += bytes.byteLength;
1061
+ // A client that reads slowly holds the provider back: nothing more is read until what was written drains.
1062
+ if (!res.write(bytes)) {
1063
+ // One wait, and nothing left behind: whichever comes first takes both listeners off.
1064
+ await new Promise((resolve) => {
1065
+ const done = () => { res.off("drain", done); res.off("close", done); resolve(); };
1066
+ res.on("drain", done);
1067
+ res.on("close", done);
1068
+ });
1069
+ }
1070
+ };
598
1071
  let watcher;
599
1072
  try {
600
- watcher = policy.watch?.();
1073
+ // The host's own side requests are never the harness's to watch.
1074
+ watcher = host === undefined ? policy.watch?.() : undefined;
601
1075
  watchEnd = watcher?.end?.bind(watcher);
602
1076
  }
603
1077
  catch (error) {
@@ -624,46 +1098,53 @@ export async function startModelProxy(options, key) {
624
1098
  watcher = undefined;
625
1099
  }
626
1100
  }
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);
1101
+ // The provider's content-filter stop, and its cut at the output limit, read before the client has the piece that
1102
+ // carries it: the harness ends the turn before its client acts on the stop (asks for the answer again, or ends
1103
+ // the turn its own way).
1104
+ // Each line is read once, as it ends, never the window again for every piece: a long answer comes in tens of
1105
+ // thousands of pieces, and reading the window for each held the runner's one thread for most of a minute.
1106
+ // A line longer than the window is read as it ends, from the window, its start among the last starts kept
1107
+ // while the lines just before it (an event's name) still are: a piece may carry the lines after it too.
632
1108
  const lines = text.split("\n");
633
1109
  for (let at = 0; at < lines.length; at++) {
1110
+ const part = lines[at];
634
1111
  if (lineStart.length < LINE_START)
635
- lineStart += lines[at].slice(0, LINE_START - lineStart.length);
636
- lineLength += lines[at].length;
1112
+ lineStart += part.slice(0, LINE_START - lineStart.length);
1113
+ lineLength += part.length;
1114
+ line = lineLength <= USAGE_WINDOW ? line + part : "";
637
1115
  if (at < lines.length - 1) {
638
1116
  starts.push(lineStart);
639
1117
  if (starts.length > LINE_STARTS)
640
1118
  starts.shift();
641
- if (upstream.ok && lineLength > USAGE_WINDOW)
642
- tellFiltered(window);
1119
+ if (upstream.ok && lineLength > 0)
1120
+ tellStops(lineLength > USAGE_WINDOW ? lastOf(tail + text) : line);
643
1121
  lineStart = "";
644
1122
  lineLength = 0;
1123
+ line = "";
645
1124
  }
646
1125
  }
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
- }
1126
+ // A whole JSON body (no event stream) may be printed across lines, so no one line holds its stop: while it fits the
1127
+ // window, it is read whole at each piece that may close it (ends in "}"), which is a few pieces, never one each.
1128
+ if (wholeBody === undefined && text.trimStart() !== "")
1129
+ wholeBody = (tail + text).trimStart().startsWith("{");
1130
+ if (upstream.ok && wholeBody && length + text.length <= USAGE_WINDOW && text.trimEnd().endsWith("}"))
1131
+ tellStops(tail + text);
1132
+ // A client gone after the stop was told is written nothing more: the answer is read on for its usage alone.
1133
+ const out = relay.push(text);
1134
+ await write(out);
659
1135
  // The usage is at the start, the end, or both: keep those, not the whole answer.
660
1136
  length += text.length;
661
- sentBytes += chunk.byteLength;
662
- sentOf.push(text);
1137
+ sentOf.push(out);
663
1138
  if (head.length < USAGE_WINDOW)
664
1139
  head += text.slice(0, USAGE_WINDOW - head.length);
665
- tail = (tail + text).slice(-USAGE_WINDOW);
1140
+ tail += text;
1141
+ if (tail.length > 2 * USAGE_WINDOW)
1142
+ tail = tail.slice(-USAGE_WINDOW);
666
1143
  }
1144
+ // What the relay held at the answer's end: an error event's or an error body's rest, cut.
1145
+ const rest = relay.end();
1146
+ await write(rest);
1147
+ sentOf.push(rest);
667
1148
  }
668
1149
  res.end();
669
1150
  answered = { ok: upstream.ok };
@@ -726,7 +1207,7 @@ export async function startModelProxy(options, key) {
726
1207
  else {
727
1208
  let unread = false;
728
1209
  try {
729
- usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${tail}`);
1210
+ usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`);
730
1211
  }
731
1212
  catch (error) {
732
1213
  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) });
@@ -771,7 +1252,7 @@ export async function startModelProxy(options, key) {
771
1252
  }
772
1253
  // An answer whose stop no piece showed before it ended (a whole JSON body): read whole once it is booked.
773
1254
  if (seen?.ok)
774
- tellFiltered(length <= USAGE_WINDOW ? tail : `${head}\n${tail}`);
1255
+ tellStops(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`);
775
1256
  settled();
776
1257
  };
777
1258
  const server = createServer((req, res) => { void serve(req, res).catch(() => { if (!res.headersSent)
@@ -788,6 +1269,17 @@ export async function startModelProxy(options, key) {
788
1269
  return {
789
1270
  url: `http://127.0.0.1:${address.port}`,
790
1271
  key,
1272
+ sideKey: (label) => {
1273
+ if (!label)
1274
+ throw new Error("agentrun-kernel: a side key needs a label");
1275
+ let minted = sideKeys.get(label);
1276
+ if (!minted)
1277
+ sideKeys.set(label, (minted = randomBytes(32).toString("base64url")));
1278
+ return minted;
1279
+ },
1280
+ openTurn: () => {
1281
+ stopTold = undefined;
1282
+ },
791
1283
  close: async () => {
792
1284
  closing = true;
793
1285
  for (const c of inflight)