@heyhuynhgiabuu/pi-oauth-antigravity 0.1.0
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.
- package/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +91 -0
- package/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/oauth.d.ts +18 -0
- package/dist/auth/oauth.js +374 -0
- package/dist/client/client.d.ts +35 -0
- package/dist/client/client.js +448 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +1 -0
- package/dist/diagnostics/diagnostics.d.ts +31 -0
- package/dist/diagnostics/diagnostics.js +68 -0
- package/dist/diagnostics/index.d.ts +1 -0
- package/dist/diagnostics/index.js +1 -0
- package/dist/image/image.d.ts +62 -0
- package/dist/image/image.js +244 -0
- package/dist/image/index.d.ts +1 -0
- package/dist/image/index.js +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +182 -0
- package/dist/models/index.d.ts +1 -0
- package/dist/models/index.js +1 -0
- package/dist/models/models.d.ts +44 -0
- package/dist/models/models.js +377 -0
- package/dist/stream/index.d.ts +1 -0
- package/dist/stream/index.js +1 -0
- package/dist/stream/stream.d.ts +24 -0
- package/dist/stream/stream.js +879 -0
- package/dist/types/enums.d.ts +41 -0
- package/dist/types/enums.js +49 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.js +2 -0
- package/dist/types/types.d.ts +259 -0
- package/dist/types/types.js +2 -0
- package/dist/usage/index.d.ts +1 -0
- package/dist/usage/index.js +1 -0
- package/dist/usage/usage.d.ts +8 -0
- package/dist/usage/usage.js +388 -0
- package/dist/utils/http.d.ts +7 -0
- package/dist/utils/http.js +81 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/security.d.ts +8 -0
- package/dist/utils/security.js +60 -0
- package/dist/utils/util.d.ts +40 -0
- package/dist/utils/util.js +176 -0
- package/package.json +73 -0
|
@@ -0,0 +1,879 @@
|
|
|
1
|
+
import { calculateCost, createAssistantMessageEventStream, } from "@earendil-works/pi-ai";
|
|
2
|
+
import { antigravityHeaders, endpointCandidates, fetchAvailableRuntimeModel, formatRequestDiagnostics, jsonOrTextError, loadCodeAssist, parseApiKey, resolveProjectId, } from "../client/client.js";
|
|
3
|
+
import { getCurrentEndpoint, runWithDiagnostics, setLastEndpoint, setLastError, setLastLatencyMs, setLastProjectId, setLastResolvedRuntimeModel, setLastStatus, } from "../diagnostics/diagnostics.js";
|
|
4
|
+
import { AntigravityRequestType, AntigravityUserAgent, GeminiRole, GeminiToolCallingMode, StopReason, ToolChoice, } from "../types/enums.js";
|
|
5
|
+
import { ANTIGRAVITY_ROUTING, getMaxOutputTokens, getAntigravityRequestModelId, getFallbackRuntimeModel, getThinkingConfig, PROVIDER_ID, } from "../models/models.js";
|
|
6
|
+
import { redactSecrets, safeError } from "../utils/security.js";
|
|
7
|
+
import { ANTIGRAVITY_API, } from "../types/types.js";
|
|
8
|
+
import { antigravityEnv, antigravityRequestEnvelope, deriveAntigravitySessionId, getOrCreateAntigravitySession, isRecord, persistAntigravitySessions, sanitizeText, } from "../utils/util.js";
|
|
9
|
+
import { antigravityFetch } from "../utils/http.js";
|
|
10
|
+
export { ANTIGRAVITY_API };
|
|
11
|
+
const ANTIGRAVITY_SYSTEM_INSTRUCTION = "You are Antigravity, a powerful agentic AI coding assistant designed by Google DeepMind. " +
|
|
12
|
+
"You are pair programming with a user to solve coding tasks. Be concise, practical, and tool-aware.";
|
|
13
|
+
const ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION = 'CRITICAL: NEVER output rule checks, formatting guidelines, constraint checklists (e.g. "No emdashes"), or your thinking/personality preambles in the final response. Output only the final response.';
|
|
14
|
+
let toolCallCounter = 0;
|
|
15
|
+
function sanitizeToolCallId(id, fallbackName) {
|
|
16
|
+
const cleaned = id.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
17
|
+
const capped = cleaned.slice(0, 64);
|
|
18
|
+
return capped || `${fallbackName || "tool"}_${++toolCallCounter}`;
|
|
19
|
+
}
|
|
20
|
+
function toolCallIdNeeded(modelId, runtimeModel) {
|
|
21
|
+
return (modelId.startsWith("claude-") ||
|
|
22
|
+
modelId.startsWith("gpt-oss-") ||
|
|
23
|
+
runtimeModel.startsWith("claude-") ||
|
|
24
|
+
runtimeModel.startsWith("gpt-oss-"));
|
|
25
|
+
}
|
|
26
|
+
const base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
27
|
+
function isValidThoughtSignature(signature) {
|
|
28
|
+
if (!signature || typeof signature !== "string" || signature.length === 0)
|
|
29
|
+
return false;
|
|
30
|
+
if (signature.length % 4 !== 0)
|
|
31
|
+
return false;
|
|
32
|
+
return base64SignaturePattern.test(signature);
|
|
33
|
+
}
|
|
34
|
+
function geminiRequiresThoughtSignature(runtimeModel) {
|
|
35
|
+
if (!runtimeModel.startsWith("gemini-"))
|
|
36
|
+
return false;
|
|
37
|
+
const match = runtimeModel.match(/^gemini-(\d+)/);
|
|
38
|
+
if (match) {
|
|
39
|
+
const major = Number.parseInt(match[1], 10);
|
|
40
|
+
return major >= 3;
|
|
41
|
+
}
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
function parseImageData(raw, explicitMime) {
|
|
45
|
+
const match = raw.match(/^data:([^;]+);base64,(.+)$/s);
|
|
46
|
+
if (match) {
|
|
47
|
+
return {
|
|
48
|
+
mimeType: explicitMime || match[1] || "image/png",
|
|
49
|
+
data: match[2].trim(),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
mimeType: explicitMime || "image/png",
|
|
54
|
+
data: raw.trim(),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function asTextParts(content) {
|
|
58
|
+
if (typeof content === "string")
|
|
59
|
+
return [{ text: sanitizeText(content) }];
|
|
60
|
+
if (!Array.isArray(content))
|
|
61
|
+
return [];
|
|
62
|
+
return content.flatMap((item) => {
|
|
63
|
+
if (!isRecord(item))
|
|
64
|
+
return [];
|
|
65
|
+
const block = item;
|
|
66
|
+
if (block.type === "text")
|
|
67
|
+
return [{ text: sanitizeText(block.text) }];
|
|
68
|
+
if (block.type === "image") {
|
|
69
|
+
const rawData = block.data || block.source?.data;
|
|
70
|
+
if (!rawData)
|
|
71
|
+
return [];
|
|
72
|
+
const explicitMime = block.mimeType || block.mediaType || block.source?.mediaType;
|
|
73
|
+
const { data, mimeType } = parseImageData(rawData, explicitMime);
|
|
74
|
+
return data ? [{ inlineData: { mimeType, data } }] : [];
|
|
75
|
+
}
|
|
76
|
+
return [];
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function asImageParts(content) {
|
|
80
|
+
if (!Array.isArray(content))
|
|
81
|
+
return [];
|
|
82
|
+
return content.flatMap((item) => {
|
|
83
|
+
if (!isRecord(item))
|
|
84
|
+
return [];
|
|
85
|
+
const block = item;
|
|
86
|
+
if (block.type === "image") {
|
|
87
|
+
const rawData = block.data || block.source?.data;
|
|
88
|
+
if (!rawData)
|
|
89
|
+
return [];
|
|
90
|
+
const explicitMime = block.mimeType || block.mediaType || block.source?.mediaType;
|
|
91
|
+
const { data, mimeType } = parseImageData(rawData, explicitMime);
|
|
92
|
+
return data ? [{ inlineData: { mimeType, data } }] : [];
|
|
93
|
+
}
|
|
94
|
+
return [];
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
function appendTurn(contents, role, parts) {
|
|
98
|
+
if (!parts.length)
|
|
99
|
+
return;
|
|
100
|
+
const last = contents[contents.length - 1];
|
|
101
|
+
if (last && last.role === role) {
|
|
102
|
+
last.parts.push(...parts);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
contents.push({ role, parts });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Exported for unit tests. */
|
|
109
|
+
export function convertMessages(model, context, runtimeModel) {
|
|
110
|
+
const contents = [];
|
|
111
|
+
const requiresSig = geminiRequiresThoughtSignature(runtimeModel);
|
|
112
|
+
const droppedToolCallIds = new Map();
|
|
113
|
+
for (const msg of context.messages) {
|
|
114
|
+
if (msg.role === "user") {
|
|
115
|
+
const parts = asTextParts(msg.content);
|
|
116
|
+
appendTurn(contents, GeminiRole.User, parts);
|
|
117
|
+
}
|
|
118
|
+
else if (msg.role === "assistant") {
|
|
119
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted") {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const parts = [];
|
|
123
|
+
const isSameModel = msg.provider === PROVIDER_ID && msg.model === model.id;
|
|
124
|
+
const toolCalls = msg.content.filter((b) => b.type === "toolCall");
|
|
125
|
+
const firstCallHasSig = toolCalls.length > 0 && isValidThoughtSignature(toolCalls[0]?.thoughtSignature);
|
|
126
|
+
const allSigsValid = toolCalls.every((tc) => !tc.thoughtSignature || isValidThoughtSignature(tc.thoughtSignature));
|
|
127
|
+
const groupIsSigned = isSameModel && firstCallHasSig && allSigsValid;
|
|
128
|
+
for (const block of msg.content) {
|
|
129
|
+
if (block.type === "text") {
|
|
130
|
+
const textSig = isSameModel && isValidThoughtSignature(block.textSignature)
|
|
131
|
+
? block.textSignature
|
|
132
|
+
: undefined;
|
|
133
|
+
if ((!block.text || block.text.trim() === "") && !textSig) {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
parts.push({
|
|
137
|
+
text: sanitizeText(block.text),
|
|
138
|
+
...(textSig ? { thoughtSignature: textSig } : {}),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
else if (block.type === "thinking" && String(block.thinking || "").trim()) {
|
|
142
|
+
if (!isSameModel)
|
|
143
|
+
continue;
|
|
144
|
+
parts.push({
|
|
145
|
+
thought: true,
|
|
146
|
+
text: sanitizeText(block.thinking),
|
|
147
|
+
...(block.thinkingSignature ? { thoughtSignature: block.thinkingSignature } : {}),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
else if (block.type === "toolCall") {
|
|
151
|
+
if (requiresSig && !groupIsSigned) {
|
|
152
|
+
const rawId = block.id || "";
|
|
153
|
+
const argsText = (() => {
|
|
154
|
+
try {
|
|
155
|
+
return JSON.stringify(block.arguments ?? {});
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return "{}";
|
|
159
|
+
}
|
|
160
|
+
})();
|
|
161
|
+
if (rawId) {
|
|
162
|
+
droppedToolCallIds.set(rawId, argsText);
|
|
163
|
+
droppedToolCallIds.set(sanitizeToolCallId(rawId, block.name), argsText);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
droppedToolCallIds.set(`empty:${block.name}`, argsText);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
parts.push({
|
|
171
|
+
functionCall: {
|
|
172
|
+
name: block.name,
|
|
173
|
+
args: block.arguments ?? {},
|
|
174
|
+
...(toolCallIdNeeded(model.id, runtimeModel)
|
|
175
|
+
? { id: sanitizeToolCallId(block.id || "", block.name) }
|
|
176
|
+
: {}),
|
|
177
|
+
},
|
|
178
|
+
...(block.thoughtSignature ? { thoughtSignature: block.thoughtSignature } : {}),
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
appendTurn(contents, GeminiRole.Model, parts);
|
|
184
|
+
}
|
|
185
|
+
else if (msg.role === "toolResult") {
|
|
186
|
+
const text = msg.content
|
|
187
|
+
.filter((c) => c.type === "text")
|
|
188
|
+
.map((c) => sanitizeText(c.text))
|
|
189
|
+
.join("\n");
|
|
190
|
+
const responseText = text || (msg.isError ? "Tool failed" : "");
|
|
191
|
+
const imageParts = asImageParts(msg.content);
|
|
192
|
+
const rawId = msg.toolCallId || "";
|
|
193
|
+
const sanitizedId = toolCallIdNeeded(model.id, runtimeModel)
|
|
194
|
+
? sanitizeToolCallId(rawId, msg.toolName)
|
|
195
|
+
: rawId;
|
|
196
|
+
const droppedArgs = requiresSig
|
|
197
|
+
? (droppedToolCallIds.get(rawId) ??
|
|
198
|
+
droppedToolCallIds.get(sanitizedId) ??
|
|
199
|
+
(rawId === "" ? droppedToolCallIds.get(`empty:${msg.toolName}`) : undefined))
|
|
200
|
+
: undefined;
|
|
201
|
+
if (droppedArgs !== undefined) {
|
|
202
|
+
const label = droppedArgs === "{}" ? `\`${msg.toolName}\`` : `\`${msg.toolName}\` (${droppedArgs})`;
|
|
203
|
+
appendTurn(contents, GeminiRole.User, [
|
|
204
|
+
{ text: sanitizeText(`[Observation from ${label}:\n${responseText}]`) },
|
|
205
|
+
...imageParts,
|
|
206
|
+
]);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
const part = {
|
|
210
|
+
functionResponse: {
|
|
211
|
+
name: msg.toolName,
|
|
212
|
+
response: msg.isError ? { error: responseText } : { output: responseText },
|
|
213
|
+
...(toolCallIdNeeded(model.id, runtimeModel)
|
|
214
|
+
? { id: sanitizeToolCallId(msg.toolCallId || "", msg.toolName) }
|
|
215
|
+
: {}),
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
appendTurn(contents, GeminiRole.User, [part, ...imageParts]);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// Google Antigravity / Gemini requires the first turn to be from 'user'.
|
|
223
|
+
// If the conversation starts with 'model' (e.g. initial assistant greeting),
|
|
224
|
+
// prepend a minimal user message to prevent backend 400 rejection.
|
|
225
|
+
if (contents.length > 0 && contents[0]?.role === GeminiRole.Model) {
|
|
226
|
+
contents.unshift({
|
|
227
|
+
role: GeminiRole.User,
|
|
228
|
+
parts: [{ text: "Hello" }],
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
return contents;
|
|
232
|
+
}
|
|
233
|
+
function dereferenceSchema(schema, rootDefs = {}, visited = new Set()) {
|
|
234
|
+
if (!schema || typeof schema !== "object")
|
|
235
|
+
return schema;
|
|
236
|
+
if (Array.isArray(schema)) {
|
|
237
|
+
return schema.map((item) => dereferenceSchema(item, rootDefs, visited));
|
|
238
|
+
}
|
|
239
|
+
const s = schema;
|
|
240
|
+
if (visited.has(s))
|
|
241
|
+
return s;
|
|
242
|
+
visited.add(s);
|
|
243
|
+
const defs = { ...rootDefs };
|
|
244
|
+
if (isRecord(s.$defs))
|
|
245
|
+
Object.assign(defs, s.$defs);
|
|
246
|
+
if (isRecord(s.definitions))
|
|
247
|
+
Object.assign(defs, s.definitions);
|
|
248
|
+
if (typeof s.$ref === "string") {
|
|
249
|
+
const ref = s.$ref;
|
|
250
|
+
const match = ref.match(/^#\/(?:\$defs|definitions)\/(.+)$/);
|
|
251
|
+
if (match && match[1] && defs[match[1]] !== undefined) {
|
|
252
|
+
const resolved = dereferenceSchema(defs[match[1]], defs, visited);
|
|
253
|
+
if (isRecord(resolved)) {
|
|
254
|
+
const { $ref: _, ...rest } = s;
|
|
255
|
+
const restCleaned = dereferenceSchema(rest, defs, visited);
|
|
256
|
+
return isRecord(restCleaned) ? { ...resolved, ...restCleaned } : resolved;
|
|
257
|
+
}
|
|
258
|
+
return resolved;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const out = {};
|
|
262
|
+
for (const [key, value] of Object.entries(s)) {
|
|
263
|
+
out[key] = dereferenceSchema(value, defs, visited);
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
function ensureRootObjectSchema(schema) {
|
|
268
|
+
if (!isRecord(schema)) {
|
|
269
|
+
return { type: "object", properties: {} };
|
|
270
|
+
}
|
|
271
|
+
if (!schema.type) {
|
|
272
|
+
return { ...schema, type: "object", properties: schema.properties || {} };
|
|
273
|
+
}
|
|
274
|
+
return schema;
|
|
275
|
+
}
|
|
276
|
+
function stripMetaSchema(schema) {
|
|
277
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema))
|
|
278
|
+
return schema;
|
|
279
|
+
const omit = new Set([
|
|
280
|
+
"$schema",
|
|
281
|
+
"$id",
|
|
282
|
+
"$anchor",
|
|
283
|
+
"$dynamicAnchor",
|
|
284
|
+
"$vocabulary",
|
|
285
|
+
"$comment",
|
|
286
|
+
"$defs",
|
|
287
|
+
"definitions",
|
|
288
|
+
]);
|
|
289
|
+
const out = {};
|
|
290
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
291
|
+
if (!omit.has(key))
|
|
292
|
+
out[key] = stripMetaSchema(value);
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Protobuf `Schema` fields accepted by Cloud Code Assist's Claude/GPT custom-tool
|
|
298
|
+
* bridge (`parameters` field). Anything else — `nullable`, `anyOf`, `format`,
|
|
299
|
+
* `$ref`, etc. — returns `Unknown name "..."` / Invalid JSON payload (400).
|
|
300
|
+
* Allowlist rather than denylist so new JSON Schema keywords cannot 400 the request.
|
|
301
|
+
* Pi still validates tool args after the model calls them.
|
|
302
|
+
*/
|
|
303
|
+
const CUSTOM_TOOL_SCHEMA_ALLOW = new Set([
|
|
304
|
+
"type",
|
|
305
|
+
"description",
|
|
306
|
+
"properties",
|
|
307
|
+
"required",
|
|
308
|
+
"items",
|
|
309
|
+
"enum",
|
|
310
|
+
]);
|
|
311
|
+
function normalizeCustomToolType(value) {
|
|
312
|
+
if (typeof value === "string")
|
|
313
|
+
return value;
|
|
314
|
+
if (!Array.isArray(value))
|
|
315
|
+
return undefined;
|
|
316
|
+
// JSON Schema union types like ["string","null"] → first non-null scalar type.
|
|
317
|
+
const entries = value;
|
|
318
|
+
const scalar = entries.find((entry) => typeof entry === "string" && entry !== "null");
|
|
319
|
+
return scalar;
|
|
320
|
+
}
|
|
321
|
+
function normalizeCustomToolSchema(schema) {
|
|
322
|
+
if (!schema || typeof schema !== "object")
|
|
323
|
+
return schema;
|
|
324
|
+
if (Array.isArray(schema))
|
|
325
|
+
return schema.map(normalizeCustomToolSchema);
|
|
326
|
+
const out = {};
|
|
327
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
328
|
+
if (!CUSTOM_TOOL_SCHEMA_ALLOW.has(key))
|
|
329
|
+
continue;
|
|
330
|
+
if (key === "type") {
|
|
331
|
+
const normalizedType = normalizeCustomToolType(value);
|
|
332
|
+
if (normalizedType !== undefined)
|
|
333
|
+
out.type = normalizedType;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (key === "properties" && value && typeof value === "object" && !Array.isArray(value)) {
|
|
337
|
+
// Property names are user-defined, not Schema keywords — never allowlist-filter them.
|
|
338
|
+
const props = {};
|
|
339
|
+
for (const [propName, propSchema] of Object.entries(value)) {
|
|
340
|
+
props[propName] = normalizeCustomToolSchema(propSchema);
|
|
341
|
+
}
|
|
342
|
+
out.properties = props;
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (key === "enum" &&
|
|
346
|
+
Array.isArray(value) &&
|
|
347
|
+
!value.every((entry) => typeof entry === "string")) {
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
out[key] = normalizeCustomToolSchema(value);
|
|
351
|
+
}
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Gemini accepts JSON Schema through parametersJsonSchema. Claude and GPT-OSS
|
|
356
|
+
* use Cloud Code Assist's custom-tool bridge, which requires a compatible
|
|
357
|
+
* Draft 2020-12 subset in the legacy parameters field.
|
|
358
|
+
*/
|
|
359
|
+
export function convertTools(tools, useLegacyParameters = false) {
|
|
360
|
+
if (!tools?.length)
|
|
361
|
+
return undefined;
|
|
362
|
+
return [
|
|
363
|
+
{
|
|
364
|
+
functionDeclarations: tools.map((tool) => {
|
|
365
|
+
const dereferenced = dereferenceSchema(tool.parameters);
|
|
366
|
+
const rootObject = ensureRootObjectSchema(dereferenced);
|
|
367
|
+
const schema = stripMetaSchema(rootObject);
|
|
368
|
+
return {
|
|
369
|
+
name: tool.name,
|
|
370
|
+
description: tool.description,
|
|
371
|
+
...(useLegacyParameters
|
|
372
|
+
? { parameters: normalizeCustomToolSchema(schema) }
|
|
373
|
+
: { parametersJsonSchema: schema }),
|
|
374
|
+
};
|
|
375
|
+
}),
|
|
376
|
+
},
|
|
377
|
+
];
|
|
378
|
+
}
|
|
379
|
+
function mapToolChoiceMode(toolChoice) {
|
|
380
|
+
if (toolChoice === ToolChoice.None)
|
|
381
|
+
return GeminiToolCallingMode.None;
|
|
382
|
+
if (toolChoice === ToolChoice.Any || toolChoice === ToolChoice.Required)
|
|
383
|
+
return GeminiToolCallingMode.Any;
|
|
384
|
+
return GeminiToolCallingMode.Auto;
|
|
385
|
+
}
|
|
386
|
+
/** Exported for unit tests. */
|
|
387
|
+
export function buildRequest(model, context, projectId, options, runtimeModel, sessionState) {
|
|
388
|
+
const request = {
|
|
389
|
+
contents: convertMessages(model, context, runtimeModel),
|
|
390
|
+
systemInstruction: {
|
|
391
|
+
role: GeminiRole.User,
|
|
392
|
+
parts: context.systemPrompt
|
|
393
|
+
? [{ text: sanitizeText(context.systemPrompt) }]
|
|
394
|
+
: [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION }, { text: ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION }],
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
const generationConfig = {};
|
|
398
|
+
if (options.temperature !== undefined)
|
|
399
|
+
generationConfig.temperature = options.temperature;
|
|
400
|
+
const thinking = getThinkingConfig(model.id, options.reasoning ?? "off");
|
|
401
|
+
if (thinking)
|
|
402
|
+
generationConfig.thinkingConfig = thinking;
|
|
403
|
+
const maxAllowed = getMaxOutputTokens(model.id, runtimeModel);
|
|
404
|
+
if (options.maxTokens !== undefined) {
|
|
405
|
+
generationConfig.maxOutputTokens = Math.min(options.maxTokens, maxAllowed);
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
generationConfig.maxOutputTokens = Math.min(maxAllowed, model.maxTokens || maxAllowed);
|
|
409
|
+
}
|
|
410
|
+
if (Object.keys(generationConfig).length)
|
|
411
|
+
request.generationConfig = generationConfig;
|
|
412
|
+
const isClaude = model.id.startsWith("claude-") || runtimeModel.startsWith("claude-");
|
|
413
|
+
const tools = convertTools(context.tools, isClaude || model.id.startsWith("gpt-oss-"));
|
|
414
|
+
if (tools) {
|
|
415
|
+
request.tools = tools;
|
|
416
|
+
request.toolConfig = {
|
|
417
|
+
functionCallingConfig: {
|
|
418
|
+
mode: options.toolChoice && options.toolChoice !== ToolChoice.Auto
|
|
419
|
+
? mapToolChoiceMode(options.toolChoice)
|
|
420
|
+
: GeminiToolCallingMode.Validated,
|
|
421
|
+
},
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
else if (isClaude) {
|
|
425
|
+
request.toolConfig = {
|
|
426
|
+
functionCallingConfig: { mode: GeminiToolCallingMode.Validated },
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
const sid = options.sessionId || deriveAntigravitySessionId(context);
|
|
430
|
+
const state = sessionState ?? getOrCreateAntigravitySession(sid);
|
|
431
|
+
const envelope = antigravityRequestEnvelope(runtimeModel, isClaude, state);
|
|
432
|
+
request.sessionId = envelope.sessionId;
|
|
433
|
+
request.labels = envelope.labels;
|
|
434
|
+
return {
|
|
435
|
+
project: projectId,
|
|
436
|
+
model: runtimeModel,
|
|
437
|
+
request,
|
|
438
|
+
requestType: AntigravityRequestType.Agent,
|
|
439
|
+
userAgent: AntigravityUserAgent.Antigravity,
|
|
440
|
+
requestId: envelope.requestId,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
/** Exported for unit tests. */
|
|
444
|
+
export function mapStopReason(reason) {
|
|
445
|
+
if (reason === "STOP")
|
|
446
|
+
return StopReason.Stop;
|
|
447
|
+
if (reason === "MAX_TOKENS")
|
|
448
|
+
return StopReason.Length;
|
|
449
|
+
return reason ? StopReason.Error : StopReason.Stop;
|
|
450
|
+
}
|
|
451
|
+
/** Exported for unit tests. */
|
|
452
|
+
export function friendlyAntigravityError(status, text) {
|
|
453
|
+
const msg = redactSecrets(jsonOrTextError(text)).slice(0, 500);
|
|
454
|
+
if (status === 400) {
|
|
455
|
+
if (/API key not valid|API_KEY_INVALID/i.test(msg)) {
|
|
456
|
+
return "Antigravity login expired or credentials are invalid. Next: run /login antigravity, then retry.";
|
|
457
|
+
}
|
|
458
|
+
if (/Invalid JSON payload|Unknown name/i.test(msg)) {
|
|
459
|
+
return `Antigravity request format was rejected by the backend (${msg}). Next: switch to a simpler model or retry after updating the extension.`;
|
|
460
|
+
}
|
|
461
|
+
if (/Request contains an invalid argument/i.test(msg)) {
|
|
462
|
+
return `Antigravity rejected this request (${msg}). Next: retry once; if it keeps failing, switch models or re-login.`;
|
|
463
|
+
}
|
|
464
|
+
return `Bad request from Antigravity. Next: retry once, then run /login antigravity if it keeps failing. Backend said: ${msg}`;
|
|
465
|
+
}
|
|
466
|
+
if (status === 401) {
|
|
467
|
+
return "Antigravity authentication failed. Next: run /login antigravity, then retry.";
|
|
468
|
+
}
|
|
469
|
+
if (status === 403) {
|
|
470
|
+
if (/permission|forbidden|access/i.test(msg)) {
|
|
471
|
+
return "Antigravity access was denied for this account or project. Next: try another model, re-login, or use an account with access.";
|
|
472
|
+
}
|
|
473
|
+
return `Antigravity denied this request. Next: re-login or try another model. Backend said: ${msg}`;
|
|
474
|
+
}
|
|
475
|
+
if (status === 404) {
|
|
476
|
+
if (/Requested entity was not found/i.test(msg)) {
|
|
477
|
+
return "This model is not available right now. Next: switch to gemini-3.7-flash, gemini-3.6-flash, gemini-3.5-flash, gemini-3.1-pro, or another working model.";
|
|
478
|
+
}
|
|
479
|
+
return `Antigravity could not find the requested resource. Next: retry or switch models. Backend said: ${msg}`;
|
|
480
|
+
}
|
|
481
|
+
if (status === 408)
|
|
482
|
+
return "Antigravity timed out. Next: retry the same request.";
|
|
483
|
+
if (status === 409) {
|
|
484
|
+
return "Antigravity reported a conflict for this request. Next: retry once or start a new chat session.";
|
|
485
|
+
}
|
|
486
|
+
if (status === 429) {
|
|
487
|
+
const wait = msg.match(/Resets? in ([^.\n]+)/i)?.[1]?.trim();
|
|
488
|
+
if (/Individual quota reached/i.test(msg)) {
|
|
489
|
+
return `Quota reached. Please wait ${wait || "for reset"}. Next: switch models or try again after reset.`;
|
|
490
|
+
}
|
|
491
|
+
if (/quota/i.test(msg)) {
|
|
492
|
+
return `Quota reached.${wait ? ` Please wait ${wait}.` : ""} Next: switch models or retry later.`;
|
|
493
|
+
}
|
|
494
|
+
return `Rate limited by Antigravity. Next: wait a bit and retry.${wait ? ` Reset: ${wait}.` : ""}`;
|
|
495
|
+
}
|
|
496
|
+
if (status === 500) {
|
|
497
|
+
return "Antigravity had an internal server error. Next: retry in a moment or switch models.";
|
|
498
|
+
}
|
|
499
|
+
if (status === 502)
|
|
500
|
+
return "Antigravity returned a bad gateway error. Next: retry in a moment.";
|
|
501
|
+
if (status === 503) {
|
|
502
|
+
if (/No capacity available/i.test(msg)) {
|
|
503
|
+
return "This model has no capacity right now. Next: retry later or switch to another model.";
|
|
504
|
+
}
|
|
505
|
+
return "Antigravity is temporarily unavailable. Next: retry in a moment or switch models.";
|
|
506
|
+
}
|
|
507
|
+
if (status === 504)
|
|
508
|
+
return "Antigravity timed out upstream. Next: retry in a moment.";
|
|
509
|
+
return msg;
|
|
510
|
+
}
|
|
511
|
+
function createOutput(model) {
|
|
512
|
+
return {
|
|
513
|
+
role: "assistant",
|
|
514
|
+
content: [],
|
|
515
|
+
api: ANTIGRAVITY_API,
|
|
516
|
+
provider: PROVIDER_ID,
|
|
517
|
+
model: model.id,
|
|
518
|
+
usage: {
|
|
519
|
+
input: 0,
|
|
520
|
+
output: 0,
|
|
521
|
+
cacheRead: 0,
|
|
522
|
+
cacheWrite: 0,
|
|
523
|
+
totalTokens: 0,
|
|
524
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
525
|
+
},
|
|
526
|
+
stopReason: "stop",
|
|
527
|
+
timestamp: Date.now(),
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
function asToolCallArguments(args) {
|
|
531
|
+
return (args ?? {});
|
|
532
|
+
}
|
|
533
|
+
/** Exported for unit tests. */
|
|
534
|
+
export async function streamResponse(response, stream, output, model, sessionState) {
|
|
535
|
+
if (!response.body)
|
|
536
|
+
throw new Error("No response body");
|
|
537
|
+
const reader = response.body.getReader();
|
|
538
|
+
const decoder = new TextDecoder();
|
|
539
|
+
let buffer = "";
|
|
540
|
+
// Consumed-prefix offset: the buffer is compacted once per network chunk instead of
|
|
541
|
+
// re-copying the whole remainder for every SSE line.
|
|
542
|
+
let scanStart = 0;
|
|
543
|
+
let started = false;
|
|
544
|
+
let currentBlock = null;
|
|
545
|
+
let hasContent = false;
|
|
546
|
+
let lastResponseId;
|
|
547
|
+
const blocks = output.content;
|
|
548
|
+
const blockIndex = () => blocks.length - 1;
|
|
549
|
+
const ensureStarted = () => {
|
|
550
|
+
if (!started) {
|
|
551
|
+
stream.push({ type: "start", partial: output });
|
|
552
|
+
started = true;
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
const finishCurrent = () => {
|
|
556
|
+
if (!currentBlock)
|
|
557
|
+
return;
|
|
558
|
+
if (currentBlock.type === "text") {
|
|
559
|
+
stream.push({
|
|
560
|
+
type: "text_end",
|
|
561
|
+
contentIndex: blockIndex(),
|
|
562
|
+
content: currentBlock.text,
|
|
563
|
+
partial: output,
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
else {
|
|
567
|
+
stream.push({
|
|
568
|
+
type: "thinking_end",
|
|
569
|
+
contentIndex: blockIndex(),
|
|
570
|
+
content: currentBlock.thinking,
|
|
571
|
+
partial: output,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
currentBlock = null;
|
|
575
|
+
};
|
|
576
|
+
while (true) {
|
|
577
|
+
const result = await reader.read();
|
|
578
|
+
if (result.done)
|
|
579
|
+
break;
|
|
580
|
+
if (!(result.value instanceof Uint8Array))
|
|
581
|
+
continue;
|
|
582
|
+
buffer += decoder.decode(result.value, { stream: true });
|
|
583
|
+
let newlineIdx;
|
|
584
|
+
while ((newlineIdx = buffer.indexOf("\n", scanStart)) !== -1) {
|
|
585
|
+
const line = buffer.slice(scanStart, newlineIdx);
|
|
586
|
+
scanStart = newlineIdx + 1;
|
|
587
|
+
if (!line.startsWith("data:"))
|
|
588
|
+
continue;
|
|
589
|
+
const json = line.slice(5).trim();
|
|
590
|
+
if (!json || json === "[DONE]")
|
|
591
|
+
continue;
|
|
592
|
+
let chunk;
|
|
593
|
+
try {
|
|
594
|
+
chunk = JSON.parse(json);
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
if (chunk.error) {
|
|
600
|
+
throw new Error(chunk.error.message || JSON.stringify(chunk.error));
|
|
601
|
+
}
|
|
602
|
+
const responseData = chunk.response || chunk;
|
|
603
|
+
const candidate = responseData.candidates?.[0];
|
|
604
|
+
for (const part of candidate?.content?.parts || []) {
|
|
605
|
+
if (part.text !== undefined) {
|
|
606
|
+
hasContent = true;
|
|
607
|
+
const isThinking = part.thought === true;
|
|
608
|
+
const type = isThinking ? "thinking" : "text";
|
|
609
|
+
if (!currentBlock || currentBlock.type !== type) {
|
|
610
|
+
finishCurrent();
|
|
611
|
+
currentBlock = isThinking
|
|
612
|
+
? { type: "thinking", thinking: "", thinkingSignature: undefined }
|
|
613
|
+
: { type: "text", text: "" };
|
|
614
|
+
blocks.push(currentBlock);
|
|
615
|
+
ensureStarted();
|
|
616
|
+
stream.push({
|
|
617
|
+
type: isThinking ? "thinking_start" : "text_start",
|
|
618
|
+
contentIndex: blockIndex(),
|
|
619
|
+
partial: output,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
if (isThinking && currentBlock.type === "thinking") {
|
|
623
|
+
currentBlock.thinking += part.text;
|
|
624
|
+
if (part.thoughtSignature)
|
|
625
|
+
currentBlock.thinkingSignature = part.thoughtSignature;
|
|
626
|
+
stream.push({
|
|
627
|
+
type: "thinking_delta",
|
|
628
|
+
contentIndex: blockIndex(),
|
|
629
|
+
delta: part.text,
|
|
630
|
+
partial: output,
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
else if (!isThinking && currentBlock.type === "text") {
|
|
634
|
+
currentBlock.text += part.text;
|
|
635
|
+
if (part.thoughtSignature)
|
|
636
|
+
currentBlock.textSignature = part.thoughtSignature;
|
|
637
|
+
stream.push({
|
|
638
|
+
type: "text_delta",
|
|
639
|
+
contentIndex: blockIndex(),
|
|
640
|
+
delta: part.text,
|
|
641
|
+
partial: output,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (part.functionCall) {
|
|
646
|
+
hasContent = true;
|
|
647
|
+
finishCurrent();
|
|
648
|
+
const rawId = part.functionCall.id || "";
|
|
649
|
+
const toolCall = {
|
|
650
|
+
type: "toolCall",
|
|
651
|
+
id: sanitizeToolCallId(rawId, part.functionCall.name),
|
|
652
|
+
name: part.functionCall.name || "",
|
|
653
|
+
arguments: asToolCallArguments(part.functionCall.args),
|
|
654
|
+
...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}),
|
|
655
|
+
};
|
|
656
|
+
blocks.push(toolCall);
|
|
657
|
+
ensureStarted();
|
|
658
|
+
stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
|
|
659
|
+
stream.push({
|
|
660
|
+
type: "toolcall_delta",
|
|
661
|
+
contentIndex: blockIndex(),
|
|
662
|
+
delta: JSON.stringify(toolCall.arguments),
|
|
663
|
+
partial: output,
|
|
664
|
+
});
|
|
665
|
+
stream.push({
|
|
666
|
+
type: "toolcall_end",
|
|
667
|
+
contentIndex: blockIndex(),
|
|
668
|
+
toolCall,
|
|
669
|
+
partial: output,
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (candidate?.finishReason) {
|
|
674
|
+
output.rawStopReason = candidate.finishReason;
|
|
675
|
+
output.stopReason = blocks.some((b) => b.type === "toolCall")
|
|
676
|
+
? StopReason.ToolUse
|
|
677
|
+
: mapStopReason(candidate.finishReason);
|
|
678
|
+
}
|
|
679
|
+
if (responseData.responseId) {
|
|
680
|
+
lastResponseId = responseData.responseId;
|
|
681
|
+
}
|
|
682
|
+
if (responseData.usageMetadata) {
|
|
683
|
+
const prompt = responseData.usageMetadata.promptTokenCount || 0;
|
|
684
|
+
const cacheRead = responseData.usageMetadata.cachedContentTokenCount || 0;
|
|
685
|
+
const thoughts = responseData.usageMetadata.thoughtsTokenCount || 0;
|
|
686
|
+
output.usage.input = prompt - cacheRead;
|
|
687
|
+
output.usage.output = (responseData.usageMetadata.candidatesTokenCount || 0) + thoughts;
|
|
688
|
+
output.usage.reasoning = thoughts;
|
|
689
|
+
output.usage.cacheRead = cacheRead;
|
|
690
|
+
output.usage.totalTokens = responseData.usageMetadata.totalTokenCount || 0;
|
|
691
|
+
if (model?.cost) {
|
|
692
|
+
calculateCost(model, output.usage);
|
|
693
|
+
}
|
|
694
|
+
else {
|
|
695
|
+
output.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
if (scanStart > 0) {
|
|
700
|
+
buffer = buffer.slice(scanStart);
|
|
701
|
+
scanStart = 0;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
finishCurrent();
|
|
705
|
+
if (sessionState && lastResponseId) {
|
|
706
|
+
sessionState.lastExecutionId = lastResponseId;
|
|
707
|
+
persistAntigravitySessions();
|
|
708
|
+
}
|
|
709
|
+
return hasContent;
|
|
710
|
+
}
|
|
711
|
+
export function streamAntigravity(model, context, options) {
|
|
712
|
+
const stream = createAssistantMessageEventStream();
|
|
713
|
+
const opts = options ?? {};
|
|
714
|
+
void runWithDiagnostics(async () => {
|
|
715
|
+
const startTime = Date.now();
|
|
716
|
+
const output = createOutput(model);
|
|
717
|
+
try {
|
|
718
|
+
const creds = parseApiKey(opts.apiKey);
|
|
719
|
+
// Skip loadCodeAssist roundtrip when credentials already carry a projectId.
|
|
720
|
+
const warmedProject = creds.projectId ? null : await loadCodeAssist(creds.token);
|
|
721
|
+
const projectId = resolveProjectId({
|
|
722
|
+
token: creds.token,
|
|
723
|
+
warmedProject,
|
|
724
|
+
credentialProjectId: creds.projectId,
|
|
725
|
+
});
|
|
726
|
+
setLastProjectId(projectId);
|
|
727
|
+
const effort = opts.reasoning ?? "off";
|
|
728
|
+
const isKnownModel = model.id in ANTIGRAVITY_ROUTING;
|
|
729
|
+
const baseRuntimeModel = antigravityEnv("RUNTIME_MODEL")?.trim() || getAntigravityRequestModelId(model.id, effort);
|
|
730
|
+
let initialRuntimeModel = baseRuntimeModel;
|
|
731
|
+
// Skip pre-flight model discovery for known static models to optimize TTFT latency.
|
|
732
|
+
// Dynamic lookup is only needed for unmapped custom models.
|
|
733
|
+
if (!isKnownModel && !antigravityEnv("RUNTIME_MODEL")) {
|
|
734
|
+
const dynamic = await fetchAvailableRuntimeModel(creds.token, projectId, baseRuntimeModel);
|
|
735
|
+
if (dynamic?.id && /^(gemini-|claude-|gpt-oss-)/i.test(dynamic.id)) {
|
|
736
|
+
initialRuntimeModel = dynamic.id;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const sid = opts.sessionId || deriveAntigravitySessionId(context);
|
|
740
|
+
const sessionState = getOrCreateAntigravitySession(sid);
|
|
741
|
+
const runtimeCandidates = [initialRuntimeModel];
|
|
742
|
+
const fallback = getFallbackRuntimeModel(initialRuntimeModel, effort);
|
|
743
|
+
if (fallback && fallback !== initialRuntimeModel) {
|
|
744
|
+
runtimeCandidates.push(fallback);
|
|
745
|
+
}
|
|
746
|
+
const isClaudeReasoning = model.id.startsWith("claude-") && model.reasoning;
|
|
747
|
+
const requestHeaders = {
|
|
748
|
+
...antigravityHeaders(creds.token),
|
|
749
|
+
...(isClaudeReasoning ? { "anthropic-beta": "interleaved-thinking-2025-05-14" } : {}),
|
|
750
|
+
};
|
|
751
|
+
let response;
|
|
752
|
+
let lastText = "";
|
|
753
|
+
let received = false;
|
|
754
|
+
let runtimeModel = initialRuntimeModel;
|
|
755
|
+
for (let emptyAttempt = 0; emptyAttempt <= 2; emptyAttempt++) {
|
|
756
|
+
if (opts.signal?.aborted)
|
|
757
|
+
throw new Error("Request was aborted");
|
|
758
|
+
if (emptyAttempt > 0) {
|
|
759
|
+
const delay = 500 * 2 ** (emptyAttempt - 1);
|
|
760
|
+
await new Promise((res) => setTimeout(res, delay));
|
|
761
|
+
}
|
|
762
|
+
for (let candIdx = 0; candIdx < runtimeCandidates.length; candIdx++) {
|
|
763
|
+
runtimeModel = runtimeCandidates[candIdx];
|
|
764
|
+
setLastResolvedRuntimeModel(runtimeModel);
|
|
765
|
+
const body = JSON.stringify(buildRequest(model, context, projectId, opts, runtimeModel, sessionState));
|
|
766
|
+
for (const endpoint of endpointCandidates(sessionState.lastGoodEndpoint)) {
|
|
767
|
+
setLastEndpoint(endpoint);
|
|
768
|
+
response = await antigravityFetch(`${endpoint}/v1internal:streamGenerateContent?alt=sse`, {
|
|
769
|
+
method: "POST",
|
|
770
|
+
headers: requestHeaders,
|
|
771
|
+
body,
|
|
772
|
+
signal: opts.signal,
|
|
773
|
+
});
|
|
774
|
+
setLastStatus(response.status);
|
|
775
|
+
if (response.ok) {
|
|
776
|
+
sessionState.lastGoodEndpoint = endpoint;
|
|
777
|
+
persistAntigravitySessions();
|
|
778
|
+
break;
|
|
779
|
+
}
|
|
780
|
+
lastText = await response.text();
|
|
781
|
+
if (response.status === 429 && /Individual quota reached/i.test(lastText))
|
|
782
|
+
break;
|
|
783
|
+
if (![403, 404, 429, 500, 502, 503, 504].includes(response.status))
|
|
784
|
+
break;
|
|
785
|
+
}
|
|
786
|
+
if (response?.ok)
|
|
787
|
+
break;
|
|
788
|
+
if (response?.status === 404) {
|
|
789
|
+
if (candIdx + 1 < runtimeCandidates.length) {
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
if (isKnownModel && candIdx === runtimeCandidates.length - 1) {
|
|
793
|
+
const dynamic = await fetchAvailableRuntimeModel(creds.token, projectId, baseRuntimeModel);
|
|
794
|
+
if (dynamic?.id &&
|
|
795
|
+
!runtimeCandidates.includes(dynamic.id) &&
|
|
796
|
+
/^(gemini-|claude-|gpt-oss-)/i.test(dynamic.id)) {
|
|
797
|
+
runtimeCandidates.push(dynamic.id);
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
break;
|
|
803
|
+
}
|
|
804
|
+
if (!response || !response.ok) {
|
|
805
|
+
if (antigravityEnv("DEBUG_DUMP") === "1") {
|
|
806
|
+
try {
|
|
807
|
+
const body = JSON.stringify(buildRequest(model, context, projectId, opts, runtimeModel));
|
|
808
|
+
let parsedBody = body;
|
|
809
|
+
try {
|
|
810
|
+
parsedBody = JSON.parse(body);
|
|
811
|
+
}
|
|
812
|
+
catch {
|
|
813
|
+
parsedBody = body;
|
|
814
|
+
}
|
|
815
|
+
await (await import("node:fs/promises")).writeFile("/tmp/antigravity-last-request.json", JSON.stringify({
|
|
816
|
+
status: response?.status,
|
|
817
|
+
runtimeModel,
|
|
818
|
+
lastText: lastText.slice(0, 4000),
|
|
819
|
+
body: parsedBody,
|
|
820
|
+
}, null, 2));
|
|
821
|
+
}
|
|
822
|
+
catch {
|
|
823
|
+
// ignore dump failures
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
const friendly = friendlyAntigravityError(response?.status, lastText);
|
|
827
|
+
if (response?.status === 429 && /Quota reached\./i.test(friendly)) {
|
|
828
|
+
throw new Error(friendly);
|
|
829
|
+
}
|
|
830
|
+
throw new Error(`Antigravity API error (${response?.status ?? "no response"}, ${formatRequestDiagnostics({ projectId, runtimeModel })}): ${friendly}`);
|
|
831
|
+
}
|
|
832
|
+
output.content = [];
|
|
833
|
+
output.usage = {
|
|
834
|
+
input: 0,
|
|
835
|
+
output: 0,
|
|
836
|
+
cacheRead: 0,
|
|
837
|
+
cacheWrite: 0,
|
|
838
|
+
totalTokens: 0,
|
|
839
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
840
|
+
};
|
|
841
|
+
output.stopReason = "stop";
|
|
842
|
+
received = await streamResponse(response, stream, output, model, sessionState);
|
|
843
|
+
if (received)
|
|
844
|
+
break;
|
|
845
|
+
}
|
|
846
|
+
if (!received)
|
|
847
|
+
throw new Error("Antigravity API returned an empty response");
|
|
848
|
+
setLastLatencyMs(Date.now() - startTime);
|
|
849
|
+
if (output.stopReason === "error" || output.stopReason === "aborted") {
|
|
850
|
+
const errorDetail = output.rawStopReason
|
|
851
|
+
? `Provider stopped with: ${output.rawStopReason}`
|
|
852
|
+
: "An unknown error occurred";
|
|
853
|
+
output.errorMessage = output.errorMessage || errorDetail;
|
|
854
|
+
setLastError(output.errorMessage);
|
|
855
|
+
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
856
|
+
}
|
|
857
|
+
else if (output.stopReason === "pending") {
|
|
858
|
+
throw new Error("Antigravity API returned no stop reason");
|
|
859
|
+
}
|
|
860
|
+
else {
|
|
861
|
+
stream.push({ type: "done", reason: output.stopReason, message: output });
|
|
862
|
+
}
|
|
863
|
+
stream.end();
|
|
864
|
+
}
|
|
865
|
+
catch (error) {
|
|
866
|
+
setLastLatencyMs(Date.now() - startTime);
|
|
867
|
+
output.stopReason = opts.signal?.aborted ? "aborted" : "error";
|
|
868
|
+
output.errorMessage = safeError(error);
|
|
869
|
+
setLastError(output.errorMessage);
|
|
870
|
+
// Ensure endpoint is recorded even if failure happened before setLastEndpoint.
|
|
871
|
+
if (!getCurrentEndpoint() && endpointCandidates()[0]) {
|
|
872
|
+
setLastEndpoint(endpointCandidates()[0]);
|
|
873
|
+
}
|
|
874
|
+
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
875
|
+
stream.end();
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
return stream;
|
|
879
|
+
}
|