@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,327 @@
1
+ // The `openai` provider profile (ADR 0023): everything the model proxy's core
2
+ // (../core.mjs) knows about the OpenAI API. The real key goes in as the bearer
3
+ // value of `Authorization`, and only the request headers Codex CLI sends pass
4
+ // on: an organization or project header from the sandbox would pick what the
5
+ // real key bills to.
6
+ //
7
+ // What it lets through is only what the sandboxed Codex CLI needs:
8
+ // - only `POST /v1/responses`, with no query string;
9
+ // - only a body with nothing that makes the API act outside the sandbox: only
10
+ // the fields Codex CLI sends; `store` set to false, since the API keeps a
11
+ // request that says nothing; no premium service tier; every declared tool a
12
+ // client tool (a function, a custom tool, a namespace of those, or a tool
13
+ // search the client runs), wherever it is declared; only the input items
14
+ // Codex CLI sends, none naming something the API holds or ran; and no
15
+ // content that names a file or URL for the API to fetch.
16
+ //
17
+ // The body sent on is the one judged, written out again, with an output limit
18
+ // where the request declared none.
19
+
20
+ /** The model API every forwarded request goes to. */
21
+ export const MODEL_API = "https://api.openai.com";
22
+
23
+ /** The Responses API's own path, which alone spends tokens, and alone is forwarded. */
24
+ export const RESPONSES_PATH = "/v1/responses";
25
+
26
+ const ROUTES = Object.freeze([
27
+ Object.freeze({ method: "POST", path: RESPONSES_PATH, spends: true }),
28
+ ]);
29
+
30
+ /** The largest request body the proxy reads, judges and forwards. */
31
+ export const MAX_REQUEST = 32 * 1024 * 1024;
32
+
33
+ /**
34
+ * The longest line of a stream the meter reads. A stream's closing event holds
35
+ * the whole answer beside its usage, so a line far over the core's default is
36
+ * ordinary, and one left unread would leave its tokens uncounted.
37
+ */
38
+ const MAX_STREAM_LINE = 32 * 1024 * 1024;
39
+
40
+ /** As the `anthropic` profile: fewer bytes per token than ordinary text takes. */
41
+ const BYTES_PER_TOKEN = 2;
42
+
43
+ // A request that declares no output limit, as Codex CLI's declare none, is
44
+ // given one: written into the body sent on, so the API holds the answer to what
45
+ // the cap reserves for it. The API refuses a limit above the model's own
46
+ // ceiling, so it goes by the model.
47
+
48
+ /** The output ceiling of the models in CEILING_MODELS. */
49
+ export const OUTPUT_CEILING = 128_000;
50
+
51
+ /**
52
+ * The limit for any other model: low enough for every model that serves the
53
+ * Responses API with tools, so a model the profile does not know still runs,
54
+ * with shorter answers.
55
+ */
56
+ export const UNKNOWN_MODEL_OUTPUT = 16_384;
57
+
58
+ /**
59
+ * The models known to take OUTPUT_CEILING: those the pinned Codex CLI bundles
60
+ * (`codex debug models --bundled`). A pin bump updates the list.
61
+ */
62
+ export const CEILING_MODELS = Object.freeze([
63
+ "codex-auto-review",
64
+ "gpt-5.5",
65
+ "gpt-5.6-luna",
66
+ "gpt-5.6-sol",
67
+ "gpt-5.6-terra",
68
+ "gpt-6-astra",
69
+ "gpt-6-luna",
70
+ "gpt-6-sol",
71
+ "gpt-6.1-sol",
72
+ "gpt-6.1-terra",
73
+ "gpt-6.2-astra",
74
+ "gpt-6.2-sol",
75
+ "gpt-daybreak-blue-latest",
76
+ "gpt-daybreak-red-latest",
77
+ ]);
78
+
79
+ /** A model id's date, as a snapshot of a model is named. */
80
+ const SNAPSHOT = /-\d{4}-\d{2}-\d{2}$/;
81
+
82
+ /** The output limit for a request naming `model` and declaring none. */
83
+ const outputLimit = (model) =>
84
+ typeof model === "string" && CEILING_MODELS.includes(model.replace(SNAPSHOT, ""))
85
+ ? OUTPUT_CEILING
86
+ : UNKNOWN_MODEL_OUTPUT;
87
+
88
+ /** How deep the body's input is walked; deeper is refused. */
89
+ const MAX_DEPTH = 64;
90
+
91
+ /** The request headers passed on, by name, beside those that start with one of the prefixes. */
92
+ const FORWARDED_HEADERS = Object.freeze([
93
+ "accept",
94
+ "content-type",
95
+ "originator",
96
+ "session-id",
97
+ "thread-id",
98
+ "user-agent",
99
+ "x-client-request-id",
100
+ ]);
101
+ const FORWARDED_PREFIXES = Object.freeze([
102
+ "x-codex-",
103
+ "x-openai-internal-codex-",
104
+ "x-openai-subagent",
105
+ ]);
106
+
107
+ /** The error type for each of the proxy's own refusals. */
108
+ const ERROR_TYPES = Object.freeze({
109
+ unauthenticated: "authentication_error",
110
+ cap_reached: "permission_error",
111
+ invalid_request: "invalid_request_error",
112
+ too_large: "invalid_request_error",
113
+ busy: "rate_limit_error",
114
+ });
115
+
116
+ /**
117
+ * The body fields passed on: those Codex CLI sends. Any other is refused, so a
118
+ * field that names something the API holds (`prompt`, `conversation`,
119
+ * `previous_response_id`), or one the API adds later, never passes unjudged.
120
+ */
121
+ export const BODY_FIELDS = Object.freeze([
122
+ "client_metadata",
123
+ "include",
124
+ "input",
125
+ "instructions",
126
+ "max_output_tokens",
127
+ "model",
128
+ "parallel_tool_calls",
129
+ "prompt_cache_key",
130
+ "reasoning",
131
+ "service_tier",
132
+ "store",
133
+ "stream",
134
+ "stream_options",
135
+ "text",
136
+ "tool_choice",
137
+ "tools",
138
+ ]);
139
+
140
+ /** The service tiers that bill a token at its ordinary price. */
141
+ const SERVICE_TIERS = Object.freeze(["auto", "default"]);
142
+
143
+ /**
144
+ * The input items passed on: those Codex CLI sends, each its own or a call a
145
+ * client ran. An item with no `type` is passed only as a message.
146
+ */
147
+ export const INPUT_ITEMS = Object.freeze([
148
+ "additional_tools",
149
+ "agent_message",
150
+ "compaction",
151
+ "compaction_trigger",
152
+ "configuration_update",
153
+ "context_compaction",
154
+ "custom_tool_call",
155
+ "custom_tool_call_output",
156
+ "function_call",
157
+ "function_call_output",
158
+ "local_shell_call",
159
+ "message",
160
+ "reasoning",
161
+ "tool_search_call",
162
+ "tool_search_output",
163
+ ]);
164
+
165
+ /** Fields that name content for the API to fetch: any value but `data:` is a fetch. */
166
+ const FETCHED_URL = Object.freeze(["image_url", "audio_url", "file_url"]);
167
+
168
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
169
+
170
+ /**
171
+ * Why a list of declared tools is refused, or null: each must be one the
172
+ * client runs.
173
+ * @param {unknown} tools @param {number} depth @returns {string | null}
174
+ */
175
+ function toolsRefusal(tools, depth) {
176
+ if (!Array.isArray(tools)) return "tools that are not a list";
177
+ if (depth > MAX_DEPTH) return "content nested too deeply";
178
+ for (const tool of tools) {
179
+ if (!isObject(tool)) return "a tool that is not an object";
180
+ if (tool.type === "function" || tool.type === "custom") continue;
181
+ if (tool.type === "tool_search" && tool.execution === "client") continue;
182
+ if (tool.type !== "namespace") return "a server-side tool";
183
+ const why = toolsRefusal(tool.tools, depth + 1);
184
+ if (why) return why;
185
+ }
186
+ return null;
187
+ }
188
+
189
+ /** @param {unknown} value @param {number} depth @returns {string | null} */
190
+ function contentRefusal(value, depth) {
191
+ if (value === null || typeof value !== "object") return null;
192
+ if (depth > MAX_DEPTH) return "content nested too deeply";
193
+ if (Array.isArray(value)) {
194
+ for (const item of value) {
195
+ const why = contentRefusal(item, depth + 1);
196
+ if (why) return why;
197
+ }
198
+ return null;
199
+ }
200
+ if (value.file_id !== undefined && value.file_id !== null) return "a file reference";
201
+ for (const key of FETCHED_URL) {
202
+ const url = value[key];
203
+ if (url === undefined || url === null) continue;
204
+ if (typeof url !== "string" || !url.startsWith("data:")) return "a URL to fetch";
205
+ }
206
+ for (const [key, child] of Object.entries(value)) {
207
+ // A declaration of tools is judged as one: a tool's schema may well name a
208
+ // property `file_id`.
209
+ const why = key === "tools" ? toolsRefusal(child, depth + 1) : contentRefusal(child, depth + 1);
210
+ if (why) return why;
211
+ }
212
+ return null;
213
+ }
214
+
215
+ /**
216
+ * Why the body's input is refused, or null: a string, or a list of the items
217
+ * passed on, with nothing in them to fetch.
218
+ * @param {unknown} input @returns {string | null}
219
+ */
220
+ function inputRefusal(input) {
221
+ if (input === undefined || typeof input === "string") return null;
222
+ if (!Array.isArray(input)) return "an input that is neither text nor a list";
223
+ for (const item of input) {
224
+ if (!isObject(item)) return "an input item that is not an object";
225
+ const message = item.type === undefined && "role" in item && "content" in item;
226
+ if (!message && !INPUT_ITEMS.includes(item.type)) {
227
+ return "an input item the sandbox does not send";
228
+ }
229
+ if (item.type?.startsWith("tool_search_") && (item.execution ?? "client") !== "client") {
230
+ return "a tool search the model API runs";
231
+ }
232
+ }
233
+ return contentRefusal(input, 0);
234
+ }
235
+
236
+ /**
237
+ * Why a Responses API request body, a JSON object, is refused, or null.
238
+ * @param {Record<string, unknown>} body
239
+ * @returns {string | null} a short, fixed reason, never the sandbox's text
240
+ */
241
+ export function requestRefusal(body) {
242
+ if (!Object.keys(body).every((key) => BODY_FIELDS.includes(key))) {
243
+ return "a request field the sandbox does not send";
244
+ }
245
+ if (body.store !== false) return "a request the model API would keep (store is not false)";
246
+ const tier = body.service_tier;
247
+ if (tier !== undefined && tier !== null && !SERVICE_TIERS.includes(tier)) {
248
+ return "a premium service tier";
249
+ }
250
+ const limit = body.max_output_tokens;
251
+ if (limit !== undefined && limit !== null && !(Number.isSafeInteger(limit) && limit > 0)) {
252
+ return "an output limit that is not a positive whole number";
253
+ }
254
+ const instructions = body.instructions;
255
+ if (instructions !== undefined && instructions !== null && typeof instructions !== "string") {
256
+ return "instructions that are not text";
257
+ }
258
+ if (Object.hasOwn(body, "tools")) {
259
+ const why = toolsRefusal(body.tools, 0);
260
+ if (why) return why;
261
+ }
262
+ // An object here would name one tool, a server-side one among them.
263
+ if (body.tool_choice !== undefined && typeof body.tool_choice !== "string") {
264
+ return "a tool choice that names a tool";
265
+ }
266
+ return inputRefusal(body.input);
267
+ }
268
+
269
+ /**
270
+ * The `usage` of one answer, each token counted once: its input and its output
271
+ * tokens, from a JSON body or from a stream's closing event. The cached and
272
+ * the reasoning tokens are parts of those two, and so is the total. A figure
273
+ * repeated counts its highest value once.
274
+ * @returns {(answer: any) => number} the tokens the body or event newly reports
275
+ */
276
+ function usageReducer() {
277
+ const seen = { input_tokens: 0, output_tokens: 0 };
278
+ return (answer) => {
279
+ const usage = answer?.usage ?? answer?.response?.usage;
280
+ if (!usage || typeof usage !== "object") return 0;
281
+ let added = 0;
282
+ for (const key of Object.keys(seen)) {
283
+ const n = usage[key];
284
+ if (typeof n === "number" && Number.isFinite(n) && n > seen[key]) {
285
+ added += n - seen[key];
286
+ seen[key] = n;
287
+ }
288
+ }
289
+ return added;
290
+ };
291
+ }
292
+
293
+ /** @type {Readonly<import("../core.mjs").ProviderProfile>} */
294
+ export const openai = Object.freeze({
295
+ upstream: MODEL_API,
296
+ credentialKinds: Object.freeze({
297
+ "api-key": (credential) => ["authorization", `Bearer ${credential}`],
298
+ }),
299
+ // The sandbox carries its caller key as a bearer value, which the core reads.
300
+ keyHeaders: Object.freeze([]),
301
+ forwardsHeader: (header) =>
302
+ FORWARDED_HEADERS.includes(header) ||
303
+ FORWARDED_PREFIXES.some((prefix) => header.startsWith(prefix)),
304
+ inScope: (path, decoded) => path === decoded && decoded.startsWith("/v1/"),
305
+ routes: ROUTES,
306
+ refusesQuery: true,
307
+ rewrite: (body) => ({
308
+ ...body,
309
+ max_output_tokens: body.max_output_tokens ?? outputLimit(body.model),
310
+ }),
311
+ refusals: Object.freeze({
312
+ scope: "only the model API's /v1/ paths",
313
+ route: "only POST to the Responses API, with no query string",
314
+ }),
315
+ maxRequestBytes: MAX_REQUEST,
316
+ maxStreamLine: MAX_STREAM_LINE,
317
+ requestRefusal,
318
+ inputEstimate: (body) => Math.ceil(body.length / BYTES_PER_TOKEN),
319
+ declaredLimit: (body) => body.max_output_tokens,
320
+ errorBody: (kind, message) => ({
321
+ error: { message, type: ERROR_TYPES[kind], code: kind },
322
+ }),
323
+ streamHint: /"(usage|model)"/,
324
+ // A JSON body names its model, and so does each of a stream's `response` events.
325
+ answeringModel: (answer) => answer?.model ?? answer?.response?.model,
326
+ usageReducer,
327
+ });
@@ -0,0 +1,110 @@
1
+ // The stub model's `anthropic` dialect (ADR 0031): how a Messages API request
2
+ // reads and how an answer is written, whole or as a stream. The stub itself
3
+ // (../stub.mjs) holds the script; this holds the wire shapes. Node core only
4
+ // (ADR 0001).
5
+
6
+ /** The tokens every answer reports, so the proxy has usage to count. */
7
+ const USAGE = Object.freeze({ input_tokens: 10, output_tokens: 5 });
8
+
9
+ /** A tool result's text: a string, or its text blocks joined. */
10
+ function textOf(content) {
11
+ if (typeof content === "string") return content;
12
+ if (!Array.isArray(content)) return "";
13
+ return content.map((block) => (typeof block?.text === "string" ? block.text : "")).join("");
14
+ }
15
+
16
+ /** The Messages API answer's body for one turn. */
17
+ function message({ id, model, turn }) {
18
+ const content = turn.call
19
+ ? [{ type: "tool_use", id: turn.call.id, name: turn.call.name, input: turn.call.input }]
20
+ : [{ type: "text", text: turn.text }];
21
+ return {
22
+ id,
23
+ type: "message",
24
+ role: "assistant",
25
+ model,
26
+ content,
27
+ stop_reason: turn.call ? "tool_use" : "end_turn",
28
+ stop_sequence: null,
29
+ usage: { ...USAGE },
30
+ };
31
+ }
32
+
33
+ /** The same answer as the API's server-sent events. */
34
+ function stream(whole) {
35
+ const [block] = whole.content;
36
+ const isCall = block.type === "tool_use";
37
+ const events = [
38
+ [
39
+ "message_start",
40
+ {
41
+ message: {
42
+ ...whole,
43
+ content: [],
44
+ stop_reason: null,
45
+ usage: { input_tokens: USAGE.input_tokens, output_tokens: 1 },
46
+ },
47
+ },
48
+ ],
49
+ [
50
+ "content_block_start",
51
+ { index: 0, content_block: isCall ? { ...block, input: {} } : { type: "text", text: "" } },
52
+ ],
53
+ [
54
+ "content_block_delta",
55
+ {
56
+ index: 0,
57
+ delta: isCall
58
+ ? { type: "input_json_delta", partial_json: JSON.stringify(block.input) }
59
+ : { type: "text_delta", text: block.text },
60
+ },
61
+ ],
62
+ ["content_block_stop", { index: 0 }],
63
+ [
64
+ "message_delta",
65
+ {
66
+ delta: { stop_reason: whole.stop_reason, stop_sequence: null },
67
+ usage: { output_tokens: USAGE.output_tokens },
68
+ },
69
+ ],
70
+ ["message_stop", {}],
71
+ ];
72
+ return events
73
+ .map(([type, data]) => `event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`)
74
+ .join("");
75
+ }
76
+
77
+ /** @type {Readonly<import("../stub.mjs").StubDialect>} */
78
+ export const anthropicDialect = Object.freeze({
79
+ /** The tools a request declares. */
80
+ tools: (request) => request.tools,
81
+ /** The input a shell tool is called with: its command, and a timeout when it takes one. */
82
+ shellInput: (tool, command, timeoutMs) => ({
83
+ command,
84
+ ...(tool.input_schema?.properties?.timeout ? { timeout: timeoutMs } : {}),
85
+ }),
86
+ /** Every tool result the conversation holds. */
87
+ toolResults: (request) =>
88
+ (Array.isArray(request.messages) ? request.messages : [])
89
+ .flatMap((m) => (Array.isArray(m?.content) ? m.content : []))
90
+ .filter((block) => block?.type === "tool_result")
91
+ .map((block) => ({
92
+ id: String(block.tool_use_id),
93
+ text: textOf(block.content),
94
+ isError: block.is_error === true,
95
+ })),
96
+ /** The answer to a POST of `path`, or null for a path this dialect does not speak. */
97
+ answer({ path, request, id, turn }) {
98
+ if (path === "/v1/messages/count_tokens") {
99
+ return json({ input_tokens: USAGE.input_tokens });
100
+ }
101
+ if (path !== "/v1/messages") return null;
102
+ const whole = message({ id, model: String(request.model ?? "stub-model"), turn: turn() });
103
+ if (request.stream !== true) return json(whole);
104
+ return { type: "text/event-stream", body: stream(whole) };
105
+ },
106
+ });
107
+
108
+ function json(body) {
109
+ return { type: "application/json", body: JSON.stringify(body) };
110
+ }
@@ -0,0 +1,178 @@
1
+ // The stub model's `gemini-api` dialect (ADR 0031): how a Gemini API request
2
+ // reads and how an answer is written, whole or as a stream, in the shapes the
3
+ // pinned Gemini CLI speaks. The stub itself (../stub.mjs) holds the script;
4
+ // this holds the wire shapes. Node core only (ADR 0001).
5
+ //
6
+ // The model and the method are in the path. Gemini CLI declares its tools as
7
+ // function declarations, prefixes a call's id with the tool's name when it
8
+ // sends the result back, and wraps its shell's output in an
9
+ // `untrusted_context` element with `Output:` before it and the command's
10
+ // status after it.
11
+ //
12
+ // Antigravity CLI speaks the same API. Its shell tool is `run_command`, which
13
+ // takes the command as `CommandLine`, reports it with its exit status before
14
+ // its output, cuts the middle out of a long output, and after ten seconds at
15
+ // most puts a command in the background, reporting it later in a message of
16
+ // its own. So its command goes to bash encoded and the output comes back
17
+ // compressed, and a command still in the background is pending.
18
+ //
19
+ // Headless, Gemini CLI denies a command that repeats a flag, a URL or a path
20
+ // outside the workspace seen in an earlier tool's output, even with every tool
21
+ // approved. So each of the script's commands is handed to the shell encoded:
22
+ // what the live suite probes is the sandbox's Guards, not that filter, which
23
+ // anything the agent runs can pass the same way.
24
+
25
+ import { gunzipSync } from "node:zlib";
26
+
27
+ /** The tokens every answer reports, so the proxy has usage to count. */
28
+ const USAGE = Object.freeze({
29
+ promptTokenCount: 10,
30
+ candidatesTokenCount: 5,
31
+ totalTokenCount: 15,
32
+ });
33
+
34
+ /** Antigravity CLI's shell tool. */
35
+ const AGY_SHELL = "run_command";
36
+
37
+ /** The longest Antigravity CLI waits on a command before it backgrounds it. */
38
+ const AGY_WAIT_MS = 10_000;
39
+
40
+ /** What Antigravity CLI says of a command it put in the background, with its task's id. */
41
+ const BACKGROUND = /^Tool is running as a background task with task id: (\S+)/;
42
+
43
+ /** A command's exit status, as Antigravity CLI reports it. */
44
+ const EXITED = /Command exited with code (\d+)\./;
45
+
46
+ /** A command's output, compressed, as `agyCommand` writes it. */
47
+ const PACKED = /<gz>([A-Za-z0-9+/=\s]*)<\/gz>/;
48
+
49
+ /** The most a command's output may unpack to. */
50
+ const MAX_UNPACKED = 10 * 1024 * 1024;
51
+
52
+ /** The bash line that runs `command`, writes its output compressed and keeps its status. */
53
+ const agyCommand = (command) =>
54
+ [
55
+ "printf '<gz>'",
56
+ `echo ${Buffer.from(command, "utf8").toString("base64")} | base64 -d | bash 2>&1 | gzip -9nc | base64 -w0`,
57
+ "status=${PIPESTATUS[2]}",
58
+ "printf '</gz>'",
59
+ "exit $status",
60
+ ].join("; ");
61
+
62
+ /** Every text part of the conversation. */
63
+ const texts = (request) =>
64
+ (Array.isArray(request.contents) ? request.contents : [])
65
+ .flatMap((content) => (Array.isArray(content?.parts) ? content.parts : []))
66
+ .map((part) => part?.text)
67
+ .filter((text) => typeof text === "string");
68
+
69
+ /** A `run_command` result: pending while its task has not been reported. */
70
+ function agyResult(request, { id, response }) {
71
+ const failed = typeof response?.error === "string";
72
+ let said = failed ? response.error : String(response?.output ?? "");
73
+ const task = BACKGROUND.exec(said)?.[1];
74
+ if (task !== undefined) {
75
+ const finished = `Task id "${task}" finished with result:`;
76
+ const report = texts(request).find((text) => text.includes(finished));
77
+ if (report === undefined) return { id: String(id), text: "", isError: false, pending: true };
78
+ said = report.slice(report.indexOf(finished) + finished.length);
79
+ }
80
+ const status = EXITED.exec(said)?.[1];
81
+ const packed = PACKED.exec(said)?.[1];
82
+ let text = said;
83
+ if (packed !== undefined) {
84
+ try {
85
+ text = gunzipSync(Buffer.from(packed, "base64"), {
86
+ maxOutputLength: MAX_UNPACKED,
87
+ }).toString("utf8");
88
+ } catch {
89
+ text = said;
90
+ }
91
+ }
92
+ return { id: String(id), text, isError: failed || (status ?? "0") !== "0" };
93
+ }
94
+
95
+ const PATH = /^\/v1beta\/models\/([^/:]+):(generateContent|streamGenerateContent|countTokens)$/;
96
+
97
+ /** What Gemini CLI appends to a shell's output, each on a line of its own. */
98
+ const STATUS = /\n(?:Error|Exit Code|Signal|Background PIDs|Process Group PGID): [^\n]*$/;
99
+
100
+ /** A shell result's text as the command printed it; any other text as it is. */
101
+ function printed(text) {
102
+ const wrapped = /^<untrusted_context[^>]*>\n([\s\S]*)\n<\/untrusted_context>$/.exec(text);
103
+ let inner = wrapped ? wrapped[1] : text;
104
+ inner = inner.replaceAll("&lt;/untrusted_context&gt;", "</untrusted_context>");
105
+ if (!inner.startsWith("Output: ")) return inner;
106
+ inner = inner.slice("Output: ".length);
107
+ while (STATUS.test(inner)) inner = inner.replace(STATUS, "");
108
+ return inner;
109
+ }
110
+
111
+ /** The function responses the conversation holds. */
112
+ const responses = (request) =>
113
+ (Array.isArray(request.contents) ? request.contents : [])
114
+ .flatMap((content) => (Array.isArray(content?.parts) ? content.parts : []))
115
+ .map((part) => part?.functionResponse)
116
+ .filter(Boolean);
117
+
118
+ /** @type {Readonly<import("../stub.mjs").StubDialect>} */
119
+ export const geminiApiDialect = Object.freeze({
120
+ /** The functions a request declares, each in the shape the stub picks a shell by. */
121
+ tools: (request) =>
122
+ (Array.isArray(request.tools) ? request.tools : [])
123
+ .flatMap((tool) => tool?.functionDeclarations ?? [])
124
+ .map((f) => {
125
+ const schema = f?.parametersJsonSchema ?? f?.parameters;
126
+ // The stub picks a shell by its `command` input.
127
+ return f?.name === AGY_SHELL && schema?.properties?.CommandLine
128
+ ? { name: f.name, input_schema: { properties: { command: { type: "string" } } } }
129
+ : { name: f?.name, input_schema: schema };
130
+ }),
131
+ /** What the shell tool is called with: the command, encoded, for bash to run. */
132
+ shellInput: (tool, command) =>
133
+ tool?.name === AGY_SHELL
134
+ ? {
135
+ CommandLine: agyCommand(command),
136
+ toolSummary: "Stub probe",
137
+ WaitMsBeforeAsync: AGY_WAIT_MS,
138
+ }
139
+ : { command: `echo ${Buffer.from(command, "utf8").toString("base64")} | base64 -d | bash` },
140
+ /** Every tool result the conversation holds, each by the id the stub gave its call. */
141
+ toolResults: (request) =>
142
+ responses(request).map(({ id, name, response }) => {
143
+ if (name === AGY_SHELL) return agyResult(request, { id, response });
144
+ const failed = typeof response?.error === "string";
145
+ return {
146
+ id: String(id).replace(new RegExp(`^${String(name).replace(/\W/g, "\\$&")}__`), ""),
147
+ // Gemini CLI's result is `output`; opencode's is `content`.
148
+ text: failed
149
+ ? response.error
150
+ : printed(String(response?.output ?? response?.content ?? "")),
151
+ isError: failed,
152
+ };
153
+ }),
154
+ /** The answer to a POST of `path`, or null for a path this dialect does not speak. */
155
+ answer({ path, request, turn }) {
156
+ const [, model, method] = PATH.exec(path) ?? [];
157
+ if (!model) return null;
158
+ if (method === "countTokens") return json({ totalTokens: USAGE.promptTokenCount });
159
+ // A side call that asks for JSON, as Gemini CLI's model router does, gets
160
+ // an empty object, which it reads as no choice of its own.
161
+ const asksJson = request.generationConfig?.responseMimeType === "application/json";
162
+ const next = asksJson && !request.tools ? { text: "{}" } : turn();
163
+ const part = next.call
164
+ ? { functionCall: { id: next.call.id, name: next.call.name, args: next.call.input } }
165
+ : { text: next.text };
166
+ const whole = {
167
+ candidates: [{ content: { role: "model", parts: [part] }, finishReason: "STOP", index: 0 }],
168
+ usageMetadata: USAGE,
169
+ modelVersion: model,
170
+ };
171
+ if (method === "generateContent") return json(whole);
172
+ return { type: "text/event-stream", body: `data: ${JSON.stringify(whole)}\r\n\r\n` };
173
+ },
174
+ });
175
+
176
+ function json(body) {
177
+ return { type: "application/json", body: JSON.stringify(body) };
178
+ }