@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
@@ -1,614 +1,59 @@
1
- // The scan phase's only route out (#370): a key-injecting reverse proxy that
2
- // runs in the launcher, on the host, outside the sandbox. The sandboxed
3
- // Claude Code holds only a placeholder key and reaches the model API through
4
- // this proxy, which forwards only to the model API, strips the placeholder
5
- // (`x-api-key`, `Authorization`) and inserts the real credential: as
6
- // `x-api-key` for an API key, or, on the subscription path (#375), as the
7
- // bearer value of `Authorization` and nothing else, so every other header
8
- // Claude Code sends (its OAuth beta header among them) passes on as it is
9
- // and need not be known here. The
10
- // credential lives only in this process's memory: it is never an argument,
11
- // an environment variable or a file of any command the launcher runs.
12
- // Node core only (ADR 0001).
13
- //
14
- // It also holds the run's token cap (#371): it counts the `usage` each
15
- // model API answer returns, and once the count reaches the cap it refuses
16
- // every further request and tells the launcher, which stops the agent step.
17
- // From the same answers it reads the `model` each one names, so the launcher
18
- // can say which model the API answered with, not only which was asked for.
19
- //
20
- // What it forwards is only what the sandboxed Claude Code needs, judged on
21
- // every request, since anything in the sandbox can reach the proxy:
22
- // - only `POST` to the Messages API's own two paths (FORWARDED);
23
- // - with `callerKey`, only a request that carries the run's caller key, the
24
- // value the launcher gave the sandboxed Claude Code in place of a real
25
- // credential, so another process in the sandbox that never read it cannot
26
- // spend the real one;
27
- // - only a JSON body with nothing that makes the model API act outside the
28
- // sandbox: no server-side tool (any `tools` entry but a client tool with an
29
- // `input_schema`), no `mcp_servers` or `container`, and no content that
30
- // names a file or URL for the API to fetch. Every beta feature that acts
31
- // on the API's side is turned on through one of those body fields, so the
32
- // beta header itself passes as Claude Code sent it;
33
- // - at most MAX_IN_FLIGHT requests at once, each holding a reservation of
34
- // the tokens it may spend, so the cap holds against requests sent together.
35
-
36
- import { timingSafeEqual } from "node:crypto";
37
- import { createServer, request as httpRequest } from "node:http";
38
- import { request as httpsRequest } from "node:https";
39
- import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
40
-
41
- /** The model API every forwarded request goes to. */
42
- export const MODEL_API = "https://api.anthropic.com";
43
-
44
- /** Every path is checked against /v1/ first, then against FORWARDED. */
45
- const MODEL_PATH = /^\/v1\//;
46
-
47
- /** The only requests forwarded, by decoded path, and only as `POST`: Claude Code's Messages API calls. */
48
- export const FORWARDED = Object.freeze(["/v1/messages", "/v1/messages/count_tokens"]);
49
-
50
- /** The largest request body the proxy reads, judges and forwards. */
51
- export const MAX_REQUEST = 32 * 1024 * 1024;
52
-
53
- /** How many requests may be in flight to the model API at once. */
54
- export const MAX_IN_FLIGHT = 4;
55
-
56
- /**
57
- * A request's input tokens, estimated from its body for its reservation:
58
- * one token per this many bytes, which is fewer bytes than any ordinary text
59
- * takes per token, so the estimate is high rather than low.
60
- */
61
- const BYTES_PER_TOKEN = 2;
62
-
63
- /** How deep the body's messages and system blocks are walked; deeper is refused. */
64
- const MAX_DEPTH = 64;
65
-
66
- /**
67
- * Paths whose spend an answer's `usage` would not show (a batch is billed
68
- * later, outside this run), so the token cap could not hold: refused.
69
- */
70
- const UNCOUNTED_PATH = /^\/v1\/(messages\/batches|complete)(\/|$)/i;
71
-
72
- /** The `usage` fields the cap counts: every kind of token billed. */
73
- export const COUNTED_USAGE = Object.freeze([
74
- "input_tokens",
75
- "cache_creation_input_tokens",
76
- "cache_read_input_tokens",
77
- "output_tokens",
78
- ]);
79
-
80
- /** How much of an answer the meter reads: a line of a stream, or a whole JSON body. */
81
- const MAX_LINE = 1024 * 1024;
82
- const MAX_BODY = 16 * 1024 * 1024;
1
+ // The scan phase's only route out (#370): the model proxy's core
2
+ // (../model-proxy/core.mjs), which runs in the launcher, on the host, outside
3
+ // the sandbox, with the provider profile the harness's launch plan names
4
+ // (ADR 0023): `anthropic`, `openai` or `gemini-api`. The core's header says what is
5
+ // forwarded and how the run's token cap (#371) holds; each profile's says what
6
+ // of its API passes, and how the real credential goes in. Node core only
7
+ // (ADR 0001).
8
+
9
+ import { startProxy } from "../model-proxy/core.mjs";
10
+ import { anthropic } from "../model-proxy/profiles/anthropic.mjs";
11
+ import { geminiApi } from "../model-proxy/profiles/gemini-api.mjs";
12
+ import { openai } from "../model-proxy/profiles/openai.mjs";
13
+
14
+ /** The provider profiles a launch plan's model route may name. */
15
+ export const PROFILES = Object.freeze({ anthropic, openai, "gemini-api": geminiApi });
16
+
17
+ export { MAX_IN_FLIGHT, MODEL_ID } from "../model-proxy/core.mjs";
18
+ export {
19
+ COUNTED_USAGE,
20
+ FORWARDED,
21
+ MAX_REQUEST,
22
+ MODEL_API,
23
+ requestRefusal,
24
+ } from "../model-proxy/profiles/anthropic.mjs";
83
25
 
84
26
  /**
85
- * A model id as Claude Code's --model takes it, and nothing more: the
86
- * launcher's check of --model, which goes into the agent step's command
87
- * line (so no space, quote or leading dash; the same pattern as the static
88
- * workflow's model input), and the only form of an answer's `model` the
89
- * summary names, so an answer cannot write a line of its own.
90
- */
91
- export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@/[\]-]*$/;
92
-
93
- /** How many distinct refused hosts, paths or answered models the summary keeps, and how long each. */
94
- const MAX_KEPT = 5;
95
- const MAX_ENTRY = 80;
96
-
97
- // Hop-by-hop headers (RFC 9110 7.6.1), the client's credentials, and the
98
- // Host, which is the model API's own.
99
- const DROPPED = new Set([
100
- "x-api-key",
101
- "authorization",
102
- "proxy-authorization",
103
- "proxy-authenticate",
104
- "proxy-connection",
105
- "connection",
106
- "keep-alive",
107
- "te",
108
- "trailer",
109
- "transfer-encoding",
110
- "upgrade",
111
- "host",
112
- "cookie",
113
- ]);
114
-
115
- /**
116
- * Start the proxy on `bind` (an address the relay reaches, never all
117
- * interfaces; on Docker Sandboxes, 127.0.0.1, which its policy lets the
118
- * sandbox reach). `refused` collects every host or path it turned away.
119
- * With `maxTokens`, the first request once the counted tokens reach it is
120
- * refused, as is every one after, and `onCap` is called once. The answer
121
- * that crosses the cap is delivered: a request in flight is never cut. A
122
- * request is held back (429, retry after a second) while MAX_IN_FLIGHT are
123
- * in flight, or while the counted tokens and the reservations of those in
124
- * flight reach the cap, so requests sent together cannot all pass the check
125
- * before any answer is counted.
126
- * @param {{ credential: string, kind?: "api-key" | "subscription", bind: string, upstream?: string, maxTokens?: number, onCap?: () => void, callerKey?: string }} opts
127
- * `kind` is the credential's (default an API key). `upstream` is the
128
- * model API; only tests pass another. `callerKey`, when given, is the
129
- * only value accepted as the caller's `x-api-key` or `Authorization`
130
- * bearer value; the launcher always gives one.
131
- * @returns {Promise<{ port: number, refused: string[], tokens: () => number, models: () => string[], credentialRefused: () => boolean, summary: () => string, close: () => Promise<void> }>}
132
- * `models` is each distinct model id the answers named, in the order first
133
- * seen, at most MAX_KEPT of them, and only plain ids of MAX_ENTRY or fewer.
134
- * `credentialRefused` is true when at least one request was forwarded and
135
- * the model API answered every one with 401 or 403: it refused the
136
- * credential (a request that got no answer, or still waits for one, is not
137
- * a refusal). The proxy's own refusals (a path, a host, the cap) are not
138
- * answers of the model API, so they never count.
27
+ * Start the Deep scan's model proxy on `bind`. See startProxy in the core for
28
+ * every option and for what it returns.
29
+ * @param {{ profile?: string, credential: string, kind?: "api-key" | "subscription", bind: string, upstream?: string, maxTokens?: number, onCap?: () => void, callerKey?: string }} opts
30
+ * `profile` names one of PROFILES (default `anthropic`). `kind` is the
31
+ * credential's (default an API key). `upstream` is the model API; only
32
+ * tests pass another. `callerKey`, when given, is the only value accepted
33
+ * as the caller's key, in the profile's key headers or as a bearer value;
34
+ * the launcher always gives one.
139
35
  */
140
36
  export async function startModelProxy({
37
+ profile = "anthropic",
141
38
  credential,
142
39
  kind = "api-key",
143
40
  bind,
144
- upstream = MODEL_API,
41
+ upstream,
145
42
  maxTokens,
146
- onCap = () => {},
43
+ onCap,
147
44
  callerKey,
148
45
  }) {
149
- if (kind !== "api-key" && kind !== "subscription") {
150
- throw new Error(`the model proxy has no credential kind ${JSON.stringify(kind)}`);
151
- }
152
- if (callerKey !== undefined && (typeof callerKey !== "string" || callerKey.length < 32)) {
153
- throw new Error("the model proxy's caller key must be a string of at least 32 characters");
154
- }
155
- // The one header the proxy writes: the sandbox's x-api-key and
156
- // Authorization are always dropped, so the placeholder never passes on.
157
- const auth =
158
- kind === "subscription" ? ["authorization", `Bearer ${credential}`] : ["x-api-key", credential];
159
- const target = new URL(upstream);
160
- const send = target.protocol === "https:" ? httpsRequest : httpRequest;
161
- const refused = [];
162
- let refusedCount = 0;
163
- // What the sandbox sends is untrusted: keep a few short entries, and a count.
164
- const refuse = (what) => {
165
- refusedCount += 1;
166
- const entry = what.slice(0, MAX_ENTRY);
167
- if (refused.length < MAX_KEPT && !refused.includes(entry)) refused.push(entry);
168
- };
169
- /** @type {Map<string, number>} upstream status (or "error") to count */
170
- const statuses = new Map();
171
- let forwarded = 0;
172
- let tokens = 0;
173
- /** @type {string[]} */
174
- const models = [];
175
- let moreModels = false;
176
- // What an answer names is kept only as a plain, short id.
177
- const answeredBy = (model) => {
178
- if (typeof model !== "string" || model.length > MAX_ENTRY || !MODEL_ID.test(model)) return;
179
- if (models.includes(model)) return;
180
- if (models.length < MAX_KEPT) models.push(model);
181
- else moreModels = true;
182
- };
183
- let pastCap = 0;
184
- let inFlight = 0;
185
- let reserved = 0;
186
- let heldBack = 0;
187
- const sockets = new Set();
188
- const count = (key) => statuses.set(key, (statuses.get(key) ?? 0) + 1);
189
- const answerError = (res, status, type, message, headers = {}) =>
190
- res.writeHead(status, { "content-type": "application/json", ...headers }).end(
191
- JSON.stringify({
192
- type: "error",
193
- error: { type, message: `deep-scan model proxy: ${message}` },
194
- }),
195
- );
196
-
197
- const server = createServer((req, res) => {
198
- const raw = req.url ?? "";
199
- if (!raw.startsWith("/")) {
200
- // An absolute URL: someone is using the proxy as a forward proxy.
201
- let host = raw;
202
- try {
203
- host = new URL(raw).host;
204
- } catch {
205
- host = raw;
206
- }
207
- refuse(host);
208
- res.writeHead(403).end("deep-scan model proxy: only the model API is reachable\n");
209
- return;
210
- }
211
- const path = raw.split("?")[0];
212
- // The checks run on the path as the API would route it, percent-decoded,
213
- // so `/v1/%6dessages/batches` is the batch path it names. A path that
214
- // does not decode, or still holds a `%` once decoded (encoded twice), is
215
- // refused. No dot segment, plain or encoded, may walk it out of /v1/.
216
- let decoded = null;
217
- try {
218
- decoded = decodeURIComponent(path);
219
- } catch {
220
- decoded = null;
221
- }
222
- if (
223
- decoded === null ||
224
- decoded.includes("%") ||
225
- !MODEL_PATH.test(path) ||
226
- !MODEL_PATH.test(decoded) ||
227
- UNCOUNTED_PATH.test(decoded) ||
228
- // An empty segment (`/v1//messages/batches`): a front end that merges
229
- // slashes would route it past the uncounted-path check.
230
- /\/\/|\/$/.test(decoded) ||
231
- /(^|\/)\.{1,2}(\/|$)|\\/.test(decoded) ||
232
- /(^|\/)(\.|%2e){1,2}(\/|$)|%2f|\\/i.test(path)
233
- ) {
234
- refuse(path);
235
- res.writeHead(403).end("deep-scan model proxy: only the model API's /v1/ paths\n");
236
- return;
237
- }
238
- // Only Claude Code's own Messages API calls: POST, to one of two paths.
239
- if (req.method !== "POST" || !FORWARDED.includes(decoded)) {
240
- refuse(`${req.method} ${path}`);
241
- res.writeHead(403).end("deep-scan model proxy: only POST to the Messages API\n");
242
- return;
243
- }
244
- if (callerKey !== undefined && !callerHolds(req.headers, callerKey)) {
245
- refuse("a caller without the run's key");
246
- answerError(res, 401, "authentication_error", "this caller does not hold the run's key");
247
- return;
248
- }
249
- if (maxTokens !== undefined && tokens >= maxTokens) {
250
- pastCap += 1;
251
- if (pastCap === 1) onCap();
252
- answerError(res, 403, "permission_error", `this run's token cap (${maxTokens}) is reached`);
253
- return;
254
- }
255
- const encoding = String(req.headers["content-encoding"] ?? "identity")
256
- .trim()
257
- .toLowerCase();
258
- if (encoding !== "identity" && encoding !== "") {
259
- refuse("a compressed request body");
260
- answerError(res, 415, "invalid_request_error", "a request body must not be compressed");
261
- return;
262
- }
263
- // The whole body, bounded, so it is judged before any of it is sent.
264
- const chunks = [];
265
- let size = 0;
266
- let tooLarge = false;
267
- req.on("data", (chunk) => {
268
- if (tooLarge) return;
269
- size += chunk.length;
270
- if (size > MAX_REQUEST) {
271
- tooLarge = true;
272
- chunks.length = 0;
273
- return;
274
- }
275
- chunks.push(chunk);
276
- });
277
- req.on("error", () => res.destroy());
278
- req.on("end", () => {
279
- if (tooLarge) {
280
- refuse("a request body over the size limit");
281
- answerError(
282
- res,
283
- 413,
284
- "request_too_large",
285
- `a request body is at most ${MAX_REQUEST} bytes`,
286
- );
287
- return;
288
- }
289
- const body = Buffer.concat(chunks);
290
- let parsed;
291
- try {
292
- parsed = JSON.parse(body.toString("utf8"));
293
- } catch {
294
- parsed = undefined;
295
- }
296
- const why = requestRefusal(parsed);
297
- if (why) {
298
- refuse(why);
299
- answerError(res, 400, "invalid_request_error", `refused ${why}`);
300
- return;
301
- }
302
- // What this request may spend, held against the cap while it is in
303
- // flight: its declared output and an estimate of its input. A token
304
- // count spends nothing.
305
- const reservation =
306
- decoded === "/v1/messages"
307
- ? Math.ceil(body.length / BYTES_PER_TOKEN) +
308
- (Number.isSafeInteger(parsed.max_tokens) && parsed.max_tokens > 0
309
- ? parsed.max_tokens
310
- : 0)
311
- : 0;
312
- if (
313
- inFlight >= MAX_IN_FLIGHT ||
314
- (maxTokens !== undefined && inFlight > 0 && tokens + reserved >= maxTokens)
315
- ) {
316
- heldBack += 1;
317
- answerError(
318
- res,
319
- 429,
320
- "rate_limit_error",
321
- "too many requests in flight for this run's token cap; retry",
322
- { "retry-after": "1" },
323
- );
324
- return;
325
- }
326
- inFlight += 1;
327
- reserved += reservation;
328
- let settled = false;
329
- const settle = () => {
330
- if (settled) return;
331
- settled = true;
332
- inFlight -= 1;
333
- reserved -= reservation;
334
- };
335
- const headers = {};
336
- for (const [name, value] of Object.entries(req.headers)) {
337
- if (!DROPPED.has(name.toLowerCase()) && value !== undefined) headers[name] = value;
338
- }
339
- headers[auth[0]] = auth[1];
340
- headers["content-length"] = String(body.length);
341
- // A plain body, so the meter can read its usage.
342
- headers["accept-encoding"] = "identity";
343
- forwarded += 1;
344
- const upstreamReq = send(
345
- {
346
- protocol: target.protocol,
347
- hostname: target.hostname,
348
- port: target.port || undefined,
349
- method: "POST",
350
- path: raw,
351
- headers,
352
- },
353
- (r) => {
354
- count(String(r.statusCode ?? "error"));
355
- // The reservation holds until the answer has been read whole, and
356
- // so counted, even if the sandbox stops listening first.
357
- r.on("close", settle);
358
- const back = {};
359
- for (const [name, value] of Object.entries(r.headers)) {
360
- if (!DROPPED.has(name.toLowerCase()) && value !== undefined) back[name] = value;
361
- }
362
- res.writeHead(r.statusCode ?? 502, back);
363
- meter(
364
- r,
365
- (n) => {
366
- tokens += n;
367
- },
368
- answeredBy,
369
- );
370
- r.pipe(res);
371
- },
372
- );
373
- upstreamReq.on("error", () => {
374
- settle();
375
- count("error");
376
- if (!res.headersSent) {
377
- res.writeHead(502).end("deep-scan model proxy: the model API could not be reached\n");
378
- } else {
379
- res.destroy();
380
- }
381
- });
382
- upstreamReq.end(body);
383
- });
384
- });
385
-
386
- // A CONNECT tunnel would reach any host: refused.
387
- server.on("connect", (req, socket) => {
388
- socket.on("error", () => {});
389
- refuse(req.url ?? "");
390
- socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
391
- });
392
- server.on("connection", (socket) => {
393
- sockets.add(socket);
394
- socket.on("close", () => sockets.delete(socket));
395
- });
396
-
397
- await new Promise((resolve, reject) => {
398
- server.once("error", reject);
399
- server.listen(0, bind, () => resolve(undefined));
400
- });
401
- const address = server.address();
402
- return {
403
- port: typeof address === "object" && address ? address.port : 0,
404
- refused,
405
- tokens: () => tokens,
406
- models: () => [...models],
407
- // Every forwarded request answered, and each answer a 401 or 403.
408
- credentialRefused: () =>
409
- forwarded > 0 &&
410
- [...statuses].reduce(
411
- (sum, [status, n]) => (status === "401" || status === "403" ? sum + n : sum),
412
- 0,
413
- ) === forwarded,
414
- summary() {
415
- const byStatus = [...statuses].map(([s, n]) => `${s} x${n}`).join(", ");
416
- const parts = [
417
- `forwarded ${forwarded} request(s) to ${target.host}${byStatus ? ` (answers: ${byStatus})` : ""}`,
418
- ];
419
- if (forwarded) {
420
- parts.push(
421
- models.length
422
- ? `the model API answered with ${models.join(", ")}${moreModels ? ", ..." : ""}`
423
- : "no answer named a model",
424
- );
425
- }
426
- if (refusedCount) {
427
- const more = refusedCount > refused.length ? ", ..." : "";
428
- parts.push(`refused ${refusedCount} (${refused.join(", ")}${more})`);
429
- }
430
- if (heldBack) {
431
- parts.push(`held back ${heldBack} request(s) while others were in flight`);
432
- }
433
- if (maxTokens !== undefined) {
434
- parts.push(
435
- `counted ${tokens} of the ${maxTokens}-token cap${pastCap ? `, and refused ${pastCap} request(s) past it` : ""}`,
436
- );
437
- }
438
- return parts.join("; ");
439
- },
440
- close: () =>
441
- new Promise((resolve) => {
442
- for (const s of sockets) s.destroy();
443
- server.close(() => resolve(undefined));
444
- }),
445
- };
446
- }
447
-
448
- /**
449
- * Whether the request carries the run's caller key, as Claude Code sends
450
- * its key: `x-api-key`, or the bearer value of `Authorization`. Compared in
451
- * constant time.
452
- * @param {import("node:http").IncomingHttpHeaders} headers
453
- * @param {string} key
454
- */
455
- function callerHolds(headers, key) {
456
- const want = Buffer.from(key, "utf8");
457
- const offered = [];
458
- const apiKey = headers["x-api-key"];
459
- if (typeof apiKey === "string") offered.push(apiKey);
460
- const bearer = /^Bearer (\S+)$/.exec(String(headers.authorization ?? ""));
461
- if (bearer) offered.push(bearer[1]);
462
- return offered.some((value) => {
463
- const got = Buffer.from(value, "utf8");
464
- return got.length === want.length && timingSafeEqual(got, want);
465
- });
466
- }
467
-
468
- /** Content sources that make the model API fetch something: a URL, or a file it holds. */
469
- const FETCHED_SOURCE = new Set(["url", "file"]);
470
-
471
- /** Content blocks that hand the model API something to act on outside the request. */
472
- const ACTING_BLOCK = new Set(["container_upload", "mcp_tool_use", "server_tool_use"]);
473
-
474
- /**
475
- * Why a Messages API request body is refused, or null. The body must be a
476
- * JSON object; no `mcp_servers` or `container`; every `tools` entry a
477
- * client tool (no `type`, or `custom`, and an `input_schema` object), so no
478
- * server-side tool; and nothing in `messages` or `system` that names a URL
479
- * or a file for the API to fetch, or an upload or server-side call.
480
- * @param {unknown} body
481
- * @returns {string | null} a short, fixed reason, never the sandbox's text
482
- */
483
- export function requestRefusal(body) {
484
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
485
- return "a body that is not a JSON object";
486
- }
487
- for (const key of ["mcp_servers", "container"]) {
488
- if (Object.hasOwn(body, key)) return `a request with ${key}`;
489
- }
490
- if (Object.hasOwn(body, "tools")) {
491
- if (!Array.isArray(body.tools)) return "tools that are not a list";
492
- for (const tool of body.tools) {
493
- if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
494
- return "a tool that is not an object";
495
- }
496
- if (tool.type !== undefined && tool.type !== "custom") return "a server-side tool";
497
- if (tool.input_schema === null || typeof tool.input_schema !== "object") {
498
- return "a tool with no input_schema";
499
- }
500
- }
501
- }
502
- for (const key of ["messages", "system"]) {
503
- if (!Object.hasOwn(body, key)) continue;
504
- const why = contentRefusal(body[key], 0);
505
- if (why) return why;
506
- }
507
- return null;
508
- }
509
-
510
- /** @param {unknown} value @param {number} depth @returns {string | null} */
511
- function contentRefusal(value, depth) {
512
- if (value === null || typeof value !== "object") return null;
513
- if (depth > MAX_DEPTH) return "content nested too deeply";
514
- if (Array.isArray(value)) {
515
- for (const item of value) {
516
- const why = contentRefusal(item, depth + 1);
517
- if (why) return why;
518
- }
519
- return null;
520
- }
521
- if (typeof value.type === "string" && ACTING_BLOCK.has(value.type)) {
522
- return `a ${value.type} block`;
523
- }
524
- if (Object.hasOwn(value, "file_id")) return "a file reference";
525
- const source = value.source;
526
- if (source && typeof source === "object" && FETCHED_SOURCE.has(source.type)) {
527
- return `a ${source.type} source`;
528
- }
529
- for (const child of Object.values(value)) {
530
- const why = contentRefusal(child, depth + 1);
531
- if (why) return why;
532
- }
533
- return null;
534
- }
535
-
536
- /**
537
- * Count the tokens an answer's `usage` reports, as the answer streams past:
538
- * each kind in COUNTED_USAGE, from a JSON body or from a stream's
539
- * `message_start` and `message_delta` events. A stream's usage is
540
- * cumulative, so each kind counts its highest value once. A compressed body
541
- * (sent although the proxy asked for none) is decoded for counting only.
542
- * The `model` the answer names (a JSON body's, or a stream's
543
- * `message_start`'s) goes to `named`, unchecked.
544
- * @param {import("node:http").IncomingMessage} r
545
- * @param {(n: number) => void} add called with each newly counted amount
546
- * @param {(model: unknown) => void} named called with each `model` an answer names
547
- */
548
- function meter(r, add, named) {
549
- const seen = Object.fromEntries(COUNTED_USAGE.map((k) => [k, 0]));
550
- const take = (obj) => {
551
- const model = obj?.model ?? obj?.message?.model;
552
- if (model !== undefined) named(model);
553
- const usage = obj?.usage ?? obj?.message?.usage;
554
- if (!usage || typeof usage !== "object") return;
555
- for (const key of COUNTED_USAGE) {
556
- const n = usage[key];
557
- if (typeof n === "number" && Number.isFinite(n) && n > seen[key]) {
558
- add(n - seen[key]);
559
- seen[key] = n;
560
- }
561
- }
562
- };
563
- const parse = (text) => {
564
- try {
565
- take(JSON.parse(text));
566
- } catch {
567
- // Not JSON: nothing to count.
568
- }
569
- };
570
- const stream = /text\/event-stream/i.test(String(r.headers["content-type"] ?? ""));
571
- const decoders = {
572
- gzip: createGunzip,
573
- "x-gzip": createGunzip,
574
- deflate: createInflate,
575
- br: createBrotliDecompress,
576
- };
577
- const encoding = String(r.headers["content-encoding"] ?? "identity")
578
- .trim()
579
- .toLowerCase();
580
- /** @type {import("node:stream").Readable} */
581
- let body = r;
582
- if (encoding !== "identity" && encoding !== "") {
583
- const make = decoders[encoding];
584
- if (!make) return;
585
- const decoder = make();
586
- decoder.on("error", () => {});
587
- r.on("data", (chunk) => decoder.write(chunk));
588
- r.on("end", () => decoder.end());
589
- body = decoder;
590
- }
591
- let pending = "";
592
- let size = 0;
593
- let overflow = false;
594
- body.on("data", (chunk) => {
595
- const text = chunk.toString("utf8");
596
- if (!stream) {
597
- size += text.length;
598
- if (size > MAX_BODY) overflow = true;
599
- if (!overflow) pending += text;
600
- return;
601
- }
602
- pending += text;
603
- const lines = pending.split(/\r?\n/);
604
- pending = lines.pop() ?? "";
605
- if (pending.length > MAX_LINE) pending = "";
606
- for (const line of lines) {
607
- if (line.startsWith("data:") && /"(usage|model)"/.test(line)) parse(line.slice(5).trim());
608
- }
609
- });
610
- body.on("end", () => {
611
- if (!stream && !overflow) parse(pending);
612
- else if (stream && pending.startsWith("data:")) parse(pending.slice(5).trim());
46
+ if (!Object.hasOwn(PROFILES, profile)) {
47
+ throw new Error(`the model proxy has no provider profile ${JSON.stringify(profile)}`);
48
+ }
49
+ return startProxy(PROFILES[profile], {
50
+ credential,
51
+ kind,
52
+ bind,
53
+ upstream,
54
+ maxTokens,
55
+ onCap,
56
+ callerKey,
57
+ name: "deep-scan model proxy",
613
58
  });
614
59
  }