@mnaimfaizy/agent-kit 1.0.0-beta.13 → 1.0.0-beta.15

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