hiveagents-runtime 0.1.0-beta.1 → 0.1.0-beta.3

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 (62) hide show
  1. package/README.md +9 -5
  2. package/dist/adapter-kit.d.ts +4 -4
  3. package/dist/adapter-kit.js +2 -1
  4. package/dist/{agent-D0HS38G3.d.ts → agent-Bj5YPrO7.d.ts} +2 -2
  5. package/dist/{agent-OLSXNGNN.js → agent-D6OXR7UF.js} +9 -8
  6. package/dist/{agent-readiness-V36OJME4.js → agent-readiness-KSGNKTGK.js} +3 -3
  7. package/dist/chunk-2RK74GCA.js +2397 -0
  8. package/dist/chunk-2RK74GCA.js.map +1 -0
  9. package/dist/chunk-6FIXXWNM.js +1 -0
  10. package/dist/{chunk-ALLOMOUN.js → chunk-DAXPAV2L.js} +2 -2
  11. package/dist/{chunk-3B3JW4U3.js → chunk-DQEMIGKC.js} +5 -5
  12. package/dist/{chunk-SRJUZJKV.js → chunk-G6JV7WV6.js} +2 -2
  13. package/dist/{chunk-SRJUZJKV.js.map → chunk-G6JV7WV6.js.map} +1 -1
  14. package/dist/{chunk-TIZKGD4R.js → chunk-RH5A5U7G.js} +2 -2
  15. package/dist/{chunk-DBFXFWQZ.js → chunk-RX3XZENU.js} +93 -93
  16. package/dist/chunk-RX3XZENU.js.map +1 -0
  17. package/dist/{chunk-2RUEC63U.js → chunk-TWGEYWMO.js} +2 -2
  18. package/dist/{chunk-GJ4FTDBJ.js → chunk-UZPDDQVJ.js} +6 -6
  19. package/dist/{chunk-COKYQUTK.js → chunk-WVT5SEKC.js} +2 -2
  20. package/dist/cli.js +9 -8
  21. package/dist/cli.js.map +1 -1
  22. package/dist/{errors-DgehLwqI.d.ts → errors-BNHvvjn9.d.ts} +1 -1
  23. package/dist/{execution-halt-CW0Oi9s9.d.ts → execution-halt-B8G0fOKS.d.ts} +1 -1
  24. package/dist/{execution-types-UJ6gAF48.d.ts → execution-types-ClYYqPQP.d.ts} +1 -1
  25. package/dist/hosted-runtime.d.ts +3 -3
  26. package/dist/hosted-runtime.js +5 -4
  27. package/dist/hosted-runtime.js.map +1 -1
  28. package/dist/index.d.ts +25 -8
  29. package/dist/index.js +16 -9
  30. package/dist/index.js.map +1 -1
  31. package/dist/orchestration/dynamic.d.ts +3 -3
  32. package/dist/orchestration/dynamic.js +4 -4
  33. package/dist/orchestration/index.d.ts +7 -7
  34. package/dist/orchestration/index.js +19 -13
  35. package/dist/orchestration/index.js.map +1 -1
  36. package/dist/orchestration/log.d.ts +4 -4
  37. package/dist/{provider-XCpWjJ6a.d.ts → provider-DX5Mf0uq.d.ts} +1 -1
  38. package/dist/routing/index.d.ts +6 -6
  39. package/dist/routing/index.js +9 -8
  40. package/dist/routing/index.js.map +1 -1
  41. package/dist/routing/learning/index.d.ts +5 -5
  42. package/dist/routing/learning/index.js +9 -8
  43. package/dist/routing/learning/index.js.map +1 -1
  44. package/dist/{runtime-C6Cu2fvw.d.ts → runtime-BSjrnxeF.d.ts} +2 -2
  45. package/dist/{runtime-Y72XJFFO.js → runtime-OISPXS4I.js} +6 -5
  46. package/dist/runtime-OISPXS4I.js.map +1 -0
  47. package/dist/{types-BBRKjIc7.d.ts → types-CIqkKXix.d.ts} +1 -1
  48. package/docs/releases/0.1.0-beta.3.md +13 -0
  49. package/package.json +3 -3
  50. package/dist/chunk-C2DN6KL4.js +0 -853
  51. package/dist/chunk-C2DN6KL4.js.map +0 -1
  52. package/dist/chunk-DBFXFWQZ.js.map +0 -1
  53. package/docs/releases/0.1.0-beta.1.md +0 -13
  54. /package/dist/{agent-OLSXNGNN.js.map → agent-D6OXR7UF.js.map} +0 -0
  55. /package/dist/{agent-readiness-V36OJME4.js.map → agent-readiness-KSGNKTGK.js.map} +0 -0
  56. /package/dist/{runtime-Y72XJFFO.js.map → chunk-6FIXXWNM.js.map} +0 -0
  57. /package/dist/{chunk-ALLOMOUN.js.map → chunk-DAXPAV2L.js.map} +0 -0
  58. /package/dist/{chunk-3B3JW4U3.js.map → chunk-DQEMIGKC.js.map} +0 -0
  59. /package/dist/{chunk-TIZKGD4R.js.map → chunk-RH5A5U7G.js.map} +0 -0
  60. /package/dist/{chunk-2RUEC63U.js.map → chunk-TWGEYWMO.js.map} +0 -0
  61. /package/dist/{chunk-GJ4FTDBJ.js.map → chunk-UZPDDQVJ.js.map} +0 -0
  62. /package/dist/{chunk-COKYQUTK.js.map → chunk-WVT5SEKC.js.map} +0 -0
@@ -0,0 +1,2397 @@
1
+ import {
2
+ boundedInteger,
3
+ captureIdentity,
4
+ createRequiredLogCapture,
5
+ field
6
+ } from "./chunk-J7VAYJKM.js";
7
+ import {
8
+ AdapterRegistry,
9
+ EXEC_TRANSPORT_TOKENS,
10
+ RUNTIME_ADAPTER_VERSION,
11
+ assertRespondPolicy,
12
+ snapshotProvider
13
+ } from "./chunk-G6JV7WV6.js";
14
+ import {
15
+ CodexExecAdapter,
16
+ ExecStreamPump,
17
+ assessCliCompatibility,
18
+ classifyClaudeFailure,
19
+ compatibilityModels,
20
+ isSafeSessionId,
21
+ numberValue,
22
+ parseObject,
23
+ resolveModel,
24
+ stringValue
25
+ } from "./chunk-TWGEYWMO.js";
26
+ import {
27
+ method,
28
+ object
29
+ } from "./chunk-EEUYQFCP.js";
30
+ import {
31
+ ExecDiscovery,
32
+ IncrementalLineDecoder,
33
+ confirmedUsageRetryAt,
34
+ guardJsonlFrames,
35
+ jsonlFrames,
36
+ readProviderRateLimits,
37
+ resolveProviderRateLimits
38
+ } from "./chunk-RX3XZENU.js";
39
+ import {
40
+ runProcess
41
+ } from "./chunk-7LDQKJKI.js";
42
+ import {
43
+ ExecutionHaltedError,
44
+ isExecutionHalted
45
+ } from "./chunk-NCNSHOF7.js";
46
+ import {
47
+ AbortError,
48
+ AmbiguousModelError,
49
+ OutputLimitError,
50
+ ProtocolError,
51
+ ProviderUnavailableError,
52
+ UnexpectedAuthSourceError,
53
+ UnknownModelError,
54
+ UnknownProviderError,
55
+ UnsupportedCapabilityError,
56
+ UnsupportedCliVersionError
57
+ } from "./chunk-TG7NTMTR.js";
58
+
59
+ // src/adapters/antigravity/compatibility.ts
60
+ var ANTIGRAVITY_VERSION = "1.5.3";
61
+ var REQUIRED_FLAGS = [
62
+ "--print",
63
+ "--model",
64
+ "--output-format",
65
+ "--conversation",
66
+ "--disable-slash-commands",
67
+ "--settings",
68
+ "--print-timeout"
69
+ ];
70
+ var EXEC_CAPABILITIES = Object.freeze({
71
+ turns: "supported",
72
+ resume: "supported",
73
+ messageDeltas: "supported",
74
+ tokenDeltas: "supported",
75
+ permissions: "partial",
76
+ forkWithPrompt: "unsupported",
77
+ forkWithoutPrompt: "unsupported",
78
+ structuredOutput: "unsupported",
79
+ cleanContext: "unsupported",
80
+ interactiveApprovals: "unsupported",
81
+ userInputDuringTurn: "unsupported",
82
+ steering: "unsupported",
83
+ inProcessTools: "unsupported",
84
+ processPersistence: "unsupported",
85
+ dynamicPermissions: "unsupported",
86
+ sessionInspection: "unsupported",
87
+ checkpointOrRollback: "unsupported",
88
+ subagentLifecycle: "unsupported",
89
+ subagentMessages: "unsupported",
90
+ subagentDeltas: "unsupported",
91
+ // protocol.ts has no refusal signal in the result event; turns never report refused.
92
+ refusalDetection: "unsupported",
93
+ images: "unsupported",
94
+ files: "unsupported"
95
+ });
96
+ function assessAntigravityCompatibility(version, help) {
97
+ const flags = /* @__PURE__ */ new Set();
98
+ for (const line of help.split(/\r?\n/)) {
99
+ if (!/^\s*-/.test(line)) continue;
100
+ for (const match of (line.trimStart().split(/ {2,}|\t/)[0] ?? "").matchAll(
101
+ /--[\w-]+/g
102
+ ))
103
+ flags.add(match[0]);
104
+ }
105
+ const missingFlags = REQUIRED_FLAGS.filter((flag) => !flags.has(flag));
106
+ const verified = version === ANTIGRAVITY_VERSION && missingFlags.length === 0;
107
+ return {
108
+ provider: "antigravity",
109
+ cliVersion: version,
110
+ transport: "exec",
111
+ evidence: verified ? "help-probe" : "unverified",
112
+ missingFlags,
113
+ features: Object.fromEntries(
114
+ Object.entries(EXEC_CAPABILITIES).map(([key, value]) => [
115
+ key,
116
+ (value === "supported" || value === "partial") && !verified ? "unsupported" : value
117
+ ])
118
+ ),
119
+ knownIssues: [
120
+ "Only explicit edit intent is supported; request-review is not a read-only sandbox.",
121
+ "Native configuration, grants and startup side effects remain active.",
122
+ "Authentication and model entitlement remain unverified until a turn succeeds."
123
+ ]
124
+ };
125
+ }
126
+
127
+ // src/adapters/antigravity/exec-adapter.ts
128
+ import { realpath } from "node:fs/promises";
129
+
130
+ // src/adapters/antigravity/auth.ts
131
+ async function inspectAntigravityAuth(_env) {
132
+ return {
133
+ authenticated: false,
134
+ state: "unknown",
135
+ source: "unknown"
136
+ };
137
+ }
138
+
139
+ // src/adapters/antigravity/session-id.ts
140
+ function isAntigravitySessionId(value) {
141
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
142
+ value
143
+ );
144
+ }
145
+
146
+ // src/adapters/antigravity/policy.ts
147
+ var EDIT_MARKER = "oar-antigravity-edit-request-review-v1";
148
+ function translateAntigravityContext(requested = {}) {
149
+ const profile = requested.profile ?? "native", memory = requested.memory ?? "inherit";
150
+ return {
151
+ args: [],
152
+ unsupported: [
153
+ ...profile === "native" ? [] : [`context.${profile}`],
154
+ ...memory === "inherit" ? [] : [`memory.${memory}`]
155
+ ],
156
+ warnings: [],
157
+ report: {
158
+ profile,
159
+ memory,
160
+ active: [
161
+ "user-settings",
162
+ "workspace-settings",
163
+ "native-instructions",
164
+ "provider-memory",
165
+ "native-mcp-configuration"
166
+ ],
167
+ inactive: [],
168
+ unavoidable: ["provider-session-storage"],
169
+ unknown: [
170
+ "startup-side-effects",
171
+ "native-config-trust",
172
+ "native-tool-grants"
173
+ ]
174
+ }
175
+ };
176
+ }
177
+ function translateAntigravityPermissions(requested, transport) {
178
+ const unsupported2 = [
179
+ ...transport === "exec" ? [] : ["transport.control"],
180
+ ...requested.mode === "edit" ? [] : [`permissions.${requested.mode}`],
181
+ ...requested.network === "deny" ? ["network.deny"] : [],
182
+ ...requested.additionalDirectories?.length ? ["additionalDirectories"] : [],
183
+ ...requested.minimumEnforcement ? [`minimumEnforcement.${requested.minimumEnforcement}`] : []
184
+ ];
185
+ return {
186
+ args: [EDIT_MARKER],
187
+ report: {
188
+ requested: { ...requested },
189
+ unsupported: unsupported2,
190
+ effective: {
191
+ filesystem: "native tool permissions; edits may be allowed by existing native grants; no OS sandbox",
192
+ network: "provider-default",
193
+ approvals: "native request-review; headless cannot answer permission requests",
194
+ enforcedBy: []
195
+ },
196
+ warnings: [
197
+ "Native startup, MCP configuration, persisted grants and provider storage remain active.",
198
+ "Request-review is provider behavior; existing native tool grants may still permit edits or commands."
199
+ ]
200
+ }
201
+ };
202
+ }
203
+
204
+ // src/adapters/antigravity/argv.ts
205
+ function buildAntigravityArgs(request) {
206
+ if (typeof request.prompt !== "string" || request.prompt.includes("\0"))
207
+ throw new TypeError("Invalid Antigravity prompt");
208
+ if (!["open", "one-shot", "resume"].includes(request.mode) || request.instructions !== void 0 || request.effort !== void 0 || request.outputSchema !== void 0 || request.contextArgs.length || request.permissionArgs.length !== 1 || request.permissionArgs[0] !== EDIT_MARKER || request.providerOptions && Object.keys(request.providerOptions).length)
209
+ throw new UnsupportedCapabilityError(
210
+ { provider: "antigravity", retryable: false },
211
+ "Antigravity exec requires native context and explicit edit/request-review policy; fork, instructions, effort, schema and custom options are unsupported"
212
+ );
213
+ if (!request.modelId || request.modelId.startsWith("-") || request.modelId.includes("\0"))
214
+ throw new TypeError("Invalid Antigravity model ID");
215
+ if (!Number.isFinite(request.timeoutMs) || request.timeoutMs <= 0 || !Number.isSafeInteger(request.maxOutputBytes) || request.maxOutputBytes <= 0)
216
+ throw new TypeError("Invalid Antigravity execution bounds");
217
+ const args = [
218
+ `--print=${request.prompt}`,
219
+ "--model",
220
+ request.modelId,
221
+ "--output-format",
222
+ "stream-json",
223
+ "--disable-slash-commands",
224
+ "--print-timeout",
225
+ `${request.timeoutMs}ms`,
226
+ "--settings",
227
+ JSON.stringify({ toolPermission: "request-review", agentMode: "" })
228
+ ];
229
+ if (request.mode === "resume") {
230
+ if (!isAntigravitySessionId(request.sessionId))
231
+ throw new TypeError(
232
+ "Resume requires an exact Antigravity conversation UUID"
233
+ );
234
+ args.push("--conversation", request.sessionId);
235
+ } else if (request.sessionId !== void 0)
236
+ throw new TypeError("Antigravity session ID requires resume mode");
237
+ return args;
238
+ }
239
+
240
+ // src/adapters/antigravity/protocol.ts
241
+ var object2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : void 0;
242
+ var count = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : void 0;
243
+ var SAFE_MACHINE_CODES = /* @__PURE__ */ new Set([
244
+ "401",
245
+ "429",
246
+ "UNAUTHENTICATED",
247
+ "AUTHENTICATION_REQUIRED",
248
+ "AUTHENTICATION_ERROR",
249
+ "AUTH_ERROR",
250
+ "LOGIN_REQUIRED",
251
+ "RESOURCE_EXHAUSTED",
252
+ "QUOTA_EXCEEDED",
253
+ "RATE_LIMIT",
254
+ "RATE_LIMITED",
255
+ "MODEL_NOT_FOUND",
256
+ "UNKNOWN_MODEL",
257
+ "MODEL_UNAVAILABLE",
258
+ "MODEL_CAPACITY",
259
+ "INTERNAL"
260
+ ]);
261
+ function classifyAntigravityError(error) {
262
+ const value = object2(error);
263
+ const code = String(value?.type ?? value?.code ?? error ?? "").toUpperCase();
264
+ const kind = /401|UNAUTHENTICATED|AUTHENTICATION|AUTH_ERROR|LOGIN_REQUIRED/.test(code) ? "not-authenticated" : /429|RESOURCE_EXHAUSTED|QUOTA|RATE_LIMIT/.test(code) ? "usage-limit" : /MODEL_?NOT_?FOUND|UNKNOWN_?MODEL/.test(code) ? "unknown-model" : /MODEL_?UNAVAILABLE|MODEL_?CAPACITY/.test(code) ? "model-unavailable" : "provider-unavailable";
265
+ return {
266
+ kind,
267
+ message: `Antigravity ${kind}`,
268
+ ...SAFE_MACHINE_CODES.has(code) ? { rawCode: code } : {}
269
+ };
270
+ }
271
+ var AntigravityProtocol = class {
272
+ constructor(expectedSession, identity = {}) {
273
+ this.expectedSession = expectedSession;
274
+ this.identity = identity;
275
+ }
276
+ expectedSession;
277
+ identity;
278
+ #native = [];
279
+ #events = [];
280
+ #steps = /* @__PURE__ */ new Map();
281
+ #session;
282
+ #text = "";
283
+ #hasText = false;
284
+ #terminal;
285
+ #failure;
286
+ #usage;
287
+ #finished;
288
+ #invalid(message) {
289
+ this.#failure = { kind: "protocol", message };
290
+ }
291
+ #provider(frame) {
292
+ this.#events.push({
293
+ type: "provider.event",
294
+ provider: "antigravity",
295
+ event: frame
296
+ });
297
+ }
298
+ #sameSession(id) {
299
+ return isAntigravitySessionId(id) && this.#session === id;
300
+ }
301
+ line(line) {
302
+ if (line.trim() === "") return [];
303
+ const start = this.#events.length;
304
+ let frame;
305
+ try {
306
+ frame = object2(JSON.parse(line));
307
+ } catch {
308
+ }
309
+ if (!frame || typeof frame.event !== "string") {
310
+ this.#invalid("Invalid Antigravity NDJSON frame");
311
+ return [];
312
+ }
313
+ this.#native.push(frame);
314
+ if (this.#terminal || this.#finished) {
315
+ this.#invalid("Antigravity emitted data after its terminal result");
316
+ return [];
317
+ }
318
+ if (frame.event === "init") {
319
+ const init = object2(frame.init);
320
+ if (this.#session !== void 0 || !isAntigravitySessionId(frame.conversation_id) || this.expectedSession !== void 0 && this.expectedSession !== frame.conversation_id || init?.permission_mode !== "request-review" || this.identity.model !== void 0 && init.model !== this.identity.model || this.identity.cwd !== void 0 && init.cwd !== this.identity.cwd) {
321
+ this.#invalid(
322
+ "Antigravity init identity or request-review permissions are invalid"
323
+ );
324
+ } else this.#session = frame.conversation_id;
325
+ } else if (frame.event === "step_update") {
326
+ const step = object2(frame.step_update);
327
+ if (!step || !this.#sameSession(step.conversation_id) || count(step.step_index) === void 0 || typeof step.step_type !== "string" || step.state !== "ACTIVE" && step.state !== "DONE") {
328
+ this.#invalid("Invalid Antigravity step identity or state");
329
+ return [];
330
+ }
331
+ const index = step.step_index, previous = this.#steps.get(index);
332
+ if (previous?.done || previous && previous.type !== step.step_type) {
333
+ this.#invalid(
334
+ "Antigravity replayed a completed step or changed its type"
335
+ );
336
+ return [];
337
+ }
338
+ this.#steps.set(index, {
339
+ type: step.step_type,
340
+ done: step.state === "DONE"
341
+ });
342
+ if (step.step_type === "agent_response") {
343
+ if (step.text_delta !== void 0 && typeof step.text_delta !== "string")
344
+ this.#invalid("Invalid Antigravity text delta");
345
+ else if (typeof step.text_delta === "string") {
346
+ this.#hasText = true;
347
+ this.#text += step.text_delta;
348
+ this.#events.push({ type: "message.delta", text: step.text_delta });
349
+ }
350
+ } else if (step.step_type === "tool") {
351
+ const tool = object2(step.tool_info), name = step.tool_name ?? tool?.name;
352
+ if (typeof name !== "string" || !name || tool?.name !== void 0 && tool.name !== name)
353
+ this.#invalid("Invalid Antigravity tool name");
354
+ else {
355
+ if (!previous)
356
+ this.#events.push({
357
+ type: "tool.started",
358
+ id: String(index),
359
+ name,
360
+ ...tool?.parameters === void 0 ? {} : { input: tool.parameters }
361
+ });
362
+ if (step.state === "DONE")
363
+ this.#events.push({
364
+ type: "tool.completed",
365
+ id: String(index),
366
+ ...tool?.output === void 0 ? {} : { output: tool.output },
367
+ ...tool?.error === void 0 ? {} : { error: tool.error }
368
+ });
369
+ else if (previous)
370
+ this.#events.push({
371
+ type: "tool.updated",
372
+ id: String(index),
373
+ update: tool ?? step
374
+ });
375
+ }
376
+ } else this.#provider(frame);
377
+ } else if (frame.event === "result") {
378
+ this.#terminal = frame;
379
+ const result = object2(frame.result);
380
+ const statuses = [
381
+ "SUCCESS",
382
+ "ERROR",
383
+ "CANCELED",
384
+ "INTERRUPTED",
385
+ "INVALID",
386
+ "WAITING",
387
+ "RUNNING"
388
+ ];
389
+ if (!result || !statuses.includes(String(result.status)) || typeof result.response !== "string")
390
+ this.#invalid("Invalid Antigravity terminal result");
391
+ else {
392
+ if (this.#session ? !this.#sameSession(result.conversation_id) : result.status === "SUCCESS" || result.conversation_id !== "" && result.conversation_id !== void 0 && !isAntigravitySessionId(result.conversation_id))
393
+ this.#invalid(
394
+ "Antigravity terminal identity changed or init is absent"
395
+ );
396
+ if (result.status === "SUCCESS") {
397
+ if (this.#hasText && this.#text !== result.response)
398
+ this.#invalid("Antigravity response contradicts streamed deltas");
399
+ if (!this.#hasText) this.#text = result.response;
400
+ if (result.error !== void 0 && result.error !== null && result.error !== "")
401
+ this.#invalid("Antigravity success includes an error");
402
+ } else if (this.#failure?.kind !== "protocol")
403
+ this.#failure = classifyAntigravityError(result.error);
404
+ const usage = object2(result.usage);
405
+ if (usage) {
406
+ this.#usage = { costMeaning: "unavailable" };
407
+ if (this.expectedSession === void 0 && result.num_turns === 1) {
408
+ const input = count(usage.input_tokens), output = count(usage.output_tokens), cached = count(usage.cache_read_tokens);
409
+ if (input !== void 0) this.#usage.inputTokens = input;
410
+ if (output !== void 0) this.#usage.outputTokens = output;
411
+ if (cached !== void 0) this.#usage.cachedInputTokens = cached;
412
+ }
413
+ }
414
+ }
415
+ } else this.#provider(frame);
416
+ return this.#events.slice(start);
417
+ }
418
+ get sessionId() {
419
+ return this.#session;
420
+ }
421
+ /** A protocol violation is terminal while the native process is still alive. */
422
+ get fatalProtocolFailure() {
423
+ return this.#failure?.kind === "protocol" ? { ...this.#failure } : void 0;
424
+ }
425
+ finish(code) {
426
+ if (this.#finished) return this.#finished;
427
+ if (!this.#terminal || !this.#session)
428
+ this.#failure ??= {
429
+ kind: "protocol",
430
+ message: "Antigravity ended without terminal result or init identity"
431
+ };
432
+ if (code !== 0)
433
+ this.#failure ??= {
434
+ kind: "provider-unavailable",
435
+ message: "Antigravity process did not exit successfully"
436
+ };
437
+ if (!this.#failure && [...this.#steps.values()].some((step) => !step.done))
438
+ this.#invalid("Antigravity ended with an unfinished step");
439
+ const completed = !this.#failure && code === 0 && object2(this.#terminal?.result)?.status === "SUCCESS";
440
+ if (completed)
441
+ this.#events.push({ type: "message.completed", text: this.#text });
442
+ return this.#finished = {
443
+ completed,
444
+ failed: !completed,
445
+ refused: false,
446
+ text: this.#text,
447
+ events: [...this.#events],
448
+ nativeEvents: [...this.#native],
449
+ ...this.#session === void 0 ? {} : { sessionId: this.#session },
450
+ ...this.#terminal === void 0 ? {} : { terminalEvent: this.#terminal },
451
+ ...this.#failure === void 0 ? {} : { failure: this.#failure },
452
+ ...this.#usage === void 0 ? {} : { usage: this.#usage }
453
+ };
454
+ }
455
+ };
456
+
457
+ // src/adapters/antigravity/streaming.ts
458
+ var StreamQueue = class {
459
+ #values = [];
460
+ #wake;
461
+ #ended = false;
462
+ #error;
463
+ push(value) {
464
+ if (this.#ended) return;
465
+ if (this.#values.length >= 1024)
466
+ throw new OutputLimitError(
467
+ { provider: "antigravity", retryable: false },
468
+ "Antigravity consumer exceeded the bounded stream queue"
469
+ );
470
+ this.#values.push(value);
471
+ this.#wake?.();
472
+ }
473
+ close(error) {
474
+ this.#ended = true;
475
+ this.#error = error;
476
+ this.#wake?.();
477
+ }
478
+ async *[Symbol.asyncIterator]() {
479
+ while (true) {
480
+ if (this.#values.length) {
481
+ yield this.#values.shift();
482
+ continue;
483
+ }
484
+ if (this.#ended) {
485
+ if (this.#error) throw this.#error;
486
+ return;
487
+ }
488
+ await new Promise((resolve2) => {
489
+ this.#wake = resolve2;
490
+ });
491
+ this.#wake = void 0;
492
+ }
493
+ }
494
+ };
495
+
496
+ // src/adapters/antigravity/exec-adapter.ts
497
+ var AntigravityExecAdapter = class {
498
+ id = "antigravity";
499
+ #runner;
500
+ #discovery;
501
+ #catalog;
502
+ constructor(options = {}) {
503
+ this.#runner = options.runner ?? runProcess;
504
+ const target = options.target ? {
505
+ command: options.target.command,
506
+ argsPrefix: [...options.target.argsPrefix]
507
+ } : void 0;
508
+ this.#discovery = new ExecDiscovery("agy", this.#runner, target);
509
+ this.#catalog = (options.modelCatalog ?? []).map((model) => ({
510
+ ...model,
511
+ aliases: [...model.aliases]
512
+ }));
513
+ }
514
+ detect(env, context) {
515
+ return this.#discovery.detect(env, context);
516
+ }
517
+ auth(env) {
518
+ return inspectAntigravityAuth(env);
519
+ }
520
+ async models() {
521
+ return this.#catalog.map((model) => ({
522
+ ...model,
523
+ aliases: [...model.aliases]
524
+ }));
525
+ }
526
+ async compatibility(env, version, context) {
527
+ if (context?.signal.aborted) throw context.signal.reason;
528
+ const target = this.#discovery.target(env);
529
+ if (!target) return void 0;
530
+ const result = await this.#runner({
531
+ command: target.command,
532
+ args: [...target.argsPrefix, "--help"],
533
+ cwd: process.cwd(),
534
+ env,
535
+ stdin: "",
536
+ timeoutMs: Math.max(1, Math.min(15e3, context?.remainingMs() ?? 15e3)),
537
+ ...context ? { signal: context.signal } : {},
538
+ maxOutputBytes: 256 * 1024
539
+ });
540
+ return assessAntigravityCompatibility(
541
+ version,
542
+ result.code === 0 ? `${result.stdout}
543
+ ${result.stderr}` : ""
544
+ );
545
+ }
546
+ async execute(request) {
547
+ let result;
548
+ for await (const item of this.stream(request))
549
+ if (item.kind === "result") result = item.result;
550
+ if (!result)
551
+ throw new ProviderUnavailableError(
552
+ { provider: "antigravity", retryable: false },
553
+ "Antigravity returned no result"
554
+ );
555
+ return result;
556
+ }
557
+ async *stream(request) {
558
+ if (request.signal?.aborted)
559
+ throw new AbortError({ provider: "antigravity", retryable: true });
560
+ const args = buildAntigravityArgs(request);
561
+ const expires = performance.now() + request.timeoutMs;
562
+ const context = {
563
+ signal: request.signal ?? AbortSignal.timeout(request.timeoutMs),
564
+ deadline: Date.now() + request.timeoutMs,
565
+ remainingMs: () => Math.max(0, Math.floor(expires - performance.now()))
566
+ };
567
+ const installation = await this.detect(request.env, context), target = this.#discovery.target(request.env);
568
+ if (!installation.installed || !target)
569
+ throw new ProviderUnavailableError(
570
+ { provider: "antigravity", retryable: false },
571
+ "Antigravity CLI unavailable"
572
+ );
573
+ if (installation.version !== ANTIGRAVITY_VERSION)
574
+ throw new UnsupportedCliVersionError(
575
+ "antigravity",
576
+ installation.version ?? "unknown",
577
+ { provider: "antigravity", retryable: false }
578
+ );
579
+ const compatibility = await this.compatibility(
580
+ request.env,
581
+ ANTIGRAVITY_VERSION,
582
+ context
583
+ );
584
+ if (!compatibility || compatibility.missingFlags.length)
585
+ throw new UnsupportedCliVersionError("antigravity", ANTIGRAVITY_VERSION, {
586
+ provider: "antigravity",
587
+ retryable: false
588
+ });
589
+ const cwd = await realpath(request.cwd);
590
+ if (request.signal?.aborted)
591
+ throw new AbortError({ provider: "antigravity", retryable: true });
592
+ const abort = new AbortController(), signal = request.signal ? AbortSignal.any([request.signal, abort.signal]) : abort.signal;
593
+ const queue = new StreamQueue();
594
+ const protocol = new AntigravityProtocol(
595
+ request.mode === "resume" ? request.sessionId : void 0,
596
+ { model: request.modelId, cwd }
597
+ );
598
+ const decoder = new IncrementalLineDecoder({
599
+ maxBufferedBytes: Math.min(request.maxOutputBytes, 1024 * 1024)
600
+ });
601
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
602
+ let announced, observed = false, stdoutBytes = 0;
603
+ const line = (raw) => {
604
+ const events = protocol.line(raw);
605
+ if (protocol.fatalProtocolFailure) {
606
+ throw new ProtocolError(
607
+ { provider: "antigravity", transport: "exec", retryable: false },
608
+ "Antigravity emitted an invalid native protocol frame"
609
+ );
610
+ }
611
+ if (protocol.sessionId && protocol.sessionId !== announced) {
612
+ announced = protocol.sessionId;
613
+ queue.push({ kind: "session", sessionId: announced });
614
+ }
615
+ for (const event of events) queue.push({ kind: "event", event });
616
+ };
617
+ const chunk = (value) => {
618
+ stdoutBytes += value.byteLength;
619
+ if (stdoutBytes > request.maxOutputBytes)
620
+ throw new OutputLimitError({
621
+ provider: "antigravity",
622
+ retryable: false
623
+ });
624
+ utf8.decode(value, { stream: true });
625
+ for (const raw of decoder.push(value)) line(raw);
626
+ };
627
+ const execution = Promise.resolve().then(
628
+ () => this.#runner({
629
+ command: target.command,
630
+ args: [...target.argsPrefix, ...args],
631
+ cwd,
632
+ env: request.env,
633
+ stdin: "",
634
+ timeoutMs: request.timeoutMs,
635
+ maxOutputBytes: request.maxOutputBytes,
636
+ signal,
637
+ onStdout: (value) => {
638
+ observed = true;
639
+ chunk(value);
640
+ }
641
+ })
642
+ ).then((outcome) => {
643
+ if (!observed && outcome.stdout) chunk(Buffer.from(outcome.stdout));
644
+ utf8.decode();
645
+ for (const raw of decoder.finish()) line(raw);
646
+ let result = protocol.finish(outcome.code);
647
+ if (result.failure?.kind === "protocol" && result.nativeEvents.length === 0 && outcome.stdout.trim() === "" && outcome.code !== 0) {
648
+ const exit = outcome.code === null ? "null" : String(outcome.code);
649
+ const authenticationRequired = /(?:^|\r?\n)(?:error:\s*)?(?:authentication required|UNAUTHENTICATED|LOGIN_REQUIRED)(?:[ \t]*(?:[.!:]|\r?\n|$))/i.test(
650
+ outcome.stderr.slice(0, 8192)
651
+ );
652
+ result = {
653
+ ...result,
654
+ failure: {
655
+ kind: authenticationRequired ? "not-authenticated" : "provider-unavailable",
656
+ rawCode: authenticationRequired ? "AUTHENTICATION_REQUIRED" : `EXIT_${exit}`,
657
+ message: `Antigravity ended before NDJSON initialization (exit=${exit}; stderrBytes=${Buffer.byteLength(outcome.stderr, "utf8")})`
658
+ }
659
+ };
660
+ }
661
+ for (const event of result.events)
662
+ if (event.type === "message.completed")
663
+ queue.push({ kind: "event", event });
664
+ queue.push({ kind: "result", result });
665
+ queue.close();
666
+ }).catch((error) => queue.close(error));
667
+ try {
668
+ yield* queue;
669
+ } finally {
670
+ abort.abort();
671
+ await execution;
672
+ }
673
+ }
674
+ };
675
+
676
+ // src/adapters/antigravity/registration.ts
677
+ var defaults = ["low", "medium", "high"].map(
678
+ (level) => ({
679
+ provider: "antigravity",
680
+ id: `gemini-3.8-flash-${level}`,
681
+ aliases: [`flash-${level}`],
682
+ source: "compatibility-catalog",
683
+ availability: "unverified"
684
+ })
685
+ );
686
+ var copy = (model) => ({
687
+ ...model,
688
+ aliases: [...model.aliases],
689
+ ...model.supportedEffort ? { supportedEffort: [...model.supportedEffort] } : {}
690
+ });
691
+ function createAntigravityCliProvider(options = {}) {
692
+ const runner = options.runner;
693
+ const catalog = (options.modelCatalog ?? defaults).map(copy);
694
+ for (const model of catalog)
695
+ if (model.provider !== "antigravity")
696
+ throw new TypeError("Antigravity catalog contains a foreign provider");
697
+ const executable = options.executable ? {
698
+ command: options.executable.command,
699
+ argsPrefix: [...options.executable.argsPrefix]
700
+ } : void 0;
701
+ const adapter = (target) => new AntigravityExecAdapter({
702
+ modelCatalog: catalog,
703
+ ...target ? { target } : {},
704
+ ...runner ? { runner } : {}
705
+ });
706
+ return {
707
+ apiVersion: 1,
708
+ id: "antigravity",
709
+ exec: {
710
+ adapter: adapter(executable),
711
+ token: "antigravityExecV1",
712
+ adapterVersion: RUNTIME_ADAPTER_VERSION,
713
+ withTarget: (target) => adapter(target)
714
+ },
715
+ modelCatalog: catalog.map(copy),
716
+ resolveModel(nativeId) {
717
+ if (!nativeId || nativeId.startsWith("-") || nativeId.includes("\0"))
718
+ throw new TypeError("Invalid Antigravity model identifier");
719
+ const found = catalog.find(
720
+ (model) => model.id === nativeId || model.aliases.includes(nativeId)
721
+ );
722
+ return found ? copy(found) : {
723
+ id: nativeId,
724
+ provider: "antigravity",
725
+ aliases: [],
726
+ source: "explicit",
727
+ availability: "unverified"
728
+ };
729
+ },
730
+ execCapabilities: EXEC_CAPABILITIES,
731
+ translateContext: translateAntigravityContext,
732
+ translatePermissions: translateAntigravityPermissions,
733
+ validateOptions(value, transport) {
734
+ const unsupported2 = translateAntigravityPermissions(
735
+ value.permissions ?? { mode: "analyze" },
736
+ transport
737
+ ).report.unsupported;
738
+ unsupported2.push(
739
+ ...translateAntigravityContext(value.context).unsupported
740
+ );
741
+ if (value.instructions !== void 0 || value.effort !== void 0)
742
+ unsupported2.push("privileged-instructions-effort");
743
+ if (Object.keys(value.providerOptions?.external?.antigravity ?? {}).length)
744
+ unsupported2.push("providerOptions.external.antigravity");
745
+ if (unsupported2.length)
746
+ throw new UnsupportedCapabilityError(
747
+ {
748
+ provider: "antigravity",
749
+ transport,
750
+ retryable: false,
751
+ sanitizedDiagnostics: { unsupported: unsupported2 }
752
+ },
753
+ "Antigravity cannot enforce requested options"
754
+ );
755
+ }
756
+ };
757
+ }
758
+
759
+ // src/adapters/gemini/compatibility.ts
760
+ var GEMINI_VERSION = "0.56.0";
761
+ var EXEC_CAPABILITIES2 = Object.freeze({
762
+ turns: "unverified",
763
+ resume: "unverified",
764
+ messageDeltas: "unverified",
765
+ tokenDeltas: "unverified",
766
+ permissions: "unverified",
767
+ forkWithPrompt: "unsupported",
768
+ forkWithoutPrompt: "unsupported",
769
+ structuredOutput: "unsupported",
770
+ cleanContext: "unsupported",
771
+ interactiveApprovals: "unsupported",
772
+ userInputDuringTurn: "unsupported",
773
+ steering: "unsupported",
774
+ inProcessTools: "unsupported",
775
+ processPersistence: "unsupported",
776
+ dynamicPermissions: "unsupported",
777
+ sessionInspection: "unsupported",
778
+ checkpointOrRollback: "unsupported",
779
+ subagentLifecycle: "unsupported",
780
+ subagentMessages: "unsupported",
781
+ subagentDeltas: "unsupported",
782
+ refusalDetection: "unsupported",
783
+ images: "unsupported",
784
+ files: "unsupported"
785
+ });
786
+ function assessGeminiCompatibility(version, help) {
787
+ const flags = /* @__PURE__ */ new Set();
788
+ for (const line of help.split(/\r?\n/)) {
789
+ if (!/^\s*-/.test(line)) continue;
790
+ for (const match of (line.trimStart().split(/ {2,}|\t/)[0] ?? "").matchAll(
791
+ /--[\w-]+/g
792
+ ))
793
+ flags.add(match[0]);
794
+ }
795
+ const missingFlags = [
796
+ "--prompt",
797
+ "--model",
798
+ "--output-format",
799
+ "--resume",
800
+ "--admin-policy",
801
+ "--extensions"
802
+ ].filter((f) => !flags.has(f));
803
+ const verified = version === GEMINI_VERSION && missingFlags.length === 0;
804
+ const features = { ...EXEC_CAPABILITIES2 };
805
+ return {
806
+ provider: "gemini",
807
+ cliVersion: version,
808
+ transport: "exec",
809
+ evidence: verified ? "help-probe" : "unverified",
810
+ features,
811
+ missingFlags,
812
+ knownIssues: [
813
+ "Analyze requires an empty system policy directory and temporary restrictive administrative settings.",
814
+ "Google OAuth does not establish subscription entitlement."
815
+ ]
816
+ };
817
+ }
818
+
819
+ // src/adapters/gemini/exec-adapter.ts
820
+ import { realpath as realpath3 } from "node:fs/promises";
821
+
822
+ // src/adapters/gemini/auth.ts
823
+ import { readFile as readFile2 } from "node:fs/promises";
824
+ import { homedir as homedir2 } from "node:os";
825
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2 } from "node:path";
826
+
827
+ // src/adapters/gemini/envelope.ts
828
+ import {
829
+ mkdtemp,
830
+ readFile,
831
+ readdir,
832
+ realpath as realpath2,
833
+ rm,
834
+ writeFile
835
+ } from "node:fs/promises";
836
+ import { dirname, isAbsolute, join } from "node:path";
837
+ import { homedir, tmpdir } from "node:os";
838
+
839
+ // src/adapters/gemini/policy.ts
840
+ var ANALYZE_MARKER = "oar-gemini-analyze-v1";
841
+ var READ_TOOLS = Object.freeze([
842
+ "glob",
843
+ "grep_search",
844
+ "list_directory",
845
+ "read_file"
846
+ ]);
847
+ var ANALYZE_POLICY = `[[rule]]
848
+ toolName = "*"
849
+ decision = "deny"
850
+ priority = 998
851
+
852
+ [[rule]]
853
+ toolName = [${READ_TOOLS.map((t) => JSON.stringify(t)).join(", ")}]
854
+ decision = "allow"
855
+ priority = 999
856
+ `;
857
+ function translateGeminiContext(requested = {}) {
858
+ const profile = requested.profile ?? "native", memory = requested.memory ?? "inherit";
859
+ const unsupported2 = [
860
+ ...profile === "native" ? [] : [`context.${profile}`],
861
+ ...memory === "inherit" ? [] : [`memory.${memory}`]
862
+ ];
863
+ return {
864
+ args: [],
865
+ unsupported: unsupported2,
866
+ warnings: [],
867
+ report: {
868
+ profile,
869
+ memory,
870
+ active: [
871
+ "user-settings",
872
+ "workspace-settings",
873
+ "GEMINI.md",
874
+ "provider-memory",
875
+ "native-mcp-configuration"
876
+ ],
877
+ inactive: ["hooks", "extensions"],
878
+ unavoidable: ["admin-managed-policy", "provider-session-storage"],
879
+ unknown: ["mcp-startup-side-effects"]
880
+ }
881
+ };
882
+ }
883
+ function translateGeminiPermissions(requested, transport) {
884
+ const unsupported2 = [];
885
+ if (transport !== "exec") unsupported2.push("transport.control");
886
+ if (requested.mode !== "analyze")
887
+ unsupported2.push(`permissions.${requested.mode}`);
888
+ if (requested.network === "deny") unsupported2.push("network.deny");
889
+ if (requested.additionalDirectories?.length)
890
+ unsupported2.push("additionalDirectories");
891
+ if (requested.minimumEnforcement && requested.minimumEnforcement !== "harness")
892
+ unsupported2.push(`minimumEnforcement.${requested.minimumEnforcement}`);
893
+ return {
894
+ args: [ANALYZE_MARKER],
895
+ report: {
896
+ requested: { ...requested },
897
+ effective: {
898
+ filesystem: "read tool allowlist; provider session storage remains writable; no OS sandbox",
899
+ network: "provider-default",
900
+ approvals: "deny-unapproved",
901
+ enforcedBy: ["harness"]
902
+ },
903
+ unsupported: unsupported2,
904
+ warnings: [
905
+ "Analyze restricts model tools; Gemini still writes its own session and telemetry state."
906
+ ]
907
+ }
908
+ };
909
+ }
910
+
911
+ // src/adapters/gemini/envelope.ts
912
+ var unsupported = (message) => {
913
+ throw new UnsupportedCapabilityError(
914
+ { provider: "gemini", transport: "exec", retryable: false },
915
+ message
916
+ );
917
+ };
918
+ var object3 = (x) => typeof x === "object" && x !== null && !Array.isArray(x) ? x : {};
919
+ function systemConfigDirectory(platform = process.platform) {
920
+ return platform === "darwin" ? "/Library/Application Support/GeminiCli" : platform === "win32" ? "C:\\ProgramData\\gemini-cli" : "/etc/gemini-cli";
921
+ }
922
+ async function assertNoSystemPolicies(directory = join(systemConfigDirectory(), "policies")) {
923
+ try {
924
+ if ((await readdir(directory)).some((name) => name.endsWith(".toml")))
925
+ unsupported(
926
+ "Gemini analyze overlay is ineffective when system policies exist"
927
+ );
928
+ } catch (error) {
929
+ if (error.code !== "ENOENT") throw error;
930
+ }
931
+ }
932
+ function restrictSystemSettings(original) {
933
+ const value = object3(original);
934
+ const tools = object3(value.tools);
935
+ const core = Array.isArray(tools.core) ? READ_TOOLS.filter((tool) => tools.core.includes(tool)) : [...READ_TOOLS];
936
+ return {
937
+ ...value,
938
+ hooksConfig: { ...object3(value.hooksConfig), enabled: false },
939
+ tools: { ...tools, core }
940
+ };
941
+ }
942
+ async function prepareAnalyzeEnvelope(env, cwd) {
943
+ await assertNoSystemPolicies();
944
+ const systemPath = env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? join(systemConfigDirectory(), "settings.json");
945
+ if (!isAbsolute(systemPath))
946
+ unsupported("Gemini system settings path must be absolute");
947
+ let original = {};
948
+ try {
949
+ original = JSON.parse(await readFile(systemPath, "utf8"));
950
+ } catch (error) {
951
+ if (error.code !== "ENOENT")
952
+ unsupported("Cannot safely preserve Gemini administrative settings");
953
+ }
954
+ if (typeof original !== "object" || original === null || Array.isArray(original))
955
+ unsupported("Gemini administrative settings must be a JSON object");
956
+ if (object3(original).adminPolicyPaths !== void 0)
957
+ unsupported(
958
+ "Existing custom administrative policies cannot be safely composed with Gemini analyze"
959
+ );
960
+ const home = env.GEMINI_CLI_HOME ?? env.HOME ?? env.USERPROFILE ?? homedir();
961
+ for (const path of [
962
+ env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join(dirname(systemPath), "system-defaults.json"),
963
+ join(home, ".gemini", "settings.json"),
964
+ join(cwd, ".gemini", "settings.json")
965
+ ]) {
966
+ let settings;
967
+ try {
968
+ settings = JSON.parse(await readFile(path, "utf8"));
969
+ } catch (error) {
970
+ if (error.code === "ENOENT") continue;
971
+ unsupported(
972
+ "Cannot safely inspect Gemini administrative policy settings"
973
+ );
974
+ }
975
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings))
976
+ unsupported(
977
+ "Gemini settings must be a JSON object to preserve policy authority"
978
+ );
979
+ if (Object.hasOwn(settings, "adminPolicyPaths"))
980
+ unsupported(
981
+ "Existing custom administrative policies cannot be safely composed with Gemini analyze"
982
+ );
983
+ }
984
+ const directory = await realpath2(
985
+ await mkdtemp(join(tmpdir(), "oar-gemini-"))
986
+ );
987
+ try {
988
+ const settingsPath = join(directory, "settings.json"), policyPath = join(directory, "analyze.toml");
989
+ await writeFile(
990
+ settingsPath,
991
+ JSON.stringify(restrictSystemSettings(original)),
992
+ { mode: 384 }
993
+ );
994
+ await writeFile(policyPath, ANALYZE_POLICY, { mode: 384 });
995
+ return {
996
+ args: ["--admin-policy", policyPath, "--extensions", "none"],
997
+ env: {
998
+ ...env,
999
+ GEMINI_CLI_SYSTEM_SETTINGS_PATH: settingsPath,
1000
+ GEMINI_CLI_SYSTEM_DEFAULTS_PATH: env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join(dirname(systemPath), "system-defaults.json")
1001
+ },
1002
+ cleanup: () => rm(directory, { recursive: true, force: true })
1003
+ };
1004
+ } catch (error) {
1005
+ await rm(directory, { recursive: true, force: true });
1006
+ throw error;
1007
+ }
1008
+ }
1009
+
1010
+ // src/adapters/gemini/auth.ts
1011
+ function authConfiguration(settings) {
1012
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings))
1013
+ throw new TypeError("Unknown settings shape");
1014
+ return settings.security?.auth ?? {};
1015
+ }
1016
+ function environmentMethod(env) {
1017
+ if (env.GOOGLE_GENAI_USE_GCA === "true") return "oauth-personal";
1018
+ if (env.GOOGLE_GENAI_USE_VERTEXAI === "true") return "vertex-ai";
1019
+ if (env.GOOGLE_GEMINI_BASE_URL) return "gateway";
1020
+ if (env.GEMINI_API_KEY) return "gemini-api-key";
1021
+ if (env.CLOUD_SHELL === "true" || env.GEMINI_CLI_USE_COMPUTE_ADC === "true")
1022
+ return "compute-default-credentials";
1023
+ return void 0;
1024
+ }
1025
+ function classifyMethod(method2) {
1026
+ switch (method2) {
1027
+ case "oauth-personal":
1028
+ return "oauth";
1029
+ case "gemini-api-key":
1030
+ return "api-key";
1031
+ case "vertex-ai":
1032
+ case "cloud-shell":
1033
+ case "compute-default-credentials":
1034
+ return "cloud-provider";
1035
+ default:
1036
+ return "unknown";
1037
+ }
1038
+ }
1039
+ async function inspectGeminiAuth(env) {
1040
+ let source = "unknown";
1041
+ const home = env.GEMINI_CLI_HOME ?? env.HOME ?? env.USERPROFILE ?? homedir2();
1042
+ const systemPath = env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? join2(systemConfigDirectory(), "settings.json");
1043
+ try {
1044
+ if (!isAbsolute2(systemPath))
1045
+ throw new TypeError("Unknown administrative settings path");
1046
+ let configured = {};
1047
+ for (const path of [
1048
+ env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join2(dirname2(systemPath), "system-defaults.json"),
1049
+ join2(home, ".gemini", "settings.json"),
1050
+ systemPath
1051
+ ]) {
1052
+ try {
1053
+ configured = {
1054
+ ...configured,
1055
+ ...authConfiguration(JSON.parse(await readFile2(path, "utf8")))
1056
+ };
1057
+ } catch (error) {
1058
+ if (error.code !== "ENOENT") throw error;
1059
+ }
1060
+ }
1061
+ const method2 = configured.selectedType || environmentMethod(env);
1062
+ if (!configured.useExternal && (!configured.enforcedType || configured.enforcedType === method2))
1063
+ source = classifyMethod(method2);
1064
+ try {
1065
+ const workspace = authConfiguration(
1066
+ JSON.parse(
1067
+ await readFile2(
1068
+ join2(process.cwd(), ".gemini", "settings.json"),
1069
+ "utf8"
1070
+ )
1071
+ )
1072
+ );
1073
+ if (Object.keys(workspace).length) source = "unknown";
1074
+ } catch (error) {
1075
+ if (error.code !== "ENOENT")
1076
+ source = "unknown";
1077
+ }
1078
+ } catch {
1079
+ }
1080
+ return {
1081
+ authenticated: false,
1082
+ state: "unknown",
1083
+ source,
1084
+ evidence: "local-configuration"
1085
+ };
1086
+ }
1087
+
1088
+ // src/adapters/gemini/session-id.ts
1089
+ function isGeminiSessionId(value) {
1090
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
1091
+ value
1092
+ );
1093
+ }
1094
+
1095
+ // src/adapters/gemini/argv.ts
1096
+ function buildGeminiArgs(request) {
1097
+ if (typeof request.prompt !== "string" || request.prompt.includes("\0"))
1098
+ throw new TypeError("Invalid Gemini prompt");
1099
+ if (request.prompt.trimStart().startsWith("/"))
1100
+ throw new UnsupportedCapabilityError(
1101
+ { provider: "gemini", retryable: false },
1102
+ "Gemini custom slash commands are outside analyze model-tool enforcement"
1103
+ );
1104
+ if (!["open", "one-shot", "resume"].includes(request.mode) || request.instructions !== void 0 || request.effort !== void 0 || request.outputSchema !== void 0)
1105
+ throw new UnsupportedCapabilityError(
1106
+ { provider: "gemini", retryable: false },
1107
+ "Gemini exec does not implement fork, privileged instructions, effort, or native schema"
1108
+ );
1109
+ if (request.contextArgs.length || request.permissionArgs.length !== 1 || request.permissionArgs[0] !== ANALYZE_MARKER)
1110
+ throw new UnsupportedCapabilityError(
1111
+ { provider: "gemini", retryable: false },
1112
+ "Gemini requires its restricted analyze policy envelope"
1113
+ );
1114
+ if (!request.modelId || request.modelId.includes("\0") || request.modelId.startsWith("-"))
1115
+ throw new TypeError("Invalid Gemini model ID");
1116
+ const args = [
1117
+ `--prompt=${request.prompt}`,
1118
+ "--model",
1119
+ request.modelId,
1120
+ "--output-format",
1121
+ "stream-json"
1122
+ ];
1123
+ if (request.mode === "resume") {
1124
+ if (!isGeminiSessionId(request.sessionId))
1125
+ throw new TypeError("Resume requires an exact Gemini session ID");
1126
+ args.push("--resume", request.sessionId);
1127
+ }
1128
+ return args;
1129
+ }
1130
+
1131
+ // src/adapters/gemini/protocol.ts
1132
+ var object4 = (x) => typeof x === "object" && x !== null && !Array.isArray(x) ? x : void 0;
1133
+ var count2 = (x) => typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : void 0;
1134
+ function rejectUnsupportedClient(error) {
1135
+ if (error.reasonCode === "UNSUPPORTED_CLIENT" || error.code === "UNSUPPORTED_CLIENT")
1136
+ throw new UnsupportedCliVersionError("gemini", GEMINI_VERSION, {
1137
+ provider: "gemini",
1138
+ transport: "exec",
1139
+ rawCode: "UNSUPPORTED_CLIENT",
1140
+ retryable: false
1141
+ });
1142
+ }
1143
+ function classify(error) {
1144
+ const code = String(error.code ?? error.type ?? "").toUpperCase();
1145
+ const kind = /401|UNAUTHENTICATED|AUTHENTICATION|AUTH_ERROR|LOGIN_REQUIRED/.test(code) ? "not-authenticated" : /429|RESOURCE_EXHAUSTED|QUOTA|RATE_LIMIT/.test(code) ? "usage-limit" : /MODEL_?NOT_?FOUND|UNKNOWN_?MODEL/.test(code) ? "unknown-model" : /MODEL_?UNAVAILABLE|MODEL_?CAPACITY/.test(code) ? "model-unavailable" : "provider-unavailable";
1146
+ return {
1147
+ kind,
1148
+ message: `Gemini ${kind}`,
1149
+ .../^[A-Z0-9_-]{1,80}$/.test(code) ? { rawCode: code } : {}
1150
+ };
1151
+ }
1152
+ var GeminiProtocol = class {
1153
+ constructor(expectedSession) {
1154
+ this.expectedSession = expectedSession;
1155
+ }
1156
+ expectedSession;
1157
+ #native = [];
1158
+ #events = [];
1159
+ #sessionId;
1160
+ #text = "";
1161
+ #terminal;
1162
+ #failure;
1163
+ #usage;
1164
+ #invalid(message) {
1165
+ this.#failure = { kind: "protocol", message };
1166
+ }
1167
+ line(line) {
1168
+ if (line.trim() === "") return [];
1169
+ const start = this.#events.length;
1170
+ let frame;
1171
+ try {
1172
+ frame = object4(JSON.parse(line));
1173
+ } catch {
1174
+ }
1175
+ if (!frame || typeof frame.type !== "string") {
1176
+ this.#invalid("Invalid Gemini JSONL frame");
1177
+ return [];
1178
+ }
1179
+ this.#native.push(frame);
1180
+ if (this.#terminal)
1181
+ this.#invalid("Gemini emitted data after its terminal result");
1182
+ if (frame.type === "init") {
1183
+ const id = frame.session_id;
1184
+ if (!isGeminiSessionId(id) || this.#sessionId !== void 0 && this.#sessionId !== id || this.expectedSession !== void 0 && this.expectedSession !== id)
1185
+ this.#invalid("Gemini native session identity changed or is invalid");
1186
+ else this.#sessionId = id;
1187
+ } else if (frame.type === "message" && frame.role === "assistant") {
1188
+ if (typeof frame.content !== "string")
1189
+ this.#invalid("Invalid Gemini assistant message");
1190
+ else {
1191
+ this.#text += frame.content;
1192
+ this.#events.push({ type: "message.delta", text: frame.content });
1193
+ }
1194
+ } else if (frame.type === "tool_use") {
1195
+ if (typeof frame.tool_id !== "string" || typeof frame.tool_name !== "string")
1196
+ this.#invalid("Invalid Gemini tool use");
1197
+ else
1198
+ this.#events.push({
1199
+ type: "tool.started",
1200
+ id: frame.tool_id,
1201
+ name: frame.tool_name,
1202
+ input: frame.parameters
1203
+ });
1204
+ } else if (frame.type === "tool_result") {
1205
+ if (typeof frame.tool_id !== "string")
1206
+ this.#invalid("Invalid Gemini tool result");
1207
+ else
1208
+ this.#events.push({
1209
+ type: "tool.completed",
1210
+ id: frame.tool_id,
1211
+ output: frame.output,
1212
+ ...frame.status === "error" ? { error: frame.error ?? true } : {}
1213
+ });
1214
+ } else if (frame.type === "error") {
1215
+ this.#events.push({
1216
+ type: "provider.event",
1217
+ provider: "gemini",
1218
+ event: frame
1219
+ });
1220
+ if (frame.severity !== "warning" && this.#failure?.kind !== "protocol") {
1221
+ rejectUnsupportedClient(frame);
1222
+ this.#failure = classify(frame);
1223
+ }
1224
+ } else if (frame.type === "result") {
1225
+ this.#terminal = frame;
1226
+ if (frame.status !== "success" && frame.status !== "error")
1227
+ this.#invalid("Invalid Gemini terminal status");
1228
+ if (frame.status === "error" && this.#failure?.kind !== "protocol") {
1229
+ const error = object4(frame.error) ?? {};
1230
+ rejectUnsupportedClient(error);
1231
+ this.#failure = classify(error);
1232
+ }
1233
+ const stats = object4(frame.stats);
1234
+ if (stats) {
1235
+ const input = count2(stats.input_tokens), output = count2(stats.output_tokens), cached = count2(stats.cached);
1236
+ this.#usage = {
1237
+ costMeaning: "unavailable",
1238
+ ...input === void 0 ? {} : { inputTokens: input },
1239
+ ...output === void 0 ? {} : { outputTokens: output },
1240
+ ...cached === void 0 ? {} : { cachedInputTokens: cached }
1241
+ };
1242
+ }
1243
+ } else
1244
+ this.#events.push({
1245
+ type: "provider.event",
1246
+ provider: "gemini",
1247
+ event: frame
1248
+ });
1249
+ return this.#events.slice(start);
1250
+ }
1251
+ get sessionId() {
1252
+ return this.#sessionId;
1253
+ }
1254
+ finish(exitCode) {
1255
+ if (exitCode === 41 && !this.#failure) {
1256
+ this.#failure = this.#terminal?.status === "success" ? {
1257
+ kind: "protocol",
1258
+ message: "Gemini auth failure exit contradicts terminal success"
1259
+ } : {
1260
+ kind: "not-authenticated",
1261
+ message: "Gemini authentication failed before terminal result",
1262
+ rawCode: "41"
1263
+ };
1264
+ }
1265
+ if (!this.#terminal || !this.#sessionId)
1266
+ this.#failure ??= {
1267
+ kind: "protocol",
1268
+ message: "Gemini stream ended without terminal result or session identity"
1269
+ };
1270
+ if (exitCode !== 0 && !this.#failure)
1271
+ this.#failure = {
1272
+ kind: "provider-unavailable",
1273
+ message: "Gemini process failed despite terminal success"
1274
+ };
1275
+ const completed = !this.#failure && this.#terminal?.status === "success" && exitCode === 0;
1276
+ if (completed)
1277
+ this.#events.push({ type: "message.completed", text: this.#text });
1278
+ return {
1279
+ completed,
1280
+ failed: !completed,
1281
+ refused: false,
1282
+ text: this.#text,
1283
+ events: [...this.#events],
1284
+ nativeEvents: [...this.#native],
1285
+ ...this.#sessionId === void 0 ? {} : { sessionId: this.#sessionId },
1286
+ ...this.#terminal === void 0 ? {} : { terminalEvent: this.#terminal },
1287
+ ...this.#failure === void 0 ? {} : { failure: this.#failure },
1288
+ ...this.#usage === void 0 ? {} : { usage: this.#usage }
1289
+ };
1290
+ }
1291
+ };
1292
+
1293
+ // src/adapters/gemini/streaming.ts
1294
+ var StreamQueue2 = class {
1295
+ #values = [];
1296
+ #wake;
1297
+ #ended = false;
1298
+ #error;
1299
+ push(value) {
1300
+ if (this.#ended) return;
1301
+ if (this.#values.length >= 1024)
1302
+ throw new OutputLimitError(
1303
+ { provider: "gemini", retryable: false },
1304
+ "Gemini consumer fell behind the bounded stream"
1305
+ );
1306
+ this.#values.push(value);
1307
+ this.#wake?.();
1308
+ }
1309
+ close(error) {
1310
+ this.#ended = true;
1311
+ this.#error = error;
1312
+ this.#wake?.();
1313
+ }
1314
+ async *[Symbol.asyncIterator]() {
1315
+ while (true) {
1316
+ if (this.#values.length) {
1317
+ yield this.#values.shift();
1318
+ continue;
1319
+ }
1320
+ if (this.#ended) {
1321
+ if (this.#error) throw this.#error;
1322
+ return;
1323
+ }
1324
+ await new Promise((resolve2) => {
1325
+ this.#wake = resolve2;
1326
+ });
1327
+ this.#wake = void 0;
1328
+ }
1329
+ }
1330
+ };
1331
+
1332
+ // src/adapters/gemini/exec-adapter.ts
1333
+ var GeminiExecAdapter = class {
1334
+ id = "gemini";
1335
+ #runner;
1336
+ #probeRunner;
1337
+ #discovery;
1338
+ #catalog;
1339
+ constructor(options = {}) {
1340
+ this.#runner = options.runner ?? runProcess;
1341
+ this.#probeRunner = options.probeRunner ?? this.#runner;
1342
+ const target = options.target ? {
1343
+ command: options.target.command,
1344
+ argsPrefix: [...options.target.argsPrefix]
1345
+ } : void 0;
1346
+ this.#discovery = new ExecDiscovery("gemini", this.#probeRunner, target);
1347
+ this.#catalog = (options.modelCatalog ?? []).map((model) => ({
1348
+ ...model,
1349
+ aliases: [...model.aliases]
1350
+ }));
1351
+ }
1352
+ detect(env, context) {
1353
+ return this.#discovery.detect(env, context);
1354
+ }
1355
+ auth(env) {
1356
+ return inspectGeminiAuth(env);
1357
+ }
1358
+ async models() {
1359
+ return this.#catalog.map((m) => ({ ...m, aliases: [...m.aliases] }));
1360
+ }
1361
+ async compatibility(env, version, context) {
1362
+ if (context?.signal.aborted) throw context.signal.reason;
1363
+ const target = this.#discovery.target(env);
1364
+ if (!target) return void 0;
1365
+ const result = await this.#probeRunner({
1366
+ command: target.command,
1367
+ args: [...target.argsPrefix, "--help"],
1368
+ cwd: process.cwd(),
1369
+ env,
1370
+ stdin: "",
1371
+ timeoutMs: Math.max(1, Math.min(15e3, context?.remainingMs() ?? 15e3)),
1372
+ ...context ? { signal: context.signal } : {},
1373
+ maxOutputBytes: 256 * 1024
1374
+ });
1375
+ return assessGeminiCompatibility(
1376
+ version,
1377
+ result.code === 0 ? result.stdout : ""
1378
+ );
1379
+ }
1380
+ async execute(request) {
1381
+ let result;
1382
+ for await (const item of this.stream(request))
1383
+ if (item.kind === "result") result = item.result;
1384
+ if (!result)
1385
+ throw new ProviderUnavailableError(
1386
+ { provider: "gemini", retryable: false },
1387
+ "Gemini stream returned no result"
1388
+ );
1389
+ return result;
1390
+ }
1391
+ async *stream(request) {
1392
+ if (request.signal?.aborted)
1393
+ throw new AbortError({ provider: "gemini", retryable: true });
1394
+ const args = buildGeminiArgs(request);
1395
+ if (request.providerOptions && Object.keys(request.providerOptions).length)
1396
+ throw new TypeError("Gemini provider options are not supported");
1397
+ const expires = performance.now() + request.timeoutMs;
1398
+ const context = {
1399
+ signal: request.signal ?? AbortSignal.timeout(request.timeoutMs),
1400
+ deadline: Date.now() + request.timeoutMs,
1401
+ remainingMs: () => Math.max(0, Math.floor(expires - performance.now()))
1402
+ };
1403
+ const installation = await this.detect(request.env, context), target = this.#discovery.target(request.env);
1404
+ if (!installation.installed || !target)
1405
+ throw new ProviderUnavailableError(
1406
+ { provider: "gemini", retryable: false },
1407
+ "Gemini CLI unavailable"
1408
+ );
1409
+ if (installation.version !== GEMINI_VERSION)
1410
+ throw new UnsupportedCliVersionError(
1411
+ "gemini",
1412
+ installation.version ?? "unknown",
1413
+ { provider: "gemini", retryable: false }
1414
+ );
1415
+ const compatibility = await this.compatibility(request.env, GEMINI_VERSION, context);
1416
+ if (!compatibility || compatibility.missingFlags.length)
1417
+ throw new UnsupportedCliVersionError("gemini", GEMINI_VERSION, {
1418
+ provider: "gemini",
1419
+ retryable: false
1420
+ });
1421
+ const cwd = await realpath3(request.cwd);
1422
+ const envelope = await prepareAnalyzeEnvelope(request.env, cwd);
1423
+ const abort = new AbortController();
1424
+ const signal = request.signal ? AbortSignal.any([request.signal, abort.signal]) : abort.signal;
1425
+ const queue = new StreamQueue2();
1426
+ const protocol = new GeminiProtocol(
1427
+ request.mode === "resume" ? request.sessionId : void 0
1428
+ );
1429
+ const decoder = new IncrementalLineDecoder({
1430
+ maxBufferedBytes: Math.min(request.maxOutputBytes, 1024 * 1024)
1431
+ });
1432
+ let announced, observed = false;
1433
+ const line = (raw) => {
1434
+ const events = protocol.line(raw);
1435
+ if (protocol.sessionId && protocol.sessionId !== announced) {
1436
+ announced = protocol.sessionId;
1437
+ queue.push({ kind: "session", sessionId: announced });
1438
+ }
1439
+ for (const event of events) queue.push({ kind: "event", event });
1440
+ };
1441
+ const execution = Promise.resolve().then(
1442
+ () => this.#runner({
1443
+ command: target.command,
1444
+ args: [...target.argsPrefix, ...args, ...envelope.args],
1445
+ cwd,
1446
+ env: envelope.env,
1447
+ stdin: "",
1448
+ timeoutMs: request.timeoutMs,
1449
+ maxOutputBytes: request.maxOutputBytes,
1450
+ signal,
1451
+ onStdout: (chunk) => {
1452
+ observed = true;
1453
+ for (const raw of decoder.push(chunk)) line(raw);
1454
+ }
1455
+ })
1456
+ ).then((outcome) => {
1457
+ if (!observed && outcome.stdout)
1458
+ for (const raw of decoder.push(Buffer.from(outcome.stdout)))
1459
+ line(raw);
1460
+ for (const raw of decoder.finish()) line(raw);
1461
+ let result = protocol.finish(outcome.code);
1462
+ if (result.failure && result.nativeEvents.length === 0 && outcome.stdout.trim() === "") {
1463
+ if (outcome.code !== 0 && result.failure.kind !== "not-authenticated" && /["']?reasonCode["']?\s*:\s*["']UNSUPPORTED_CLIENT["']/.test(
1464
+ outcome.stderr
1465
+ ))
1466
+ throw new UnsupportedCliVersionError("gemini", GEMINI_VERSION, {
1467
+ provider: "gemini",
1468
+ transport: "exec",
1469
+ rawCode: "UNSUPPORTED_CLIENT",
1470
+ retryable: false
1471
+ });
1472
+ const exit = outcome.code === null ? "null" : String(outcome.code);
1473
+ const signal2 = outcome.signal && /^[A-Z0-9]+$/.test(outcome.signal) ? outcome.signal : "none";
1474
+ const stderrBytes = Buffer.byteLength(outcome.stderr, "utf8");
1475
+ result = {
1476
+ ...result,
1477
+ failure: {
1478
+ kind: result.failure.kind === "protocol" && outcome.code !== 0 ? outcome.code === 55 ? "untrusted-workspace" : "provider-unavailable" : result.failure.kind,
1479
+ message: `Gemini process ended before JSONL initialization (exit=${exit}; signal=${signal2}; stderrBytes=${stderrBytes})`,
1480
+ rawCode: result.failure.rawCode ?? `EXIT_${exit}`
1481
+ }
1482
+ };
1483
+ }
1484
+ for (const event of result.events)
1485
+ if (event.type === "message.completed")
1486
+ queue.push({ kind: "event", event });
1487
+ queue.push({ kind: "result", result });
1488
+ queue.close();
1489
+ }).catch((error) => queue.close(error));
1490
+ try {
1491
+ yield* queue;
1492
+ } finally {
1493
+ abort.abort();
1494
+ await execution;
1495
+ await envelope.cleanup();
1496
+ }
1497
+ }
1498
+ };
1499
+
1500
+ // src/adapters/gemini/registration.ts
1501
+ var defaultModels = [{
1502
+ id: "gemini-2.5-flash",
1503
+ provider: "gemini",
1504
+ aliases: [],
1505
+ source: "compatibility-catalog",
1506
+ availability: "unverified"
1507
+ }];
1508
+ function createGeminiCliProvider(options = {}) {
1509
+ const catalog = (options.modelCatalog ?? defaultModels).map((model) => ({
1510
+ ...model,
1511
+ aliases: [...model.aliases],
1512
+ ...model.supportedEffort ? { supportedEffort: [...model.supportedEffort] } : {}
1513
+ }));
1514
+ for (const model of catalog)
1515
+ if (model.provider !== "gemini")
1516
+ throw new TypeError("Gemini catalog contains a foreign provider");
1517
+ const runner = options.runner;
1518
+ const probeRunner = options.probeRunner;
1519
+ if (probeRunner !== void 0 && typeof probeRunner !== "function") throw new TypeError("probeRunner must be a function");
1520
+ const executable = options.executable ? {
1521
+ command: options.executable.command,
1522
+ argsPrefix: [...options.executable.argsPrefix]
1523
+ } : void 0;
1524
+ const adapter = (target) => new GeminiExecAdapter({
1525
+ modelCatalog: catalog,
1526
+ ...target ? { target } : {},
1527
+ ...runner ? { runner } : {},
1528
+ ...probeRunner === void 0 ? {} : { probeRunner }
1529
+ });
1530
+ return {
1531
+ apiVersion: 1,
1532
+ id: "gemini",
1533
+ exec: {
1534
+ adapter: adapter(executable),
1535
+ token: "geminiExecV1",
1536
+ adapterVersion: RUNTIME_ADAPTER_VERSION,
1537
+ withTarget: (target) => adapter(target)
1538
+ },
1539
+ modelCatalog: catalog.map((model) => ({
1540
+ ...model,
1541
+ aliases: [...model.aliases],
1542
+ ...model.supportedEffort ? { supportedEffort: [...model.supportedEffort] } : {}
1543
+ })),
1544
+ resolveModel(nativeId) {
1545
+ if (!nativeId || nativeId.startsWith("-") || nativeId.includes("\0"))
1546
+ throw new TypeError("Invalid Gemini model identifier");
1547
+ const found = catalog.find(
1548
+ (m) => m.id === nativeId || m.aliases.includes(nativeId)
1549
+ );
1550
+ return found ? {
1551
+ ...found,
1552
+ aliases: [...found.aliases],
1553
+ ...found.supportedEffort ? { supportedEffort: [...found.supportedEffort] } : {}
1554
+ } : {
1555
+ id: nativeId,
1556
+ provider: "gemini",
1557
+ aliases: [],
1558
+ source: "explicit",
1559
+ availability: "unverified"
1560
+ };
1561
+ },
1562
+ execCapabilities: EXEC_CAPABILITIES2,
1563
+ translateContext: translateGeminiContext,
1564
+ translatePermissions: translateGeminiPermissions,
1565
+ validateOptions(value, transport) {
1566
+ const unsupported2 = translateGeminiPermissions(
1567
+ value.permissions ?? { mode: "analyze" },
1568
+ transport
1569
+ ).report.unsupported;
1570
+ unsupported2.push(...translateGeminiContext(value.context).unsupported);
1571
+ if (value.instructions !== void 0 || value.effort !== void 0)
1572
+ unsupported2.push("privileged-instructions-effort-schema");
1573
+ const external = value.providerOptions?.external?.gemini;
1574
+ if (external && Object.keys(external).length)
1575
+ unsupported2.push("providerOptions.external.gemini");
1576
+ if (unsupported2.length)
1577
+ throw new UnsupportedCapabilityError(
1578
+ {
1579
+ provider: "gemini",
1580
+ transport,
1581
+ retryable: false,
1582
+ sanitizedDiagnostics: { unsupported: unsupported2 }
1583
+ },
1584
+ "Gemini cannot enforce requested options"
1585
+ );
1586
+ }
1587
+ };
1588
+ }
1589
+
1590
+ // src/adapters/claude/exec-adapter.ts
1591
+ import { randomUUID } from "node:crypto";
1592
+ import { readFile as readFile3 } from "node:fs/promises";
1593
+ import { homedir as homedir3 } from "node:os";
1594
+ import { join as join3, resolve } from "node:path";
1595
+
1596
+ // src/adapters/claude/protocol.ts
1597
+ function setNumber(target, key, value) {
1598
+ const parsed = numberValue(value);
1599
+ if (parsed !== void 0) target[key] = parsed;
1600
+ }
1601
+ function parseUsage(event) {
1602
+ const rawModels = event.modelUsage;
1603
+ if (typeof rawModels === "object" && rawModels !== null && !Array.isArray(rawModels)) {
1604
+ const perModel = {};
1605
+ let inputTokens = 0;
1606
+ let outputTokens = 0;
1607
+ let cachedInputTokens = 0;
1608
+ let cacheCreationTokens = 0;
1609
+ let reportedCostUsd = 0;
1610
+ for (const [model, raw] of Object.entries(rawModels)) {
1611
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
1612
+ const value2 = raw;
1613
+ const usage2 = {};
1614
+ setNumber(usage2, "inputTokens", value2.inputTokens);
1615
+ setNumber(usage2, "outputTokens", value2.outputTokens);
1616
+ setNumber(usage2, "cachedInputTokens", value2.cacheReadInputTokens);
1617
+ setNumber(usage2, "cacheCreationTokens", value2.cacheCreationInputTokens);
1618
+ setNumber(usage2, "reportedCostUsd", value2.costUSD);
1619
+ perModel[model] = usage2;
1620
+ inputTokens += usage2.inputTokens ?? 0;
1621
+ outputTokens += usage2.outputTokens ?? 0;
1622
+ cachedInputTokens += usage2.cachedInputTokens ?? 0;
1623
+ cacheCreationTokens += usage2.cacheCreationTokens ?? 0;
1624
+ reportedCostUsd += usage2.reportedCostUsd ?? 0;
1625
+ }
1626
+ if (Object.keys(perModel).length > 0) {
1627
+ const totalCost = numberValue(event.total_cost_usd);
1628
+ const hasReportedCost = totalCost !== void 0 || Object.values(perModel).some((m) => m.reportedCostUsd !== void 0);
1629
+ return {
1630
+ inputTokens,
1631
+ outputTokens,
1632
+ cachedInputTokens,
1633
+ cacheCreationTokens,
1634
+ perModel,
1635
+ // Sin costo reportado por el CLI no se inventa un 0 api-equivalent.
1636
+ ...hasReportedCost ? { reportedCostUsd: totalCost ?? reportedCostUsd } : {},
1637
+ costMeaning: hasReportedCost ? "api-equivalent" : "unavailable"
1638
+ };
1639
+ }
1640
+ }
1641
+ const rawUsage = event.usage;
1642
+ if (typeof rawUsage !== "object" || rawUsage === null || Array.isArray(rawUsage)) return void 0;
1643
+ const value = rawUsage;
1644
+ const usage = {
1645
+ costMeaning: numberValue(event.total_cost_usd) === void 0 ? "unavailable" : "api-equivalent"
1646
+ };
1647
+ setNumber(usage, "inputTokens", value.input_tokens);
1648
+ setNumber(usage, "outputTokens", value.output_tokens);
1649
+ setNumber(usage, "cachedInputTokens", value.cache_read_input_tokens);
1650
+ setNumber(usage, "cacheCreationTokens", value.cache_creation_input_tokens);
1651
+ setNumber(usage, "reportedCostUsd", event.total_cost_usd);
1652
+ return usage;
1653
+ }
1654
+ function parseClaudeJsonl(raw, state = { toolFallbackIndex: 0 }) {
1655
+ const events = [];
1656
+ const nativeEvents = [];
1657
+ let sessionId;
1658
+ let text = "";
1659
+ let output;
1660
+ let usage;
1661
+ let terminalEvent;
1662
+ let failure;
1663
+ for (const line of jsonlFrames(raw)) {
1664
+ if (!line.trim()) continue;
1665
+ const event = parseObject(line);
1666
+ if (!event) {
1667
+ events.push({ type: "provider.event", provider: "claude", event: { type: "non-json-output", line } });
1668
+ continue;
1669
+ }
1670
+ nativeEvents.push(event);
1671
+ const limits = resolveProviderRateLimits(readProviderRateLimits("claude", event));
1672
+ if (limits) {
1673
+ events.push({ type: "provider.event", provider: "claude", event: limits });
1674
+ continue;
1675
+ }
1676
+ const type = stringValue(event.type);
1677
+ if (type === "system" && event.subtype === "init") {
1678
+ sessionId = stringValue(event.session_id) ?? sessionId;
1679
+ } else if (type === "stream_event") {
1680
+ const nested = event.event;
1681
+ if (typeof nested === "object" && nested !== null && !Array.isArray(nested)) {
1682
+ const delta = nested.delta;
1683
+ if (typeof delta === "object" && delta !== null && !Array.isArray(delta)) {
1684
+ const deltaText = stringValue(delta.text);
1685
+ if (deltaText !== void 0) events.push({ type: "message.delta", text: deltaText });
1686
+ else events.push({ type: "provider.event", provider: "claude", event });
1687
+ }
1688
+ }
1689
+ } else if (type === "assistant") {
1690
+ const message = event.message;
1691
+ const content = typeof message === "object" && message !== null && !Array.isArray(message) ? message.content : void 0;
1692
+ if (Array.isArray(content)) {
1693
+ for (const block of content) {
1694
+ if (typeof block !== "object" || block === null || Array.isArray(block)) continue;
1695
+ const value = block;
1696
+ if (value.type === "tool_use") {
1697
+ events.push({
1698
+ type: "tool.started",
1699
+ // One counter for a complete transcript or the incremental turn.
1700
+ id: stringValue(value.id) ?? `claude-tool-${state.toolFallbackIndex++}`,
1701
+ name: stringValue(value.name) ?? "unknown",
1702
+ ...value.input === void 0 ? {} : { input: value.input }
1703
+ });
1704
+ }
1705
+ }
1706
+ }
1707
+ } else if (type === "result") {
1708
+ terminalEvent = event;
1709
+ sessionId = stringValue(event.session_id) ?? sessionId;
1710
+ text = stringValue(event.result) ?? "";
1711
+ output = event.structured_output;
1712
+ usage = parseUsage(event);
1713
+ events.push({ type: "message.completed", text });
1714
+ if (event.is_error === true || event.terminal_reason === "api_error") {
1715
+ failure = classifyClaudeFailure(event);
1716
+ }
1717
+ } else {
1718
+ events.push({ type: "provider.event", provider: "claude", event });
1719
+ }
1720
+ }
1721
+ if (!terminalEvent && !failure) {
1722
+ failure = { kind: "protocol", message: "Claude stream ended without a result event" };
1723
+ }
1724
+ const retryAt = confirmedUsageRetryAt(events);
1725
+ if (failure && terminalEvent?.api_error_status === 429 && retryAt !== void 0)
1726
+ failure = { kind: "usage-limit", message: "Provider usage limit reached" };
1727
+ if (failure?.kind === "usage-limit" && retryAt !== void 0) failure = { ...failure, retryAt };
1728
+ return {
1729
+ completed: terminalEvent !== void 0 && failure === void 0,
1730
+ failed: failure !== void 0,
1731
+ refused: false,
1732
+ ...sessionId === void 0 ? {} : { sessionId },
1733
+ text,
1734
+ ...output === void 0 ? {} : { output },
1735
+ ...usage === void 0 ? {} : { usage },
1736
+ events,
1737
+ ...failure === void 0 ? {} : { failure },
1738
+ ...terminalEvent === void 0 ? {} : { terminalEvent },
1739
+ nativeEvents
1740
+ };
1741
+ }
1742
+
1743
+ // src/adapters/claude/exec-adapter.ts
1744
+ function claudeProviderArgs(options) {
1745
+ if (!options) return [];
1746
+ if (options.systemPromptMode !== void 0 && !["append", "replace"].includes(String(options.systemPromptMode))) {
1747
+ throw new TypeError("systemPromptMode must be append or replace.");
1748
+ }
1749
+ const args = [];
1750
+ if (options.tools !== void 0) {
1751
+ if (!Array.isArray(options.tools) || !options.tools.every((tool) => typeof tool === "string" && /^[A-Za-z][A-Za-z0-9_]*$/.test(tool))) {
1752
+ throw new TypeError("Claude tools must be an array of built-in tool names.");
1753
+ }
1754
+ args.push("--tools", options.tools.join(","));
1755
+ }
1756
+ if (options.strictMcpConfig !== void 0) {
1757
+ if (typeof options.strictMcpConfig !== "boolean") throw new TypeError("strictMcpConfig must be boolean.");
1758
+ if (options.strictMcpConfig) args.push("--strict-mcp-config");
1759
+ }
1760
+ if (options.mcpConfigs !== void 0) {
1761
+ if (!Array.isArray(options.mcpConfigs) || !options.mcpConfigs.every((config) => typeof config === "string" && config.trim() !== "" && !config.includes("\0") && !config.startsWith("-"))) {
1762
+ throw new TypeError("Claude MCP configs must be non-empty paths or JSON strings.");
1763
+ }
1764
+ if (options.mcpConfigs.length) args.push("--mcp-config", ...options.mcpConfigs);
1765
+ }
1766
+ args.push(...claudeSettingsArgs(options));
1767
+ return args;
1768
+ }
1769
+ function claudeSettingsArgs(options) {
1770
+ if (options?.settings === void 0) return [];
1771
+ const settings = typeof options.settings === "string" ? options.settings : options.settings !== null && typeof options.settings === "object" && !Array.isArray(options.settings) ? JSON.stringify(options.settings) : void 0;
1772
+ if (!settings || settings.includes("\0") || settings.startsWith("-")) throw new TypeError("Claude settings must be a path or JSON object.");
1773
+ return ["--settings", settings];
1774
+ }
1775
+ function buildClaudeExecArgs(request, newSessionId) {
1776
+ const args = [
1777
+ "-p",
1778
+ "--output-format",
1779
+ "stream-json",
1780
+ "--verbose",
1781
+ "--include-partial-messages",
1782
+ "--model",
1783
+ request.modelId
1784
+ ];
1785
+ if (request.mode === "resume" || request.mode === "fork") {
1786
+ if (!request.sessionId) throw new TypeError(`${request.mode} requires a sessionId`);
1787
+ if (!isSafeSessionId(request.sessionId)) throw new TypeError("sessionId is not a safe CLI argument");
1788
+ args.push("--resume", request.sessionId);
1789
+ if (request.mode === "fork") args.push("--fork-session");
1790
+ } else {
1791
+ args.push("--session-id", newSessionId);
1792
+ }
1793
+ if (request.instructions) args.push(request.providerOptions?.systemPromptMode === "replace" ? "--system-prompt" : "--append-system-prompt", request.instructions);
1794
+ if (request.effort) args.push("--effort", request.effort);
1795
+ if (request.outputSchema) args.push("--json-schema", JSON.stringify(request.outputSchema));
1796
+ args.push(...claudeProviderArgs(request.providerOptions));
1797
+ if (request.permissionArgs.includes("dontAsk") && Array.isArray(request.providerOptions?.tools) && request.providerOptions.tools.includes("WebSearch")) args.push("--allowed-tools", "WebSearch");
1798
+ args.push(...request.contextArgs, ...request.permissionArgs);
1799
+ return args;
1800
+ }
1801
+ function namesApiBilling(vars) {
1802
+ return Boolean(vars.ANTHROPIC_AUTH_TOKEN || vars.ANTHROPIC_PROFILE || vars.ANTHROPIC_FEDERATION_RULE_ID && vars.ANTHROPIC_ORGANIZATION_ID);
1803
+ }
1804
+ async function explicitClaudeSettings(settings, cwd) {
1805
+ if (typeof settings !== "string") return settings;
1806
+ try {
1807
+ return JSON.parse(settings.trimStart().startsWith("{") ? settings : await readFile3(resolve(cwd, settings), "utf8"));
1808
+ } catch {
1809
+ throw new TypeError("Claude settings must be valid JSON or a readable JSON file.");
1810
+ }
1811
+ }
1812
+ async function settingsMoveBilling(turn, env) {
1813
+ const files = [join3(turn.cwd, ".claude", "settings.json"), join3(turn.cwd, ".claude", "settings.local.json")];
1814
+ if (!turn.contextArgs.includes("--setting-sources")) {
1815
+ files.push(join3(env.CLAUDE_CONFIG_DIR || join3(env.HOME || homedir3(), ".claude"), "settings.json"));
1816
+ }
1817
+ const layers = await Promise.all(files.map((file) => readFile3(file, "utf8").then((text) => JSON.parse(text)).catch(() => void 0)));
1818
+ layers.push(await explicitClaudeSettings(turn.providerOptions?.settings, turn.cwd));
1819
+ return layers.some((layer) => {
1820
+ const block = layer?.env;
1821
+ if (typeof block !== "object" || block === null) return false;
1822
+ const vars = block;
1823
+ return Boolean(vars.ANTHROPIC_API_KEY || vars.ANTHROPIC_BASE_URL) || namesApiBilling(vars);
1824
+ });
1825
+ }
1826
+ function parseClaudeAuth(raw, env, movedBySettings) {
1827
+ try {
1828
+ const value = JSON.parse(raw);
1829
+ const authenticated = value.loggedIn === true;
1830
+ const method2 = typeof value.authMethod === "string" ? value.authMethod.toLowerCase() : "";
1831
+ const loginSource = !authenticated ? "unknown" : method2.includes("claude.ai") || method2.includes("oauth") ? "subscription" : method2.includes("api") ? "api-key" : method2.includes("bedrock") || method2.includes("vertex") ? "cloud-provider" : "unknown";
1832
+ const keyInUse = typeof value.apiKeySource === "string" && !["", "none"].includes(value.apiKeySource) || namesApiBilling(env) || movedBySettings;
1833
+ const source = loginSource === "subscription" && keyInUse ? "api-key" : loginSource;
1834
+ const plan = typeof value.subscriptionType === "string" && source === loginSource ? value.subscriptionType : void 0;
1835
+ return {
1836
+ authenticated,
1837
+ source,
1838
+ ...plan === void 0 ? {} : { account: { plan } }
1839
+ };
1840
+ } catch {
1841
+ return { authenticated: false, source: "unknown" };
1842
+ }
1843
+ }
1844
+ var ClaudeExecAdapter = class {
1845
+ id = "claude";
1846
+ #runner;
1847
+ #probeRunner;
1848
+ #discovery;
1849
+ constructor(options = {}) {
1850
+ this.#runner = options.runner ?? runProcess;
1851
+ this.#probeRunner = options.probeRunner ?? this.#runner;
1852
+ this.#discovery = new ExecDiscovery("claude", this.#probeRunner, options.target);
1853
+ }
1854
+ #target(env) {
1855
+ return this.#discovery.target(env);
1856
+ }
1857
+ async detect(env, context) {
1858
+ return this.#discovery.detect(env, context);
1859
+ }
1860
+ async auth(env, context, turn) {
1861
+ const target = this.#target(env);
1862
+ if (!target) return { authenticated: false, source: "unknown" };
1863
+ const turnArgs = turn ? [...turn.contextArgs, ...claudeSettingsArgs(turn.providerOptions)] : [];
1864
+ const movedBySettings = turn ? await settingsMoveBilling(turn, env) : false;
1865
+ const outcome = await this.#probeRunner({
1866
+ command: target.command,
1867
+ args: [...target.argsPrefix, ...turnArgs, "auth", "status", "--json"],
1868
+ cwd: turn?.cwd ?? process.cwd(),
1869
+ env,
1870
+ stdin: "",
1871
+ timeoutMs: Math.min(15e3, context?.remainingMs() ?? 15e3),
1872
+ ...context ? { signal: context.signal } : {},
1873
+ maxOutputBytes: 64 * 1024
1874
+ });
1875
+ return parseClaudeAuth(outcome.stdout, env, movedBySettings);
1876
+ }
1877
+ async models() {
1878
+ return compatibilityModels("claude");
1879
+ }
1880
+ async compatibility(env, version, context) {
1881
+ const target = this.#target(env);
1882
+ if (!target) return void 0;
1883
+ const outcome = await this.#probeRunner({
1884
+ command: target.command,
1885
+ args: [...target.argsPrefix, "--help"],
1886
+ cwd: process.cwd(),
1887
+ env,
1888
+ stdin: "",
1889
+ timeoutMs: Math.min(15e3, context?.remainingMs() ?? 15e3),
1890
+ ...context ? { signal: context.signal } : {},
1891
+ maxOutputBytes: 256 * 1024
1892
+ });
1893
+ const assessment = assessCliCompatibility("claude", version, {
1894
+ main: `${outcome.stdout}
1895
+ ${outcome.stderr}`
1896
+ });
1897
+ return { ...assessment, features: { ...assessment.features, refusalDetection: "unsupported" } };
1898
+ }
1899
+ async execute(request) {
1900
+ const target = this.#target(request.env);
1901
+ if (!target) {
1902
+ return {
1903
+ completed: false,
1904
+ failed: true,
1905
+ refused: false,
1906
+ text: "",
1907
+ events: [],
1908
+ failure: { kind: "provider-unavailable", message: "Claude CLI not found" },
1909
+ nativeEvents: []
1910
+ };
1911
+ }
1912
+ const outcome = await guardJsonlFrames((onStdout) => this.#runner({
1913
+ command: target.command,
1914
+ args: [...target.argsPrefix, ...buildClaudeExecArgs(request, randomUUID())],
1915
+ cwd: request.cwd,
1916
+ env: request.env,
1917
+ stdin: request.prompt,
1918
+ timeoutMs: request.timeoutMs,
1919
+ maxOutputBytes: request.maxOutputBytes,
1920
+ onStdout,
1921
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1922
+ }));
1923
+ const result = parseClaudeJsonl(outcome.stdout);
1924
+ if (outcome.code !== 0 && result.failure?.kind === "protocol") {
1925
+ return {
1926
+ ...result,
1927
+ failure: classifyClaudeFailure({ result: outcome.stderr.trim() || `Claude exited with code ${outcome.code}` })
1928
+ };
1929
+ }
1930
+ return result;
1931
+ }
1932
+ async *stream(request) {
1933
+ const target = this.#target(request.env);
1934
+ if (!target) {
1935
+ yield {
1936
+ kind: "result",
1937
+ result: {
1938
+ completed: false,
1939
+ failed: true,
1940
+ refused: false,
1941
+ text: "",
1942
+ events: [],
1943
+ failure: { kind: "provider-unavailable", message: "Claude CLI not found" },
1944
+ nativeEvents: []
1945
+ }
1946
+ };
1947
+ return;
1948
+ }
1949
+ const parseState = { toolFallbackIndex: 0 };
1950
+ const pump = new ExecStreamPump(request.signal, (line) => parseClaudeJsonl(line, parseState), parseClaudeJsonl);
1951
+ const execution = this.#runner({
1952
+ command: target.command,
1953
+ args: [...target.argsPrefix, ...buildClaudeExecArgs(request, randomUUID())],
1954
+ cwd: request.cwd,
1955
+ env: request.env,
1956
+ stdin: request.prompt,
1957
+ timeoutMs: request.timeoutMs,
1958
+ maxOutputBytes: request.maxOutputBytes,
1959
+ captureStdout: false,
1960
+ // The pump retains the incremental result; legacy runners still receive onStdout.
1961
+ signal: pump.signal,
1962
+ onStdout: pump.onStdout,
1963
+ onStdoutAsync: pump.onStdoutAsync,
1964
+ onFailure: (error) => pump.fail(error)
1965
+ }).then((outcome) => pump.finish((parsed) => {
1966
+ let result = parsed;
1967
+ if (outcome.code !== 0 && result.failure?.kind === "protocol") {
1968
+ result = {
1969
+ ...result,
1970
+ failure: classifyClaudeFailure({ result: outcome.stderr.trim() || `Claude exited with code ${outcome.code}` })
1971
+ };
1972
+ }
1973
+ return result;
1974
+ })).catch((error) => pump.fail(error));
1975
+ try {
1976
+ yield* pump.items();
1977
+ } catch (error) {
1978
+ pump.cancel();
1979
+ if (request.awaitSettlement) {
1980
+ await execution;
1981
+ throw pump.afterSettlement(error);
1982
+ }
1983
+ throw error;
1984
+ } finally {
1985
+ pump.cancel();
1986
+ if (request.awaitSettlement) await execution;
1987
+ }
1988
+ }
1989
+ };
1990
+
1991
+ // src/core/context.ts
1992
+ function normalizeContextPolicy(policy = {}) {
1993
+ return {
1994
+ profile: policy.profile ?? "native",
1995
+ memory: policy.memory ?? "inherit"
1996
+ };
1997
+ }
1998
+ function translateContext(provider, requested = {}) {
1999
+ if (provider !== "claude" && provider !== "codex") throw new UnknownProviderError(provider);
2000
+ const policy = normalizeContextPolicy(requested);
2001
+ const args = [];
2002
+ const unsupported2 = [];
2003
+ const warnings = [];
2004
+ const active = [];
2005
+ const inactive = [];
2006
+ const unavoidable = ["admin-managed-policy"];
2007
+ const unknown = [];
2008
+ if (provider === "claude") {
2009
+ if (policy.profile === "native") {
2010
+ active.push("user-settings", "project-settings", "discovered-instructions", "skills", "hooks", "plugins", "mcp");
2011
+ } else if (policy.profile === "project") {
2012
+ args.push("--setting-sources", "project,local");
2013
+ active.push("project-settings", "local-settings", "discovered-instructions");
2014
+ inactive.push("user-settings");
2015
+ unknown.push("provider-memory");
2016
+ } else {
2017
+ args.push("--safe-mode");
2018
+ inactive.push("discovered-instructions", "skills", "hooks", "plugins", "mcp", "provider-memory");
2019
+ active.push("authentication", "model-selection", "built-in-tools", "permissions");
2020
+ }
2021
+ if (policy.memory === "read-only") unsupported2.push("memory.read-only");
2022
+ if (policy.memory === "off" && policy.profile !== "clean") {
2023
+ unsupported2.push("memory.off-without-clean-profile");
2024
+ }
2025
+ } else {
2026
+ if (policy.profile === "native") {
2027
+ active.push("user-config", "project-config", "AGENTS.md", "rules", "skills", "hooks", "plugins", "mcp");
2028
+ } else if (policy.profile === "project") {
2029
+ args.push("--ignore-user-config");
2030
+ inactive.push("user-config");
2031
+ active.push("project-config", "AGENTS.md", "rules");
2032
+ unsupported2.push("context.project.global-instructions");
2033
+ } else {
2034
+ args.push("--ignore-user-config", "--ignore-rules");
2035
+ inactive.push("user-config", "rules");
2036
+ unsupported2.push("context.clean.project-instructions", "context.clean.plugins-skills-hooks-mcp");
2037
+ unknown.push("AGENTS.md", "plugins", "skills", "hooks", "mcp");
2038
+ }
2039
+ if (policy.memory === "off") {
2040
+ args.push("--disable", "memories");
2041
+ inactive.push("provider-memory");
2042
+ } else if (policy.memory === "read-only") {
2043
+ unsupported2.push("memory.read-only");
2044
+ } else {
2045
+ unknown.push("provider-memory");
2046
+ }
2047
+ }
2048
+ if (unsupported2.length > 0) {
2049
+ warnings.push(`Context policy is not fully enforceable by ${provider} exec`);
2050
+ }
2051
+ return {
2052
+ args,
2053
+ unsupported: unsupported2,
2054
+ warnings,
2055
+ report: {
2056
+ profile: policy.profile,
2057
+ memory: policy.memory,
2058
+ active: [...new Set(active)],
2059
+ inactive: [...new Set(inactive)],
2060
+ unavoidable,
2061
+ unknown: [...new Set(unknown)]
2062
+ }
2063
+ };
2064
+ }
2065
+
2066
+ // src/core/permissions.ts
2067
+ function translatePermissions(provider, requested, transport = "exec") {
2068
+ if (provider !== "claude" && provider !== "codex") throw new UnknownProviderError(provider);
2069
+ if (requested.mode === "respond" && (provider !== "claude" || transport !== "exec")) {
2070
+ throw new TypeError("respond is only supported by Claude exec");
2071
+ }
2072
+ if (!["analyze", "respond", "edit", "unrestricted"].includes(requested.mode)) {
2073
+ throw new TypeError("Unknown permission mode");
2074
+ }
2075
+ const args = [];
2076
+ const unsupported2 = [];
2077
+ const warnings = [];
2078
+ const enforcedBy = [];
2079
+ let filesystem = "unknown";
2080
+ let network = "provider-default";
2081
+ let approvals = "non-interactive";
2082
+ if (provider === "claude") {
2083
+ if (requested.mode === "respond") {
2084
+ args.push("--permission-mode", "dontAsk", "--strict-mcp-config");
2085
+ filesystem = "no filesystem tools; harness tool restriction, not an OS sandbox";
2086
+ approvals = "deny-unapproved";
2087
+ enforcedBy.push("harness");
2088
+ } else if (requested.mode === "analyze") {
2089
+ args.push("--permission-mode", "plan");
2090
+ filesystem = "provider plan mode; write prevention is not an OS sandbox";
2091
+ enforcedBy.push("harness");
2092
+ } else if (requested.mode === "edit") {
2093
+ args.push("--permission-mode", "acceptEdits");
2094
+ filesystem = "provider edit permissions within configured roots";
2095
+ enforcedBy.push("harness");
2096
+ warnings.push("Exec cannot answer interactive approval requests");
2097
+ } else {
2098
+ args.push("--dangerously-skip-permissions");
2099
+ filesystem = "unrestricted";
2100
+ network = "unrestricted";
2101
+ approvals = "bypassed";
2102
+ warnings.push("Claude permission checks are bypassed");
2103
+ }
2104
+ if (requested.network === "deny") unsupported2.push("network.deny");
2105
+ if (requested.network === "allow") network = "provider-default; not guaranteed";
2106
+ } else {
2107
+ const never = transport === "exec" ? ["--ask-for-approval", "never"] : [];
2108
+ if (requested.mode === "analyze") {
2109
+ args.push("--sandbox", "read-only", ...never);
2110
+ filesystem = "read-only sandbox";
2111
+ enforcedBy.push("sandbox");
2112
+ if (never.length) approvals = "never; escalation requests are rejected";
2113
+ } else if (requested.mode === "edit") {
2114
+ args.push("--sandbox", "workspace-write", ...never);
2115
+ filesystem = "workspace-write sandbox";
2116
+ enforcedBy.push("sandbox");
2117
+ if (never.length) approvals = "never; escalation requests are rejected";
2118
+ warnings.push("Exec cannot answer interactive approval requests");
2119
+ } else {
2120
+ args.push("--dangerously-bypass-approvals-and-sandbox");
2121
+ filesystem = "unrestricted";
2122
+ network = "unrestricted";
2123
+ approvals = "bypassed";
2124
+ warnings.push("Codex approvals and sandbox are bypassed");
2125
+ }
2126
+ if (requested.network === "deny") unsupported2.push("network.deny");
2127
+ if (requested.network === "allow") network = "provider-default; not guaranteed";
2128
+ }
2129
+ for (const directory of requested.additionalDirectories ?? []) {
2130
+ args.push("--add-dir", directory);
2131
+ }
2132
+ if (requested.minimumEnforcement && !enforcedBy.includes(requested.minimumEnforcement)) {
2133
+ unsupported2.push(`minimumEnforcement.${requested.minimumEnforcement}`);
2134
+ }
2135
+ if (transport === "control" && requested.mode !== "unrestricted") {
2136
+ approvals = provider === "claude" ? "interactive" : "interactive; decline-only for command and file-change escalations below unrestricted";
2137
+ const execWarning = warnings.indexOf("Exec cannot answer interactive approval requests");
2138
+ if (execWarning !== -1) warnings.splice(execWarning, 1);
2139
+ }
2140
+ return {
2141
+ args,
2142
+ report: {
2143
+ requested: { ...requested },
2144
+ effective: { filesystem, network, approvals, enforcedBy },
2145
+ unsupported: unsupported2,
2146
+ warnings
2147
+ }
2148
+ };
2149
+ }
2150
+
2151
+ // src/core/builtin-providers.ts
2152
+ function builtin(id, options = {}) {
2153
+ const runner = options.runner;
2154
+ const probeRunner = options.probeRunner;
2155
+ if (runner !== void 0 && typeof runner !== "function") throw new TypeError("runner must be a function");
2156
+ if (probeRunner !== void 0 && typeof probeRunner !== "function") throw new TypeError("probeRunner must be a function");
2157
+ const create = (target) => {
2158
+ const adapterOptions = { ...runner === void 0 ? {} : { runner }, ...probeRunner === void 0 ? {} : { probeRunner }, ...target === void 0 ? {} : { target } };
2159
+ return id === "claude" ? new ClaudeExecAdapter(adapterOptions) : new CodexExecAdapter(adapterOptions);
2160
+ };
2161
+ return {
2162
+ apiVersion: 1,
2163
+ id,
2164
+ exec: {
2165
+ adapter: create(),
2166
+ token: EXEC_TRANSPORT_TOKENS[id],
2167
+ adapterVersion: RUNTIME_ADAPTER_VERSION,
2168
+ withTarget: create
2169
+ },
2170
+ modelCatalog: compatibilityModels(id),
2171
+ resolveModel: (nativeId) => resolveModel(`${id}/${nativeId}`),
2172
+ execCapabilities: { tokenDeltas: id === "claude" ? "unverified" : "unsupported" },
2173
+ translateContext: (requested) => translateContext(id, requested),
2174
+ translatePermissions: (requested, transport) => translatePermissions(id, requested, transport),
2175
+ validateOptions: (options2, transport) => {
2176
+ assertRespondPolicy(options2, id, transport);
2177
+ const config = id === "codex" && options2.requireAuth === "subscription" ? options2.providerOptions?.codex?.config : void 0;
2178
+ if (config && (config.profile !== void 0 || config.openai_base_url !== void 0 || (config.model_provider ?? "openai") !== "openai")) throw new UnexpectedAuthSourceError(id, {
2179
+ transport,
2180
+ retryable: false,
2181
+ sanitizedDiagnostics: { detectedSource: "provider-config" }
2182
+ });
2183
+ }
2184
+ };
2185
+ }
2186
+ function createClaudeProvider(options) {
2187
+ return builtin("claude", options);
2188
+ }
2189
+ function createCodexProvider(options) {
2190
+ return builtin("codex", options);
2191
+ }
2192
+ function createDefaultProviders() {
2193
+ return [createClaudeProvider(), createCodexProvider(), createGeminiCliProvider(), createAntigravityCliProvider()];
2194
+ }
2195
+
2196
+ // src/orchestration/log/capture-runtime.ts
2197
+ import { randomUUID as randomUUID2 } from "node:crypto";
2198
+ function createRuntimeCapture(options) {
2199
+ object(options, ["store", "identity", "maxPending", "maxWriteMs"]);
2200
+ const base = captureIdentity(options.identity), maxPending = boundedInteger(options.maxPending ?? 2, 1, 64), maxWriteMs = boundedInteger(options.maxWriteMs ?? 5e3, 1, 3e4);
2201
+ const append = method(options.store, "append");
2202
+ let pending = 0, failure;
2203
+ const stopped = new AbortController();
2204
+ const fail = (cause) => {
2205
+ if (!failure) {
2206
+ failure = isExecutionHalted(cause) ? cause : new ExecutionHaltedError({}, { cause });
2207
+ stopped.abort(failure);
2208
+ }
2209
+ return failure;
2210
+ };
2211
+ const store = Object.freeze({ append(commit) {
2212
+ if (failure) return Promise.reject(failure);
2213
+ if (pending >= maxPending) return Promise.reject(fail(Error("CAPTURE_CAPACITY")));
2214
+ pending++;
2215
+ let work;
2216
+ try {
2217
+ work = Promise.resolve(append(commit));
2218
+ } catch (error) {
2219
+ pending--;
2220
+ return Promise.reject(fail(error));
2221
+ }
2222
+ return work.then((receipt) => receipt, (error) => {
2223
+ throw fail(error);
2224
+ }).finally(() => {
2225
+ pending--;
2226
+ });
2227
+ } });
2228
+ return Object.freeze({ bindAgent() {
2229
+ const identity = captureIdentity({ ...base, agentId: `agent-${randomUUID2()}` });
2230
+ return Object.freeze({ identity, assertActive() {
2231
+ if (failure) throw failure;
2232
+ }, create(model, transport, phase, signal, session) {
2233
+ if (failure) throw failure;
2234
+ const operationSignal = signal ? AbortSignal.any([signal, stopped.signal]) : stopped.signal;
2235
+ const capture = createRequiredLogCapture({ store, identity, actual: { provider: model.provider, model: model.id, transport, phase, attemptId: randomUUID2(), ...session ? { sessionId: session.id, transportEpoch: session.transportEpoch } : {} }, maxPending, maxWriteMs, signal: operationSignal });
2236
+ capture.signal.addEventListener("abort", () => {
2237
+ fail(capture.signal.reason);
2238
+ }, { once: true });
2239
+ return Object.freeze({
2240
+ ...capture,
2241
+ signal: AbortSignal.any([capture.signal, stopped.signal]),
2242
+ async run(work) {
2243
+ try {
2244
+ return await capture.run(work);
2245
+ } catch (error) {
2246
+ if (isExecutionHalted(error)) fail(error);
2247
+ throw error;
2248
+ }
2249
+ }
2250
+ });
2251
+ } });
2252
+ } });
2253
+ }
2254
+
2255
+ // src/core/runtime.ts
2256
+ var Runtime = class {
2257
+ #registry = new AdapterRegistry();
2258
+ #providers = /* @__PURE__ */ new Map();
2259
+ #legacyAdapters;
2260
+ #capture;
2261
+ #memory;
2262
+ constructor(options = {}) {
2263
+ const memory = options.memory;
2264
+ if (memory !== void 0 && (typeof memory !== "object" || memory === null || typeof memory.scope !== "function")) {
2265
+ throw new TypeError("The Runtime memory default must be an object whose scope is a function");
2266
+ }
2267
+ this.#memory = memory === void 0 ? void 0 : Object.freeze({ ...memory });
2268
+ const capture = field(options, "capture");
2269
+ this.#capture = capture === void 0 ? void 0 : createRuntimeCapture(capture);
2270
+ this.#legacyAdapters = options.adapters !== void 0;
2271
+ if (options.providers && (options.adapters || options.controlAdapters)) {
2272
+ throw new TypeError("providers cannot be combined with adapters or controlAdapters");
2273
+ }
2274
+ const providers = options.providers ?? (this.#legacyAdapters ? [createClaudeProvider(), createCodexProvider()] : createDefaultProviders());
2275
+ for (const input of providers) {
2276
+ const registration = snapshotProvider(input);
2277
+ if (this.#providers.has(registration.id)) {
2278
+ throw new TypeError(`Provider ${registration.id} is already registered`);
2279
+ }
2280
+ this.#providers.set(registration.id, registration);
2281
+ if (!options.adapters) this.#registry.registerExec(registration.exec);
2282
+ if (registration.control) this.#registry.registerControl(registration.control);
2283
+ }
2284
+ for (const adapter of options.adapters ?? []) {
2285
+ this.#registry.registerExec({ adapter });
2286
+ }
2287
+ for (const registration of options.controlAdapters ?? []) {
2288
+ this.#registry.registerControl(registration);
2289
+ }
2290
+ }
2291
+ get registry() {
2292
+ return this.#registry;
2293
+ }
2294
+ bindLogCapture() {
2295
+ return this.#capture?.bindAgent();
2296
+ }
2297
+ /** The memory every Agent of this Runtime gets unless it says otherwise. */
2298
+ memoryDefault() {
2299
+ return this.#memory;
2300
+ }
2301
+ registration(provider) {
2302
+ const registration = this.#providers.get(provider);
2303
+ if (!registration) throw new UnknownProviderError(provider);
2304
+ return registration;
2305
+ }
2306
+ resolveModel(requested) {
2307
+ const value = requested.trim();
2308
+ if (!value) throw new UnknownModelError(requested);
2309
+ const slash = value.indexOf("/");
2310
+ if (slash > 0) {
2311
+ const prefix = value.slice(0, slash);
2312
+ const provider = ["claude", "codex"].includes(prefix.toLowerCase()) ? prefix.toLowerCase() : prefix;
2313
+ const native = value.slice(slash + 1);
2314
+ if (!native) throw new UnknownModelError(requested);
2315
+ const registration = this.registration(provider);
2316
+ const known = this.#find(registration, native);
2317
+ const model = known ?? registration.resolveModel(native);
2318
+ if (model.provider !== provider || !model.id.trim()) {
2319
+ throw new TypeError("Resolved model provider mismatch");
2320
+ }
2321
+ return structuredClone(model);
2322
+ }
2323
+ const matches = [...this.#providers.values()].flatMap((registration) => {
2324
+ const match = this.#find(registration, value);
2325
+ return match ? [match] : [];
2326
+ });
2327
+ if (matches.length > 1 || ["best", "default"].includes(value.toLowerCase()) && this.#providers.size > 1) {
2328
+ throw new AmbiguousModelError(requested, matches.length ? matches.map((model) => model.provider) : [...this.#providers.keys()]);
2329
+ }
2330
+ if (matches[0]) return structuredClone(matches[0]);
2331
+ const inferred = value.toLowerCase().startsWith("claude-") ? "claude" : value.toLowerCase().startsWith("gpt-") || /^o\d/.test(value.toLowerCase()) ? "codex" : void 0;
2332
+ if (inferred && this.#providers.has(inferred)) {
2333
+ const model = this.registration(inferred).resolveModel(value);
2334
+ if (model.provider !== inferred || !model.id.trim()) throw new TypeError("Resolved model provider mismatch");
2335
+ return structuredClone(model);
2336
+ }
2337
+ try {
2338
+ resolveModel(requested);
2339
+ } catch (error) {
2340
+ if (error instanceof UnknownModelError) throw error;
2341
+ }
2342
+ throw new UnknownModelError(requested);
2343
+ }
2344
+ #find(registration, id) {
2345
+ const builtin2 = registration.id === "claude" || registration.id === "codex";
2346
+ const value = builtin2 ? id.toLowerCase() : id;
2347
+ return registration.modelCatalog.find((model) => model.id === value || model.aliases.includes(value));
2348
+ }
2349
+ async models(provider) {
2350
+ if (this.#legacyAdapters) {
2351
+ const ids = provider === void 0 ? this.providers() : [provider];
2352
+ const catalogs = await Promise.all(ids.map(async (id) => {
2353
+ const models = await this.adapter(id).models();
2354
+ if (models.some((model) => model.provider !== id)) throw new TypeError("Model catalog provider mismatch");
2355
+ return structuredClone(models);
2356
+ }));
2357
+ return catalogs.flat();
2358
+ }
2359
+ const providers = provider === void 0 ? [...this.#providers.values()] : [this.registration(provider)];
2360
+ return providers.flatMap((registration) => structuredClone([...registration.modelCatalog]));
2361
+ }
2362
+ adapter(provider) {
2363
+ const registration = this.#registry.execRegistration(provider);
2364
+ if (!registration) throw new UnknownProviderError(provider);
2365
+ return registration.adapter;
2366
+ }
2367
+ adapterWithTarget(provider, target) {
2368
+ const registration = this.#registry.execRegistration(provider);
2369
+ if (!registration) throw new UnknownProviderError(provider);
2370
+ const adapter = registration.withTarget?.(target) ?? registration.adapter;
2371
+ if (adapter.id !== provider) throw new TypeError("Bound adapter provider mismatch");
2372
+ return adapter;
2373
+ }
2374
+ controlRegistration(provider) {
2375
+ return this.#registry.control(provider);
2376
+ }
2377
+ providers() {
2378
+ return this.#registry.providers();
2379
+ }
2380
+ };
2381
+ var defaultRuntime = new Runtime();
2382
+
2383
+ export {
2384
+ createAntigravityCliProvider,
2385
+ createGeminiCliProvider,
2386
+ parseClaudeJsonl,
2387
+ ClaudeExecAdapter,
2388
+ normalizeContextPolicy,
2389
+ translateContext,
2390
+ translatePermissions,
2391
+ createClaudeProvider,
2392
+ createCodexProvider,
2393
+ createDefaultProviders,
2394
+ Runtime,
2395
+ defaultRuntime
2396
+ };
2397
+ //# sourceMappingURL=chunk-2RK74GCA.js.map