@draht/ai 2026.3.2-2

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 (154) hide show
  1. package/README.md +1185 -0
  2. package/dist/api-registry.d.ts +20 -0
  3. package/dist/api-registry.d.ts.map +1 -0
  4. package/dist/api-registry.js +44 -0
  5. package/dist/api-registry.js.map +1 -0
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +116 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/env-api-keys.d.ts +9 -0
  11. package/dist/env-api-keys.d.ts.map +1 -0
  12. package/dist/env-api-keys.js +99 -0
  13. package/dist/env-api-keys.js.map +1 -0
  14. package/dist/index.d.ts +22 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +21 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/models.d.ts +24 -0
  19. package/dist/models.d.ts.map +1 -0
  20. package/dist/models.generated.d.ts +13133 -0
  21. package/dist/models.generated.d.ts.map +1 -0
  22. package/dist/models.generated.js +12939 -0
  23. package/dist/models.generated.js.map +1 -0
  24. package/dist/models.js +55 -0
  25. package/dist/models.js.map +1 -0
  26. package/dist/providers/amazon-bedrock.d.ts +15 -0
  27. package/dist/providers/amazon-bedrock.d.ts.map +1 -0
  28. package/dist/providers/amazon-bedrock.js +585 -0
  29. package/dist/providers/amazon-bedrock.js.map +1 -0
  30. package/dist/providers/anthropic.d.ts +33 -0
  31. package/dist/providers/anthropic.d.ts.map +1 -0
  32. package/dist/providers/anthropic.js +729 -0
  33. package/dist/providers/anthropic.js.map +1 -0
  34. package/dist/providers/azure-openai-responses.d.ts +15 -0
  35. package/dist/providers/azure-openai-responses.d.ts.map +1 -0
  36. package/dist/providers/azure-openai-responses.js +184 -0
  37. package/dist/providers/azure-openai-responses.js.map +1 -0
  38. package/dist/providers/github-copilot-headers.d.ts +8 -0
  39. package/dist/providers/github-copilot-headers.d.ts.map +1 -0
  40. package/dist/providers/github-copilot-headers.js +29 -0
  41. package/dist/providers/github-copilot-headers.js.map +1 -0
  42. package/dist/providers/google-gemini-cli.d.ts +74 -0
  43. package/dist/providers/google-gemini-cli.d.ts.map +1 -0
  44. package/dist/providers/google-gemini-cli.js +735 -0
  45. package/dist/providers/google-gemini-cli.js.map +1 -0
  46. package/dist/providers/google-shared.d.ts +65 -0
  47. package/dist/providers/google-shared.d.ts.map +1 -0
  48. package/dist/providers/google-shared.js +306 -0
  49. package/dist/providers/google-shared.js.map +1 -0
  50. package/dist/providers/google-vertex.d.ts +15 -0
  51. package/dist/providers/google-vertex.d.ts.map +1 -0
  52. package/dist/providers/google-vertex.js +371 -0
  53. package/dist/providers/google-vertex.js.map +1 -0
  54. package/dist/providers/google.d.ts +13 -0
  55. package/dist/providers/google.d.ts.map +1 -0
  56. package/dist/providers/google.js +352 -0
  57. package/dist/providers/google.js.map +1 -0
  58. package/dist/providers/openai-codex-responses.d.ts +9 -0
  59. package/dist/providers/openai-codex-responses.d.ts.map +1 -0
  60. package/dist/providers/openai-codex-responses.js +699 -0
  61. package/dist/providers/openai-codex-responses.js.map +1 -0
  62. package/dist/providers/openai-completions.d.ts +15 -0
  63. package/dist/providers/openai-completions.d.ts.map +1 -0
  64. package/dist/providers/openai-completions.js +712 -0
  65. package/dist/providers/openai-completions.js.map +1 -0
  66. package/dist/providers/openai-responses-shared.d.ts +17 -0
  67. package/dist/providers/openai-responses-shared.d.ts.map +1 -0
  68. package/dist/providers/openai-responses-shared.js +427 -0
  69. package/dist/providers/openai-responses-shared.js.map +1 -0
  70. package/dist/providers/openai-responses.d.ts +13 -0
  71. package/dist/providers/openai-responses.d.ts.map +1 -0
  72. package/dist/providers/openai-responses.js +198 -0
  73. package/dist/providers/openai-responses.js.map +1 -0
  74. package/dist/providers/register-builtins.d.ts +3 -0
  75. package/dist/providers/register-builtins.d.ts.map +1 -0
  76. package/dist/providers/register-builtins.js +63 -0
  77. package/dist/providers/register-builtins.js.map +1 -0
  78. package/dist/providers/simple-options.d.ts +8 -0
  79. package/dist/providers/simple-options.d.ts.map +1 -0
  80. package/dist/providers/simple-options.js +35 -0
  81. package/dist/providers/simple-options.js.map +1 -0
  82. package/dist/providers/transform-messages.d.ts +8 -0
  83. package/dist/providers/transform-messages.d.ts.map +1 -0
  84. package/dist/providers/transform-messages.js +155 -0
  85. package/dist/providers/transform-messages.js.map +1 -0
  86. package/dist/stream.d.ts +9 -0
  87. package/dist/stream.d.ts.map +1 -0
  88. package/dist/stream.js +28 -0
  89. package/dist/stream.js.map +1 -0
  90. package/dist/types.d.ts +279 -0
  91. package/dist/types.d.ts.map +1 -0
  92. package/dist/types.js +2 -0
  93. package/dist/types.js.map +1 -0
  94. package/dist/utils/event-stream.d.ts +21 -0
  95. package/dist/utils/event-stream.d.ts.map +1 -0
  96. package/dist/utils/event-stream.js +81 -0
  97. package/dist/utils/event-stream.js.map +1 -0
  98. package/dist/utils/http-proxy.d.ts +2 -0
  99. package/dist/utils/http-proxy.d.ts.map +1 -0
  100. package/dist/utils/http-proxy.js +15 -0
  101. package/dist/utils/http-proxy.js.map +1 -0
  102. package/dist/utils/json-parse.d.ts +9 -0
  103. package/dist/utils/json-parse.d.ts.map +1 -0
  104. package/dist/utils/json-parse.js +29 -0
  105. package/dist/utils/json-parse.js.map +1 -0
  106. package/dist/utils/oauth/anthropic.d.ts +17 -0
  107. package/dist/utils/oauth/anthropic.d.ts.map +1 -0
  108. package/dist/utils/oauth/anthropic.js +104 -0
  109. package/dist/utils/oauth/anthropic.js.map +1 -0
  110. package/dist/utils/oauth/github-copilot.d.ts +30 -0
  111. package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
  112. package/dist/utils/oauth/github-copilot.js +281 -0
  113. package/dist/utils/oauth/github-copilot.js.map +1 -0
  114. package/dist/utils/oauth/google-antigravity.d.ts +26 -0
  115. package/dist/utils/oauth/google-antigravity.d.ts.map +1 -0
  116. package/dist/utils/oauth/google-antigravity.js +373 -0
  117. package/dist/utils/oauth/google-antigravity.js.map +1 -0
  118. package/dist/utils/oauth/google-gemini-cli.d.ts +26 -0
  119. package/dist/utils/oauth/google-gemini-cli.d.ts.map +1 -0
  120. package/dist/utils/oauth/google-gemini-cli.js +478 -0
  121. package/dist/utils/oauth/google-gemini-cli.js.map +1 -0
  122. package/dist/utils/oauth/index.d.ts +62 -0
  123. package/dist/utils/oauth/index.d.ts.map +1 -0
  124. package/dist/utils/oauth/index.js +133 -0
  125. package/dist/utils/oauth/index.js.map +1 -0
  126. package/dist/utils/oauth/openai-codex.d.ts +34 -0
  127. package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
  128. package/dist/utils/oauth/openai-codex.js +380 -0
  129. package/dist/utils/oauth/openai-codex.js.map +1 -0
  130. package/dist/utils/oauth/pkce.d.ts +13 -0
  131. package/dist/utils/oauth/pkce.d.ts.map +1 -0
  132. package/dist/utils/oauth/pkce.js +31 -0
  133. package/dist/utils/oauth/pkce.js.map +1 -0
  134. package/dist/utils/oauth/types.d.ts +47 -0
  135. package/dist/utils/oauth/types.d.ts.map +1 -0
  136. package/dist/utils/oauth/types.js +2 -0
  137. package/dist/utils/oauth/types.js.map +1 -0
  138. package/dist/utils/overflow.d.ts +52 -0
  139. package/dist/utils/overflow.d.ts.map +1 -0
  140. package/dist/utils/overflow.js +115 -0
  141. package/dist/utils/overflow.js.map +1 -0
  142. package/dist/utils/sanitize-unicode.d.ts +22 -0
  143. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  144. package/dist/utils/sanitize-unicode.js +26 -0
  145. package/dist/utils/sanitize-unicode.js.map +1 -0
  146. package/dist/utils/typebox-helpers.d.ts +17 -0
  147. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  148. package/dist/utils/typebox-helpers.js +21 -0
  149. package/dist/utils/typebox-helpers.js.map +1 -0
  150. package/dist/utils/validation.d.ts +18 -0
  151. package/dist/utils/validation.d.ts.map +1 -0
  152. package/dist/utils/validation.js +72 -0
  153. package/dist/utils/validation.js.map +1 -0
  154. package/package.json +67 -0
@@ -0,0 +1,735 @@
1
+ /**
2
+ * Google Gemini CLI / Antigravity provider.
3
+ * Shared implementation for both google-gemini-cli and google-antigravity providers.
4
+ * Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.
5
+ */
6
+ import { calculateCost } from "../models.js";
7
+ import { AssistantMessageEventStream } from "../utils/event-stream.js";
8
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
9
+ import { convertMessages, convertTools, isThinkingPart, mapStopReasonString, mapToolChoice, retainThoughtSignature, } from "./google-shared.js";
10
+ import { buildBaseOptions, clampReasoning } from "./simple-options.js";
11
+ const DEFAULT_ENDPOINT = "https://cloudcode-pa.googleapis.com";
12
+ const ANTIGRAVITY_DAILY_ENDPOINT = "https://daily-cloudcode-pa.sandbox.googleapis.com";
13
+ const ANTIGRAVITY_ENDPOINT_FALLBACKS = [ANTIGRAVITY_DAILY_ENDPOINT, DEFAULT_ENDPOINT];
14
+ // Headers for Gemini CLI (prod endpoint)
15
+ const GEMINI_CLI_HEADERS = {
16
+ "User-Agent": "google-cloud-sdk vscode_cloudshelleditor/0.1",
17
+ "X-Goog-Api-Client": "gl-node/22.17.0",
18
+ "Client-Metadata": JSON.stringify({
19
+ ideType: "IDE_UNSPECIFIED",
20
+ platform: "PLATFORM_UNSPECIFIED",
21
+ pluginType: "GEMINI",
22
+ }),
23
+ };
24
+ // Headers for Antigravity (sandbox endpoint) - requires specific User-Agent
25
+ const DEFAULT_ANTIGRAVITY_VERSION = "1.15.8";
26
+ function getAntigravityHeaders() {
27
+ const version = process.env.DRAHT_AI_ANTIGRAVITY_VERSION || DEFAULT_ANTIGRAVITY_VERSION;
28
+ return {
29
+ "User-Agent": `antigravity/${version} darwin/arm64`,
30
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
31
+ "Client-Metadata": JSON.stringify({
32
+ ideType: "IDE_UNSPECIFIED",
33
+ platform: "PLATFORM_UNSPECIFIED",
34
+ pluginType: "GEMINI",
35
+ }),
36
+ };
37
+ }
38
+ // Antigravity system instruction (compact version from CLIProxyAPI).
39
+ const ANTIGRAVITY_SYSTEM_INSTRUCTION = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding." +
40
+ "You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question." +
41
+ "**Absolute paths only**" +
42
+ "**Proactiveness**";
43
+ // Counter for generating unique tool call IDs
44
+ let toolCallCounter = 0;
45
+ // Retry configuration
46
+ const MAX_RETRIES = 3;
47
+ const BASE_DELAY_MS = 1000;
48
+ const MAX_EMPTY_STREAM_RETRIES = 2;
49
+ const EMPTY_STREAM_BASE_DELAY_MS = 500;
50
+ const CLAUDE_THINKING_BETA_HEADER = "interleaved-thinking-2025-05-14";
51
+ /**
52
+ * Extract retry delay from Gemini error response (in milliseconds).
53
+ * Checks headers first (Retry-After, x-ratelimit-reset, x-ratelimit-reset-after),
54
+ * then parses body patterns like:
55
+ * - "Your quota will reset after 39s"
56
+ * - "Your quota will reset after 18h31m10s"
57
+ * - "Please retry in Xs" or "Please retry in Xms"
58
+ * - "retryDelay": "34.074824224s" (JSON field)
59
+ */
60
+ export function extractRetryDelay(errorText, response) {
61
+ const normalizeDelay = (ms) => (ms > 0 ? Math.ceil(ms + 1000) : undefined);
62
+ const headers = response instanceof Headers ? response : response?.headers;
63
+ if (headers) {
64
+ const retryAfter = headers.get("retry-after");
65
+ if (retryAfter) {
66
+ const retryAfterSeconds = Number(retryAfter);
67
+ if (Number.isFinite(retryAfterSeconds)) {
68
+ const delay = normalizeDelay(retryAfterSeconds * 1000);
69
+ if (delay !== undefined) {
70
+ return delay;
71
+ }
72
+ }
73
+ const retryAfterDate = new Date(retryAfter);
74
+ const retryAfterMs = retryAfterDate.getTime();
75
+ if (!Number.isNaN(retryAfterMs)) {
76
+ const delay = normalizeDelay(retryAfterMs - Date.now());
77
+ if (delay !== undefined) {
78
+ return delay;
79
+ }
80
+ }
81
+ }
82
+ const rateLimitReset = headers.get("x-ratelimit-reset");
83
+ if (rateLimitReset) {
84
+ const resetSeconds = Number.parseInt(rateLimitReset, 10);
85
+ if (!Number.isNaN(resetSeconds)) {
86
+ const delay = normalizeDelay(resetSeconds * 1000 - Date.now());
87
+ if (delay !== undefined) {
88
+ return delay;
89
+ }
90
+ }
91
+ }
92
+ const rateLimitResetAfter = headers.get("x-ratelimit-reset-after");
93
+ if (rateLimitResetAfter) {
94
+ const resetAfterSeconds = Number(rateLimitResetAfter);
95
+ if (Number.isFinite(resetAfterSeconds)) {
96
+ const delay = normalizeDelay(resetAfterSeconds * 1000);
97
+ if (delay !== undefined) {
98
+ return delay;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ // Pattern 1: "Your quota will reset after ..." (formats: "18h31m10s", "10m15s", "6s", "39s")
104
+ const durationMatch = errorText.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);
105
+ if (durationMatch) {
106
+ const hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0;
107
+ const minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;
108
+ const seconds = parseFloat(durationMatch[3]);
109
+ if (!Number.isNaN(seconds)) {
110
+ const totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;
111
+ const delay = normalizeDelay(totalMs);
112
+ if (delay !== undefined) {
113
+ return delay;
114
+ }
115
+ }
116
+ }
117
+ // Pattern 2: "Please retry in X[ms|s]"
118
+ const retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i);
119
+ if (retryInMatch?.[1]) {
120
+ const value = parseFloat(retryInMatch[1]);
121
+ if (!Number.isNaN(value) && value > 0) {
122
+ const ms = retryInMatch[2].toLowerCase() === "ms" ? value : value * 1000;
123
+ const delay = normalizeDelay(ms);
124
+ if (delay !== undefined) {
125
+ return delay;
126
+ }
127
+ }
128
+ }
129
+ // Pattern 3: "retryDelay": "34.074824224s" (JSON field in error details)
130
+ const retryDelayMatch = errorText.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i);
131
+ if (retryDelayMatch?.[1]) {
132
+ const value = parseFloat(retryDelayMatch[1]);
133
+ if (!Number.isNaN(value) && value > 0) {
134
+ const ms = retryDelayMatch[2].toLowerCase() === "ms" ? value : value * 1000;
135
+ const delay = normalizeDelay(ms);
136
+ if (delay !== undefined) {
137
+ return delay;
138
+ }
139
+ }
140
+ }
141
+ return undefined;
142
+ }
143
+ function isClaudeThinkingModel(modelId) {
144
+ const normalized = modelId.toLowerCase();
145
+ return normalized.includes("claude") && normalized.includes("thinking");
146
+ }
147
+ /**
148
+ * Check if an error is retryable (rate limit, server error, network error, etc.)
149
+ */
150
+ function isRetryableError(status, errorText) {
151
+ if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
152
+ return true;
153
+ }
154
+ return /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText);
155
+ }
156
+ /**
157
+ * Extract a clean, user-friendly error message from Google API error response.
158
+ * Parses JSON error responses and returns just the message field.
159
+ */
160
+ function extractErrorMessage(errorText) {
161
+ try {
162
+ const parsed = JSON.parse(errorText);
163
+ if (parsed.error?.message) {
164
+ return parsed.error.message;
165
+ }
166
+ }
167
+ catch {
168
+ // Not JSON, return as-is
169
+ }
170
+ return errorText;
171
+ }
172
+ /**
173
+ * Sleep for a given number of milliseconds, respecting abort signal.
174
+ */
175
+ function sleep(ms, signal) {
176
+ return new Promise((resolve, reject) => {
177
+ if (signal?.aborted) {
178
+ reject(new Error("Request was aborted"));
179
+ return;
180
+ }
181
+ const timeout = setTimeout(resolve, ms);
182
+ signal?.addEventListener("abort", () => {
183
+ clearTimeout(timeout);
184
+ reject(new Error("Request was aborted"));
185
+ });
186
+ });
187
+ }
188
+ export const streamGoogleGeminiCli = (model, context, options) => {
189
+ const stream = new AssistantMessageEventStream();
190
+ (async () => {
191
+ const output = {
192
+ role: "assistant",
193
+ content: [],
194
+ api: "google-gemini-cli",
195
+ provider: model.provider,
196
+ model: model.id,
197
+ usage: {
198
+ input: 0,
199
+ output: 0,
200
+ cacheRead: 0,
201
+ cacheWrite: 0,
202
+ totalTokens: 0,
203
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
204
+ },
205
+ stopReason: "stop",
206
+ timestamp: Date.now(),
207
+ };
208
+ try {
209
+ // apiKey is JSON-encoded: { token, projectId }
210
+ const apiKeyRaw = options?.apiKey;
211
+ if (!apiKeyRaw) {
212
+ throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
213
+ }
214
+ let accessToken;
215
+ let projectId;
216
+ try {
217
+ const parsed = JSON.parse(apiKeyRaw);
218
+ accessToken = parsed.token;
219
+ projectId = parsed.projectId;
220
+ }
221
+ catch {
222
+ throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.");
223
+ }
224
+ if (!accessToken || !projectId) {
225
+ throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.");
226
+ }
227
+ const isAntigravity = model.provider === "google-antigravity";
228
+ const baseUrl = model.baseUrl?.trim();
229
+ const endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS : [DEFAULT_ENDPOINT];
230
+ const requestBody = buildRequest(model, context, projectId, options, isAntigravity);
231
+ options?.onPayload?.(requestBody);
232
+ const headers = isAntigravity ? getAntigravityHeaders() : GEMINI_CLI_HEADERS;
233
+ const requestHeaders = {
234
+ Authorization: `Bearer ${accessToken}`,
235
+ "Content-Type": "application/json",
236
+ Accept: "text/event-stream",
237
+ ...headers,
238
+ ...(isClaudeThinkingModel(model.id) ? { "anthropic-beta": CLAUDE_THINKING_BETA_HEADER } : {}),
239
+ ...options?.headers,
240
+ };
241
+ const requestBodyJson = JSON.stringify(requestBody);
242
+ // Fetch with retry logic for rate limits and transient errors
243
+ let response;
244
+ let lastError;
245
+ let requestUrl;
246
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
247
+ if (options?.signal?.aborted) {
248
+ throw new Error("Request was aborted");
249
+ }
250
+ try {
251
+ const endpoint = endpoints[Math.min(attempt, endpoints.length - 1)];
252
+ requestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
253
+ response = await fetch(requestUrl, {
254
+ method: "POST",
255
+ headers: requestHeaders,
256
+ body: requestBodyJson,
257
+ signal: options?.signal,
258
+ });
259
+ if (response.ok) {
260
+ break; // Success, exit retry loop
261
+ }
262
+ const errorText = await response.text();
263
+ // Check if retryable
264
+ if (attempt < MAX_RETRIES && isRetryableError(response.status, errorText)) {
265
+ // Use server-provided delay or exponential backoff
266
+ const serverDelay = extractRetryDelay(errorText, response);
267
+ const delayMs = serverDelay ?? BASE_DELAY_MS * 2 ** attempt;
268
+ // Check if server delay exceeds max allowed (default: 60s)
269
+ const maxDelayMs = options?.maxRetryDelayMs ?? 60000;
270
+ if (maxDelayMs > 0 && serverDelay && serverDelay > maxDelayMs) {
271
+ const delaySeconds = Math.ceil(serverDelay / 1000);
272
+ throw new Error(`Server requested ${delaySeconds}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${extractErrorMessage(errorText)}`);
273
+ }
274
+ await sleep(delayMs, options?.signal);
275
+ continue;
276
+ }
277
+ // Not retryable or max retries exceeded
278
+ throw new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage(errorText)}`);
279
+ }
280
+ catch (error) {
281
+ // Check for abort - fetch throws AbortError, our code throws "Request was aborted"
282
+ if (error instanceof Error) {
283
+ if (error.name === "AbortError" || error.message === "Request was aborted") {
284
+ throw new Error("Request was aborted");
285
+ }
286
+ }
287
+ // Extract detailed error message from fetch errors (Node includes cause)
288
+ lastError = error instanceof Error ? error : new Error(String(error));
289
+ if (lastError.message === "fetch failed" && lastError.cause instanceof Error) {
290
+ lastError = new Error(`Network error: ${lastError.cause.message}`);
291
+ }
292
+ // Network errors are retryable
293
+ if (attempt < MAX_RETRIES) {
294
+ const delayMs = BASE_DELAY_MS * 2 ** attempt;
295
+ await sleep(delayMs, options?.signal);
296
+ continue;
297
+ }
298
+ throw lastError;
299
+ }
300
+ }
301
+ if (!response || !response.ok) {
302
+ throw lastError ?? new Error("Failed to get response after retries");
303
+ }
304
+ let started = false;
305
+ const ensureStarted = () => {
306
+ if (!started) {
307
+ stream.push({ type: "start", partial: output });
308
+ started = true;
309
+ }
310
+ };
311
+ const resetOutput = () => {
312
+ output.content = [];
313
+ output.usage = {
314
+ input: 0,
315
+ output: 0,
316
+ cacheRead: 0,
317
+ cacheWrite: 0,
318
+ totalTokens: 0,
319
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
320
+ };
321
+ output.stopReason = "stop";
322
+ output.errorMessage = undefined;
323
+ output.timestamp = Date.now();
324
+ started = false;
325
+ };
326
+ const streamResponse = async (activeResponse) => {
327
+ if (!activeResponse.body) {
328
+ throw new Error("No response body");
329
+ }
330
+ let hasContent = false;
331
+ let currentBlock = null;
332
+ const blocks = output.content;
333
+ const blockIndex = () => blocks.length - 1;
334
+ // Read SSE stream
335
+ const reader = activeResponse.body.getReader();
336
+ const decoder = new TextDecoder();
337
+ let buffer = "";
338
+ // Set up abort handler to cancel reader when signal fires
339
+ const abortHandler = () => {
340
+ void reader.cancel().catch(() => { });
341
+ };
342
+ options?.signal?.addEventListener("abort", abortHandler);
343
+ try {
344
+ while (true) {
345
+ // Check abort signal before each read
346
+ if (options?.signal?.aborted) {
347
+ throw new Error("Request was aborted");
348
+ }
349
+ const { done, value } = await reader.read();
350
+ if (done)
351
+ break;
352
+ buffer += decoder.decode(value, { stream: true });
353
+ const lines = buffer.split("\n");
354
+ buffer = lines.pop() || "";
355
+ for (const line of lines) {
356
+ if (!line.startsWith("data:"))
357
+ continue;
358
+ const jsonStr = line.slice(5).trim();
359
+ if (!jsonStr)
360
+ continue;
361
+ let chunk;
362
+ try {
363
+ chunk = JSON.parse(jsonStr);
364
+ }
365
+ catch {
366
+ continue;
367
+ }
368
+ // Unwrap the response
369
+ const responseData = chunk.response;
370
+ if (!responseData)
371
+ continue;
372
+ const candidate = responseData.candidates?.[0];
373
+ if (candidate?.content?.parts) {
374
+ for (const part of candidate.content.parts) {
375
+ if (part.text !== undefined) {
376
+ hasContent = true;
377
+ const isThinking = isThinkingPart(part);
378
+ if (!currentBlock ||
379
+ (isThinking && currentBlock.type !== "thinking") ||
380
+ (!isThinking && currentBlock.type !== "text")) {
381
+ if (currentBlock) {
382
+ if (currentBlock.type === "text") {
383
+ stream.push({
384
+ type: "text_end",
385
+ contentIndex: blocks.length - 1,
386
+ content: currentBlock.text,
387
+ partial: output,
388
+ });
389
+ }
390
+ else {
391
+ stream.push({
392
+ type: "thinking_end",
393
+ contentIndex: blockIndex(),
394
+ content: currentBlock.thinking,
395
+ partial: output,
396
+ });
397
+ }
398
+ }
399
+ if (isThinking) {
400
+ currentBlock = { type: "thinking", thinking: "", thinkingSignature: undefined };
401
+ output.content.push(currentBlock);
402
+ ensureStarted();
403
+ stream.push({
404
+ type: "thinking_start",
405
+ contentIndex: blockIndex(),
406
+ partial: output,
407
+ });
408
+ }
409
+ else {
410
+ currentBlock = { type: "text", text: "" };
411
+ output.content.push(currentBlock);
412
+ ensureStarted();
413
+ stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
414
+ }
415
+ }
416
+ if (currentBlock.type === "thinking") {
417
+ currentBlock.thinking += part.text;
418
+ currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);
419
+ stream.push({
420
+ type: "thinking_delta",
421
+ contentIndex: blockIndex(),
422
+ delta: part.text,
423
+ partial: output,
424
+ });
425
+ }
426
+ else {
427
+ currentBlock.text += part.text;
428
+ currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);
429
+ stream.push({
430
+ type: "text_delta",
431
+ contentIndex: blockIndex(),
432
+ delta: part.text,
433
+ partial: output,
434
+ });
435
+ }
436
+ }
437
+ if (part.functionCall) {
438
+ hasContent = true;
439
+ if (currentBlock) {
440
+ if (currentBlock.type === "text") {
441
+ stream.push({
442
+ type: "text_end",
443
+ contentIndex: blockIndex(),
444
+ content: currentBlock.text,
445
+ partial: output,
446
+ });
447
+ }
448
+ else {
449
+ stream.push({
450
+ type: "thinking_end",
451
+ contentIndex: blockIndex(),
452
+ content: currentBlock.thinking,
453
+ partial: output,
454
+ });
455
+ }
456
+ currentBlock = null;
457
+ }
458
+ const providedId = part.functionCall.id;
459
+ const needsNewId = !providedId ||
460
+ output.content.some((b) => b.type === "toolCall" && b.id === providedId);
461
+ const toolCallId = needsNewId
462
+ ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`
463
+ : providedId;
464
+ const toolCall = {
465
+ type: "toolCall",
466
+ id: toolCallId,
467
+ name: part.functionCall.name || "",
468
+ arguments: part.functionCall.args ?? {},
469
+ ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),
470
+ };
471
+ output.content.push(toolCall);
472
+ ensureStarted();
473
+ stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
474
+ stream.push({
475
+ type: "toolcall_delta",
476
+ contentIndex: blockIndex(),
477
+ delta: JSON.stringify(toolCall.arguments),
478
+ partial: output,
479
+ });
480
+ stream.push({
481
+ type: "toolcall_end",
482
+ contentIndex: blockIndex(),
483
+ toolCall,
484
+ partial: output,
485
+ });
486
+ }
487
+ }
488
+ }
489
+ if (candidate?.finishReason) {
490
+ output.stopReason = mapStopReasonString(candidate.finishReason);
491
+ if (output.content.some((b) => b.type === "toolCall")) {
492
+ output.stopReason = "toolUse";
493
+ }
494
+ }
495
+ if (responseData.usageMetadata) {
496
+ // promptTokenCount includes cachedContentTokenCount, so subtract to get fresh input
497
+ const promptTokens = responseData.usageMetadata.promptTokenCount || 0;
498
+ const cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;
499
+ output.usage = {
500
+ input: promptTokens - cacheReadTokens,
501
+ output: (responseData.usageMetadata.candidatesTokenCount || 0) +
502
+ (responseData.usageMetadata.thoughtsTokenCount || 0),
503
+ cacheRead: cacheReadTokens,
504
+ cacheWrite: 0,
505
+ totalTokens: responseData.usageMetadata.totalTokenCount || 0,
506
+ cost: {
507
+ input: 0,
508
+ output: 0,
509
+ cacheRead: 0,
510
+ cacheWrite: 0,
511
+ total: 0,
512
+ },
513
+ };
514
+ calculateCost(model, output.usage);
515
+ }
516
+ }
517
+ }
518
+ }
519
+ finally {
520
+ options?.signal?.removeEventListener("abort", abortHandler);
521
+ }
522
+ if (currentBlock) {
523
+ if (currentBlock.type === "text") {
524
+ stream.push({
525
+ type: "text_end",
526
+ contentIndex: blockIndex(),
527
+ content: currentBlock.text,
528
+ partial: output,
529
+ });
530
+ }
531
+ else {
532
+ stream.push({
533
+ type: "thinking_end",
534
+ contentIndex: blockIndex(),
535
+ content: currentBlock.thinking,
536
+ partial: output,
537
+ });
538
+ }
539
+ }
540
+ return hasContent;
541
+ };
542
+ let receivedContent = false;
543
+ let currentResponse = response;
544
+ for (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES; emptyAttempt++) {
545
+ if (options?.signal?.aborted) {
546
+ throw new Error("Request was aborted");
547
+ }
548
+ if (emptyAttempt > 0) {
549
+ const backoffMs = EMPTY_STREAM_BASE_DELAY_MS * 2 ** (emptyAttempt - 1);
550
+ await sleep(backoffMs, options?.signal);
551
+ if (!requestUrl) {
552
+ throw new Error("Missing request URL");
553
+ }
554
+ currentResponse = await fetch(requestUrl, {
555
+ method: "POST",
556
+ headers: requestHeaders,
557
+ body: requestBodyJson,
558
+ signal: options?.signal,
559
+ });
560
+ if (!currentResponse.ok) {
561
+ const retryErrorText = await currentResponse.text();
562
+ throw new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`);
563
+ }
564
+ }
565
+ const streamed = await streamResponse(currentResponse);
566
+ if (streamed) {
567
+ receivedContent = true;
568
+ break;
569
+ }
570
+ if (emptyAttempt < MAX_EMPTY_STREAM_RETRIES) {
571
+ resetOutput();
572
+ }
573
+ }
574
+ if (!receivedContent) {
575
+ throw new Error("Cloud Code Assist API returned an empty response");
576
+ }
577
+ if (options?.signal?.aborted) {
578
+ throw new Error("Request was aborted");
579
+ }
580
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
581
+ throw new Error("An unknown error occurred");
582
+ }
583
+ stream.push({ type: "done", reason: output.stopReason, message: output });
584
+ stream.end();
585
+ }
586
+ catch (error) {
587
+ for (const block of output.content) {
588
+ if ("index" in block) {
589
+ delete block.index;
590
+ }
591
+ }
592
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
593
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
594
+ stream.push({ type: "error", reason: output.stopReason, error: output });
595
+ stream.end();
596
+ }
597
+ })();
598
+ return stream;
599
+ };
600
+ export const streamSimpleGoogleGeminiCli = (model, context, options) => {
601
+ const apiKey = options?.apiKey;
602
+ if (!apiKey) {
603
+ throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
604
+ }
605
+ const base = buildBaseOptions(model, options, apiKey);
606
+ if (!options?.reasoning) {
607
+ return streamGoogleGeminiCli(model, context, {
608
+ ...base,
609
+ thinking: { enabled: false },
610
+ });
611
+ }
612
+ const effort = clampReasoning(options.reasoning);
613
+ if (model.id.includes("3-pro") || model.id.includes("3-flash")) {
614
+ return streamGoogleGeminiCli(model, context, {
615
+ ...base,
616
+ thinking: {
617
+ enabled: true,
618
+ level: getGeminiCliThinkingLevel(effort, model.id),
619
+ },
620
+ });
621
+ }
622
+ const defaultBudgets = {
623
+ minimal: 1024,
624
+ low: 2048,
625
+ medium: 8192,
626
+ high: 16384,
627
+ };
628
+ const budgets = { ...defaultBudgets, ...options.thinkingBudgets };
629
+ const minOutputTokens = 1024;
630
+ let thinkingBudget = budgets[effort];
631
+ const maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens);
632
+ if (maxTokens <= thinkingBudget) {
633
+ thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
634
+ }
635
+ return streamGoogleGeminiCli(model, context, {
636
+ ...base,
637
+ maxTokens,
638
+ thinking: {
639
+ enabled: true,
640
+ budgetTokens: thinkingBudget,
641
+ },
642
+ });
643
+ };
644
+ export function buildRequest(model, context, projectId, options = {}, isAntigravity = false) {
645
+ const contents = convertMessages(model, context);
646
+ const generationConfig = {};
647
+ if (options.temperature !== undefined) {
648
+ generationConfig.temperature = options.temperature;
649
+ }
650
+ if (options.maxTokens !== undefined) {
651
+ generationConfig.maxOutputTokens = options.maxTokens;
652
+ }
653
+ // Thinking config
654
+ if (options.thinking?.enabled && model.reasoning) {
655
+ generationConfig.thinkingConfig = {
656
+ includeThoughts: true,
657
+ };
658
+ // Gemini 3 models use thinkingLevel, older models use thinkingBudget
659
+ if (options.thinking.level !== undefined) {
660
+ // Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values
661
+ generationConfig.thinkingConfig.thinkingLevel = options.thinking.level;
662
+ }
663
+ else if (options.thinking.budgetTokens !== undefined) {
664
+ generationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
665
+ }
666
+ }
667
+ const request = {
668
+ contents,
669
+ };
670
+ request.sessionId = options.sessionId;
671
+ // System instruction must be object with parts, not plain string
672
+ if (context.systemPrompt) {
673
+ request.systemInstruction = {
674
+ parts: [{ text: sanitizeSurrogates(context.systemPrompt) }],
675
+ };
676
+ }
677
+ if (Object.keys(generationConfig).length > 0) {
678
+ request.generationConfig = generationConfig;
679
+ }
680
+ if (context.tools && context.tools.length > 0) {
681
+ // Claude models on Cloud Code Assist need the legacy `parameters` field;
682
+ // the API translates it into Anthropic's `input_schema`.
683
+ const useParameters = model.id.startsWith("claude-");
684
+ request.tools = convertTools(context.tools, useParameters);
685
+ if (options.toolChoice) {
686
+ request.toolConfig = {
687
+ functionCallingConfig: {
688
+ mode: mapToolChoice(options.toolChoice),
689
+ },
690
+ };
691
+ }
692
+ }
693
+ if (isAntigravity) {
694
+ const existingParts = request.systemInstruction?.parts ?? [];
695
+ request.systemInstruction = {
696
+ role: "user",
697
+ parts: [
698
+ { text: ANTIGRAVITY_SYSTEM_INSTRUCTION },
699
+ { text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION}[/ignore]` },
700
+ ...existingParts,
701
+ ],
702
+ };
703
+ }
704
+ return {
705
+ project: projectId,
706
+ model: model.id,
707
+ request,
708
+ ...(isAntigravity ? { requestType: "agent" } : {}),
709
+ userAgent: isAntigravity ? "antigravity" : "pi-coding-agent",
710
+ requestId: `${isAntigravity ? "agent" : "draht"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
711
+ };
712
+ }
713
+ function getGeminiCliThinkingLevel(effort, modelId) {
714
+ if (modelId.includes("3-pro")) {
715
+ switch (effort) {
716
+ case "minimal":
717
+ case "low":
718
+ return "LOW";
719
+ case "medium":
720
+ case "high":
721
+ return "HIGH";
722
+ }
723
+ }
724
+ switch (effort) {
725
+ case "minimal":
726
+ return "MINIMAL";
727
+ case "low":
728
+ return "LOW";
729
+ case "medium":
730
+ return "MEDIUM";
731
+ case "high":
732
+ return "HIGH";
733
+ }
734
+ }
735
+ //# sourceMappingURL=google-gemini-cli.js.map