@averyyy/pi-ai 1.2.0-piclient.1 → 1.2.0-piclient.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 (53) hide show
  1. package/dist/api/google-antigravity.d.ts +13 -0
  2. package/dist/api/google-antigravity.d.ts.map +1 -0
  3. package/dist/api/google-antigravity.js +291 -0
  4. package/dist/api/google-antigravity.js.map +1 -0
  5. package/dist/api/google-shared.d.ts +1 -1
  6. package/dist/api/google-shared.d.ts.map +1 -1
  7. package/dist/api/google-shared.js.map +1 -1
  8. package/dist/auth/oauth/google-antigravity.d.ts +5 -0
  9. package/dist/auth/oauth/google-antigravity.d.ts.map +1 -0
  10. package/dist/auth/oauth/google-antigravity.js +259 -0
  11. package/dist/auth/oauth/google-antigravity.js.map +1 -0
  12. package/dist/auth/oauth/load.d.ts +8 -1
  13. package/dist/auth/oauth/load.d.ts.map +1 -1
  14. package/dist/auth/oauth/load.js +11 -0
  15. package/dist/auth/oauth/load.js.map +1 -1
  16. package/dist/bun-oauth.d.ts.map +1 -1
  17. package/dist/bun-oauth.js +3 -0
  18. package/dist/bun-oauth.js.map +1 -1
  19. package/dist/compat.d.ts.map +1 -1
  20. package/dist/compat.js +2 -0
  21. package/dist/compat.js.map +1 -1
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/all.d.ts.map +1 -1
  26. package/dist/providers/all.js +2 -0
  27. package/dist/providers/all.js.map +1 -1
  28. package/dist/providers/data/.manifest.json +1 -1
  29. package/dist/providers/data/fireworks.json +1 -1
  30. package/dist/providers/data/github-copilot.json +1 -1
  31. package/dist/providers/data/meta.json +1 -1
  32. package/dist/providers/data/nvidia.json +1 -1
  33. package/dist/providers/data/opencode-go.json +1 -1
  34. package/dist/providers/data/opencode.json +1 -1
  35. package/dist/providers/data/openrouter.json +1 -1
  36. package/dist/providers/data/radius.json +1 -1
  37. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  38. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  39. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  40. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  41. package/dist/providers/data/xiaomi.json +1 -1
  42. package/dist/providers/google-antigravity.d.ts +3 -0
  43. package/dist/providers/google-antigravity.d.ts.map +1 -0
  44. package/dist/providers/google-antigravity.js +27 -0
  45. package/dist/providers/google-antigravity.js.map +1 -0
  46. package/dist/providers/opencode-go.d.ts +3 -1
  47. package/dist/providers/opencode-go.d.ts.map +1 -1
  48. package/dist/providers/opencode-go.js +2 -0
  49. package/dist/providers/opencode-go.js.map +1 -1
  50. package/dist/types.d.ts +4 -2
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/types.js.map +1 -1
  53. package/package.json +1 -1
@@ -0,0 +1,13 @@
1
+ import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.ts";
2
+ import { type GoogleApiThinkingLevel } from "./google-shared.ts";
3
+ export interface GoogleAntigravityOptions extends StreamOptions {
4
+ toolChoice?: "auto" | "none" | "any";
5
+ thinking?: {
6
+ enabled: boolean;
7
+ budgetTokens?: number;
8
+ level?: GoogleApiThinkingLevel;
9
+ };
10
+ }
11
+ export declare const stream: StreamFunction<"google-antigravity", GoogleAntigravityOptions>;
12
+ export declare const streamSimple: StreamFunction<"google-antigravity", SimpleStreamOptions>;
13
+ //# sourceMappingURL=google-antigravity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"google-antigravity.d.ts","sourceRoot":"","sources":["../../src/api/google-antigravity.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAIX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAKb,MAAM,aAAa,CAAC;AAOrB,OAAO,EAGN,KAAK,sBAAsB,EAW3B,MAAM,oBAAoB,CAAC;AAG5B,MAAM,WAAW,wBAAyB,SAAQ,aAAa;IAC9D,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;IACrC,QAAQ,CAAC,EAAE;QACV,OAAO,EAAE,OAAO,CAAC;QACjB,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,KAAK,CAAC,EAAE,sBAAsB,CAAC;KAC/B,CAAC;CACF;AAyBD,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,oBAAoB,EAAE,wBAAwB,CAkMjF,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,oBAAoB,EAAE,mBAAmB,CAmBlF,CAAC"}
@@ -0,0 +1,291 @@
1
+ import { calculateCost, clampThinkingLevel } from "../models.js";
2
+ import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
3
+ import { AssistantMessageEventStream } from "../utils/event-stream.js";
4
+ import { headersToRecord, providerHeadersToRecord } from "../utils/headers.js";
5
+ import { retryProviderRequest } from "../utils/provider-retry.js";
6
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
7
+ import { getCurrentSystemPrompt, getCurrentTools } from "../utils/transcript.js";
8
+ import { convertMessages, convertTools, getDisabledGoogleThinkingConfig, isThinkingPart, mapStopReasonString, resolveGoogleFunctionCallingMode, resolveGoogleThinkingLevel, retainThoughtSignature, supportsGoogleStrictToolSampling, toGoogleSdkThinkingLevel, toGoogleThinkingLevel, usesGoogleThinkingLevel, } from "./google-shared.js";
9
+ import { adjustMaxTokensForThinking, buildBaseOptions } from "./simple-options.js";
10
+ const DEFAULT_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
11
+ export const stream = (model, context, options) => {
12
+ const events = new AssistantMessageEventStream();
13
+ const output = {
14
+ role: "assistant",
15
+ content: [],
16
+ api: "google-antigravity",
17
+ provider: model.provider,
18
+ model: model.id,
19
+ usage: {
20
+ input: 0,
21
+ output: 0,
22
+ cacheRead: 0,
23
+ cacheWrite: 0,
24
+ totalTokens: 0,
25
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
26
+ },
27
+ stopReason: "pending",
28
+ timestamp: Date.now(),
29
+ };
30
+ (async () => {
31
+ try {
32
+ if (typeof process !== "undefined" && process.env.PI_SERVER_MODE === "true") {
33
+ throw new Error("Google Antigravity inference must use pi-server in PI_SERVER_MODE");
34
+ }
35
+ if (!options?.apiKey)
36
+ throw new Error("Google Antigravity requires OAuth authentication. Use /login.");
37
+ const credential = JSON.parse(options.apiKey);
38
+ if (!credential || typeof credential.token !== "string" || typeof credential.projectId !== "string") {
39
+ throw new Error("Invalid Google Antigravity credentials. Use /login to authenticate.");
40
+ }
41
+ let payload = buildRequest(model, context, credential.projectId, options);
42
+ const transformed = await options.onPayload?.(payload, model);
43
+ if (transformed !== undefined)
44
+ payload = transformed;
45
+ const headers = providerHeadersToRecord({
46
+ Authorization: `Bearer ${credential.token}`,
47
+ "Content-Type": "application/json",
48
+ Accept: "text/event-stream",
49
+ "User-Agent": "antigravity/hub/2.23.0 darwin/arm64",
50
+ ...(model.id.startsWith("claude-") && model.reasoning
51
+ ? { "anthropic-beta": "interleaved-thinking-2025-05-14" }
52
+ : {}),
53
+ }, model.headers, options.headers);
54
+ const body = JSON.stringify(payload);
55
+ const { response, signal } = await retryProviderRequest(async () => {
56
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 600_000);
57
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
58
+ signal.throwIfAborted();
59
+ let response;
60
+ try {
61
+ response = await (options.fetch ?? globalThis.fetch)(`${(model.baseUrl || DEFAULT_ENDPOINT).replace(/\/$/, "")}/v1internal:streamGenerateContent?alt=sse`, { method: "POST", headers, body, signal });
62
+ }
63
+ catch (error) {
64
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), {
65
+ status: undefined,
66
+ headers: undefined,
67
+ });
68
+ }
69
+ await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
70
+ if (!response.ok) {
71
+ throw Object.assign(new Error("Google Antigravity request failed"), {
72
+ status: response.status,
73
+ headers: response.headers,
74
+ body: await response.text(),
75
+ });
76
+ }
77
+ return { response, signal };
78
+ }, { maxRetries: options.maxRetries ?? 2, maxRetryDelayMs: options.maxRetryDelayMs, signal: options.signal });
79
+ events.push({ type: "start", partial: output });
80
+ let current;
81
+ const endBlock = () => {
82
+ if (!current)
83
+ return;
84
+ const contentIndex = output.content.length - 1;
85
+ if (current.type === "text") {
86
+ events.push({ type: "text_end", contentIndex, content: current.text, partial: output });
87
+ }
88
+ else {
89
+ events.push({ type: "thinking_end", contentIndex, content: current.thinking, partial: output });
90
+ }
91
+ current = undefined;
92
+ };
93
+ for await (const chunk of parseStream(response, signal)) {
94
+ await options.onProviderStreamEvent?.(chunk, model);
95
+ if (chunk.error)
96
+ throw new Error(chunk.error.message ?? JSON.stringify(chunk.error));
97
+ if (!chunk.response)
98
+ throw new Error("Google Antigravity stream event has no response");
99
+ const data = chunk.response;
100
+ output.responseId ||= data.responseId;
101
+ output.responseModel ||= data.modelVersion;
102
+ const candidate = data.candidates?.[0];
103
+ for (const part of candidate?.content?.parts ?? []) {
104
+ if (part.text !== undefined || (part.thoughtSignature && !part.functionCall)) {
105
+ const thinking = isThinkingPart(part);
106
+ const signature = current?.type === "thinking" ? current.thinkingSignature : current?.textSignature;
107
+ if (!current ||
108
+ (thinking ? current.type !== "thinking" : current.type !== "text") ||
109
+ (signature && part.thoughtSignature && signature !== part.thoughtSignature)) {
110
+ endBlock();
111
+ current = thinking ? { type: "thinking", thinking: "" } : { type: "text", text: "" };
112
+ output.content.push(current);
113
+ events.push({
114
+ type: thinking ? "thinking_start" : "text_start",
115
+ contentIndex: output.content.length - 1,
116
+ partial: output,
117
+ });
118
+ }
119
+ const delta = part.text ?? "";
120
+ const contentIndex = output.content.length - 1;
121
+ if (current.type === "thinking") {
122
+ current.thinking += delta;
123
+ current.thinkingSignature = retainThoughtSignature(current.thinkingSignature, part.thoughtSignature);
124
+ events.push({ type: "thinking_delta", contentIndex, delta, partial: output });
125
+ }
126
+ else {
127
+ current.text += delta;
128
+ current.textSignature = retainThoughtSignature(current.textSignature, part.thoughtSignature);
129
+ events.push({ type: "text_delta", contentIndex, delta, partial: output });
130
+ }
131
+ }
132
+ if (part.functionCall) {
133
+ endBlock();
134
+ const call = part.functionCall;
135
+ if (!call.name ||
136
+ (call.args !== undefined &&
137
+ (call.args === null || Array.isArray(call.args) || typeof call.args !== "object"))) {
138
+ throw new Error("Google Antigravity returned an invalid function call");
139
+ }
140
+ const toolCall = {
141
+ type: "toolCall",
142
+ id: call.id ?? `call_${crypto.randomUUID()}`,
143
+ name: call.name,
144
+ arguments: (call.args ?? {}),
145
+ ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),
146
+ };
147
+ const contentIndex = output.content.length;
148
+ output.content.push(toolCall);
149
+ events.push({ type: "toolcall_start", contentIndex, partial: output });
150
+ events.push({
151
+ type: "toolcall_delta",
152
+ contentIndex,
153
+ delta: JSON.stringify(toolCall.arguments),
154
+ partial: output,
155
+ });
156
+ events.push({ type: "toolcall_end", contentIndex, toolCall, partial: output });
157
+ }
158
+ }
159
+ if (candidate?.finishReason) {
160
+ output.rawStopReason = candidate.finishReason;
161
+ output.stopReason = mapStopReasonString(candidate.finishReason);
162
+ if (output.stopReason === "stop" && output.content.some((part) => part.type === "toolCall")) {
163
+ output.stopReason = "toolUse";
164
+ }
165
+ }
166
+ if (data.usageMetadata) {
167
+ const usage = data.usageMetadata;
168
+ output.usage.input = (usage.promptTokenCount ?? 0) - (usage.cachedContentTokenCount ?? 0);
169
+ output.usage.output = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);
170
+ output.usage.cacheRead = usage.cachedContentTokenCount ?? 0;
171
+ output.usage.reasoning = usage.thoughtsTokenCount ?? 0;
172
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead;
173
+ calculateCost(model, output.usage);
174
+ }
175
+ }
176
+ endBlock();
177
+ signal.throwIfAborted();
178
+ if (output.stopReason === "pending")
179
+ throw new Error("Google Antigravity stream ended without a finish reason");
180
+ if (output.stopReason === "error" || output.stopReason === "aborted") {
181
+ throw new Error(`Google Antigravity stopped with: ${output.rawStopReason}`);
182
+ }
183
+ events.push({ type: "done", reason: output.stopReason, message: output });
184
+ }
185
+ catch (error) {
186
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
187
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
188
+ events.push({ type: "error", reason: output.stopReason, error: output });
189
+ }
190
+ events.end();
191
+ })();
192
+ return events;
193
+ };
194
+ export const streamSimple = (model, context, options) => {
195
+ if (!options?.apiKey)
196
+ throw new Error("Google Antigravity requires OAuth authentication. Use /login.");
197
+ const base = { ...buildBaseOptions(model, context, options), toolChoice: options?.toolChoice };
198
+ if (!options?.reasoning)
199
+ return stream(model, context, { ...base, thinking: { enabled: false } });
200
+ const level = clampThinkingLevel(model, options.reasoning);
201
+ if (level === "off")
202
+ return stream(model, context, { ...base, thinking: { enabled: false } });
203
+ if (usesGoogleThinkingLevel(model)) {
204
+ return stream(model, context, {
205
+ ...base,
206
+ thinking: { enabled: true, level: toGoogleThinkingLevel(resolveGoogleThinkingLevel(model, level)) },
207
+ });
208
+ }
209
+ const { maxTokens, thinkingBudget } = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, level, options?.thinkingBudgets);
210
+ return stream(model, context, { ...base, maxTokens, thinking: { enabled: true, budgetTokens: thinkingBudget } });
211
+ };
212
+ function buildRequest(model, context, projectId, options) {
213
+ const tools = getCurrentTools(context.messages);
214
+ const systemPrompt = getCurrentSystemPrompt(context.messages);
215
+ const strict = supportsGoogleStrictToolSampling(model.id);
216
+ const mode = tools.length > 0 ? resolveGoogleFunctionCallingMode(tools, options.toolChoice, strict) : undefined;
217
+ const generationConfig = {
218
+ temperature: options.temperature,
219
+ maxOutputTokens: options.maxTokens,
220
+ };
221
+ if (model.reasoning && options.thinking) {
222
+ generationConfig.thinkingConfig = options.thinking.enabled
223
+ ? {
224
+ includeThoughts: true,
225
+ ...(options.thinking.level !== undefined
226
+ ? { thinkingLevel: toGoogleSdkThinkingLevel(options.thinking.level) }
227
+ : { thinkingBudget: options.thinking.budgetTokens }),
228
+ }
229
+ : getDisabledGoogleThinkingConfig(model);
230
+ }
231
+ return {
232
+ project: projectId,
233
+ model: model.id,
234
+ requestType: "agent",
235
+ userAgent: "antigravity",
236
+ requestId: `agent-${crypto.randomUUID()}`,
237
+ request: {
238
+ contents: convertMessages(model, context),
239
+ sessionId: options.sessionId,
240
+ generationConfig,
241
+ ...(systemPrompt && { systemInstruction: { parts: [{ text: sanitizeSurrogates(systemPrompt) }] } }),
242
+ ...(tools.length > 0 && { tools: convertTools(tools, model.id.startsWith("claude-"), strict) }),
243
+ ...(mode !== undefined && { toolConfig: { functionCallingConfig: { mode } } }),
244
+ },
245
+ };
246
+ }
247
+ async function* parseStream(response, signal) {
248
+ if (!response.body)
249
+ throw new Error("Google Antigravity response has no body");
250
+ const reader = response.body.getReader();
251
+ const decoder = new TextDecoder();
252
+ let buffer = "";
253
+ const data = [];
254
+ const abort = () => {
255
+ void reader.cancel(signal.reason);
256
+ };
257
+ signal.addEventListener("abort", abort, { once: true });
258
+ try {
259
+ for (;;) {
260
+ signal.throwIfAborted();
261
+ const { value, done } = await reader.read();
262
+ signal.throwIfAborted();
263
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
264
+ if (done && buffer.length > 0)
265
+ buffer += "\n";
266
+ let end = buffer.indexOf("\n");
267
+ while (end !== -1) {
268
+ const line = buffer.slice(0, end).replace(/\r$/, "");
269
+ buffer = buffer.slice(end + 1);
270
+ if (line.startsWith("data:"))
271
+ data.push(line.slice(5).trimStart());
272
+ if (line === "" && data.length > 0) {
273
+ yield JSON.parse(data.join("\n"));
274
+ data.length = 0;
275
+ }
276
+ end = buffer.indexOf("\n");
277
+ }
278
+ if (done) {
279
+ if (data.length > 0)
280
+ yield JSON.parse(data.join("\n"));
281
+ break;
282
+ }
283
+ }
284
+ }
285
+ finally {
286
+ signal.removeEventListener("abort", abort);
287
+ await reader.cancel();
288
+ reader.releaseLock();
289
+ }
290
+ }
291
+ //# sourceMappingURL=google-antigravity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"google-antigravity.js","sourceRoot":"","sources":["../../src/api/google-antigravity.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAajE,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACjF,OAAO,EACN,eAAe,EACf,YAAY,EAEZ,+BAA+B,EAC/B,cAAc,EACd,mBAAmB,EACnB,gCAAgC,EAChC,0BAA0B,EAC1B,sBAAsB,EACtB,gCAAgC,EAChC,wBAAwB,EACxB,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAgCnF,MAAM,gBAAgB,GAAG,2CAA2C,CAAC;AAErE,MAAM,CAAC,MAAM,MAAM,GAAmE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;IACjH,MAAM,MAAM,GAAG,IAAI,2BAA2B,EAAE,CAAC;IACjD,MAAM,MAAM,GAAqB;QAChC,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,EAAE;QACX,GAAG,EAAE,oBAAoB;QACzB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,KAAK,EAAE,KAAK,CAAC,EAAE;QACf,KAAK,EAAE;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CAAqB,CAAC;oBACtD,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;gBACjB,CAAC;gBACD,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YAC5B,CAAC;YACD,IAAI,IAAI,EAAE,CAAC;gBACV,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;oBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAqB,CAAC;gBAC3E,MAAM;YACP,CAAC;QACF,CAAC;IACF,CAAC;YAAS,CAAC;QACV,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC3C,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;QACtB,MAAM,CAAC,WAAW,EAAE,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["import type { Content, GenerateContentResponse, ThinkingConfig } from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tJsonObject,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tTranscriptContext,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getCurrentSystemPrompt, getCurrentTools } from \"../utils/transcript.ts\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\ttype GoogleApiThinkingLevel,\n\tgetDisabledGoogleThinkingConfig,\n\tisThinkingPart,\n\tmapStopReasonString,\n\tresolveGoogleFunctionCallingMode,\n\tresolveGoogleThinkingLevel,\n\tretainThoughtSignature,\n\tsupportsGoogleStrictToolSampling,\n\ttoGoogleSdkThinkingLevel,\n\ttoGoogleThinkingLevel,\n\tusesGoogleThinkingLevel,\n} from \"./google-shared.ts\";\nimport { adjustMaxTokensForThinking, buildBaseOptions } from \"./simple-options.ts\";\n\nexport interface GoogleAntigravityOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\";\n\tthinking?: {\n\t\tenabled: boolean;\n\t\tbudgetTokens?: number;\n\t\tlevel?: GoogleApiThinkingLevel;\n\t};\n}\n\ninterface AntigravityRequest {\n\tproject: string;\n\tmodel: string;\n\trequestType: \"agent\";\n\tuserAgent: \"antigravity\";\n\trequestId: string;\n\trequest: {\n\t\tcontents: Content[];\n\t\tsessionId?: string;\n\t\tsystemInstruction?: { parts: { text: string }[] };\n\t\tgenerationConfig: { temperature?: number; maxOutputTokens?: number; thinkingConfig?: ThinkingConfig };\n\t\ttools?: ReturnType<typeof convertTools>;\n\t\ttoolConfig?: { functionCallingConfig: { mode: ReturnType<typeof resolveGoogleFunctionCallingMode> } };\n\t};\n}\n\ninterface AntigravityChunk {\n\tresponse?: GenerateContentResponse;\n\terror?: { code?: number; message?: string; status?: string };\n}\n\nconst DEFAULT_ENDPOINT = \"https://daily-cloudcode-pa.googleapis.com\";\n\nexport const stream: StreamFunction<\"google-antigravity\", GoogleAntigravityOptions> = (model, context, options) => {\n\tconst events = new AssistantMessageEventStream();\n\tconst output: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: \"google-antigravity\",\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"pending\",\n\t\ttimestamp: Date.now(),\n\t};\n\n\t(async () => {\n\t\ttry {\n\t\t\tif (typeof process !== \"undefined\" && process.env.PI_SERVER_MODE === \"true\") {\n\t\t\t\tthrow new Error(\"Google Antigravity inference must use pi-server in PI_SERVER_MODE\");\n\t\t\t}\n\t\t\tif (!options?.apiKey) throw new Error(\"Google Antigravity requires OAuth authentication. Use /login.\");\n\t\t\tconst credential = JSON.parse(options.apiKey) as { token: string; projectId: string };\n\t\t\tif (!credential || typeof credential.token !== \"string\" || typeof credential.projectId !== \"string\") {\n\t\t\t\tthrow new Error(\"Invalid Google Antigravity credentials. Use /login to authenticate.\");\n\t\t\t}\n\t\t\tlet payload: unknown = buildRequest(model, context, credential.projectId, options);\n\t\t\tconst transformed = await options.onPayload?.(payload, model);\n\t\t\tif (transformed !== undefined) payload = transformed;\n\t\t\tconst headers = providerHeadersToRecord(\n\t\t\t\t{\n\t\t\t\t\tAuthorization: `Bearer ${credential.token}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAccept: \"text/event-stream\",\n\t\t\t\t\t\"User-Agent\": \"antigravity/hub/2.23.0 darwin/arm64\",\n\t\t\t\t\t...(model.id.startsWith(\"claude-\") && model.reasoning\n\t\t\t\t\t\t? { \"anthropic-beta\": \"interleaved-thinking-2025-05-14\" }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tmodel.headers,\n\t\t\t\toptions.headers,\n\t\t\t);\n\t\t\tconst body = JSON.stringify(payload);\n\t\t\tconst { response, signal } = await retryProviderRequest(\n\t\t\t\tasync () => {\n\t\t\t\t\tconst timeout = AbortSignal.timeout(options.timeoutMs ?? 600_000);\n\t\t\t\t\tconst signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;\n\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\tlet response: Response;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresponse = await (options.fetch ?? globalThis.fetch)(\n\t\t\t\t\t\t\t`${(model.baseUrl || DEFAULT_ENDPOINT).replace(/\\/$/, \"\")}/v1internal:streamGenerateContent?alt=sse`,\n\t\t\t\t\t\t\t{ method: \"POST\", headers, body, signal },\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthrow Object.assign(error instanceof Error ? error : new Error(String(error)), {\n\t\t\t\t\t\t\tstatus: undefined,\n\t\t\t\t\t\t\theaders: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tawait options.onResponse?.(\n\t\t\t\t\t\t{ status: response.status, headers: headersToRecord(response.headers) },\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t);\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tthrow Object.assign(new Error(\"Google Antigravity request failed\"), {\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t\theaders: response.headers,\n\t\t\t\t\t\t\tbody: await response.text(),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn { response, signal };\n\t\t\t\t},\n\t\t\t\t{ maxRetries: options.maxRetries ?? 2, maxRetryDelayMs: options.maxRetryDelayMs, signal: options.signal },\n\t\t\t);\n\t\t\tevents.push({ type: \"start\", partial: output });\n\t\t\tlet current: TextContent | ThinkingContent | undefined;\n\t\t\tconst endBlock = () => {\n\t\t\t\tif (!current) return;\n\t\t\t\tconst contentIndex = output.content.length - 1;\n\t\t\t\tif (current.type === \"text\") {\n\t\t\t\t\tevents.push({ type: \"text_end\", contentIndex, content: current.text, partial: output });\n\t\t\t\t} else {\n\t\t\t\t\tevents.push({ type: \"thinking_end\", contentIndex, content: current.thinking, partial: output });\n\t\t\t\t}\n\t\t\t\tcurrent = undefined;\n\t\t\t};\n\t\t\tfor await (const chunk of parseStream(response, signal)) {\n\t\t\t\tawait options.onProviderStreamEvent?.(chunk, model);\n\t\t\t\tif (chunk.error) throw new Error(chunk.error.message ?? JSON.stringify(chunk.error));\n\t\t\t\tif (!chunk.response) throw new Error(\"Google Antigravity stream event has no response\");\n\t\t\t\tconst data = chunk.response;\n\t\t\t\toutput.responseId ||= data.responseId;\n\t\t\t\toutput.responseModel ||= data.modelVersion;\n\t\t\t\tconst candidate = data.candidates?.[0];\n\t\t\t\tfor (const part of candidate?.content?.parts ?? []) {\n\t\t\t\t\tif (part.text !== undefined || (part.thoughtSignature && !part.functionCall)) {\n\t\t\t\t\t\tconst thinking = isThinkingPart(part);\n\t\t\t\t\t\tconst signature = current?.type === \"thinking\" ? current.thinkingSignature : current?.textSignature;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!current ||\n\t\t\t\t\t\t\t(thinking ? current.type !== \"thinking\" : current.type !== \"text\") ||\n\t\t\t\t\t\t\t(signature && part.thoughtSignature && signature !== part.thoughtSignature)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tendBlock();\n\t\t\t\t\t\t\tcurrent = thinking ? { type: \"thinking\", thinking: \"\" } : { type: \"text\", text: \"\" };\n\t\t\t\t\t\t\toutput.content.push(current);\n\t\t\t\t\t\t\tevents.push({\n\t\t\t\t\t\t\t\ttype: thinking ? \"thinking_start\" : \"text_start\",\n\t\t\t\t\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst delta = part.text ?? \"\";\n\t\t\t\t\t\tconst contentIndex = output.content.length - 1;\n\t\t\t\t\t\tif (current.type === \"thinking\") {\n\t\t\t\t\t\t\tcurrent.thinking += delta;\n\t\t\t\t\t\t\tcurrent.thinkingSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\tcurrent.thinkingSignature,\n\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tevents.push({ type: \"thinking_delta\", contentIndex, delta, partial: output });\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcurrent.text += delta;\n\t\t\t\t\t\t\tcurrent.textSignature = retainThoughtSignature(current.textSignature, part.thoughtSignature);\n\t\t\t\t\t\t\tevents.push({ type: \"text_delta\", contentIndex, delta, partial: output });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\tendBlock();\n\t\t\t\t\t\tconst call = part.functionCall;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!call.name ||\n\t\t\t\t\t\t\t(call.args !== undefined &&\n\t\t\t\t\t\t\t\t(call.args === null || Array.isArray(call.args) || typeof call.args !== \"object\"))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"Google Antigravity returned an invalid function call\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\tid: call.id ?? `call_${crypto.randomUUID()}`,\n\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\targuments: (call.args ?? {}) as JsonObject,\n\t\t\t\t\t\t\t...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst contentIndex = output.content.length;\n\t\t\t\t\t\toutput.content.push(toolCall);\n\t\t\t\t\t\tevents.push({ type: \"toolcall_start\", contentIndex, partial: output });\n\t\t\t\t\t\tevents.push({\n\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\tcontentIndex,\n\t\t\t\t\t\t\tdelta: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tevents.push({ type: \"toolcall_end\", contentIndex, toolCall, partial: output });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (candidate?.finishReason) {\n\t\t\t\t\toutput.rawStopReason = candidate.finishReason;\n\t\t\t\t\toutput.stopReason = mapStopReasonString(candidate.finishReason);\n\t\t\t\t\tif (output.stopReason === \"stop\" && output.content.some((part) => part.type === \"toolCall\")) {\n\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (data.usageMetadata) {\n\t\t\t\t\tconst usage = data.usageMetadata;\n\t\t\t\t\toutput.usage.input = (usage.promptTokenCount ?? 0) - (usage.cachedContentTokenCount ?? 0);\n\t\t\t\t\toutput.usage.output = (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);\n\t\t\t\t\toutput.usage.cacheRead = usage.cachedContentTokenCount ?? 0;\n\t\t\t\t\toutput.usage.reasoning = usage.thoughtsTokenCount ?? 0;\n\t\t\t\t\toutput.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead;\n\t\t\t\t\tcalculateCost(model, output.usage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tendBlock();\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (output.stopReason === \"pending\")\n\t\t\t\tthrow new Error(\"Google Antigravity stream ended without a finish reason\");\n\t\t\tif (output.stopReason === \"error\" || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(`Google Antigravity stopped with: ${output.rawStopReason}`);\n\t\t\t}\n\t\t\tevents.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t} catch (error) {\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\tevents.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t}\n\t\tevents.end();\n\t})();\n\treturn events;\n};\n\nexport const streamSimple: StreamFunction<\"google-antigravity\", SimpleStreamOptions> = (model, context, options) => {\n\tif (!options?.apiKey) throw new Error(\"Google Antigravity requires OAuth authentication. Use /login.\");\n\tconst base = { ...buildBaseOptions(model, context, options), toolChoice: options?.toolChoice };\n\tif (!options?.reasoning) return stream(model, context, { ...base, thinking: { enabled: false } });\n\tconst level = clampThinkingLevel(model, options.reasoning);\n\tif (level === \"off\") return stream(model, context, { ...base, thinking: { enabled: false } });\n\tif (usesGoogleThinkingLevel(model)) {\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinking: { enabled: true, level: toGoogleThinkingLevel(resolveGoogleThinkingLevel(model, level)) },\n\t\t});\n\t}\n\tconst { maxTokens, thinkingBudget } = adjustMaxTokensForThinking(\n\t\tbase.maxTokens,\n\t\tmodel.maxTokens,\n\t\tlevel,\n\t\toptions?.thinkingBudgets,\n\t);\n\treturn stream(model, context, { ...base, maxTokens, thinking: { enabled: true, budgetTokens: thinkingBudget } });\n};\n\nfunction buildRequest(\n\tmodel: Model<\"google-antigravity\">,\n\tcontext: TranscriptContext,\n\tprojectId: string,\n\toptions: GoogleAntigravityOptions,\n): AntigravityRequest {\n\tconst tools = getCurrentTools(context.messages);\n\tconst systemPrompt = getCurrentSystemPrompt(context.messages);\n\tconst strict = supportsGoogleStrictToolSampling(model.id);\n\tconst mode = tools.length > 0 ? resolveGoogleFunctionCallingMode(tools, options.toolChoice, strict) : undefined;\n\tconst generationConfig: AntigravityRequest[\"request\"][\"generationConfig\"] = {\n\t\ttemperature: options.temperature,\n\t\tmaxOutputTokens: options.maxTokens,\n\t};\n\tif (model.reasoning && options.thinking) {\n\t\tgenerationConfig.thinkingConfig = options.thinking.enabled\n\t\t\t? {\n\t\t\t\t\tincludeThoughts: true,\n\t\t\t\t\t...(options.thinking.level !== undefined\n\t\t\t\t\t\t? { thinkingLevel: toGoogleSdkThinkingLevel(options.thinking.level) }\n\t\t\t\t\t\t: { thinkingBudget: options.thinking.budgetTokens }),\n\t\t\t\t}\n\t\t\t: getDisabledGoogleThinkingConfig(model);\n\t}\n\treturn {\n\t\tproject: projectId,\n\t\tmodel: model.id,\n\t\trequestType: \"agent\",\n\t\tuserAgent: \"antigravity\",\n\t\trequestId: `agent-${crypto.randomUUID()}`,\n\t\trequest: {\n\t\t\tcontents: convertMessages(model, context),\n\t\t\tsessionId: options.sessionId,\n\t\t\tgenerationConfig,\n\t\t\t...(systemPrompt && { systemInstruction: { parts: [{ text: sanitizeSurrogates(systemPrompt) }] } }),\n\t\t\t...(tools.length > 0 && { tools: convertTools(tools, model.id.startsWith(\"claude-\"), strict) }),\n\t\t\t...(mode !== undefined && { toolConfig: { functionCallingConfig: { mode } } }),\n\t\t},\n\t};\n}\n\nasync function* parseStream(response: Response, signal: AbortSignal): AsyncGenerator<AntigravityChunk> {\n\tif (!response.body) throw new Error(\"Google Antigravity response has no body\");\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst data: string[] = [];\n\tconst abort = () => {\n\t\tvoid reader.cancel(signal.reason);\n\t};\n\tsignal.addEventListener(\"abort\", abort, { once: true });\n\ttry {\n\t\tfor (;;) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tsignal.throwIfAborted();\n\t\t\tbuffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\t\t\tif (done && buffer.length > 0) buffer += \"\\n\";\n\t\t\tlet end = buffer.indexOf(\"\\n\");\n\t\t\twhile (end !== -1) {\n\t\t\t\tconst line = buffer.slice(0, end).replace(/\\r$/, \"\");\n\t\t\t\tbuffer = buffer.slice(end + 1);\n\t\t\t\tif (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n\t\t\t\tif (line === \"\" && data.length > 0) {\n\t\t\t\t\tyield JSON.parse(data.join(\"\\n\")) as AntigravityChunk;\n\t\t\t\t\tdata.length = 0;\n\t\t\t\t}\n\t\t\t\tend = buffer.indexOf(\"\\n\");\n\t\t\t}\n\t\t\tif (done) {\n\t\t\t\tif (data.length > 0) yield JSON.parse(data.join(\"\\n\")) as AntigravityChunk;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", abort);\n\t\tawait reader.cancel();\n\t\treader.releaseLock();\n\t}\n}\n"]}
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { type Content, FinishReason, FunctionCallingConfigMode, ThinkingLevel as GoogleSdkThinkingLevel, type Part, type ThinkingConfig } from "@google/genai";
5
5
  import type { Model, StopReason, StreamOptions, ThinkingLevel, Tool, TranscriptContext } from "../types.ts";
6
- type GoogleApiType = "google-generative-ai" | "google-vertex";
6
+ type GoogleApiType = "google-generative-ai" | "google-vertex" | "google-antigravity";
7
7
  /**
8
8
  * Thinking level for Gemini 3 models.
9
9
  * Mirrors Google's ThinkingLevel enum values.
@@ -1 +1 @@
1
- {"version":3,"file":"google-shared.d.ts","sourceRoot":"","sources":["../../src/api/google-shared.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACN,KAAK,OAAO,EACZ,YAAY,EACZ,yBAAyB,EACzB,aAAa,IAAI,sBAAsB,EACvC,KAAK,IAAI,EACT,KAAK,cAAc,EACnB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAEX,KAAK,EACL,UAAU,EACV,aAAa,EAEb,aAAa,EACb,IAAI,EACJ,iBAAiB,EACjB,MAAM,aAAa,CAAC;AAOrB,KAAK,aAAa,GAAG,sBAAsB,GAAG,eAAe,CAAC;AAE9D;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,4BAA4B,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAC1G,MAAM,MAAM,2BAA2B,GAAG,OAAO,CAAC,aAAa,EAAE,OAAO,GAAG,KAAK,CAAC,CAAC;AAUlF,gGAAgG;AAChG,wBAAgB,0BAA0B,CAAC,CAAC,SAAS,aAAa,EACjE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EACf,KAAK,EAAE,aAAa,GAClB,2BAA2B,CAc7B;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,aAAa,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,OAAO,CAWzF;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,2BAA2B,GAAG,sBAAsB,CAWhG;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,sBAAsB,GAAG,sBAAsB,CAE9F;AAED,wBAAgB,+BAA+B,CAAC,CAA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AM,KAAK,CAAC;QACb,CAAC;IACF,CAAC,EACD;QACC,UAAU,EAAE,OAAO,EAAE,UAAU;QAC/B,eAAe,EAAE,OAAO,EAAE,eAAe;QACzC,MAAM,EAAE,OAAO,EAAE,MAAM;KACvB,CACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared utilities for Google Generative AI and Google Vertex providers.\n */\n\nimport {\n\ttype Content,\n\tFinishReason,\n\tFunctionCallingConfigMode,\n\tThinkingLevel as GoogleSdkThinkingLevel,\n\ttype Part,\n\ttype ThinkingConfig,\n} from \"@google/genai\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tImageContent,\n\tModel,\n\tStopReason,\n\tStreamOptions,\n\tTextContent,\n\tThinkingLevel,\n\tTool,\n\tTranscriptContext,\n} from \"../types.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { collapseSystemMessages, withoutInitialSystemMessage } from \"../utils/transcript.ts\";\nimport { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\ntype GoogleApiType = \"google-generative-ai\" | \"google-vertex\";\n\n/**\n * Thinking level for Gemini 3 models.\n * Mirrors Google's ThinkingLevel enum values.\n */\nexport type GoogleApiThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\";\nexport type ResolvedGoogleThinkingLevel = Exclude<ThinkingLevel, \"xhigh\" | \"max\">;\n\nconst GOOGLE_SDK_THINKING_LEVEL_MAP: Record<GoogleApiThinkingLevel, GoogleSdkThinkingLevel> = {\n\tTHINKING_LEVEL_UNSPECIFIED: GoogleSdkThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n\tMINIMAL: GoogleSdkThinkingLevel.MINIMAL,\n\tLOW: GoogleSdkThinkingLevel.LOW,\n\tMEDIUM: GoogleSdkThinkingLevel.MEDIUM,\n\tHIGH: GoogleSdkThinkingLevel.HIGH,\n};\n\n/** Resolve a supported pi level or model-specific Google mapping to a standard Google level. */\nexport function resolveGoogleThinkingLevel<T extends GoogleApiType>(\n\tmodel: Model<T>,\n\tlevel: ThinkingLevel,\n): ResolvedGoogleThinkingLevel {\n\tconst mapped = model.thinkingLevelMap?.[level];\n\tconst resolvedLevel = typeof mapped === \"string\" ? mapped.toLowerCase() : level;\n\tswitch (resolvedLevel) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\tcase \"medium\":\n\t\tcase \"high\":\n\t\t\treturn resolvedLevel;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`,\n\t\t\t);\n\t}\n}\n\n/**\n * Whether this model uses Gemini's discrete `thinkingLevel` control instead of\n * the token-based `thinkingBudget` control. Supported levels come from the\n * model's `thinkingLevelMap`; this only selects the Google wire format.\n */\nexport function usesGoogleThinkingLevel<T extends GoogleApiType>(model: Model<T>): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn (\n\t\t// Match Gemini 3 Pro/Flash IDs with or without a minor version, such as\n\t\t// gemini-3-flash-preview, gemini-3.1-pro-preview, and gemini-3.8-flash.\n\t\t/gemini-3(?:\\.\\d+)?-(?:pro|flash)/.test(id) ||\n\t\tid === \"gemini-flash-latest\" ||\n\t\tid === \"gemini-flash-lite-latest\" ||\n\t\t// Match both hosted Gemma 4 naming forms: gemma-4-* and gemma4-*.\n\t\t/gemma-?4/.test(id)\n\t);\n}\n\nexport function toGoogleThinkingLevel(level: ResolvedGoogleThinkingLevel): GoogleApiThinkingLevel {\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\t\treturn \"MINIMAL\";\n\t\tcase \"low\":\n\t\t\treturn \"LOW\";\n\t\tcase \"medium\":\n\t\t\treturn \"MEDIUM\";\n\t\tcase \"high\":\n\t\t\treturn \"HIGH\";\n\t}\n}\n\nexport function toGoogleSdkThinkingLevel(level: GoogleApiThinkingLevel): GoogleSdkThinkingLevel {\n\treturn GOOGLE_SDK_THINKING_LEVEL_MAP[level];\n}\n\nexport function getDisabledGoogleThinkingConfig<T extends GoogleApiType>(model: Model<T>): ThinkingConfig {\n\tif (!usesGoogleThinkingLevel(model)) return { thinkingBudget: 0 };\n\n\tconst fallback = clampThinkingLevel(model, \"off\");\n\tif (fallback === \"off\") return { thinkingBudget: 0 };\n\n\tconst resolvedLevel = resolveGoogleThinkingLevel(model, fallback);\n\tconst apiLevel = toGoogleThinkingLevel(resolvedLevel);\n\treturn { thinkingLevel: toGoogleSdkThinkingLevel(apiLevel) };\n}\n\n/**\n * Determines whether a streamed Gemini `Part` should be treated as \"thinking\".\n *\n * Protocol note (Gemini / Vertex AI thought signatures):\n * - `thought: true` is the definitive marker for thinking content (thought summaries).\n * - `thoughtSignature` is an encrypted representation of the model's internal thought process\n * used to preserve reasoning context across multi-turn interactions.\n * - `thoughtSignature` can appear on ANY part type (text, functionCall, etc.) - it does NOT\n * indicate the part itself is thinking content.\n * - For non-functionCall responses, the signature appears on the last part for context replay.\n * - When persisting/replaying model outputs, signature-bearing parts must be preserved as-is;\n * do not merge/move signatures across parts.\n *\n * See: https://ai.google.dev/gemini-api/docs/thought-signatures\n */\nexport function isThinkingPart(part: Pick<Part, \"thought\" | \"thoughtSignature\">): boolean {\n\treturn part.thought === true;\n}\n\n/**\n * Retain thought signatures during streaming.\n *\n * Some backends only send `thoughtSignature` on the first delta for a given part/block; later deltas may omit it.\n * This helper preserves the last non-empty signature for the current block.\n *\n * Note: this does NOT merge or move signatures across distinct response parts. It only prevents\n * a signature from being overwritten with `undefined` within the same streamed block.\n */\nexport function retainThoughtSignature(existing: string | undefined, incoming: string | undefined): string | undefined {\n\tif (typeof incoming === \"string\" && incoming.length > 0) return incoming;\n\treturn existing;\n}\n\n// Thought signatures must be base64 for Google APIs (TYPE_BYTES).\nconst base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;\n\nfunction isValidThoughtSignature(signature: string | undefined): boolean {\n\tif (!signature) return false;\n\tif (signature.length % 4 !== 0) return false;\n\treturn base64SignaturePattern.test(signature);\n}\n\n/**\n * Only keep signatures from the same provider/model and with valid base64.\n */\nfunction resolveThoughtSignature(isSameProviderAndModel: boolean, signature: string | undefined): string | undefined {\n\treturn isSameProviderAndModel && isValidThoughtSignature(signature) ? signature : undefined;\n}\n\n/**\n * Models via Google APIs that require explicit tool call IDs in function calls/responses.\n */\nexport function requiresToolCallId(modelId: string): boolean {\n\tconst geminiMajorVersion = getGeminiMajorVersion(modelId);\n\treturn (\n\t\tmodelId.startsWith(\"claude-\") ||\n\t\tmodelId.startsWith(\"gpt-oss-\") ||\n\t\t(geminiMajorVersion !== undefined && geminiMajorVersion >= 3)\n\t);\n}\n\nfunction getGeminiMajorVersion(modelId: string): number | undefined {\n\tconst match = modelId.toLowerCase().match(/^gemini(?:-live)?-(\\d+)/);\n\tif (!match) return undefined;\n\treturn Number.parseInt(match[1], 10);\n}\n\nfunction supportsMultimodalFunctionResponse(modelId: string): boolean {\n\tconst geminiMajorVersion = getGeminiMajorVersion(modelId);\n\tif (geminiMajorVersion !== undefined) {\n\t\treturn geminiMajorVersion >= 3;\n\t}\n\treturn true;\n}\n\n/**\n * Convert internal messages to Gemini Content[] format.\n */\nexport function convertMessages<T extends GoogleApiType>(model: Model<T>, context: TranscriptContext): Content[] {\n\t// Gemini has no mid-conversation system messages; the leading prompt is sent as systemInstruction.\n\tconst conversation = withoutInitialSystemMessage(collapseSystemMessages(context).messages);\n\tconst contents: Content[] = [];\n\tconst normalizeToolCallId = (id: string): string => {\n\t\tif (!requiresToolCallId(model.id)) return id;\n\t\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 64);\n\t};\n\n\tconst transformedMessages = transformMessages(conversation, model, normalizeToolCallId);\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts: [{ text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst parts: Part[] = msg.content.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn { text: sanitizeSurrogates(item.text) };\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tinlineData: {\n\t\t\t\t\t\t\t\tmimeType: item.mimeType,\n\t\t\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (parts.length === 0) continue;\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst parts: Part[] = [];\n\t\t\t// Check if message is from same provider and model - only then keep thinking blocks\n\t\t\tconst isSameProviderAndModel = msg.provider === model.provider && msg.model === model.id;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tconst thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.textSignature);\n\t\t\t\t\t// Skip empty text blocks — unless they carry a thought signature. Gemini can attach\n\t\t\t\t\t// the signature to a part whose visible text is empty and requires it echoed back;\n\t\t\t\t\t// dropping it breaks the reasoning chain and the model intermittently ends mid-task\n\t\t\t\t\t// turns with a thought-only STOP (empty completion, no tool call).\n\t\t\t\t\tif ((!block.text || block.text.trim() === \"\") && !thoughtSignature) continue;\n\t\t\t\t\tparts.push({\n\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t\t...(thoughtSignature && { thoughtSignature }),\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t// Only keep as thinking block if same provider AND same model\n\t\t\t\t\t// Otherwise convert to plain text (no tags to avoid model mimicking them)\n\t\t\t\t\tif (isSameProviderAndModel) {\n\t\t\t\t\t\tconst thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thinkingSignature);\n\t\t\t\t\t\t// Same rule as text blocks: an empty thinking block is dropped only when it\n\t\t\t\t\t\t// carries no signature (mirrors the anthropic converter's handling).\n\t\t\t\t\t\tif ((!block.thinking || block.thinking.trim() === \"\") && !thoughtSignature) continue;\n\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\tthought: true,\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\t...(thoughtSignature && { thoughtSignature }),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Cross-provider/model: the signature is unusable, empty blocks stay dropped.\n\t\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") continue;\n\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thoughtSignature);\n\t\t\t\t\tconst part: Part = {\n\t\t\t\t\t\tfunctionCall: {\n\t\t\t\t\t\t\tname: block.name,\n\t\t\t\t\t\t\targs: block.arguments ?? {},\n\t\t\t\t\t\t\t...(requiresToolCallId(model.id) ? { id: block.id } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(thoughtSignature && { thoughtSignature }),\n\t\t\t\t\t};\n\t\t\t\t\tparts.push(part);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (parts.length === 0) continue;\n\t\t\tcontents.push({\n\t\t\t\trole: \"model\",\n\t\t\t\tparts,\n\t\t\t});\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\t// Extract text and image content\n\t\t\tconst textContent = msg.content.filter((c): c is TextContent => c.type === \"text\");\n\t\t\tconst textResult = textContent.map((c) => c.text).join(\"\\n\");\n\t\t\tconst imageContent = model.input.includes(\"image\")\n\t\t\t\t? msg.content.filter((c): c is ImageContent => c.type === \"image\")\n\t\t\t\t: [];\n\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tconst hasImages = imageContent.length > 0;\n\n\t\t\t// Gemini 3+ models support multimodal function responses with images nested inside\n\t\t\t// functionResponse.parts. Claude and other non-Gemini models behind Cloud Code Assist /\n\t\t\t// Gemini < 3 still needs a separate user image turn.\n\t\t\tconst modelSupportsMultimodalFunctionResponse = supportsMultimodalFunctionResponse(model.id);\n\n\t\t\t// Use \"output\" key for success, \"error\" key for errors as per SDK documentation\n\t\t\tconst responseValue = hasText ? sanitizeSurrogates(textResult) : hasImages ? \"(see attached image)\" : \"\";\n\n\t\t\tconst imageParts: Part[] = imageContent.map((imageBlock) => ({\n\t\t\t\tinlineData: {\n\t\t\t\t\tmimeType: imageBlock.mimeType,\n\t\t\t\t\tdata: imageBlock.data,\n\t\t\t\t},\n\t\t\t}));\n\n\t\t\tconst includeId = requiresToolCallId(model.id);\n\t\t\tconst functionResponsePart: Part = {\n\t\t\t\tfunctionResponse: {\n\t\t\t\t\tname: msg.toolName,\n\t\t\t\t\tresponse: msg.isError ? { error: responseValue } : { output: responseValue },\n\t\t\t\t\t...(hasImages && modelSupportsMultimodalFunctionResponse && { parts: imageParts }),\n\t\t\t\t\t...(includeId ? { id: msg.toolCallId } : {}),\n\t\t\t\t},\n\t\t\t};\n\n\t\t\t// Cloud Code Assist API requires all function responses to be in a single user turn.\n\t\t\t// Check if the last content is already a user turn with function responses and merge.\n\t\t\tconst lastContent = contents[contents.length - 1];\n\t\t\tif (lastContent?.role === \"user\" && lastContent.parts?.some((p) => p.functionResponse)) {\n\t\t\t\tlastContent.parts.push(functionResponsePart);\n\t\t\t} else {\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts: [functionResponsePart],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// For Gemini < 3, add images in a separate user message\n\t\t\tif (hasImages && !modelSupportsMultimodalFunctionResponse) {\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts: [{ text: \"Tool result image:\" }, ...imageParts],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn contents;\n}\n\nconst JSON_SCHEMA_META_DECLARATIONS = new Set([\n\t\"$schema\",\n\t\"$id\",\n\t\"$anchor\",\n\t\"$dynamicAnchor\",\n\t\"$vocabulary\",\n\t\"$comment\",\n\t\"$defs\",\n\t\"definitions\", // pre-draft-2019-09 equivalent of $defs\n]);\n\n/**\n * Strip meta-declarations from a schema obj\n */\nfunction sanitizeForOpenApi(schema: unknown): unknown {\n\tif (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n\t\treturn schema;\n\t}\n\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tif (JSON_SCHEMA_META_DECLARATIONS.has(key)) continue;\n\t\tresult[key] = sanitizeForOpenApi(value);\n\t}\n\treturn result;\n}\n\n/**\n * Convert tools to Gemini function declarations format.\n *\n * By default uses `parametersJsonSchema` which supports full JSON Schema (including\n * anyOf, oneOf, const, etc.). Set `useParameters` to true to use the legacy `parameters`\n * field instead (OpenAPI 3.03 Schema). This is needed for Cloud Code Assist with Claude\n * models, where the API translates `parameters` into Anthropic's `input_schema`.\n */\nexport function convertTools(\n\ttools: Tool[],\n\tuseParameters = false,\n\tsupportsStrictMode = true,\n): { functionDeclarations: Record<string, unknown>[] }[] | undefined {\n\tif (tools.length === 0) return undefined;\n\treturn [\n\t\t{\n\t\t\tfunctionDeclarations: tools.map((tool) => {\n\t\t\t\tconst strict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n\t\t\t\tconst parameters = getJsonSchemaToolParameters(tool, strict);\n\t\t\t\treturn {\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t...(useParameters\n\t\t\t\t\t\t? { parameters: sanitizeForOpenApi(parameters as unknown) }\n\t\t\t\t\t\t: { parametersJsonSchema: parameters }),\n\t\t\t\t};\n\t\t\t}),\n\t\t},\n\t];\n}\n\n/** Gemini 3+ enforces required function parameters in validated tool-calling modes. */\nexport function supportsGoogleStrictToolSampling(modelId: string): boolean {\n\tconst majorVersion = getGeminiMajorVersion(modelId);\n\treturn majorVersion !== undefined && majorVersion >= 3;\n}\n\n/** Map tool choice string to Gemini FunctionCallingConfigMode. */\nexport function mapToolChoice(choice: string): FunctionCallingConfigMode {\n\tswitch (choice) {\n\t\tcase \"auto\":\n\t\t\treturn FunctionCallingConfigMode.AUTO;\n\t\tcase \"none\":\n\t\t\treturn FunctionCallingConfigMode.NONE;\n\t\tcase \"any\":\n\t\t\treturn FunctionCallingConfigMode.ANY;\n\t\tdefault:\n\t\t\treturn FunctionCallingConfigMode.AUTO;\n\t}\n}\n\nexport function resolveGoogleFunctionCallingMode(\n\ttools: Tool[],\n\ttoolChoice: string | undefined,\n\tsupportsStrictMode: boolean,\n): FunctionCallingConfigMode | undefined {\n\tconst useStrictMode = tools.some((tool) => resolveJsonSchemaStrictSampling(tool, supportsStrictMode) === true);\n\tif (toolChoice === \"none\" || toolChoice === \"any\") {\n\t\treturn mapToolChoice(toolChoice);\n\t}\n\tif (useStrictMode) {\n\t\treturn FunctionCallingConfigMode.VALIDATED;\n\t}\n\treturn toolChoice ? mapToolChoice(toolChoice) : undefined;\n}\n\n/**\n * Map Gemini FinishReason to our StopReason.\n */\nexport function mapStopReason(reason: FinishReason): StopReason {\n\tswitch (reason) {\n\t\tcase FinishReason.STOP:\n\t\t\treturn \"stop\";\n\t\tcase FinishReason.MAX_TOKENS:\n\t\t\treturn \"length\";\n\t\tcase FinishReason.BLOCKLIST:\n\t\tcase FinishReason.PROHIBITED_CONTENT:\n\t\tcase FinishReason.SPII:\n\t\tcase FinishReason.SAFETY:\n\t\tcase FinishReason.IMAGE_SAFETY:\n\t\tcase FinishReason.IMAGE_PROHIBITED_CONTENT:\n\t\tcase FinishReason.IMAGE_RECITATION:\n\t\tcase FinishReason.IMAGE_OTHER:\n\t\tcase FinishReason.RECITATION:\n\t\tcase FinishReason.FINISH_REASON_UNSPECIFIED:\n\t\tcase FinishReason.OTHER:\n\t\tcase FinishReason.LANGUAGE:\n\t\tcase FinishReason.MALFORMED_FUNCTION_CALL:\n\t\tcase FinishReason.UNEXPECTED_TOOL_CALL:\n\t\tcase FinishReason.TOO_MANY_TOOL_CALLS:\n\t\tcase FinishReason.NO_IMAGE:\n\t\t\treturn \"error\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = reason;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n\n/**\n * Map string finish reason to our StopReason (for raw API responses).\n */\nexport function mapStopReasonString(reason: string): StopReason {\n\tswitch (reason) {\n\t\tcase \"STOP\":\n\t\t\treturn \"stop\";\n\t\tcase \"MAX_TOKENS\":\n\t\t\treturn \"length\";\n\t\tdefault:\n\t\t\treturn \"error\";\n\t}\n}\n\n/**\n * Run a Google GenAI SDK request with the shared provider retry policy\n * (408/409/429/5xx with backoff, honoring retry-after), mirroring how the\n * Anthropic and OpenAI adapters wrap their initial request in\n * retryProviderRequest. The SDK's ApiError has a `status` property but no\n * `headers` property, and retryProviderRequest only retries errors that carry\n * both, so normalize the error by adding the missing `headers` before\n * rethrowing.\n */\nexport function retryGoogleRequest<T>(\n\trequest: () => Promise<T>,\n\toptions?: Pick<StreamOptions, \"maxRetries\" | \"maxRetryDelayMs\" | \"signal\">,\n): Promise<T> {\n\treturn retryProviderRequest(\n\t\tasync () => {\n\t\t\ttry {\n\t\t\t\treturn await request();\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error && \"status\" in error && !(\"headers\" in error)) {\n\t\t\t\t\t(error as { headers?: Headers }).headers = undefined;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tmaxRetries: options?.maxRetries,\n\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\tsignal: options?.signal,\n\t\t},\n\t);\n}\n"]}
1
+ {"version":3,"file":"google-shared.js","sourceRoot":"","sources":["../../src/api/google-shared.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAEN,YAAY,EACZ,yBAAyB,EACzB,aAAa,IAAI,sBAAsB,GAGvC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAWlD,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAC7F,OAAO,EAAE,2BAA2B,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AACzG,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAW5D,MAAM,6BAA6B,GAA2D;IAC7F,0BAA0B,EAAE,sBAAsB,CAAC,0BAA0B;IAC7E,OAAO,EAAE,sBAAsB,CAAC,OAAO;IACvC,GAAG,EAAE,sBAAsB,CAAC,GAAG;IAC/B,MAAM,EAAE,sBAAsB,CAAC,MAAM;IACrC,IAAI,EAAE,sBAAsB,CAAC,IAAI;CACjC,CAAC;AAEF,gGAAgG;AAChG,MAAM,UAAU,0BAA0B,CACzC,KAAe,EACf,KAAoB;IAEpB,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,EAAE,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,aAAa,GAAG,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IAChF,QAAQ,aAAa,EAAE,CAAC;QACvB,KAAK,SAAS,CAAC;QACf,KAAK,KAAK,CAAC;QACX,K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port {\n\ttype Content,\n\tFinishReason,\n\tFunctionCallingConfigMode,\n\tThinkingLevel as GoogleSdkThinkingLevel,\n\ttype Part,\n\ttype ThinkingConfig,\n} from \"@google/genai\";\nimport { clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tImageContent,\n\tModel,\n\tStopReason,\n\tStreamOptions,\n\tTextContent,\n\tThinkingLevel,\n\tTool,\n\tTranscriptContext,\n} from \"../types.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { collapseSystemMessages, withoutInitialSystemMessage } from \"../utils/transcript.ts\";\nimport { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\ntype GoogleApiType = \"google-generative-ai\" | \"google-vertex\" | \"google-antigravity\";\n\n/**\n * Thinking level for Gemini 3 models.\n * Mirrors Google's ThinkingLevel enum values.\n */\nexport type GoogleApiThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"MINIMAL\" | \"LOW\" | \"MEDIUM\" | \"HIGH\";\nexport type ResolvedGoogleThinkingLevel = Exclude<ThinkingLevel, \"xhigh\" | \"max\">;\n\nconst GOOGLE_SDK_THINKING_LEVEL_MAP: Record<GoogleApiThinkingLevel, GoogleSdkThinkingLevel> = {\n\tTHINKING_LEVEL_UNSPECIFIED: GoogleSdkThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n\tMINIMAL: GoogleSdkThinkingLevel.MINIMAL,\n\tLOW: GoogleSdkThinkingLevel.LOW,\n\tMEDIUM: GoogleSdkThinkingLevel.MEDIUM,\n\tHIGH: GoogleSdkThinkingLevel.HIGH,\n};\n\n/** Resolve a supported pi level or model-specific Google mapping to a standard Google level. */\nexport function resolveGoogleThinkingLevel<T extends GoogleApiType>(\n\tmodel: Model<T>,\n\tlevel: ThinkingLevel,\n): ResolvedGoogleThinkingLevel {\n\tconst mapped = model.thinkingLevelMap?.[level];\n\tconst resolvedLevel = typeof mapped === \"string\" ? mapped.toLowerCase() : level;\n\tswitch (resolvedLevel) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\tcase \"medium\":\n\t\tcase \"high\":\n\t\t\treturn resolvedLevel;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`,\n\t\t\t);\n\t}\n}\n\n/**\n * Whether this model uses Gemini's discrete `thinkingLevel` control instead of\n * the token-based `thinkingBudget` control. Supported levels come from the\n * model's `thinkingLevelMap`; this only selects the Google wire format.\n */\nexport function usesGoogleThinkingLevel<T extends GoogleApiType>(model: Model<T>): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn (\n\t\t// Match Gemini 3 Pro/Flash IDs with or without a minor version, such as\n\t\t// gemini-3-flash-preview, gemini-3.1-pro-preview, and gemini-3.8-flash.\n\t\t/gemini-3(?:\\.\\d+)?-(?:pro|flash)/.test(id) ||\n\t\tid === \"gemini-flash-latest\" ||\n\t\tid === \"gemini-flash-lite-latest\" ||\n\t\t// Match both hosted Gemma 4 naming forms: gemma-4-* and gemma4-*.\n\t\t/gemma-?4/.test(id)\n\t);\n}\n\nexport function toGoogleThinkingLevel(level: ResolvedGoogleThinkingLevel): GoogleApiThinkingLevel {\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\t\treturn \"MINIMAL\";\n\t\tcase \"low\":\n\t\t\treturn \"LOW\";\n\t\tcase \"medium\":\n\t\t\treturn \"MEDIUM\";\n\t\tcase \"high\":\n\t\t\treturn \"HIGH\";\n\t}\n}\n\nexport function toGoogleSdkThinkingLevel(level: GoogleApiThinkingLevel): GoogleSdkThinkingLevel {\n\treturn GOOGLE_SDK_THINKING_LEVEL_MAP[level];\n}\n\nexport function getDisabledGoogleThinkingConfig<T extends GoogleApiType>(model: Model<T>): ThinkingConfig {\n\tif (!usesGoogleThinkingLevel(model)) return { thinkingBudget: 0 };\n\n\tconst fallback = clampThinkingLevel(model, \"off\");\n\tif (fallback === \"off\") return { thinkingBudget: 0 };\n\n\tconst resolvedLevel = resolveGoogleThinkingLevel(model, fallback);\n\tconst apiLevel = toGoogleThinkingLevel(resolvedLevel);\n\treturn { thinkingLevel: toGoogleSdkThinkingLevel(apiLevel) };\n}\n\n/**\n * Determines whether a streamed Gemini `Part` should be treated as \"thinking\".\n *\n * Protocol note (Gemini / Vertex AI thought signatures):\n * - `thought: true` is the definitive marker for thinking content (thought summaries).\n * - `thoughtSignature` is an encrypted representation of the model's internal thought process\n * used to preserve reasoning context across multi-turn interactions.\n * - `thoughtSignature` can appear on ANY part type (text, functionCall, etc.) - it does NOT\n * indicate the part itself is thinking content.\n * - For non-functionCall responses, the signature appears on the last part for context replay.\n * - When persisting/replaying model outputs, signature-bearing parts must be preserved as-is;\n * do not merge/move signatures across parts.\n *\n * See: https://ai.google.dev/gemini-api/docs/thought-signatures\n */\nexport function isThinkingPart(part: Pick<Part, \"thought\" | \"thoughtSignature\">): boolean {\n\treturn part.thought === true;\n}\n\n/**\n * Retain thought signatures during streaming.\n *\n * Some backends only send `thoughtSignature` on the first delta for a given part/block; later deltas may omit it.\n * This helper preserves the last non-empty signature for the current block.\n *\n * Note: this does NOT merge or move signatures across distinct response parts. It only prevents\n * a signature from being overwritten with `undefined` within the same streamed block.\n */\nexport function retainThoughtSignature(existing: string | undefined, incoming: string | undefined): string | undefined {\n\tif (typeof incoming === \"string\" && incoming.length > 0) return incoming;\n\treturn existing;\n}\n\n// Thought signatures must be base64 for Google APIs (TYPE_BYTES).\nconst base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;\n\nfunction isValidThoughtSignature(signature: string | undefined): boolean {\n\tif (!signature) return false;\n\tif (signature.length % 4 !== 0) return false;\n\treturn base64SignaturePattern.test(signature);\n}\n\n/**\n * Only keep signatures from the same provider/model and with valid base64.\n */\nfunction resolveThoughtSignature(isSameProviderAndModel: boolean, signature: string | undefined): string | undefined {\n\treturn isSameProviderAndModel && isValidThoughtSignature(signature) ? signature : undefined;\n}\n\n/**\n * Models via Google APIs that require explicit tool call IDs in function calls/responses.\n */\nexport function requiresToolCallId(modelId: string): boolean {\n\tconst geminiMajorVersion = getGeminiMajorVersion(modelId);\n\treturn (\n\t\tmodelId.startsWith(\"claude-\") ||\n\t\tmodelId.startsWith(\"gpt-oss-\") ||\n\t\t(geminiMajorVersion !== undefined && geminiMajorVersion >= 3)\n\t);\n}\n\nfunction getGeminiMajorVersion(modelId: string): number | undefined {\n\tconst match = modelId.toLowerCase().match(/^gemini(?:-live)?-(\\d+)/);\n\tif (!match) return undefined;\n\treturn Number.parseInt(match[1], 10);\n}\n\nfunction supportsMultimodalFunctionResponse(modelId: string): boolean {\n\tconst geminiMajorVersion = getGeminiMajorVersion(modelId);\n\tif (geminiMajorVersion !== undefined) {\n\t\treturn geminiMajorVersion >= 3;\n\t}\n\treturn true;\n}\n\n/**\n * Convert internal messages to Gemini Content[] format.\n */\nexport function convertMessages<T extends GoogleApiType>(model: Model<T>, context: TranscriptContext): Content[] {\n\t// Gemini has no mid-conversation system messages; the leading prompt is sent as systemInstruction.\n\tconst conversation = withoutInitialSystemMessage(collapseSystemMessages(context).messages);\n\tconst contents: Content[] = [];\n\tconst normalizeToolCallId = (id: string): string => {\n\t\tif (!requiresToolCallId(model.id)) return id;\n\t\treturn id.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 64);\n\t};\n\n\tconst transformedMessages = transformMessages(conversation, model, normalizeToolCallId);\n\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts: [{ text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst parts: Part[] = msg.content.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn { text: sanitizeSurrogates(item.text) };\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tinlineData: {\n\t\t\t\t\t\t\t\tmimeType: item.mimeType,\n\t\t\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (parts.length === 0) continue;\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst parts: Part[] = [];\n\t\t\t// Check if message is from same provider and model - only then keep thinking blocks\n\t\t\tconst isSameProviderAndModel = msg.provider === model.provider && msg.model === model.id;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tconst thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.textSignature);\n\t\t\t\t\t// Skip empty text blocks — unless they carry a thought signature. Gemini can attach\n\t\t\t\t\t// the signature to a part whose visible text is empty and requires it echoed back;\n\t\t\t\t\t// dropping it breaks the reasoning chain and the model intermittently ends mid-task\n\t\t\t\t\t// turns with a thought-only STOP (empty completion, no tool call).\n\t\t\t\t\tif ((!block.text || block.text.trim() === \"\") && !thoughtSignature) continue;\n\t\t\t\t\tparts.push({\n\t\t\t\t\t\ttext: sanitizeSurrogates(block.text),\n\t\t\t\t\t\t...(thoughtSignature && { thoughtSignature }),\n\t\t\t\t\t});\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\t// Only keep as thinking block if same provider AND same model\n\t\t\t\t\t// Otherwise convert to plain text (no tags to avoid model mimicking them)\n\t\t\t\t\tif (isSameProviderAndModel) {\n\t\t\t\t\t\tconst thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thinkingSignature);\n\t\t\t\t\t\t// Same rule as text blocks: an empty thinking block is dropped only when it\n\t\t\t\t\t\t// carries no signature (mirrors the anthropic converter's handling).\n\t\t\t\t\t\tif ((!block.thinking || block.thinking.trim() === \"\") && !thoughtSignature) continue;\n\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\tthought: true,\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t\t...(thoughtSignature && { thoughtSignature }),\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Cross-provider/model: the signature is unusable, empty blocks stay dropped.\n\t\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") continue;\n\t\t\t\t\t\tparts.push({\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(block.thinking),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thoughtSignature);\n\t\t\t\t\tconst part: Part = {\n\t\t\t\t\t\tfunctionCall: {\n\t\t\t\t\t\t\tname: block.name,\n\t\t\t\t\t\t\targs: block.arguments ?? {},\n\t\t\t\t\t\t\t...(requiresToolCallId(model.id) ? { id: block.id } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(thoughtSignature && { thoughtSignature }),\n\t\t\t\t\t};\n\t\t\t\t\tparts.push(part);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (parts.length === 0) continue;\n\t\t\tcontents.push({\n\t\t\t\trole: \"model\",\n\t\t\t\tparts,\n\t\t\t});\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\t// Extract text and image content\n\t\t\tconst textContent = msg.content.filter((c): c is TextContent => c.type === \"text\");\n\t\t\tconst textResult = textContent.map((c) => c.text).join(\"\\n\");\n\t\t\tconst imageContent = model.input.includes(\"image\")\n\t\t\t\t? msg.content.filter((c): c is ImageContent => c.type === \"image\")\n\t\t\t\t: [];\n\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tconst hasImages = imageContent.length > 0;\n\n\t\t\t// Gemini 3+ models support multimodal function responses with images nested inside\n\t\t\t// functionResponse.parts. Claude and other non-Gemini models behind Cloud Code Assist /\n\t\t\t// Gemini < 3 still needs a separate user image turn.\n\t\t\tconst modelSupportsMultimodalFunctionResponse = supportsMultimodalFunctionResponse(model.id);\n\n\t\t\t// Use \"output\" key for success, \"error\" key for errors as per SDK documentation\n\t\t\tconst responseValue = hasText ? sanitizeSurrogates(textResult) : hasImages ? \"(see attached image)\" : \"\";\n\n\t\t\tconst imageParts: Part[] = imageContent.map((imageBlock) => ({\n\t\t\t\tinlineData: {\n\t\t\t\t\tmimeType: imageBlock.mimeType,\n\t\t\t\t\tdata: imageBlock.data,\n\t\t\t\t},\n\t\t\t}));\n\n\t\t\tconst includeId = requiresToolCallId(model.id);\n\t\t\tconst functionResponsePart: Part = {\n\t\t\t\tfunctionResponse: {\n\t\t\t\t\tname: msg.toolName,\n\t\t\t\t\tresponse: msg.isError ? { error: responseValue } : { output: responseValue },\n\t\t\t\t\t...(hasImages && modelSupportsMultimodalFunctionResponse && { parts: imageParts }),\n\t\t\t\t\t...(includeId ? { id: msg.toolCallId } : {}),\n\t\t\t\t},\n\t\t\t};\n\n\t\t\t// Cloud Code Assist API requires all function responses to be in a single user turn.\n\t\t\t// Check if the last content is already a user turn with function responses and merge.\n\t\t\tconst lastContent = contents[contents.length - 1];\n\t\t\tif (lastContent?.role === \"user\" && lastContent.parts?.some((p) => p.functionResponse)) {\n\t\t\t\tlastContent.parts.push(functionResponsePart);\n\t\t\t} else {\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts: [functionResponsePart],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// For Gemini < 3, add images in a separate user message\n\t\t\tif (hasImages && !modelSupportsMultimodalFunctionResponse) {\n\t\t\t\tcontents.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tparts: [{ text: \"Tool result image:\" }, ...imageParts],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn contents;\n}\n\nconst JSON_SCHEMA_META_DECLARATIONS = new Set([\n\t\"$schema\",\n\t\"$id\",\n\t\"$anchor\",\n\t\"$dynamicAnchor\",\n\t\"$vocabulary\",\n\t\"$comment\",\n\t\"$defs\",\n\t\"definitions\", // pre-draft-2019-09 equivalent of $defs\n]);\n\n/**\n * Strip meta-declarations from a schema obj\n */\nfunction sanitizeForOpenApi(schema: unknown): unknown {\n\tif (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n\t\treturn schema;\n\t}\n\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tif (JSON_SCHEMA_META_DECLARATIONS.has(key)) continue;\n\t\tresult[key] = sanitizeForOpenApi(value);\n\t}\n\treturn result;\n}\n\n/**\n * Convert tools to Gemini function declarations format.\n *\n * By default uses `parametersJsonSchema` which supports full JSON Schema (including\n * anyOf, oneOf, const, etc.). Set `useParameters` to true to use the legacy `parameters`\n * field instead (OpenAPI 3.03 Schema). This is needed for Cloud Code Assist with Claude\n * models, where the API translates `parameters` into Anthropic's `input_schema`.\n */\nexport function convertTools(\n\ttools: Tool[],\n\tuseParameters = false,\n\tsupportsStrictMode = true,\n): { functionDeclarations: Record<string, unknown>[] }[] | undefined {\n\tif (tools.length === 0) return undefined;\n\treturn [\n\t\t{\n\t\t\tfunctionDeclarations: tools.map((tool) => {\n\t\t\t\tconst strict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n\t\t\t\tconst parameters = getJsonSchemaToolParameters(tool, strict);\n\t\t\t\treturn {\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t...(useParameters\n\t\t\t\t\t\t? { parameters: sanitizeForOpenApi(parameters as unknown) }\n\t\t\t\t\t\t: { parametersJsonSchema: parameters }),\n\t\t\t\t};\n\t\t\t}),\n\t\t},\n\t];\n}\n\n/** Gemini 3+ enforces required function parameters in validated tool-calling modes. */\nexport function supportsGoogleStrictToolSampling(modelId: string): boolean {\n\tconst majorVersion = getGeminiMajorVersion(modelId);\n\treturn majorVersion !== undefined && majorVersion >= 3;\n}\n\n/** Map tool choice string to Gemini FunctionCallingConfigMode. */\nexport function mapToolChoice(choice: string): FunctionCallingConfigMode {\n\tswitch (choice) {\n\t\tcase \"auto\":\n\t\t\treturn FunctionCallingConfigMode.AUTO;\n\t\tcase \"none\":\n\t\t\treturn FunctionCallingConfigMode.NONE;\n\t\tcase \"any\":\n\t\t\treturn FunctionCallingConfigMode.ANY;\n\t\tdefault:\n\t\t\treturn FunctionCallingConfigMode.AUTO;\n\t}\n}\n\nexport function resolveGoogleFunctionCallingMode(\n\ttools: Tool[],\n\ttoolChoice: string | undefined,\n\tsupportsStrictMode: boolean,\n): FunctionCallingConfigMode | undefined {\n\tconst useStrictMode = tools.some((tool) => resolveJsonSchemaStrictSampling(tool, supportsStrictMode) === true);\n\tif (toolChoice === \"none\" || toolChoice === \"any\") {\n\t\treturn mapToolChoice(toolChoice);\n\t}\n\tif (useStrictMode) {\n\t\treturn FunctionCallingConfigMode.VALIDATED;\n\t}\n\treturn toolChoice ? mapToolChoice(toolChoice) : undefined;\n}\n\n/**\n * Map Gemini FinishReason to our StopReason.\n */\nexport function mapStopReason(reason: FinishReason): StopReason {\n\tswitch (reason) {\n\t\tcase FinishReason.STOP:\n\t\t\treturn \"stop\";\n\t\tcase FinishReason.MAX_TOKENS:\n\t\t\treturn \"length\";\n\t\tcase FinishReason.BLOCKLIST:\n\t\tcase FinishReason.PROHIBITED_CONTENT:\n\t\tcase FinishReason.SPII:\n\t\tcase FinishReason.SAFETY:\n\t\tcase FinishReason.IMAGE_SAFETY:\n\t\tcase FinishReason.IMAGE_PROHIBITED_CONTENT:\n\t\tcase FinishReason.IMAGE_RECITATION:\n\t\tcase FinishReason.IMAGE_OTHER:\n\t\tcase FinishReason.RECITATION:\n\t\tcase FinishReason.FINISH_REASON_UNSPECIFIED:\n\t\tcase FinishReason.OTHER:\n\t\tcase FinishReason.LANGUAGE:\n\t\tcase FinishReason.MALFORMED_FUNCTION_CALL:\n\t\tcase FinishReason.UNEXPECTED_TOOL_CALL:\n\t\tcase FinishReason.TOO_MANY_TOOL_CALLS:\n\t\tcase FinishReason.NO_IMAGE:\n\t\t\treturn \"error\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = reason;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n\n/**\n * Map string finish reason to our StopReason (for raw API responses).\n */\nexport function mapStopReasonString(reason: string): StopReason {\n\tswitch (reason) {\n\t\tcase \"STOP\":\n\t\t\treturn \"stop\";\n\t\tcase \"MAX_TOKENS\":\n\t\t\treturn \"length\";\n\t\tdefault:\n\t\t\treturn \"error\";\n\t}\n}\n\n/**\n * Run a Google GenAI SDK request with the shared provider retry policy\n * (408/409/429/5xx with backoff, honoring retry-after), mirroring how the\n * Anthropic and OpenAI adapters wrap their initial request in\n * retryProviderRequest. The SDK's ApiError has a `status` property but no\n * `headers` property, and retryProviderRequest only retries errors that carry\n * both, so normalize the error by adding the missing `headers` before\n * rethrowing.\n */\nexport function retryGoogleRequest<T>(\n\trequest: () => Promise<T>,\n\toptions?: Pick<StreamOptions, \"maxRetries\" | \"maxRetryDelayMs\" | \"signal\">,\n): Promise<T> {\n\treturn retryProviderRequest(\n\t\tasync () => {\n\t\t\ttry {\n\t\t\t\treturn await request();\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error && \"status\" in error && !(\"headers\" in error)) {\n\t\t\t\t\t(error as { headers?: Headers }).headers = undefined;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tmaxRetries: options?.maxRetries,\n\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\tsignal: options?.signal,\n\t\t},\n\t);\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import type { Model } from "../../types.ts";
2
+ import type { OAuthAuth, OAuthCredential } from "../types.ts";
3
+ export declare const googleAntigravityOAuth: OAuthAuth;
4
+ export declare function discoverGoogleAntigravityModels(credential: OAuthCredential, signal: AbortSignal, baseUrl?: string): Promise<Model<"google-antigravity">[]>;
5
+ //# sourceMappingURL=google-antigravity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"google-antigravity.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/google-antigravity.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAG5C,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAA2B,MAAM,aAAa,CAAC;AA4MvF,eAAO,MAAM,sBAAsB,EAAE,SAgCpC,CAAC;AAkBF,wBAAsB,+BAA+B,CACpD,UAAU,EAAE,eAAe,EAC3B,MAAM,EAAE,WAAW,EACnB,OAAO,SAAe,GACpB,OAAO,CAAC,KAAK,CAAC,oBAAoB,CAAC,EAAE,CAAC,CAkDxC"}