@mnaimfaizy/agent-kit 1.0.0-beta.12 → 1.0.0-beta.14

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.
@@ -0,0 +1,549 @@
1
+ // The model proxy's core (ADR 0023): a key-injecting reverse proxy that runs
2
+ // in the launcher, on the host, outside the sandbox. It knows no model API:
3
+ // everything about one comes from its provider profile (profiles/). The
4
+ // sandboxed agent holds only a placeholder key and reaches the model API
5
+ // through this proxy, which forwards only to the profile's upstream, drops
6
+ // every header that could carry the placeholder and inserts the real
7
+ // credential in the one header the profile writes. The credential lives only
8
+ // in this process's memory: it is never an argument, an environment variable
9
+ // or a file of any command the launcher runs. Node core only (ADR 0001).
10
+ //
11
+ // It also holds the run's token cap: it counts what each answer reports as
12
+ // used, and once the count reaches the cap it refuses every further request
13
+ // and tells the launcher, which stops the agent step. From the same answers it
14
+ // reads the model each one names, so the launcher can say which model the API
15
+ // answered with, not only which was asked for.
16
+ //
17
+ // What it forwards is judged on every request, since anything in the sandbox
18
+ // can reach the proxy:
19
+ // - only a method and path the profile lists, on a path that decodes plainly;
20
+ // - with `callerKey`, only a request that carries the run's caller key, the
21
+ // value the launcher gave the sandboxed agent in place of a real
22
+ // credential, so another process in the sandbox that never read it cannot
23
+ // spend the real one;
24
+ // - only a JSON object the profile's filter passes, within its size bound;
25
+ // - at most MAX_IN_FLIGHT requests at once, each holding a reservation of
26
+ // the tokens it may spend, so the cap holds against requests sent together.
27
+
28
+ import { timingSafeEqual } from "node:crypto";
29
+ import { createServer, request as httpRequest } from "node:http";
30
+ import { request as httpsRequest } from "node:https";
31
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
32
+
33
+ /** How many requests may be in flight to the model API at once. */
34
+ export const MAX_IN_FLIGHT = 4;
35
+
36
+ /** How much of an answer the meter reads: a line of a stream, or a whole JSON body. */
37
+ const MAX_LINE = 1024 * 1024;
38
+ const MAX_BODY = 16 * 1024 * 1024;
39
+
40
+ /**
41
+ * A plain model id: no space, quote or leading dash. It is the launcher's
42
+ * check of a requested model, which goes into the agent step's command line
43
+ * (the same pattern as the static workflow's model input), and the only form
44
+ * of an answer's model the summary names, so an answer cannot write a line of
45
+ * its own.
46
+ */
47
+ export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@/[\]-]*$/;
48
+
49
+ /** How many distinct refused hosts, paths or answered models the summary keeps, and how long each. */
50
+ const MAX_KEPT = 5;
51
+ const MAX_ENTRY = 80;
52
+
53
+ // Hop-by-hop headers (RFC 9110 7.6.1), the client's standard credential
54
+ // headers, and the Host, which is the model API's own. A profile's key headers
55
+ // join them, and its `forwardsHeader` may hold back more of a request's.
56
+ const DROPPED = [
57
+ "authorization",
58
+ "proxy-authorization",
59
+ "proxy-authenticate",
60
+ "proxy-connection",
61
+ "connection",
62
+ "keep-alive",
63
+ "te",
64
+ "trailer",
65
+ "transfer-encoding",
66
+ "upgrade",
67
+ "host",
68
+ "cookie",
69
+ ];
70
+
71
+ /**
72
+ * Everything the core needs to know about one model API.
73
+ * @typedef {object} ProviderProfile
74
+ * @property {string} upstream the model API's origin, which every forwarded request goes to
75
+ * @property {Readonly<Record<string, (credential: string) => string[]>>} credentialKinds
76
+ * for each kind of credential, the one header it is written in, as [name, value]
77
+ * @property {readonly string[]} keyHeaders lower-case headers the sandbox may carry its
78
+ * caller key in, besides a bearer `Authorization`; never forwarded, either way
79
+ * @property {(header: string) => boolean} forwardsHeader whether a request header, by
80
+ * lower-case name, passes to the model API, among those the core has not already dropped
81
+ * @property {(path: string, decoded: string) => boolean} inScope whether the path, as sent
82
+ * and as percent-decoded, is one of the API's own that the cap could count
83
+ * @property {ReadonlyArray<{ method: string, path: string, spends: boolean }>} routes the
84
+ * only requests forwarded, by decoded path; one that `spends` holds a reservation
85
+ * @property {{ scope: string, route: string }} refusals what a caller refused by
86
+ * `inScope` or by `routes` is told
87
+ * @property {number} maxRequestBytes the largest request body read, judged and forwarded
88
+ * @property {(body: object) => string | null} requestRefusal why the parsed body, a JSON
89
+ * object, is refused, as a short fixed reason, or null
90
+ * @property {(body: Buffer) => number} inputEstimate the input tokens a request may spend
91
+ * @property {(body: any) => unknown} declaredLimit the output tokens a request declares
92
+ * @property {(kind: "unauthenticated" | "cap_reached" | "invalid_request" | "too_large" | "busy", message: string) => object} errorBody
93
+ * the proxy's own refusal, in the API's error shape
94
+ * @property {RegExp} streamHint what a stream's data line holds when it is worth reading
95
+ * @property {(answer: any) => unknown} answeringModel the model an answer, or one of a
96
+ * stream's events, names
97
+ * @property {() => (answer: any) => number} usageReducer for one answer, a function that
98
+ * takes its body, or each of a stream's events that `streamHint` matches, and returns
99
+ * the tokens newly counted, each once
100
+ */
101
+
102
+ /**
103
+ * Start the proxy for `profile` on `bind` (an address the relay reaches, never
104
+ * all interfaces; on Docker Sandboxes, 127.0.0.1, which its policy lets the
105
+ * sandbox reach). `refused` collects every host or path it turned away. With
106
+ * `maxTokens`, the first request once the counted tokens reach it is refused,
107
+ * as is every one after, and `onCap` is called once. The answer that crosses
108
+ * the cap is delivered: a request in flight is never cut. A request is held
109
+ * back (429, retry after a second) while MAX_IN_FLIGHT are in flight, or
110
+ * while the counted tokens and the reservations of those in flight reach the
111
+ * cap, so requests sent together cannot all pass the check before any answer
112
+ * is counted.
113
+ * @param {ProviderProfile} profile
114
+ * @param {{ credential: string, kind: string, bind: string, upstream?: string, maxTokens?: number, onCap?: () => void, callerKey?: string, name?: string }} opts
115
+ * `kind` is one of the profile's credential kinds. `upstream` is the model
116
+ * API (default the profile's); only tests pass another. `callerKey`, when
117
+ * given, is the only value accepted as the caller's key, in one of the
118
+ * profile's key headers or as a bearer value; the launcher always gives one.
119
+ * `name` is what the proxy calls itself in what it answers.
120
+ * @returns {Promise<{ port: number, refused: string[], tokens: () => number, models: () => string[], credentialRefused: () => boolean, summary: () => string, close: () => Promise<void> }>}
121
+ * `models` is each distinct model id the answers named, in the order first
122
+ * seen, at most MAX_KEPT of them, and only plain ids of MAX_ENTRY or fewer.
123
+ * `credentialRefused` is true when at least one request was forwarded and
124
+ * the model API answered every one with 401 or 403: it refused the
125
+ * credential (a request that got no answer, or still waits for one, is not
126
+ * a refusal). The proxy's own refusals (a path, a host, the cap) are not
127
+ * answers of the model API, so they never count.
128
+ */
129
+ export async function startProxy(
130
+ profile,
131
+ {
132
+ credential,
133
+ kind,
134
+ bind,
135
+ upstream = profile.upstream,
136
+ maxTokens,
137
+ onCap = () => {},
138
+ callerKey,
139
+ name = "model proxy",
140
+ },
141
+ ) {
142
+ if (typeof kind !== "string" || !Object.hasOwn(profile.credentialKinds, kind)) {
143
+ throw new Error(`the model proxy has no credential kind ${JSON.stringify(kind)}`);
144
+ }
145
+ if (callerKey !== undefined && (typeof callerKey !== "string" || callerKey.length < 32)) {
146
+ throw new Error("the model proxy's caller key must be a string of at least 32 characters");
147
+ }
148
+ // The one header the proxy writes: the sandbox's own key headers are always
149
+ // dropped, so the placeholder never passes on.
150
+ const auth = profile.credentialKinds[kind](credential);
151
+ const dropped = new Set([...DROPPED, ...profile.keyHeaders]);
152
+ const passed = (headers) =>
153
+ Object.fromEntries(
154
+ Object.entries(headers).filter(
155
+ ([header, value]) => !dropped.has(header.toLowerCase()) && value !== undefined,
156
+ ),
157
+ );
158
+ // A request's headers also pass the profile's rule.
159
+ const requestHeaders = (headers) =>
160
+ Object.fromEntries(
161
+ Object.entries(passed(headers)).filter(([header]) => profile.forwardsHeader(header)),
162
+ );
163
+ const target = new URL(upstream);
164
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
165
+ const refused = [];
166
+ let refusedCount = 0;
167
+ // What the sandbox sends is untrusted: keep a few short entries, and a count.
168
+ const refuse = (what) => {
169
+ refusedCount += 1;
170
+ const entry = what.slice(0, MAX_ENTRY);
171
+ if (refused.length < MAX_KEPT && !refused.includes(entry)) refused.push(entry);
172
+ };
173
+ /** @type {Map<string, number>} upstream status (or "error") to count */
174
+ const statuses = new Map();
175
+ let forwarded = 0;
176
+ let tokens = 0;
177
+ /** @type {string[]} */
178
+ const models = [];
179
+ let moreModels = false;
180
+ // What an answer names is kept only as a plain, short id.
181
+ const answeredBy = (model) => {
182
+ if (typeof model !== "string" || model.length > MAX_ENTRY || !MODEL_ID.test(model)) return;
183
+ if (models.includes(model)) return;
184
+ if (models.length < MAX_KEPT) models.push(model);
185
+ else moreModels = true;
186
+ };
187
+ let pastCap = 0;
188
+ let inFlight = 0;
189
+ let reserved = 0;
190
+ let heldBack = 0;
191
+ const sockets = new Set();
192
+ const count = (key) => statuses.set(key, (statuses.get(key) ?? 0) + 1);
193
+ const answerText = (res, status, message) => res.writeHead(status).end(`${name}: ${message}\n`);
194
+ const answerError = (res, status, errorKind, message, headers = {}) =>
195
+ res
196
+ .writeHead(status, { "content-type": "application/json", ...headers })
197
+ .end(JSON.stringify(profile.errorBody(errorKind, `${name}: ${message}`)));
198
+
199
+ const server = createServer((req, res) => {
200
+ const raw = req.url ?? "";
201
+ if (!raw.startsWith("/")) {
202
+ // An absolute URL: someone is using the proxy as a forward proxy.
203
+ let host = raw;
204
+ try {
205
+ host = new URL(raw).host;
206
+ } catch {
207
+ host = raw;
208
+ }
209
+ refuse(host);
210
+ answerText(res, 403, "only the model API is reachable");
211
+ return;
212
+ }
213
+ const path = raw.split("?")[0];
214
+ const decoded = decodePlainPath(path);
215
+ if (decoded === null || !profile.inScope(path, decoded)) {
216
+ refuse(path);
217
+ answerText(res, 403, profile.refusals.scope);
218
+ return;
219
+ }
220
+ const route = profile.routes.find((r) => r.method === req.method && r.path === decoded);
221
+ if (!route) {
222
+ refuse(`${req.method} ${path}`);
223
+ answerText(res, 403, profile.refusals.route);
224
+ return;
225
+ }
226
+ if (callerKey !== undefined && !callerHolds(req.headers, profile.keyHeaders, callerKey)) {
227
+ refuse("a caller without the run's key");
228
+ answerError(res, 401, "unauthenticated", "this caller does not hold the run's key");
229
+ return;
230
+ }
231
+ if (maxTokens !== undefined && tokens >= maxTokens) {
232
+ pastCap += 1;
233
+ if (pastCap === 1) onCap();
234
+ answerError(res, 403, "cap_reached", `this run's token cap (${maxTokens}) is reached`);
235
+ return;
236
+ }
237
+ const encoding = String(req.headers["content-encoding"] ?? "identity")
238
+ .trim()
239
+ .toLowerCase();
240
+ if (encoding !== "identity" && encoding !== "") {
241
+ refuse("a compressed request body");
242
+ answerError(res, 415, "invalid_request", "a request body must not be compressed");
243
+ return;
244
+ }
245
+ // The whole body, bounded, so it is judged before any of it is sent.
246
+ const chunks = [];
247
+ let size = 0;
248
+ let tooLarge = false;
249
+ req.on("data", (chunk) => {
250
+ if (tooLarge) return;
251
+ size += chunk.length;
252
+ if (size > profile.maxRequestBytes) {
253
+ tooLarge = true;
254
+ chunks.length = 0;
255
+ return;
256
+ }
257
+ chunks.push(chunk);
258
+ });
259
+ req.on("error", () => res.destroy());
260
+ req.on("end", () => {
261
+ if (tooLarge) {
262
+ refuse("a request body over the size limit");
263
+ answerError(
264
+ res,
265
+ 413,
266
+ "too_large",
267
+ `a request body is at most ${profile.maxRequestBytes} bytes`,
268
+ );
269
+ return;
270
+ }
271
+ const body = Buffer.concat(chunks);
272
+ let parsed;
273
+ try {
274
+ parsed = JSON.parse(body.toString("utf8"));
275
+ } catch {
276
+ parsed = undefined;
277
+ }
278
+ // The core refuses a body that is no object itself, so no profile's
279
+ // body hook is ever handed one.
280
+ const why = isObject(parsed)
281
+ ? profile.requestRefusal(parsed)
282
+ : "a body that is not a JSON object";
283
+ if (why) {
284
+ refuse(why);
285
+ answerError(res, 400, "invalid_request", `refused ${why}`);
286
+ return;
287
+ }
288
+ // What this request may spend, held against the cap while it is in
289
+ // flight: its declared output and an estimate of its input.
290
+ const reservation = route.spends
291
+ ? profile.inputEstimate(body) + tokenCount(profile.declaredLimit(parsed))
292
+ : 0;
293
+ if (
294
+ inFlight >= MAX_IN_FLIGHT ||
295
+ (maxTokens !== undefined && inFlight > 0 && tokens + reserved >= maxTokens)
296
+ ) {
297
+ heldBack += 1;
298
+ answerError(
299
+ res,
300
+ 429,
301
+ "busy",
302
+ "too many requests in flight for this run's token cap; retry",
303
+ { "retry-after": "1" },
304
+ );
305
+ return;
306
+ }
307
+ inFlight += 1;
308
+ reserved += reservation;
309
+ let settled = false;
310
+ const settle = () => {
311
+ if (settled) return;
312
+ settled = true;
313
+ inFlight -= 1;
314
+ reserved -= reservation;
315
+ };
316
+ const headers = requestHeaders(req.headers);
317
+ headers[auth[0]] = auth[1];
318
+ headers["content-length"] = String(body.length);
319
+ // A plain body, so the meter can read its usage.
320
+ headers["accept-encoding"] = "identity";
321
+ forwarded += 1;
322
+ const upstreamReq = send(
323
+ {
324
+ protocol: target.protocol,
325
+ hostname: target.hostname,
326
+ port: target.port || undefined,
327
+ method: route.method,
328
+ path: raw,
329
+ headers,
330
+ },
331
+ (r) => {
332
+ count(String(r.statusCode ?? "error"));
333
+ // The reservation holds until the answer has been read whole, and
334
+ // so counted, even if the sandbox stops listening first.
335
+ r.on("close", settle);
336
+ res.writeHead(r.statusCode ?? 502, passed(r.headers));
337
+ meter(
338
+ r,
339
+ profile,
340
+ (n) => {
341
+ tokens += n;
342
+ },
343
+ answeredBy,
344
+ );
345
+ r.pipe(res);
346
+ },
347
+ );
348
+ upstreamReq.on("error", () => {
349
+ settle();
350
+ count("error");
351
+ if (!res.headersSent) {
352
+ answerText(res, 502, "the model API could not be reached");
353
+ } else {
354
+ res.destroy();
355
+ }
356
+ });
357
+ upstreamReq.end(body);
358
+ });
359
+ });
360
+
361
+ // A CONNECT tunnel would reach any host: refused.
362
+ server.on("connect", (req, socket) => {
363
+ socket.on("error", () => {});
364
+ refuse(req.url ?? "");
365
+ socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
366
+ });
367
+ server.on("connection", (socket) => {
368
+ sockets.add(socket);
369
+ socket.on("close", () => sockets.delete(socket));
370
+ });
371
+
372
+ await new Promise((resolve, reject) => {
373
+ server.once("error", reject);
374
+ server.listen(0, bind, () => resolve(undefined));
375
+ });
376
+ const address = server.address();
377
+ return {
378
+ port: typeof address === "object" && address ? address.port : 0,
379
+ refused,
380
+ tokens: () => tokens,
381
+ models: () => [...models],
382
+ // Every forwarded request answered, and each answer a 401 or 403.
383
+ credentialRefused: () =>
384
+ forwarded > 0 &&
385
+ [...statuses].reduce(
386
+ (sum, [status, n]) => (status === "401" || status === "403" ? sum + n : sum),
387
+ 0,
388
+ ) === forwarded,
389
+ summary() {
390
+ const byStatus = [...statuses].map(([s, n]) => `${s} x${n}`).join(", ");
391
+ const parts = [
392
+ `forwarded ${forwarded} request(s) to ${target.host}${byStatus ? ` (answers: ${byStatus})` : ""}`,
393
+ ];
394
+ if (forwarded) {
395
+ parts.push(
396
+ models.length
397
+ ? `the model API answered with ${models.join(", ")}${moreModels ? ", ..." : ""}`
398
+ : "no answer named a model",
399
+ );
400
+ }
401
+ if (refusedCount) {
402
+ const more = refusedCount > refused.length ? ", ..." : "";
403
+ parts.push(`refused ${refusedCount} (${refused.join(", ")}${more})`);
404
+ }
405
+ if (heldBack) {
406
+ parts.push(`held back ${heldBack} request(s) while others were in flight`);
407
+ }
408
+ if (maxTokens !== undefined) {
409
+ parts.push(
410
+ `counted ${tokens} of the ${maxTokens}-token cap${pastCap ? `, and refused ${pastCap} request(s) past it` : ""}`,
411
+ );
412
+ }
413
+ return parts.join("; ");
414
+ },
415
+ close: () =>
416
+ new Promise((resolve) => {
417
+ for (const s of sockets) s.destroy();
418
+ server.close(() => resolve(undefined));
419
+ }),
420
+ };
421
+ }
422
+
423
+ /**
424
+ * A request path percent-decoded, as the API would route it, so an encoded
425
+ * letter is checked as the letter it names; or null when it does not decode
426
+ * plainly. A path that does not decode, or still holds a `%` once decoded
427
+ * (encoded twice), is refused, as is a dot segment, plain or encoded, an
428
+ * encoded slash, a backslash, and an empty segment, which a front end that
429
+ * merges slashes would route past a check of the path.
430
+ * @param {string} path without its query
431
+ * @returns {string | null}
432
+ */
433
+ function decodePlainPath(path) {
434
+ let decoded;
435
+ try {
436
+ decoded = decodeURIComponent(path);
437
+ } catch {
438
+ return null;
439
+ }
440
+ const plain =
441
+ !decoded.includes("%") &&
442
+ !/\/\/|\/$/.test(decoded) &&
443
+ !/(^|\/)\.{1,2}(\/|$)|\\/.test(decoded) &&
444
+ !/(^|\/)(\.|%2e){1,2}(\/|$)|%2f|\\/i.test(path);
445
+ return plain ? decoded : null;
446
+ }
447
+
448
+ /** Whether a parsed body is a JSON object, not a list, a bare value or nothing. */
449
+ function isObject(value) {
450
+ return value !== null && typeof value === "object" && !Array.isArray(value);
451
+ }
452
+
453
+ /** A declared token limit as a reservation counts it: a positive whole number, or nothing. */
454
+ function tokenCount(value) {
455
+ return Number.isSafeInteger(value) && value > 0 ? value : 0;
456
+ }
457
+
458
+ /**
459
+ * Whether the request carries the run's caller key, as an agent sends its
460
+ * key: in one of `keyHeaders`, or as the bearer value of `Authorization`.
461
+ * Compared in constant time.
462
+ * @param {import("node:http").IncomingHttpHeaders} headers
463
+ * @param {readonly string[]} keyHeaders
464
+ * @param {string} key
465
+ */
466
+ function callerHolds(headers, keyHeaders, key) {
467
+ const want = Buffer.from(key, "utf8");
468
+ const offered = keyHeaders
469
+ .map((header) => headers[header])
470
+ .filter((value) => typeof value === "string");
471
+ const bearer = /^Bearer (\S+)$/.exec(String(headers.authorization ?? ""));
472
+ if (bearer) offered.push(bearer[1]);
473
+ return offered.some((value) => {
474
+ const got = Buffer.from(value, "utf8");
475
+ return got.length === want.length && timingSafeEqual(got, want);
476
+ });
477
+ }
478
+
479
+ /**
480
+ * Count the tokens an answer reports, as the answer streams past: the
481
+ * profile's usage reducer takes a JSON body, or each data event of a stream
482
+ * that the profile's `streamHint` matches.
483
+ * A compressed body (sent although the proxy asked for none) is decoded for
484
+ * counting only. The model the answer names goes to `named`, unchecked.
485
+ * @param {import("node:http").IncomingMessage} r
486
+ * @param {ProviderProfile} profile
487
+ * @param {(n: number) => void} add called with each newly counted amount
488
+ * @param {(model: unknown) => void} named called with each model an answer names
489
+ */
490
+ function meter(r, profile, add, named) {
491
+ const reduce = profile.usageReducer();
492
+ const take = (answer) => {
493
+ const model = profile.answeringModel(answer);
494
+ if (model !== undefined) named(model);
495
+ const n = reduce(answer);
496
+ if (n > 0) add(n);
497
+ };
498
+ const parse = (text) => {
499
+ try {
500
+ take(JSON.parse(text));
501
+ } catch {
502
+ // Not JSON: nothing to count.
503
+ }
504
+ };
505
+ const stream = /text\/event-stream/i.test(String(r.headers["content-type"] ?? ""));
506
+ const decoders = {
507
+ gzip: createGunzip,
508
+ "x-gzip": createGunzip,
509
+ deflate: createInflate,
510
+ br: createBrotliDecompress,
511
+ };
512
+ const encoding = String(r.headers["content-encoding"] ?? "identity")
513
+ .trim()
514
+ .toLowerCase();
515
+ /** @type {import("node:stream").Readable} */
516
+ let body = r;
517
+ if (encoding !== "identity" && encoding !== "") {
518
+ const make = decoders[encoding];
519
+ if (!make) return;
520
+ const decoder = make();
521
+ decoder.on("error", () => {});
522
+ r.on("data", (chunk) => decoder.write(chunk));
523
+ r.on("end", () => decoder.end());
524
+ body = decoder;
525
+ }
526
+ let pending = "";
527
+ let size = 0;
528
+ let overflow = false;
529
+ body.on("data", (chunk) => {
530
+ const text = chunk.toString("utf8");
531
+ if (!stream) {
532
+ size += text.length;
533
+ if (size > MAX_BODY) overflow = true;
534
+ if (!overflow) pending += text;
535
+ return;
536
+ }
537
+ pending += text;
538
+ const lines = pending.split(/\r?\n/);
539
+ pending = lines.pop() ?? "";
540
+ if (pending.length > MAX_LINE) pending = "";
541
+ for (const line of lines) {
542
+ if (line.startsWith("data:") && profile.streamHint.test(line)) parse(line.slice(5).trim());
543
+ }
544
+ });
545
+ body.on("end", () => {
546
+ if (!stream && !overflow) parse(pending);
547
+ else if (stream && pending.startsWith("data:")) parse(pending.slice(5).trim());
548
+ });
549
+ }