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

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 (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -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/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -16,7 +16,8 @@
16
16
  //
17
17
  // What it forwards is judged on every request, since anything in the sandbox
18
18
  // can reach the proxy:
19
- // - only a method and path the profile lists, on a path that decodes plainly;
19
+ // - only a method and path the profile lists, on a path that decodes plainly,
20
+ // with the query string the route allows;
20
21
  // - with `callerKey`, only a request that carries the run's caller key, the
21
22
  // value the launcher gave the sandboxed agent in place of a real
22
23
  // credential, so another process in the sandbox that never read it cannot
@@ -24,6 +25,10 @@
24
25
  // - only a JSON object the profile's filter passes, within its size bound;
25
26
  // - at most MAX_IN_FLIGHT requests at once, each holding a reservation of
26
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.
27
32
 
28
33
  import { timingSafeEqual } from "node:crypto";
29
34
  import { createServer, request as httpRequest } from "node:http";
@@ -33,7 +38,10 @@ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
33
38
  /** How many requests may be in flight to the model API at once. */
34
39
  export const MAX_IN_FLIGHT = 4;
35
40
 
36
- /** How much of an answer the meter reads: a line of a stream, or a whole JSON body. */
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
+ */
37
45
  const MAX_LINE = 1024 * 1024;
38
46
  const MAX_BODY = 16 * 1024 * 1024;
39
47
 
@@ -68,6 +76,13 @@ const DROPPED = [
68
76
  "cookie",
69
77
  ];
70
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
+
71
86
  /**
72
87
  * Everything the core needs to know about one model API.
73
88
  * @typedef {object} ProviderProfile
@@ -80,13 +95,27 @@ const DROPPED = [
80
95
  * lower-case name, passes to the model API, among those the core has not already dropped
81
96
  * @property {(path: string, decoded: string) => boolean} inScope whether the path, as sent
82
97
  * 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
98
+ * @property {ReadonlyArray<Route>} routes the only requests forwarded, by decoded
99
+ * path; one that `spends` holds a reservation
85
100
  * @property {{ scope: string, route: string }} refusals what a caller refused by
86
101
  * `inScope` or by `routes` is told
87
102
  * @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
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
90
119
  * @property {(body: Buffer) => number} inputEstimate the input tokens a request may spend
91
120
  * @property {(body: any) => unknown} declaredLimit the output tokens a request declares
92
121
  * @property {(kind: "unauthenticated" | "cap_reached" | "invalid_request" | "too_large" | "busy", message: string) => object} errorBody
@@ -109,7 +138,8 @@ const DROPPED = [
109
138
  * back (429, retry after a second) while MAX_IN_FLIGHT are in flight, or
110
139
  * while the counted tokens and the reservations of those in flight reach the
111
140
  * cap, so requests sent together cannot all pass the check before any answer
112
- * is counted.
141
+ * is counted. An answer its caller abandons is read on and counted all the
142
+ * same; closing the proxy stops reading it.
113
143
  * @param {ProviderProfile} profile
114
144
  * @param {{ credential: string, kind: string, bind: string, upstream?: string, maxTokens?: number, onCap?: () => void, callerKey?: string, name?: string }} opts
115
145
  * `kind` is one of the profile's credential kinds. `upstream` is the model
@@ -121,7 +151,8 @@ const DROPPED = [
121
151
  * `models` is each distinct model id the answers named, in the order first
122
152
  * seen, at most MAX_KEPT of them, and only plain ids of MAX_ENTRY or fewer.
123
153
  * `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
154
+ * the model API answered every one with 401 or 403, or with what the
155
+ * profile reads as the same: it refused the
125
156
  * credential (a request that got no answer, or still waits for one, is not
126
157
  * a refusal). The proxy's own refusals (a path, a host, the cap) are not
127
158
  * answers of the model API, so they never count.
@@ -185,10 +216,14 @@ export async function startProxy(
185
216
  else moreModels = true;
186
217
  };
187
218
  let pastCap = 0;
219
+ /** Answers the profile read as a refused credential, by neither 401 nor 403. */
220
+ let refusedByAnswer = 0;
188
221
  let inFlight = 0;
189
222
  let reserved = 0;
190
223
  let heldBack = 0;
191
224
  const sockets = new Set();
225
+ /** Each request still upstream: how to stop it, counting what it holds. */
226
+ const unsettled = new Set();
192
227
  const count = (key) => statuses.set(key, (statuses.get(key) ?? 0) + 1);
193
228
  const answerText = (res, status, message) => res.writeHead(status).end(`${name}: ${message}\n`);
194
229
  const answerError = (res, status, errorKind, message, headers = {}) =>
@@ -217,8 +252,8 @@ export async function startProxy(
217
252
  answerText(res, 403, profile.refusals.scope);
218
253
  return;
219
254
  }
220
- const route = profile.routes.find((r) => r.method === req.method && r.path === decoded);
221
- if (!route) {
255
+ const route = profile.routes.find((r) => r.method === req.method && routes(r, decoded));
256
+ if (!route || queryRefused(profile, route, raw)) {
222
257
  refuse(`${req.method} ${path}`);
223
258
  answerText(res, 403, profile.refusals.route);
224
259
  return;
@@ -268,7 +303,7 @@ export async function startProxy(
268
303
  );
269
304
  return;
270
305
  }
271
- const body = Buffer.concat(chunks);
306
+ let body = Buffer.concat(chunks);
272
307
  let parsed;
273
308
  try {
274
309
  parsed = JSON.parse(body.toString("utf8"));
@@ -278,13 +313,17 @@ export async function startProxy(
278
313
  // The core refuses a body that is no object itself, so no profile's
279
314
  // body hook is ever handed one.
280
315
  const why = isObject(parsed)
281
- ? profile.requestRefusal(parsed)
316
+ ? profile.requestRefusal(parsed, { path: decoded, route })
282
317
  : "a body that is not a JSON object";
283
318
  if (why) {
284
319
  refuse(why);
285
320
  answerError(res, 400, "invalid_request", `refused ${why}`);
286
321
  return;
287
322
  }
323
+ if (profile.rewrite !== undefined) {
324
+ parsed = profile.rewrite(parsed, { path: decoded, route });
325
+ body = Buffer.from(JSON.stringify(parsed), "utf8");
326
+ }
288
327
  // What this request may spend, held against the cap while it is in
289
328
  // flight: its declared output and an estimate of its input.
290
329
  const reservation = route.spends
@@ -307,11 +346,20 @@ export async function startProxy(
307
346
  inFlight += 1;
308
347
  reserved += reservation;
309
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 = () => {};
310
354
  const settle = () => {
311
355
  if (settled) return;
312
356
  settled = true;
357
+ unsettled.delete(stop);
313
358
  inFlight -= 1;
314
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;
315
363
  };
316
364
  const headers = requestHeaders(req.headers);
317
365
  headers[auth[0]] = auth[1];
@@ -329,23 +377,56 @@ export async function startProxy(
329
377
  headers,
330
378
  },
331
379
  (r) => {
380
+ answered = true;
381
+ const status = r.statusCode ?? 502;
382
+ succeeded = status >= 200 && status < 300;
332
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
+ };
333
390
  // The reservation holds until the answer has been read whole, and
334
391
  // so counted, even if the sandbox stops listening first.
335
- r.on("close", settle);
336
- res.writeHead(r.statusCode ?? 502, passed(r.headers));
337
392
  meter(
338
393
  r,
339
394
  profile,
340
395
  (n) => {
396
+ used += n;
341
397
  tokens += n;
342
398
  },
343
399
  answeredBy,
400
+ judge,
401
+ settle,
344
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));
345
415
  r.pipe(res);
346
416
  },
347
417
  );
418
+ stop = () => {
419
+ upstreamReq.destroy();
420
+ settle();
421
+ };
422
+ unsettled.add(stop);
348
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
+ }
349
430
  settle();
350
431
  count("error");
351
432
  if (!res.headersSent) {
@@ -379,12 +460,12 @@ export async function startProxy(
379
460
  refused,
380
461
  tokens: () => tokens,
381
462
  models: () => [...models],
382
- // Every forwarded request answered, and each answer a 401 or 403.
463
+ // Every forwarded request answered, and each answer a refusal of the credential.
383
464
  credentialRefused: () =>
384
465
  forwarded > 0 &&
385
466
  [...statuses].reduce(
386
467
  (sum, [status, n]) => (status === "401" || status === "403" ? sum + n : sum),
387
- 0,
468
+ refusedByAnswer,
388
469
  ) === forwarded,
389
470
  summary() {
390
471
  const byStatus = [...statuses].map(([s, n]) => `${s} x${n}`).join(", ");
@@ -414,6 +495,7 @@ export async function startProxy(
414
495
  },
415
496
  close: () =>
416
497
  new Promise((resolve) => {
498
+ for (const stop of [...unsettled]) stop();
417
499
  for (const s of sockets) s.destroy();
418
500
  server.close(() => resolve(undefined));
419
501
  }),
@@ -445,6 +527,18 @@ function decodePlainPath(path) {
445
527
  return plain ? decoded : null;
446
528
  }
447
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
+
448
542
  /** Whether a parsed body is a JSON object, not a list, a bare value or nothing. */
449
543
  function isObject(value) {
450
544
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -486,10 +580,18 @@ function callerHolds(headers, keyHeaders, key) {
486
580
  * @param {ProviderProfile} profile
487
581
  * @param {(n: number) => void} add called with each newly counted amount
488
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
489
586
  */
490
- function meter(r, profile, add, named) {
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
+ });
491
592
  const reduce = profile.usageReducer();
492
593
  const take = (answer) => {
594
+ judge(answer);
493
595
  const model = profile.answeringModel(answer);
494
596
  if (model !== undefined) named(model);
495
597
  const n = reduce(answer);
@@ -516,9 +618,14 @@ function meter(r, profile, add, named) {
516
618
  let body = r;
517
619
  if (encoding !== "identity" && encoding !== "") {
518
620
  const make = decoders[encoding];
519
- if (!make) return;
621
+ if (!make) {
622
+ // An encoding it cannot read: nothing to count.
623
+ r.on("end", done);
624
+ r.resume();
625
+ return;
626
+ }
520
627
  const decoder = make();
521
- decoder.on("error", () => {});
628
+ decoder.on("error", done);
522
629
  r.on("data", (chunk) => decoder.write(chunk));
523
630
  r.on("end", () => decoder.end());
524
631
  body = decoder;
@@ -537,7 +644,7 @@ function meter(r, profile, add, named) {
537
644
  pending += text;
538
645
  const lines = pending.split(/\r?\n/);
539
646
  pending = lines.pop() ?? "";
540
- if (pending.length > MAX_LINE) pending = "";
647
+ if (pending.length > (profile.maxStreamLine ?? MAX_LINE)) pending = "";
541
648
  for (const line of lines) {
542
649
  if (line.startsWith("data:") && profile.streamHint.test(line)) parse(line.slice(5).trim());
543
650
  }
@@ -545,5 +652,6 @@ function meter(r, profile, add, named) {
545
652
  body.on("end", () => {
546
653
  if (!stream && !overflow) parse(pending);
547
654
  else if (stream && pending.startsWith("data:")) parse(pending.slice(5).trim());
655
+ done();
548
656
  });
549
657
  }
@@ -1,18 +1,24 @@
1
1
  // The `anthropic` provider profile (ADR 0023): everything the model proxy's
2
2
  // core (../core.mjs) knows about the Anthropic API. The real credential goes
3
3
  // in as `x-api-key` for an API key, or, on the subscription path (#375), as
4
- // the bearer value of `Authorization` and nothing else, so every other header
5
- // Claude Code sends (its OAuth beta header among them) passes on as it is and
6
- // need not be known here.
4
+ // the bearer value of `Authorization`.
7
5
  //
8
- // What it lets through is only what the sandboxed Claude Code needs:
6
+ // Claude Code calls through it, and so does opencode on an `anthropic/` model.
7
+ // What it lets through is only what those sandboxed harnesses need:
9
8
  // - only `POST` to the Messages API's own two paths (FORWARDED);
9
+ // - only the request headers the pinned harnesses' Messages API calls send
10
+ // and need (FORWARDED_HEADERS), on either of Claude Code's credential paths;
11
+ // any other is dropped;
10
12
  // - only a body with nothing that makes the model API act outside the sandbox:
11
13
  // no server-side tool (any `tools` entry but a client tool with an
12
14
  // `input_schema`), no `mcp_servers` or `container`, and no content that
13
15
  // names a file or URL for the API to fetch. Every beta feature that acts on
14
16
  // the API's side is turned on through one of those body fields, so the beta
15
- // header itself passes as Claude Code sent it.
17
+ // header itself passes as the harness sent it;
18
+ // - and no body field that raises the price per token (#627): fast mode
19
+ // (`speed`), US-only inference (`inference_geo`) or a premium
20
+ // `service_tier`. The token cap limits how many tokens a run spends, not
21
+ // what each costs.
16
22
 
17
23
  /** The model API every forwarded request goes to. */
18
24
  export const MODEL_API = "https://api.anthropic.com";
@@ -60,10 +66,32 @@ export const COUNTED_USAGE = Object.freeze([
60
66
  const API_KEY_HEADER = "x-api-key";
61
67
 
62
68
  /**
63
- * The request headers never passed on, beyond the hop-by-hop and standard
64
- * credential headers the core drops itself. Every other header passes.
69
+ * The request headers passed on, by name: those the pinned Claude Code (on both
70
+ * credential paths) and the pinned opencode send on their Messages API calls,
71
+ * that the calls need. The core drops the hop-by-hop and credential headers,
72
+ * `host` and `cookie` before this list is asked, and writes `content-length`
73
+ * and `accept-encoding` itself. Their other headers are dropped: Claude Code's
74
+ * SDK telemetry (`x-stainless-*`) and `anthropic-dangerous-direct-browser-access`,
75
+ * which only a browser's request needs; opencode's tracing (`b3`,
76
+ * `traceparent`) and its own client, project and session headers
77
+ * (`x-opencode-*`, `x-session-id`, `x-session-affinity`), which the Messages
78
+ * API does not read. The captures each name came from, and the reason for
79
+ * each, are recorded on #555; a bump of either pin captures them again.
65
80
  */
66
- const NEVER_FORWARDED = Object.freeze([API_KEY_HEADER]);
81
+ export const FORWARDED_HEADERS = Object.freeze([
82
+ // The body's type, and the answer's: JSON, or a stream.
83
+ "accept",
84
+ "content-type",
85
+ // The API version, and the betas Claude Code's body uses (the OAuth beta on
86
+ // the subscription path among them).
87
+ "anthropic-beta",
88
+ "anthropic-version",
89
+ // Who is calling, as the harness names itself (`x-app` and the session id are
90
+ // Claude Code's).
91
+ "user-agent",
92
+ "x-app",
93
+ "x-claude-code-session-id",
94
+ ]);
67
95
 
68
96
  /** The Messages API's error type for each of the proxy's own refusals. */
69
97
  const ERROR_TYPES = Object.freeze({
@@ -80,9 +108,17 @@ const FETCHED_SOURCE = new Set(["url", "file"]);
80
108
  /** Content blocks that hand the model API something to act on outside the request. */
81
109
  const ACTING_BLOCK = new Set(["container_upload", "mcp_tool_use", "server_tool_use"]);
82
110
 
111
+ /** The `inference_geo` values billed at the ordinary price: `"us"` bills at 1.1x. */
112
+ const INFERENCE_GEOS = Object.freeze(["global"]);
113
+
114
+ /** The service tiers that bill a token at its ordinary price, as the `openai` profile's check. */
115
+ const SERVICE_TIERS = Object.freeze(["auto", "standard_only"]);
116
+
83
117
  /**
84
118
  * Why a Messages API request body is refused, or null. The body must be a
85
- * JSON object; no `mcp_servers` or `container`; every `tools` entry a
119
+ * JSON object; no `mcp_servers` or `container`; no `speed` (fast mode has no
120
+ * documented standard value, so any is refused), no `inference_geo` but
121
+ * `"global"` and no `service_tier` but `auto` or `standard_only`; every `tools` entry a
86
122
  * client tool (no `type`, or `custom`, and an `input_schema` object), so no
87
123
  * server-side tool; and nothing in `messages` or `system` that names a URL
88
124
  * or a file for the API to fetch, or an upload or server-side call.
@@ -96,6 +132,14 @@ export function requestRefusal(body) {
96
132
  for (const key of ["mcp_servers", "container"]) {
97
133
  if (Object.hasOwn(body, key)) return `a request with ${key}`;
98
134
  }
135
+ if (Object.hasOwn(body, "speed")) return "a premium speed";
136
+ if (Object.hasOwn(body, "inference_geo") && !INFERENCE_GEOS.includes(body.inference_geo)) {
137
+ return "a premium inference_geo";
138
+ }
139
+ const tier = body.service_tier;
140
+ if (tier !== undefined && tier !== null && !SERVICE_TIERS.includes(tier)) {
141
+ return "a premium service tier";
142
+ }
99
143
  if (Object.hasOwn(body, "tools")) {
100
144
  if (!Array.isArray(body.tools)) return "tools that are not a list";
101
145
  for (const tool of body.tools) {
@@ -174,7 +218,7 @@ export const anthropic = Object.freeze({
174
218
  subscription: (credential) => ["authorization", `Bearer ${credential}`],
175
219
  }),
176
220
  keyHeaders: Object.freeze([API_KEY_HEADER]),
177
- forwardsHeader: (header) => !NEVER_FORWARDED.includes(header),
221
+ forwardsHeader: (header) => FORWARDED_HEADERS.includes(header),
178
222
  inScope: (path, decoded) =>
179
223
  MODEL_PATH.test(path) && MODEL_PATH.test(decoded) && !UNCOUNTED_PATH.test(decoded),
180
224
  routes: ROUTES,