@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,241 @@
1
+ // The `anthropic` provider profile (ADR 0023): everything the model proxy's
2
+ // core (../core.mjs) knows about the Anthropic API. The real credential goes
3
+ // in as `x-api-key` for an API key, or, on the subscription path (#375), as
4
+ // the bearer value of `Authorization`.
5
+ //
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:
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;
12
+ // - only a body with nothing that makes the model API act outside the sandbox:
13
+ // no server-side tool (any `tools` entry but a client tool with an
14
+ // `input_schema`), no `mcp_servers` or `container`, and no content that
15
+ // names a file or URL for the API to fetch. Every beta feature that acts on
16
+ // the API's side is turned on through one of those body fields, so the beta
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.
22
+
23
+ /** The model API every forwarded request goes to. */
24
+ export const MODEL_API = "https://api.anthropic.com";
25
+
26
+ /** A path must be under /v1/ and not UNCOUNTED_PATH before it is matched against ROUTES. */
27
+ const MODEL_PATH = /^\/v1\//;
28
+
29
+ /**
30
+ * Paths whose spend an answer's `usage` would not show (a batch is billed
31
+ * later, outside this run), so the token cap could not hold: refused.
32
+ */
33
+ const UNCOUNTED_PATH = /^\/v1\/(messages\/batches|complete)(\/|$)/i;
34
+
35
+ /** The call that spends tokens, and the one that only counts them. */
36
+ const ROUTES = Object.freeze([
37
+ Object.freeze({ method: "POST", path: "/v1/messages", spends: true }),
38
+ Object.freeze({ method: "POST", path: "/v1/messages/count_tokens", spends: false }),
39
+ ]);
40
+
41
+ /** The only requests forwarded, by decoded path, and only as `POST`: Claude Code's Messages API calls. */
42
+ export const FORWARDED = Object.freeze(ROUTES.map((r) => r.path));
43
+
44
+ /** The largest request body the proxy reads, judges and forwards. */
45
+ export const MAX_REQUEST = 32 * 1024 * 1024;
46
+
47
+ /**
48
+ * A request's input tokens, estimated from its body for its reservation:
49
+ * one token per this many bytes, which is fewer bytes than any ordinary text
50
+ * takes per token, so the estimate is high rather than low.
51
+ */
52
+ const BYTES_PER_TOKEN = 2;
53
+
54
+ /** How deep the body's messages and system blocks are walked; deeper is refused. */
55
+ const MAX_DEPTH = 64;
56
+
57
+ /** The `usage` fields the cap counts: every kind of token billed. */
58
+ export const COUNTED_USAGE = Object.freeze([
59
+ "input_tokens",
60
+ "cache_creation_input_tokens",
61
+ "cache_read_input_tokens",
62
+ "output_tokens",
63
+ ]);
64
+
65
+ /** The header an API key goes in, as the caller sends its key and the proxy writes the real one. */
66
+ const API_KEY_HEADER = "x-api-key";
67
+
68
+ /**
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.
80
+ */
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
+ ]);
95
+
96
+ /** The Messages API's error type for each of the proxy's own refusals. */
97
+ const ERROR_TYPES = Object.freeze({
98
+ unauthenticated: "authentication_error",
99
+ cap_reached: "permission_error",
100
+ invalid_request: "invalid_request_error",
101
+ too_large: "request_too_large",
102
+ busy: "rate_limit_error",
103
+ });
104
+
105
+ /** Content sources that make the model API fetch something: a URL, or a file it holds. */
106
+ const FETCHED_SOURCE = new Set(["url", "file"]);
107
+
108
+ /** Content blocks that hand the model API something to act on outside the request. */
109
+ const ACTING_BLOCK = new Set(["container_upload", "mcp_tool_use", "server_tool_use"]);
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
+
117
+ /**
118
+ * Why a Messages API request body is refused, or null. The body must be 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
122
+ * client tool (no `type`, or `custom`, and an `input_schema` object), so no
123
+ * server-side tool; and nothing in `messages` or `system` that names a URL
124
+ * or a file for the API to fetch, or an upload or server-side call.
125
+ * @param {unknown} body
126
+ * @returns {string | null} a short, fixed reason, never the sandbox's text
127
+ */
128
+ export function requestRefusal(body) {
129
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
130
+ return "a body that is not a JSON object";
131
+ }
132
+ for (const key of ["mcp_servers", "container"]) {
133
+ if (Object.hasOwn(body, key)) return `a request with ${key}`;
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
+ }
143
+ if (Object.hasOwn(body, "tools")) {
144
+ if (!Array.isArray(body.tools)) return "tools that are not a list";
145
+ for (const tool of body.tools) {
146
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
147
+ return "a tool that is not an object";
148
+ }
149
+ if (tool.type !== undefined && tool.type !== "custom") return "a server-side tool";
150
+ if (tool.input_schema === null || typeof tool.input_schema !== "object") {
151
+ return "a tool with no input_schema";
152
+ }
153
+ }
154
+ }
155
+ for (const key of ["messages", "system"]) {
156
+ if (!Object.hasOwn(body, key)) continue;
157
+ const why = contentRefusal(body[key], 0);
158
+ if (why) return why;
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /** @param {unknown} value @param {number} depth @returns {string | null} */
164
+ function contentRefusal(value, depth) {
165
+ if (value === null || typeof value !== "object") return null;
166
+ if (depth > MAX_DEPTH) return "content nested too deeply";
167
+ if (Array.isArray(value)) {
168
+ for (const item of value) {
169
+ const why = contentRefusal(item, depth + 1);
170
+ if (why) return why;
171
+ }
172
+ return null;
173
+ }
174
+ if (typeof value.type === "string" && ACTING_BLOCK.has(value.type)) {
175
+ return `a ${value.type} block`;
176
+ }
177
+ if (Object.hasOwn(value, "file_id")) return "a file reference";
178
+ const source = value.source;
179
+ if (source && typeof source === "object" && FETCHED_SOURCE.has(source.type)) {
180
+ return `a ${source.type} source`;
181
+ }
182
+ for (const child of Object.values(value)) {
183
+ const why = contentRefusal(child, depth + 1);
184
+ if (why) return why;
185
+ }
186
+ return null;
187
+ }
188
+
189
+ /**
190
+ * The `usage` of one answer, each token counted once: each kind in
191
+ * COUNTED_USAGE, from a JSON body or from a stream's `message_start` and
192
+ * `message_delta` events. A stream's usage is cumulative, so each kind counts
193
+ * its highest value once.
194
+ * @returns {(answer: any) => number} the tokens the body or event newly reports
195
+ */
196
+ function usageReducer() {
197
+ const seen = Object.fromEntries(COUNTED_USAGE.map((k) => [k, 0]));
198
+ return (answer) => {
199
+ const usage = answer?.usage ?? answer?.message?.usage;
200
+ if (!usage || typeof usage !== "object") return 0;
201
+ let added = 0;
202
+ for (const key of COUNTED_USAGE) {
203
+ const n = usage[key];
204
+ if (typeof n === "number" && Number.isFinite(n) && n > seen[key]) {
205
+ added += n - seen[key];
206
+ seen[key] = n;
207
+ }
208
+ }
209
+ return added;
210
+ };
211
+ }
212
+
213
+ /** @type {Readonly<import("../core.mjs").ProviderProfile>} */
214
+ export const anthropic = Object.freeze({
215
+ upstream: MODEL_API,
216
+ credentialKinds: Object.freeze({
217
+ "api-key": (credential) => [API_KEY_HEADER, credential],
218
+ subscription: (credential) => ["authorization", `Bearer ${credential}`],
219
+ }),
220
+ keyHeaders: Object.freeze([API_KEY_HEADER]),
221
+ forwardsHeader: (header) => FORWARDED_HEADERS.includes(header),
222
+ inScope: (path, decoded) =>
223
+ MODEL_PATH.test(path) && MODEL_PATH.test(decoded) && !UNCOUNTED_PATH.test(decoded),
224
+ routes: ROUTES,
225
+ refusals: Object.freeze({
226
+ scope: "only the model API's /v1/ paths",
227
+ route: "only POST to the Messages API",
228
+ }),
229
+ maxRequestBytes: MAX_REQUEST,
230
+ requestRefusal,
231
+ inputEstimate: (body) => Math.ceil(body.length / BYTES_PER_TOKEN),
232
+ declaredLimit: (body) => body.max_tokens,
233
+ errorBody: (kind, message) => ({
234
+ type: "error",
235
+ error: { type: ERROR_TYPES[kind], message },
236
+ }),
237
+ streamHint: /"(usage|model)"/,
238
+ // A JSON body names its model, and so does a stream's `message_start`.
239
+ answeringModel: (answer) => answer?.model ?? answer?.message?.model,
240
+ usageReducer,
241
+ });
@@ -0,0 +1,311 @@
1
+ // The `gemini-api` provider profile (ADR 0023): everything the model proxy's
2
+ // core (../core.mjs) knows about the Gemini API. The real key goes in as
3
+ // `x-goog-api-key`, and only the request headers Gemini CLI's client sends
4
+ // (Antigravity CLI's client is the same SDK's) pass on: a project header from the sandbox would pick what the real key
5
+ // bills to.
6
+ //
7
+ // What it lets through is only what the sandboxed Gemini CLI or Antigravity
8
+ // CLI needs:
9
+ // - only `POST` to a model's `generateContent`, `streamGenerateContent` and
10
+ // `countTokens`, the model in the path, with no query string but a stream's
11
+ // `alt=sse`. So the API's `key=` parameter, which would carry a key, never
12
+ // goes on;
13
+ // - only a body with nothing that makes the API act outside the sandbox: only
14
+ // the fields the CLI sends, at every level the API would read one, so no
15
+ // server-side tool (Google Search, URL context, code execution) and no file
16
+ // or URL for the API to fetch passes, under either of the two spellings the
17
+ // API takes a field name in; one answer, of text; and a token count of
18
+ // contents alone.
19
+ //
20
+ // The body sent on is the one judged, written out again, with an output limit
21
+ // where a spending request declared none.
22
+
23
+ /** The model API every forwarded request goes to. */
24
+ export const MODEL_API = "https://generativelanguage.googleapis.com";
25
+
26
+ /** A model's method path: the model's id is the one segment before the colon. */
27
+ const method = (name) => new RegExp(`^/v1beta/models/[A-Za-z0-9][A-Za-z0-9._-]*:${name}$`);
28
+
29
+ const ROUTES = Object.freeze([
30
+ // A stream's answer is read as it comes only as server-sent events.
31
+ Object.freeze({
32
+ method: "POST",
33
+ pattern: method("streamGenerateContent"),
34
+ query: "alt=sse",
35
+ spends: true,
36
+ }),
37
+ Object.freeze({ method: "POST", pattern: method("generateContent"), query: "", spends: true }),
38
+ Object.freeze({ method: "POST", pattern: method("countTokens"), query: "", spends: false }),
39
+ ]);
40
+
41
+ /** The largest request body the proxy reads, judges and forwards. */
42
+ export const MAX_REQUEST = 32 * 1024 * 1024;
43
+
44
+ /** The longest line of a stream the meter reads: an event holds a whole tool call. */
45
+ const MAX_STREAM_LINE = 32 * 1024 * 1024;
46
+
47
+ /** As the `anthropic` profile: fewer bytes per token than ordinary text takes. */
48
+ const BYTES_PER_TOKEN = 2;
49
+
50
+ // A request that declares no output limit is given one: written into the body
51
+ // sent on, so the API holds the answer to what the cap reserves for it. The
52
+ // API refuses a limit above the model's own ceiling, so it goes by the model.
53
+
54
+ /** The output ceiling of the Gemini 2.5 models and later. */
55
+ export const OUTPUT_CEILING = 65_536;
56
+
57
+ /** The limit for any other model, which every model that answers with tools takes. */
58
+ export const UNKNOWN_MODEL_OUTPUT = 8_192;
59
+
60
+ const CEILING_MODEL = /\/gemini-(2\.5|[3-9])[A-Za-z0-9._-]*:/;
61
+
62
+ /** The request headers passed on, by name. */
63
+ const FORWARDED_HEADERS = Object.freeze([
64
+ "accept",
65
+ "content-type",
66
+ "user-agent",
67
+ "x-goog-api-client",
68
+ ]);
69
+
70
+ /** The error status and code for each of the proxy's own refusals. */
71
+ const ERRORS = Object.freeze({
72
+ unauthenticated: [401, "UNAUTHENTICATED"],
73
+ cap_reached: [403, "PERMISSION_DENIED"],
74
+ invalid_request: [400, "INVALID_ARGUMENT"],
75
+ too_large: [413, "INVALID_ARGUMENT"],
76
+ busy: [429, "RESOURCE_EXHAUSTED"],
77
+ });
78
+
79
+ /** The body fields passed on. `cachedContent`, which names what the API holds, is not one. */
80
+ export const BODY_FIELDS = Object.freeze([
81
+ "contents",
82
+ "generationConfig",
83
+ "safetySettings",
84
+ "systemInstruction",
85
+ "toolConfig",
86
+ "tools",
87
+ ]);
88
+
89
+ /** The generation settings passed on: none that makes an answer cost more than its limit says. */
90
+ export const GENERATION_SETTINGS = Object.freeze([
91
+ "candidateCount",
92
+ "frequencyPenalty",
93
+ "maxOutputTokens",
94
+ "mediaResolution",
95
+ "presencePenalty",
96
+ "responseJsonSchema",
97
+ "responseMimeType",
98
+ "responseModalities",
99
+ "responseSchema",
100
+ "seed",
101
+ "stopSequences",
102
+ "temperature",
103
+ "thinkingConfig",
104
+ "topK",
105
+ "topP",
106
+ ]);
107
+
108
+ /** The parts passed on: text, bytes the request holds, and the client's own calls. */
109
+ const PART_FIELDS = Object.freeze([
110
+ "functionCall",
111
+ "functionResponse",
112
+ "inlineData",
113
+ "text",
114
+ "thought",
115
+ "thoughtSignature",
116
+ ]);
117
+
118
+ /** A function response's fields: its `parts` hold content, so they are judged. */
119
+ const RESPONSE_FIELDS = Object.freeze([
120
+ "id",
121
+ "name",
122
+ "parts",
123
+ "response",
124
+ "scheduling",
125
+ "willContinue",
126
+ ]);
127
+
128
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
129
+ const only = (value, fields) => Object.keys(value).every((key) => fields.includes(key));
130
+
131
+ /** @param {unknown} tools @returns {string | null} */
132
+ function toolsRefusal(tools) {
133
+ if (!Array.isArray(tools)) return "tools that are not a list";
134
+ for (const tool of tools) {
135
+ if (!isObject(tool)) return "a tool that is not an object";
136
+ // A function is the client's to run. Every other kind of tool, the API runs.
137
+ if (!only(tool, ["functionDeclarations"])) return "a server-side tool";
138
+ const declared = tool.functionDeclarations;
139
+ if (declared !== undefined && !Array.isArray(declared)) return "tools that are not a list";
140
+ }
141
+ return null;
142
+ }
143
+
144
+ /** @param {unknown} part @returns {string | null} */
145
+ function partRefusal(part) {
146
+ if (!isObject(part)) return "a part that is not an object";
147
+ if (Object.hasOwn(part, "fileData") || Object.hasOwn(part, "file_data")) {
148
+ return "a file or URL for the model API to fetch";
149
+ }
150
+ if (!only(part, PART_FIELDS)) return "a part the sandbox does not send";
151
+ const response = part.functionResponse;
152
+ if (response === undefined) return null;
153
+ if (!isObject(response) || !only(response, RESPONSE_FIELDS)) {
154
+ return "a part the sandbox does not send";
155
+ }
156
+ return response.parts === undefined ? null : partsRefusal(response.parts);
157
+ }
158
+
159
+ /** @param {unknown} parts @returns {string | null} */
160
+ function partsRefusal(parts) {
161
+ if (!Array.isArray(parts)) return "parts that are not a list";
162
+ for (const part of parts) {
163
+ const why = partRefusal(part);
164
+ if (why) return why;
165
+ }
166
+ return null;
167
+ }
168
+
169
+ /** @param {unknown} content @returns {string | null} */
170
+ function contentRefusal(content) {
171
+ if (!isObject(content)) return "a content that is not an object";
172
+ if (!only(content, ["parts", "role"])) return "a content field the sandbox does not send";
173
+ return content.parts === undefined ? null : partsRefusal(content.parts);
174
+ }
175
+
176
+ /** @param {unknown} config @returns {string | null} */
177
+ function generationRefusal(config) {
178
+ if (!isObject(config) || !only(config, GENERATION_SETTINGS)) {
179
+ return "a generation setting the sandbox does not send";
180
+ }
181
+ const { candidateCount, maxOutputTokens, responseModalities } = config;
182
+ if (candidateCount !== undefined && candidateCount !== 1) return "more than one answer";
183
+ if (
184
+ responseModalities !== undefined &&
185
+ !(Array.isArray(responseModalities) && responseModalities.every((m) => m === "TEXT"))
186
+ ) {
187
+ return "an answer that is not text";
188
+ }
189
+ if (
190
+ maxOutputTokens !== undefined &&
191
+ !(Number.isSafeInteger(maxOutputTokens) && maxOutputTokens > 0)
192
+ ) {
193
+ return "an output limit that is not a positive whole number";
194
+ }
195
+ return null;
196
+ }
197
+
198
+ /**
199
+ * Why a request body, a JSON object, is refused on `route`, or null.
200
+ * @param {Record<string, unknown>} body
201
+ * @param {{ route: { spends: boolean } }} on
202
+ * @returns {string | null} a short, fixed reason, never the sandbox's text
203
+ */
204
+ export function requestRefusal(body, { route }) {
205
+ if (!only(body, route.spends ? BODY_FIELDS : ["contents"])) {
206
+ return "a request field the sandbox does not send";
207
+ }
208
+ const { contents, systemInstruction, tools, toolConfig, generationConfig } = body;
209
+ if (contents !== undefined) {
210
+ if (!Array.isArray(contents)) return "contents that are not a list";
211
+ for (const content of contents) {
212
+ const why = contentRefusal(content);
213
+ if (why) return why;
214
+ }
215
+ }
216
+ if (systemInstruction !== undefined) {
217
+ const why = contentRefusal(systemInstruction);
218
+ if (why) return why;
219
+ }
220
+ if (tools !== undefined) {
221
+ const why = toolsRefusal(tools);
222
+ if (why) return why;
223
+ }
224
+ if (
225
+ toolConfig !== undefined &&
226
+ !(isObject(toolConfig) && only(toolConfig, ["functionCallingConfig"]))
227
+ ) {
228
+ return "a tool setting the sandbox does not send";
229
+ }
230
+ return generationConfig === undefined ? null : generationRefusal(generationConfig);
231
+ }
232
+
233
+ /** A spending request's body, with an output limit where it declared none. */
234
+ function withLimit(body, { path, route }) {
235
+ if (!route.spends || body.generationConfig?.maxOutputTokens !== undefined) return body;
236
+ const maxOutputTokens = CEILING_MODEL.test(path) ? OUTPUT_CEILING : UNKNOWN_MODEL_OUTPUT;
237
+ return { ...body, generationConfig: { ...body.generationConfig, maxOutputTokens } };
238
+ }
239
+
240
+ /**
241
+ * The `usageMetadata` of one answer, each token counted once: its total, which
242
+ * holds the prompt (the cached tokens among it), the tool-use prompt, the
243
+ * thoughts and the answer; else those four parts. A stream's events repeat a
244
+ * running total, so only its highest value counts.
245
+ * @returns {(answer: any) => number} the tokens the body or event newly reports
246
+ */
247
+ function usageReducer() {
248
+ let seen = 0;
249
+ const count = (n) => (typeof n === "number" && Number.isFinite(n) && n > 0 ? n : 0);
250
+ return (answer) => {
251
+ const usage = answer?.usageMetadata;
252
+ if (!usage || typeof usage !== "object") return 0;
253
+ const total =
254
+ count(usage.totalTokenCount) ||
255
+ count(usage.promptTokenCount) +
256
+ count(usage.toolUsePromptTokenCount) +
257
+ count(usage.thoughtsTokenCount) +
258
+ count(usage.candidatesTokenCount);
259
+ if (total <= seen) return 0;
260
+ const added = total - seen;
261
+ seen = total;
262
+ return added;
263
+ };
264
+ }
265
+
266
+ /**
267
+ * Whether an answer says the API does not accept the key, beside a 401 or 403:
268
+ * a mistyped or expired one is answered `400`, its reason `API_KEY_INVALID`.
269
+ * @param {number} status @param {any} answer one error, or a list of them
270
+ */
271
+ function refusesCredential(status, answer) {
272
+ if (status !== 400) return false;
273
+ return [answer]
274
+ .flat()
275
+ .some(
276
+ (one) =>
277
+ Array.isArray(one?.error?.details) &&
278
+ one.error.details.some((detail) => detail?.reason === "API_KEY_INVALID"),
279
+ );
280
+ }
281
+
282
+ /** @type {Readonly<import("../core.mjs").ProviderProfile>} */
283
+ export const geminiApi = Object.freeze({
284
+ upstream: MODEL_API,
285
+ credentialKinds: Object.freeze({
286
+ "api-key": (credential) => ["x-goog-api-key", credential],
287
+ }),
288
+ keyHeaders: Object.freeze(["x-goog-api-key"]),
289
+ forwardsHeader: (header) => FORWARDED_HEADERS.includes(header),
290
+ inScope: (path, decoded) => path === decoded && decoded.startsWith("/v1beta/"),
291
+ routes: ROUTES,
292
+ rewrite: withLimit,
293
+ refusals: Object.freeze({
294
+ scope: "only the model API's /v1beta/ paths",
295
+ route:
296
+ "only POST to a model's generateContent, streamGenerateContent (with alt=sse) or countTokens, with no other query string",
297
+ }),
298
+ maxRequestBytes: MAX_REQUEST,
299
+ maxStreamLine: MAX_STREAM_LINE,
300
+ requestRefusal,
301
+ refusesCredential,
302
+ inputEstimate: (body) => Math.ceil(body.length / BYTES_PER_TOKEN),
303
+ declaredLimit: (body) => body.generationConfig?.maxOutputTokens,
304
+ errorBody: (kind, message) => {
305
+ const [code, status] = ERRORS[kind];
306
+ return { error: { code, message, status } };
307
+ },
308
+ streamHint: /"(usageMetadata|modelVersion)"/,
309
+ answeringModel: (answer) => answer?.modelVersion,
310
+ usageReducer,
311
+ });