@cortexkit/pi-antigravity-auth 1.0.1 → 2.0.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/dist/index.js CHANGED
@@ -1,1499 +1,10 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // ../core/src/logger.ts
8
- var ENV_CONSOLE_LOG = "ANTIGRAVITY_CORE_CONSOLE_LOG";
9
- var _sink = null;
10
- function isTruthyFlag(flag) {
11
- return flag === "1" || flag?.toLowerCase() === "true";
12
- }
13
- function isConsoleLogEnabled() {
14
- return isTruthyFlag(process.env[ENV_CONSOLE_LOG]);
15
- }
16
- function writeConsoleLog(level, ...args) {
17
- switch (level) {
18
- case "debug":
19
- console.debug(...args);
20
- break;
21
- case "info":
22
- console.info(...args);
23
- break;
24
- case "warn":
25
- console.warn(...args);
26
- break;
27
- case "error":
28
- console.error(...args);
29
- break;
30
- }
31
- }
32
- function createLogger(module) {
33
- const service = `antigravity.${module}`;
34
- const log3 = (level, message, extra) => {
35
- if (_sink) {
36
- try {
37
- _sink({ service, level, message, extra });
38
- } catch {
39
- }
40
- }
41
- if (isConsoleLogEnabled()) {
42
- const prefix = `[${service}]`;
43
- const args = extra ? [prefix, message, extra] : [prefix, message];
44
- writeConsoleLog(level, ...args);
45
- }
46
- };
47
- return {
48
- debug: (message, extra) => log3("debug", message, extra),
49
- info: (message, extra) => log3("info", message, extra),
50
- warn: (message, extra) => log3("warn", message, extra),
51
- error: (message, extra) => log3("error", message, extra)
52
- };
53
- }
54
-
55
- // ../core/src/constants.ts
56
- var ANTIGRAVITY_CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
57
- var ANTIGRAVITY_CLIENT_SECRET = "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";
58
- var ANTIGRAVITY_SCOPES = [
59
- "https://www.googleapis.com/auth/cloud-platform",
60
- "https://www.googleapis.com/auth/userinfo.email",
61
- "https://www.googleapis.com/auth/userinfo.profile",
62
- "https://www.googleapis.com/auth/cclog",
63
- "https://www.googleapis.com/auth/experimentsandconfigs"
64
- ];
65
- var ANTIGRAVITY_REDIRECT_URI = "http://localhost:51121/oauth-callback";
66
- var ANTIGRAVITY_ENDPOINT_DAILY = "https://daily-cloudcode-pa.googleapis.com";
67
- var ANTIGRAVITY_ENDPOINT_PROD = "https://cloudcode-pa.googleapis.com";
68
- var ANTIGRAVITY_ENDPOINT_FALLBACKS = [
69
- ANTIGRAVITY_ENDPOINT_DAILY,
70
- ANTIGRAVITY_ENDPOINT_PROD
71
- ];
72
- var ANTIGRAVITY_LOAD_ENDPOINTS = [
73
- ANTIGRAVITY_ENDPOINT_DAILY,
74
- ANTIGRAVITY_ENDPOINT_PROD
75
- ];
76
- var ANTIGRAVITY_ENDPOINT = ANTIGRAVITY_ENDPOINT_DAILY;
77
- var ANTIGRAVITY_DEFAULT_PROJECT_ID = "rising-fact-p41fc";
78
- var ANTIGRAVITY_VERSION_FALLBACK = "1.18.3";
79
- var ANTIGRAVITY_VERSION = ANTIGRAVITY_VERSION_FALLBACK;
80
- var ANTIGRAVITY_HEADERS = {
81
- "User-Agent": `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${ANTIGRAVITY_VERSION} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,
82
- "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
83
- "Client-Metadata": `{"ideType":"ANTIGRAVITY","platform":"${process.platform === "win32" ? "WINDOWS" : "MACOS"}","pluginType":"GEMINI"}`
84
- };
85
- var GEMINI_CLI_HEADERS = {
86
- "User-Agent": "google-api-nodejs-client/9.15.1",
87
- "X-Goog-Api-Client": "gl-node/22.17.0",
88
- "Client-Metadata": "ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI"
89
- };
90
-
91
- // ../core/src/auth.ts
92
- var ACCESS_TOKEN_EXPIRY_BUFFER_MS = 60 * 1e3;
93
- function parseRefreshParts(refresh) {
94
- const [refreshToken = "", projectId = "", managedProjectId = ""] = (refresh ?? "").split("|");
95
- return {
96
- refreshToken,
97
- projectId: projectId || void 0,
98
- managedProjectId: managedProjectId || void 0
99
- };
100
- }
101
- function formatRefreshParts(parts) {
102
- const projectSegment = parts.projectId ?? "";
103
- const base = `${parts.refreshToken}|${projectSegment}`;
104
- return parts.managedProjectId ? `${base}|${parts.managedProjectId}` : base;
105
- }
106
- function calculateTokenExpiry(requestTimeMs, expiresInSeconds) {
107
- const seconds = typeof expiresInSeconds === "number" ? expiresInSeconds : 3600;
108
- if (isNaN(seconds) || seconds <= 0) {
109
- return requestTimeMs;
110
- }
111
- return requestTimeMs + seconds * 1e3;
112
- }
113
-
114
- // ../core/src/fingerprint.ts
115
- var AGY_CLI_VERSION = "1.0.4";
116
- function normalizeHarnessPlatform(platform = process.platform) {
117
- return platform === "win32" ? "windows" : platform || "unknown";
118
- }
119
- function normalizeHarnessArch(arch = process.arch) {
120
- switch (arch) {
121
- case "x64":
122
- return "amd64";
123
- case "ia32":
124
- return "386";
125
- default:
126
- return arch || "unknown";
127
- }
128
- }
129
- function buildAntigravityHarnessPlatformArch(platform = process.platform, arch = process.arch) {
130
- return `${normalizeHarnessPlatform(platform)}/${normalizeHarnessArch(arch)}`;
131
- }
132
- function buildAntigravityHarnessUserAgent(version = AGY_CLI_VERSION, platform = process.platform, arch = process.arch) {
133
- return `antigravity/cli/${version} ${buildAntigravityHarnessPlatformArch(platform, arch)}`;
134
- }
135
- function buildAntigravityHarnessLoadCodeAssistUserAgent(version = AGY_CLI_VERSION) {
136
- return buildAntigravityHarnessUserAgent(version);
137
- }
138
- function buildAntigravityLoadCodeAssistMetadata() {
139
- return { ideType: "ANTIGRAVITY" };
140
- }
141
- function buildAntigravityHarnessBootstrapHeaders(accessToken) {
142
- return {
143
- "User-Agent": buildAntigravityHarnessLoadCodeAssistUserAgent(),
144
- Authorization: `Bearer ${accessToken}`,
145
- "Content-Type": "application/json",
146
- "Accept-Encoding": "gzip"
147
- };
148
- }
149
-
150
- // ../core/src/agy-transport.ts
151
- import * as net from "node:net";
152
- import * as tls from "node:tls";
153
- import { Buffer as Buffer2 } from "node:buffer";
154
- import { PassThrough, Readable, Transform } from "node:stream";
155
- import { createGunzip } from "node:zlib";
156
- var DEFAULT_HTTPS_PORT = 443;
157
- var DEFAULT_PROXY_PORT = 8080;
158
- var DEFAULT_AGY_RESPONSE_HEADER_TIMEOUT_MS = 18e4;
159
- var DEFAULT_AGY_IDLE_TIMEOUT_MS = 18e4;
160
- function headersToRecord(headers) {
161
- const result = {};
162
- if (!headers) return result;
163
- const normalized = new Headers(headers);
164
- normalized.forEach((value, key) => {
165
- result[key.toLowerCase()] = value;
166
- });
167
- return result;
168
- }
169
- function getHeader(headers, name) {
170
- return headers[name.toLowerCase()];
171
- }
172
- function bodyToBuffer(body) {
173
- if (body == null) return Buffer2.alloc(0);
174
- if (typeof body === "string") return Buffer2.from(body);
175
- if (body instanceof Uint8Array) return Buffer2.from(body);
176
- if (body instanceof ArrayBuffer) return Buffer2.from(body);
177
- throw new Error("agy transport only supports string/byte request bodies");
178
- }
179
- function shouldUseChunkedBody(url) {
180
- return url.pathname.includes(":streamGenerateContent");
181
- }
182
- function buildAgyCliHeaderPairs(url, init = {}) {
183
- const parsedUrl = new URL(url);
184
- const headers = headersToRecord(init.headers);
185
- const body = bodyToBuffer(init.body);
186
- const host = parsedUrl.port ? `${parsedUrl.hostname}:${parsedUrl.port}` : parsedUrl.hostname;
187
- const userAgent = getHeader(headers, "User-Agent") ?? "antigravity/cli/1.0.4 darwin/arm64";
188
- const authorization = getHeader(headers, "Authorization");
189
- const contentType = getHeader(headers, "Content-Type") ?? "application/json";
190
- const acceptEncoding = getHeader(headers, "Accept-Encoding") ?? "gzip";
191
- const chunked = shouldUseChunkedBody(parsedUrl);
192
- const pairs = [
193
- ["Host", host],
194
- ["User-Agent", userAgent]
195
- ];
196
- if (chunked) {
197
- pairs.push(["Transfer-Encoding", "chunked"]);
198
- } else {
199
- pairs.push(["Content-Length", String(body.byteLength)]);
200
- }
201
- if (authorization) {
202
- pairs.push(["Authorization", authorization]);
203
- }
204
- pairs.push(["Content-Type", contentType]);
205
- pairs.push(["Accept-Encoding", acceptEncoding]);
206
- return pairs;
207
- }
208
- function noProxyIncludes(hostname) {
209
- const raw = process.env.NO_PROXY || process.env.no_proxy || "";
210
- if (!raw) return false;
211
- const host = hostname.toLowerCase();
212
- return raw.split(",").map((entry) => entry.trim().toLowerCase()).some((entry) => {
213
- if (!entry) return false;
214
- if (entry === "*") return true;
215
- if (entry.startsWith(".")) return host.endsWith(entry);
216
- return host === entry || host.endsWith(`.${entry}`);
217
- });
218
- }
219
- function getHttpsProxy(url) {
220
- if (url.protocol !== "https:" || noProxyIncludes(url.hostname)) return void 0;
221
- const rawProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy;
222
- if (!rawProxy) return void 0;
223
- try {
224
- return new URL(rawProxy);
225
- } catch {
226
- return void 0;
227
- }
228
- }
229
- function waitForHead(socket, timeoutMs, onTimeout) {
230
- return new Promise((resolve, reject) => {
231
- let buffer = Buffer2.alloc(0);
232
- const timeout = setTimeout(() => {
233
- onTimeout();
234
- cleanup(() => reject(new Error(`Antigravity request timed out waiting for response headers after ${timeoutMs}ms`)));
235
- }, timeoutMs);
236
- const cleanup = (finish) => {
237
- socket.off("data", onData);
238
- socket.off("error", onError);
239
- clearTimeout(timeout);
240
- finish();
241
- };
242
- const onError = (error) => cleanup(() => reject(error));
243
- const onData = (chunk) => {
244
- buffer = Buffer2.concat([buffer, chunk]);
245
- const marker = buffer.indexOf("\r\n\r\n");
246
- if (marker === -1) return;
247
- const head = buffer.subarray(0, marker).toString("latin1");
248
- const leftover = buffer.subarray(marker + 4);
249
- cleanup(() => resolve({ head, leftover }));
250
- };
251
- socket.on("data", onData);
252
- socket.once("error", onError);
253
- });
254
- }
255
- async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, onDebug) {
256
- const proxySocket = net.connect({
257
- host: proxyUrl.hostname,
258
- port: Number(proxyUrl.port || DEFAULT_PROXY_PORT)
259
- });
260
- await new Promise((resolve, reject) => {
261
- const timeout = setTimeout(() => {
262
- onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
263
- proxySocket.destroy();
264
- reject(new Error(`Antigravity request timed out connecting to HTTPS proxy after ${timeoutMs}ms`));
265
- }, timeoutMs);
266
- const cleanup = () => clearTimeout(timeout);
267
- proxySocket.once("connect", () => {
268
- cleanup();
269
- resolve();
270
- });
271
- proxySocket.once("error", (error) => {
272
- cleanup();
273
- reject(error);
274
- });
275
- });
276
- const targetHost = targetUrl.hostname;
277
- const targetPort = Number(targetUrl.port || DEFAULT_HTTPS_PORT);
278
- const auth = proxyUrl.username ? `Proxy-Authorization: Basic ${Buffer2.from(`${decodeURIComponent(proxyUrl.username)}:${decodeURIComponent(proxyUrl.password)}`).toString("base64")}\r
279
- ` : "";
280
- proxySocket.write(
281
- `CONNECT ${targetHost}:${targetPort} HTTP/1.1\r
282
- Host: ${targetHost}:${targetPort}\r
283
- ` + auth + "\r\n"
284
- );
285
- const { head, leftover } = await waitForHead(proxySocket, timeoutMs, () => {
286
- onDebug?.(`agy transport proxy CONNECT response timeout after ${timeoutMs}ms`);
287
- proxySocket.destroy();
288
- });
289
- if (!/^HTTP\/1\.[01] 2\d\d\b/.test(head)) {
290
- proxySocket.destroy();
291
- throw new Error(`Proxy CONNECT failed: ${head.split("\r\n")[0] ?? "unknown"}`);
292
- }
293
- if (leftover.length > 0) {
294
- proxySocket.unshift(leftover);
295
- }
296
- return await new Promise((resolve, reject) => {
297
- const tlsSocket = tls.connect({ socket: proxySocket, servername: targetHost });
298
- const timeout = setTimeout(() => {
299
- onDebug?.(`agy transport proxy TLS handshake timeout after ${timeoutMs}ms`);
300
- tlsSocket.destroy();
301
- reject(new Error(`Antigravity request timed out during proxy TLS handshake after ${timeoutMs}ms`));
302
- }, timeoutMs);
303
- const cleanup = () => clearTimeout(timeout);
304
- tlsSocket.once("secureConnect", () => {
305
- cleanup();
306
- resolve(tlsSocket);
307
- });
308
- tlsSocket.once("error", (error) => {
309
- cleanup();
310
- reject(error);
311
- });
312
- });
313
- }
314
- async function connectDirect(targetUrl, timeoutMs, onDebug) {
315
- return await new Promise((resolve, reject) => {
316
- const socket = tls.connect({
317
- host: targetUrl.hostname,
318
- port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
319
- servername: targetUrl.hostname
320
- });
321
- const timeout = setTimeout(() => {
322
- onDebug?.(`agy transport TLS connect timeout after ${timeoutMs}ms`);
323
- socket.destroy();
324
- reject(new Error(`Antigravity request timed out connecting after ${timeoutMs}ms`));
325
- }, timeoutMs);
326
- const cleanup = () => clearTimeout(timeout);
327
- socket.once("secureConnect", () => {
328
- cleanup();
329
- resolve(socket);
330
- });
331
- socket.once("error", (error) => {
332
- cleanup();
333
- reject(error);
334
- });
335
- });
336
- }
337
- async function connectTls(targetUrl, timeoutMs, onDebug) {
338
- const proxyUrl = getHttpsProxy(targetUrl);
339
- return proxyUrl ? await connectViaProxy(proxyUrl, targetUrl, timeoutMs, onDebug) : await connectDirect(targetUrl, timeoutMs, onDebug);
340
- }
341
- function serializeRequest(url, init, body) {
342
- const method = init.method ?? "POST";
343
- const path = `${url.pathname}${url.search}`;
344
- const headerLines = buildAgyCliHeaderPairs(url.toString(), init).map(([key, value]) => `${key}: ${value}`).join("\r\n");
345
- const head = Buffer2.from(`${method} ${path} HTTP/1.1\r
346
- ${headerLines}\r
347
- \r
348
- `);
349
- if (body.byteLength === 0) {
350
- return head;
351
- }
352
- if (!shouldUseChunkedBody(url)) {
353
- return Buffer2.concat([head, body]);
354
- }
355
- return Buffer2.concat([
356
- head,
357
- Buffer2.from(`${body.byteLength.toString(16)}\r
358
- `),
359
- body,
360
- Buffer2.from("\r\n0\r\n\r\n")
361
- ]);
362
- }
363
- function parseResponseHead(head) {
364
- const lines = head.split("\r\n");
365
- const statusLine = lines.shift() ?? "";
366
- const match = /^HTTP\/1\.[01]\s+(\d{3})\s*(.*)$/.exec(statusLine);
367
- if (!match) {
368
- throw new Error(`Invalid HTTP response: ${statusLine}`);
369
- }
370
- const headers = new Headers();
371
- let chunked = false;
372
- let gzip = false;
373
- let contentLength;
374
- for (const line of lines) {
375
- const index = line.indexOf(":");
376
- if (index <= 0) continue;
377
- const key = line.slice(0, index);
378
- const value = line.slice(index + 1).trim();
379
- const lowerKey = key.toLowerCase();
380
- const lowerValue = value.toLowerCase();
381
- if (lowerKey === "transfer-encoding" && lowerValue.includes("chunked")) {
382
- chunked = true;
383
- continue;
384
- }
385
- if (lowerKey === "content-encoding" && lowerValue.includes("gzip")) {
386
- gzip = true;
387
- continue;
388
- }
389
- if (lowerKey === "content-length") {
390
- const parsed = Number.parseInt(value, 10);
391
- if (Number.isFinite(parsed) && parsed >= 0) {
392
- contentLength = parsed;
393
- }
394
- if (gzip) continue;
395
- }
396
- headers.append(key, value);
397
- }
398
- return {
399
- status: Number(match[1]),
400
- statusText: match[2] ?? "",
401
- headers,
402
- chunked,
403
- gzip,
404
- contentLength
405
- };
406
- }
407
- var ContentLengthStream = class extends Transform {
408
- remaining;
409
- constructor(contentLength) {
410
- super();
411
- this.remaining = contentLength;
412
- }
413
- _transform(chunk, _encoding, callback) {
414
- if (this.remaining <= 0) {
415
- callback();
416
- return;
417
- }
418
- if (chunk.length <= this.remaining) {
419
- this.remaining -= chunk.length;
420
- this.push(chunk);
421
- } else {
422
- this.push(chunk.subarray(0, this.remaining));
423
- this.remaining = 0;
424
- }
425
- if (this.remaining <= 0) {
426
- this.push(null);
427
- }
428
- callback();
429
- }
430
- };
431
- var ChunkedDecodeStream = class extends Transform {
432
- buffer = Buffer2.alloc(0);
433
- _transform(chunk, _encoding, callback) {
434
- this.buffer = Buffer2.concat([this.buffer, chunk]);
435
- try {
436
- this.flushAvailableChunks();
437
- callback();
438
- } catch (error) {
439
- callback(error instanceof Error ? error : new Error(String(error)));
440
- }
441
- }
442
- _flush(callback) {
443
- try {
444
- this.flushAvailableChunks();
445
- callback();
446
- } catch (error) {
447
- callback(error instanceof Error ? error : new Error(String(error)));
448
- }
449
- }
450
- flushAvailableChunks() {
451
- while (true) {
452
- const lineEnd = this.buffer.indexOf("\r\n");
453
- if (lineEnd === -1) return;
454
- const sizeLine = this.buffer.subarray(0, lineEnd).toString("latin1");
455
- const sizeText = sizeLine.split(";", 1)[0]?.trim() ?? "";
456
- const size = Number.parseInt(sizeText, 16);
457
- if (!Number.isFinite(size)) {
458
- throw new Error(`Invalid chunk size: ${sizeLine}`);
459
- }
460
- const chunkStart = lineEnd + 2;
461
- const chunkEnd = chunkStart + size;
462
- const nextOffset = chunkEnd + 2;
463
- if (this.buffer.length < nextOffset) return;
464
- if (size === 0) {
465
- this.buffer = Buffer2.alloc(0);
466
- this.push(null);
467
- return;
468
- }
469
- this.push(this.buffer.subarray(chunkStart, chunkEnd));
470
- this.buffer = this.buffer.subarray(nextOffset);
471
- }
472
- }
473
- };
474
- function buildResponseStream(socket, leftover, head, signal, idleTimeoutMs, onDebug) {
475
- const source = new PassThrough();
476
- if (leftover.length > 0) {
477
- source.write(leftover);
478
- }
479
- socket.pipe(source);
480
- let responseBody = source;
481
- if (head.chunked) {
482
- responseBody = responseBody.pipe(new ChunkedDecodeStream());
483
- } else if (typeof head.contentLength === "number") {
484
- responseBody = responseBody.pipe(new ContentLengthStream(head.contentLength));
485
- }
486
- if (head.gzip) {
487
- responseBody = responseBody.pipe(createGunzip());
488
- }
489
- let idleTimer;
490
- const clearIdle = () => {
491
- if (idleTimer) {
492
- clearTimeout(idleTimer);
493
- idleTimer = void 0;
494
- }
495
- };
496
- const armIdle = () => {
497
- if (!idleTimeoutMs || idleTimeoutMs <= 0) return;
498
- clearIdle();
499
- idleTimer = setTimeout(() => {
500
- onDebug?.(`agy transport idle timeout after ${idleTimeoutMs}ms with no body data`);
501
- socket.destroy(new Error(`Antigravity response stalled: no data for ${idleTimeoutMs}ms`));
502
- }, idleTimeoutMs);
503
- };
504
- socket.on("data", armIdle);
505
- armIdle();
506
- const abort = () => socket.destroy(new DOMException("The operation was aborted", "AbortError"));
507
- const cleanup = () => {
508
- clearIdle();
509
- socket.off("data", armIdle);
510
- signal?.removeEventListener("abort", abort);
511
- };
512
- if (signal?.aborted) {
513
- abort();
514
- } else {
515
- signal?.addEventListener("abort", abort, { once: true });
516
- }
517
- responseBody.once("end", () => {
518
- cleanup();
519
- socket.destroy();
520
- });
521
- responseBody.once("error", () => {
522
- cleanup();
523
- socket.destroy();
524
- });
525
- responseBody.once("close", cleanup);
526
- return Readable.toWeb(responseBody);
527
- }
528
- async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
529
- const parsedUrl = new URL(url);
530
- if (parsedUrl.protocol !== "https:") {
531
- throw new Error(`agy transport only supports https URLs: ${url}`);
532
- }
533
- if (options.signal?.aborted) {
534
- throw new DOMException("The operation was aborted", "AbortError");
535
- }
536
- const body = bodyToBuffer(init.body);
537
- const requestBytes = serializeRequest(parsedUrl, init, body);
538
- const timeoutMs = options.timeoutMs ?? DEFAULT_AGY_RESPONSE_HEADER_TIMEOUT_MS;
539
- const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_AGY_IDLE_TIMEOUT_MS;
540
- options.onDebug?.(`agy transport connecting to ${parsedUrl.hostname} with header timeout ${timeoutMs}ms`);
541
- const socket = await connectTlsWithAbort(parsedUrl, timeoutMs, options.signal, options.onDebug);
542
- const abort = () => {
543
- socket.destroy(new DOMException("The operation was aborted", "AbortError"));
544
- };
545
- try {
546
- options.signal?.addEventListener("abort", abort, { once: true });
547
- socket.write(requestBytes);
548
- options.onDebug?.(`agy transport request dispatched (${requestBytes.byteLength} bytes)`);
549
- const { head, leftover } = await waitForHead(socket, timeoutMs, () => {
550
- options.onDebug?.(`agy transport response header timeout after ${timeoutMs}ms`);
551
- socket.destroy();
552
- });
553
- const parsedHead = parseResponseHead(head);
554
- options.onDebug?.(`agy transport response headers received: ${parsedHead.status} ${parsedHead.statusText}`);
555
- const bodyStream = buildResponseStream(socket, leftover, parsedHead, options.signal, idleTimeoutMs, options.onDebug);
556
- return new Response(bodyStream, {
557
- status: parsedHead.status,
558
- statusText: parsedHead.statusText,
559
- headers: parsedHead.headers
560
- });
561
- } catch (error) {
562
- socket.destroy();
563
- throw error;
564
- } finally {
565
- options.signal?.removeEventListener("abort", abort);
566
- }
567
- }
568
- async function connectTlsWithAbort(targetUrl, timeoutMs, signal, onDebug) {
569
- if (!signal) {
570
- return connectTls(targetUrl, timeoutMs, onDebug);
571
- }
572
- const connectPromise = connectTls(targetUrl, timeoutMs, onDebug);
573
- let onAbort;
574
- const abortPromise = new Promise((_, reject) => {
575
- onAbort = () => reject(new DOMException("The operation was aborted", "AbortError"));
576
- signal.addEventListener("abort", onAbort, { once: true });
577
- });
578
- try {
579
- return await Promise.race([connectPromise, abortPromise]);
580
- } catch (error) {
581
- void connectPromise.then((socket) => socket.destroy()).catch(() => {
582
- });
583
- throw error;
584
- } finally {
585
- if (onAbort) signal.removeEventListener("abort", onAbort);
586
- }
587
- }
588
-
589
- // ../core/src/project.ts
590
- var log = createLogger("project");
591
- var PROJECT_CONTEXT_CACHE_TTL_MS = 30 * 60 * 1e3;
592
- var projectContextResultCache = /* @__PURE__ */ new Map();
593
- var projectContextPendingCache = /* @__PURE__ */ new Map();
594
- var provisionFailedKeys = /* @__PURE__ */ new Set();
595
- function buildBootstrapRequestBody(extra = {}) {
596
- return {
597
- ...extra,
598
- metadata: buildAntigravityLoadCodeAssistMetadata()
599
- };
600
- }
601
- function getDefaultTierId(allowedTiers) {
602
- if (!allowedTiers || allowedTiers.length === 0) {
603
- return void 0;
604
- }
605
- for (const tier of allowedTiers) {
606
- if (tier?.isDefault) {
607
- return tier.id;
608
- }
609
- }
610
- return allowedTiers[0]?.id;
611
- }
612
- function wait(ms) {
613
- return new Promise(function(resolve) {
614
- setTimeout(resolve, ms);
615
- });
616
- }
617
- function extractManagedProjectId(payload) {
618
- if (!payload) {
619
- return void 0;
620
- }
621
- if (typeof payload.cloudaicompanionProject === "string") {
622
- return payload.cloudaicompanionProject;
623
- }
624
- if (payload.cloudaicompanionProject && typeof payload.cloudaicompanionProject.id === "string") {
625
- return payload.cloudaicompanionProject.id;
626
- }
627
- return void 0;
628
- }
629
- function getCacheKey(auth) {
630
- const refresh = auth.refresh?.trim();
631
- return refresh ? refresh : void 0;
632
- }
633
- async function loadManagedProject(accessToken, _projectId) {
634
- const requestBody = buildBootstrapRequestBody();
635
- const loadHeaders = buildAntigravityHarnessBootstrapHeaders(accessToken);
636
- const loadEndpoints = Array.from(
637
- /* @__PURE__ */ new Set([...ANTIGRAVITY_LOAD_ENDPOINTS, ...ANTIGRAVITY_ENDPOINT_FALLBACKS])
638
- );
639
- for (const baseEndpoint of loadEndpoints) {
640
- try {
641
- const response = await fetchWithAgyCliTransport(
642
- `${baseEndpoint}/v1internal:loadCodeAssist`,
643
- {
644
- method: "POST",
645
- headers: loadHeaders,
646
- body: JSON.stringify(requestBody)
647
- }
648
- );
649
- if (!response.ok) {
650
- continue;
651
- }
652
- return await response.json();
653
- } catch (error) {
654
- log.debug("Failed to load managed project", { endpoint: baseEndpoint, error: String(error) });
655
- continue;
656
- }
657
- }
658
- return null;
659
- }
660
- async function onboardManagedProject(accessToken, tierId, projectId, attempts = 10, delayMs = 5e3) {
661
- const requestBody = { tierId };
662
- const onboardEndpoints = Array.from(
663
- /* @__PURE__ */ new Set([ANTIGRAVITY_ENDPOINT_PROD, ...ANTIGRAVITY_LOAD_ENDPOINTS, ...ANTIGRAVITY_ENDPOINT_FALLBACKS])
664
- );
665
- for (const baseEndpoint of onboardEndpoints) {
666
- for (let attempt = 0; attempt < attempts; attempt += 1) {
667
- try {
668
- const response = await fetchWithAgyCliTransport(
669
- `${baseEndpoint}/v1internal:onboardUser`,
670
- {
671
- method: "POST",
672
- headers: buildAntigravityHarnessBootstrapHeaders(accessToken),
673
- body: JSON.stringify(requestBody)
674
- }
675
- );
676
- if (!response.ok) {
677
- log.debug("Onboard request failed", {
678
- endpoint: baseEndpoint,
679
- status: response.status,
680
- statusText: response.statusText
681
- });
682
- break;
683
- }
684
- const payload = await response.json();
685
- const managedProjectId = payload.response?.cloudaicompanionProject?.id;
686
- if (payload.done && managedProjectId) {
687
- return managedProjectId;
688
- }
689
- if (payload.done && projectId) {
690
- return projectId;
691
- }
692
- } catch (error) {
693
- log.debug("Failed to onboard managed project", { endpoint: baseEndpoint, error: String(error) });
694
- break;
695
- }
696
- await wait(delayMs);
697
- }
698
- }
699
- return void 0;
700
- }
701
- async function ensureProjectContext(auth) {
702
- const accessToken = auth.access;
703
- if (!accessToken) {
704
- return { auth, effectiveProjectId: "" };
705
- }
706
- const cacheKey = getCacheKey(auth);
707
- if (cacheKey) {
708
- const cached = projectContextResultCache.get(cacheKey);
709
- if (cached && Date.now() - cached.cachedAt < PROJECT_CONTEXT_CACHE_TTL_MS) {
710
- return cached.result;
711
- }
712
- if (cached) {
713
- projectContextResultCache.delete(cacheKey);
714
- }
715
- const pending = projectContextPendingCache.get(cacheKey);
716
- if (pending) {
717
- return pending;
718
- }
719
- }
720
- const resolveContext = async () => {
721
- const parts = parseRefreshParts(auth.refresh);
722
- if (parts.managedProjectId) {
723
- return { auth, effectiveProjectId: parts.managedProjectId };
724
- }
725
- const fallbackProjectId = ANTIGRAVITY_DEFAULT_PROJECT_ID;
726
- if (cacheKey && provisionFailedKeys.has(cacheKey)) {
727
- const effectiveProjectId = parts.projectId || fallbackProjectId;
728
- return { auth, effectiveProjectId };
729
- }
730
- const persistManagedProject = async (managedProjectId) => {
731
- const updatedAuth = {
732
- ...auth,
733
- refresh: formatRefreshParts({
734
- refreshToken: parts.refreshToken,
735
- projectId: parts.projectId,
736
- managedProjectId
737
- })
738
- };
739
- return { auth: updatedAuth, effectiveProjectId: managedProjectId };
740
- };
741
- const loadPayload = await loadManagedProject(accessToken, parts.projectId ?? fallbackProjectId);
742
- const resolvedManagedProjectId = extractManagedProjectId(loadPayload);
743
- if (resolvedManagedProjectId) {
744
- return persistManagedProject(resolvedManagedProjectId);
745
- }
746
- const tierId = getDefaultTierId(loadPayload?.allowedTiers) ?? "free-tier";
747
- log.debug("Auto-provisioning managed project", { tierId, projectId: parts.projectId });
748
- const provisionedProjectId = await onboardManagedProject(
749
- accessToken,
750
- tierId,
751
- parts.projectId
752
- );
753
- if (provisionedProjectId) {
754
- log.debug("Successfully provisioned managed project", { provisionedProjectId });
755
- return persistManagedProject(provisionedProjectId);
756
- }
757
- log.warn("Failed to provision managed project - account may not work correctly", {
758
- hasProjectId: !!parts.projectId
759
- });
760
- if (cacheKey) {
761
- provisionFailedKeys.add(cacheKey);
762
- }
763
- if (parts.projectId) {
764
- return { auth, effectiveProjectId: parts.projectId };
765
- }
766
- return { auth, effectiveProjectId: fallbackProjectId };
767
- };
768
- if (!cacheKey) {
769
- return resolveContext();
770
- }
771
- const promise = resolveContext().then((result) => {
772
- const nextKey = getCacheKey(result.auth) ?? cacheKey;
773
- projectContextPendingCache.delete(cacheKey);
774
- projectContextResultCache.set(nextKey, { result, cachedAt: Date.now() });
775
- if (nextKey !== cacheKey) {
776
- projectContextResultCache.delete(cacheKey);
777
- }
778
- return result;
779
- }).catch((error) => {
780
- projectContextPendingCache.delete(cacheKey);
781
- throw error;
782
- });
783
- projectContextPendingCache.set(cacheKey, promise);
784
- return promise;
785
- }
786
-
787
- // ../core/src/model-registry.ts
788
- var DEFAULT_MODALITIES = {
789
- input: ["text", "image", "pdf"],
790
- output: ["text"]
791
- };
792
- var MODEL_RELEASE_DATE = "";
793
- var DEFAULT_COST = { input: 0, output: 0 };
794
- var DEFAULT_OPTIONS = {};
795
- function defineModel(id, model) {
796
- return {
797
- id,
798
- release_date: MODEL_RELEASE_DATE,
799
- attachment: model.modalities.input.some((modality) => modality !== "text"),
800
- temperature: true,
801
- tool_call: true,
802
- cost: { ...DEFAULT_COST },
803
- options: { ...DEFAULT_OPTIONS },
804
- ...model
805
- };
806
- }
807
- var ALL_MODEL_DEFINITIONS = {
808
- "antigravity-gemini-3.1-pro": defineModel("antigravity-gemini-3.1-pro", {
809
- name: "Gemini 3.1 Pro (Antigravity)",
810
- reasoning: true,
811
- limit: { context: 1048576, output: 65535 },
812
- modalities: DEFAULT_MODALITIES,
813
- variants: {
814
- low: { thinkingLevel: "low" },
815
- high: { thinkingLevel: "high" }
816
- }
817
- }),
818
- "antigravity-gemini-3.5-flash": defineModel("antigravity-gemini-3.5-flash", {
819
- name: "Gemini 3.5 Flash (Antigravity)",
820
- reasoning: true,
821
- limit: { context: 1048576, output: 65536 },
822
- modalities: DEFAULT_MODALITIES,
823
- variants: {
824
- low: { thinkingLevel: "low" },
825
- high: { thinkingLevel: "high" }
826
- }
827
- }),
828
- "antigravity-claude-sonnet-4-6-thinking": defineModel("antigravity-claude-sonnet-4-6-thinking", {
829
- name: "Claude Sonnet 4.6 Thinking (Antigravity)",
830
- reasoning: true,
831
- limit: { context: 25e4, output: 64e3 },
832
- modalities: DEFAULT_MODALITIES,
833
- variants: {
834
- low: { disabled: true },
835
- high: { disabled: true }
836
- }
837
- }),
838
- "antigravity-claude-opus-4-6-thinking": defineModel("antigravity-claude-opus-4-6-thinking", {
839
- name: "Claude Opus 4.6 Thinking (Antigravity)",
840
- reasoning: true,
841
- limit: { context: 25e4, output: 64e3 },
842
- modalities: DEFAULT_MODALITIES,
843
- variants: {
844
- low: { disabled: true },
845
- high: { disabled: true }
846
- }
847
- }),
848
- "antigravity-gemini-3.1-flash-image": defineModel("antigravity-gemini-3.1-flash-image", {
849
- name: "Gemini 3.1 Flash Image (Antigravity)",
850
- reasoning: false,
851
- limit: { context: 66e3, output: 33e3 },
852
- modalities: {
853
- input: ["text", "image"],
854
- output: ["text", "image"]
855
- }
856
- }),
857
- "antigravity-gpt-oss-120b": defineModel("antigravity-gpt-oss-120b", {
858
- name: "GPT-OSS 120B (Antigravity)",
859
- reasoning: false,
860
- limit: { context: 128e3, output: 16384 },
861
- modalities: DEFAULT_MODALITIES,
862
- variants: {
863
- medium: {}
864
- }
865
- }),
866
- "gemini-2.5-flash": defineModel("gemini-2.5-flash", {
867
- name: "Gemini 2.5 Flash (Gemini CLI)",
868
- reasoning: true,
869
- limit: { context: 1048576, output: 65536 },
870
- modalities: DEFAULT_MODALITIES
871
- }),
872
- "gemini-2.5-pro": defineModel("gemini-2.5-pro", {
873
- name: "Gemini 2.5 Pro (Gemini CLI)",
874
- reasoning: true,
875
- limit: { context: 1048576, output: 65536 },
876
- modalities: DEFAULT_MODALITIES
877
- }),
878
- "gemini-3-flash-preview": defineModel("gemini-3-flash-preview", {
879
- name: "Gemini 3 Flash Preview (Gemini CLI)",
880
- reasoning: true,
881
- limit: { context: 1048576, output: 65536 },
882
- modalities: DEFAULT_MODALITIES
883
- }),
884
- "gemini-3.1-pro-preview": defineModel("gemini-3.1-pro-preview", {
885
- name: "Gemini 3.1 Pro Preview (Gemini CLI)",
886
- reasoning: true,
887
- limit: { context: 1048576, output: 65535 },
888
- modalities: DEFAULT_MODALITIES
889
- }),
890
- "gemini-3.5-flash-preview": defineModel("gemini-3.5-flash-preview", {
891
- name: "Gemini 3.5 Flash Preview (Gemini CLI)",
892
- reasoning: true,
893
- limit: { context: 1048576, output: 65536 },
894
- modalities: DEFAULT_MODALITIES
895
- }),
896
- "gemini-3.1-flash-image": defineModel("gemini-3.1-flash-image", {
897
- name: "Gemini 3.1 Flash Image (Gemini CLI)",
898
- reasoning: false,
899
- limit: { context: 66e3, output: 33e3 },
900
- modalities: {
901
- input: ["text", "image"],
902
- output: ["text", "image"]
903
- }
904
- }),
905
- "gemini-3.1-flash-image-preview": defineModel("gemini-3.1-flash-image-preview", {
906
- name: "Gemini 3.1 Flash Image Preview (Gemini CLI)",
907
- reasoning: false,
908
- limit: { context: 66e3, output: 33e3 },
909
- modalities: {
910
- input: ["text", "image"],
911
- output: ["text", "image"]
912
- }
913
- }),
914
- "gemini-3.1-pro-preview-customtools": defineModel("gemini-3.1-pro-preview-customtools", {
915
- name: "Gemini 3.1 Pro Preview Custom Tools (Gemini CLI)",
916
- reasoning: true,
917
- limit: { context: 1048576, output: 65535 },
918
- modalities: DEFAULT_MODALITIES
919
- })
920
- };
921
- var RESOLVER_ALIASES = {
922
- "gemini-3.1-pro-low": "gemini-3.1-pro",
923
- "gemini-3.1-pro-high": "gemini-3.1-pro",
924
- "gemini-3-flash-low": "gemini-3-flash",
925
- "gemini-3-flash-medium": "gemini-3-flash",
926
- "gemini-3-flash-high": "gemini-3-flash",
927
- "gemini-3.5-flash-low": "gemini-3.5-flash",
928
- "gemini-3.5-flash-medium": "gemini-3.5-flash",
929
- "gemini-3.5-flash-high": "gemini-3.5-flash",
930
- "gemini-claude-opus-4-6-thinking-low": "claude-opus-4-6-thinking",
931
- "gemini-claude-opus-4-6-thinking-medium": "claude-opus-4-6-thinking",
932
- "gemini-claude-opus-4-6-thinking-high": "claude-opus-4-6-thinking",
933
- "gemini-claude-sonnet-4-6-thinking-low": "claude-sonnet-4-6",
934
- "gemini-claude-sonnet-4-6-thinking-medium": "claude-sonnet-4-6",
935
- "gemini-claude-sonnet-4-6-thinking-high": "claude-sonnet-4-6",
936
- "gemini-claude-sonnet-4-6": "claude-sonnet-4-6",
937
- "claude-sonnet-4-6-thinking": "claude-sonnet-4-6",
938
- "claude-sonnet-4-6-thinking-low": "claude-sonnet-4-6",
939
- "claude-sonnet-4-6-thinking-medium": "claude-sonnet-4-6",
940
- "claude-sonnet-4-6-thinking-high": "claude-sonnet-4-6"
941
- };
942
- var GEMINI_35_FLASH_ROUTES = {
943
- antigravity: {
944
- defaultModel: "gemini-3-flash-agent",
945
- byTier: {
946
- low: "gemini-3.5-flash-extra-low",
947
- medium: "gemini-3.5-flash-low",
948
- high: "gemini-3-flash-agent"
949
- }
950
- },
951
- geminiCliFallbackModel: "gemini-3-flash-preview"
952
- };
953
- var ANTIGRAVITY_OPENCODE_MODEL_IDS = [
954
- "antigravity-gemini-3.5-flash",
955
- "antigravity-gemini-3.1-pro",
956
- "antigravity-claude-sonnet-4-6-thinking",
957
- "antigravity-claude-opus-4-6-thinking"
958
- ];
959
- function pickModelDefinitions(ids) {
960
- return Object.fromEntries(ids.map((id) => [id, ALL_MODEL_DEFINITIONS[id]]));
961
- }
962
- var OPENCODE_MODEL_DEFINITIONS = pickModelDefinitions(ANTIGRAVITY_OPENCODE_MODEL_IDS);
963
- function getPublicModelDefinitions() {
964
- return OPENCODE_MODEL_DEFINITIONS;
965
- }
966
- function getResolverAliasMap() {
967
- return RESOLVER_ALIASES;
968
- }
969
- function getGemini35FlashAntigravityModel(tier) {
970
- if (!tier) {
971
- return GEMINI_35_FLASH_ROUTES.antigravity.defaultModel;
972
- }
973
- return GEMINI_35_FLASH_ROUTES.antigravity.byTier[tier] ?? GEMINI_35_FLASH_ROUTES.antigravity.defaultModel;
974
- }
975
- function getGemini35FlashGeminiCliFallbackModel() {
976
- return GEMINI_35_FLASH_ROUTES.geminiCliFallbackModel;
977
- }
978
-
979
- // ../core/src/transform/model-resolver.ts
980
- var THINKING_TIER_BUDGETS = {
981
- claude: { low: 8192, medium: 16384, high: 32768 },
982
- "gemini-2.5-pro": { low: 8192, medium: 16384, high: 32768 },
983
- "gemini-2.5-flash": { low: 6144, medium: 12288, high: 24576 },
984
- default: { low: 4096, medium: 8192, high: 16384 }
985
- };
986
- var MODEL_ALIASES = getResolverAliasMap();
987
- var TIER_REGEX = /-(minimal|low|medium|high)$/;
988
- var QUOTA_PREFIX_REGEX = /^antigravity-/i;
989
- var GEMINI_3_PRO_REGEX = /^gemini-3(?:\.\d+)?-pro/i;
990
- var GEMINI_3_FLASH_REGEX = /^gemini-3(?:\.\d+)?-flash/i;
991
- var IMAGE_GENERATION_MODELS = /image|imagen/i;
992
- function supportsThinkingTiers(model) {
993
- const lower = model.toLowerCase();
994
- return lower.includes("gemini-3") || lower.includes("gemini-2.5") || lower.includes("claude") && lower.includes("thinking");
995
- }
996
- function extractThinkingTierFromModel(model) {
997
- if (!supportsThinkingTiers(model)) {
998
- return void 0;
999
- }
1000
- const tierMatch = model.match(TIER_REGEX);
1001
- return tierMatch?.[1];
1002
- }
1003
- function getBudgetFamily(model) {
1004
- if (model.includes("claude")) {
1005
- return "claude";
1006
- }
1007
- if (model.includes("gemini-2.5-pro")) {
1008
- return "gemini-2.5-pro";
1009
- }
1010
- if (model.includes("gemini-2.5-flash")) {
1011
- return "gemini-2.5-flash";
1012
- }
1013
- return "default";
1014
- }
1015
- function isThinkingCapableModel(model) {
1016
- const lower = model.toLowerCase();
1017
- return lower.includes("thinking") || lower.includes("gemini-3") || lower.includes("gemini-2.5");
1018
- }
1019
- function isGemini3ProModel(model) {
1020
- return GEMINI_3_PRO_REGEX.test(model);
1021
- }
1022
- function isGemini3FlashModel(model) {
1023
- return GEMINI_3_FLASH_REGEX.test(model);
1024
- }
1025
- function isGemini35FlashModel(model) {
1026
- return /^gemini-3\.5-flash/i.test(model);
1027
- }
1028
- function resolveGemini35FlashAntigravityModel(tier) {
1029
- return getGemini35FlashAntigravityModel(tier);
1030
- }
1031
- function getAgyGemini35FlashThinkingBudget(tier) {
1032
- switch (tier) {
1033
- case "low":
1034
- return 1e3;
1035
- case "high":
1036
- return 1e4;
1037
- case "medium":
1038
- default:
1039
- return 4e3;
1040
- }
1041
- }
1042
- function getAgyGemini31ProModel(tier) {
1043
- return tier === "high" ? "gemini-pro-agent" : "gemini-3.1-pro-low";
1044
- }
1045
- function getAgyGemini31ProThinkingBudget(tier) {
1046
- return tier === "high" ? 10001 : 1001;
1047
- }
1048
- function resolveModelWithTier(requestedModel, options = {}) {
1049
- const isAntigravity = QUOTA_PREFIX_REGEX.test(requestedModel);
1050
- const modelWithoutQuota = requestedModel.replace(QUOTA_PREFIX_REGEX, "");
1051
- const tier = extractThinkingTierFromModel(modelWithoutQuota);
1052
- const baseName = tier ? modelWithoutQuota.replace(TIER_REGEX, "") : modelWithoutQuota;
1053
- const isImageModel = IMAGE_GENERATION_MODELS.test(modelWithoutQuota);
1054
- const isClaudeModel2 = modelWithoutQuota.toLowerCase().includes("claude");
1055
- const preferGeminiCli = options.cli_first === true && !isAntigravity && !isImageModel && !isClaudeModel2;
1056
- const quotaPreference = preferGeminiCli ? "gemini-cli" : "antigravity";
1057
- const explicitQuota = isAntigravity || isImageModel;
1058
- const isGemini3 = modelWithoutQuota.toLowerCase().startsWith("gemini-3");
1059
- const skipAlias = isAntigravity && isGemini3;
1060
- const isGemini3Pro = isGemini3ProModel(modelWithoutQuota);
1061
- const isGemini3Flash = isGemini3FlashModel(modelWithoutQuota);
1062
- const isGemini31Pro = /^gemini-3\.1-pro/i.test(baseName);
1063
- const isGemini35Flash = /^gemini-3\.5-flash/i.test(baseName);
1064
- if (isGemini31Pro && quotaPreference === "antigravity") {
1065
- return {
1066
- actualModel: getAgyGemini31ProModel(tier),
1067
- thinkingBudget: getAgyGemini31ProThinkingBudget(tier),
1068
- tier,
1069
- isThinkingModel: true,
1070
- quotaPreference,
1071
- explicitQuota
1072
- };
1073
- }
1074
- if (isGemini35Flash && quotaPreference === "antigravity") {
1075
- return {
1076
- actualModel: resolveGemini35FlashAntigravityModel(tier ?? "medium"),
1077
- thinkingBudget: getAgyGemini35FlashThinkingBudget(tier),
1078
- tier: tier ?? "medium",
1079
- isThinkingModel: true,
1080
- quotaPreference,
1081
- explicitQuota
1082
- };
1083
- }
1084
- let antigravityModel = modelWithoutQuota;
1085
- if (skipAlias) {
1086
- if ((isGemini3Pro || isGemini3Flash) && !tier && !isImageModel) {
1087
- const defaultTier = isGemini3Pro ? "low" : "medium";
1088
- antigravityModel = `${modelWithoutQuota}-${defaultTier}`;
1089
- }
1090
- }
1091
- const actualModel = skipAlias ? antigravityModel : MODEL_ALIASES[modelWithoutQuota] || MODEL_ALIASES[baseName] || baseName;
1092
- const resolvedModel = actualModel;
1093
- const isThinking = isThinkingCapableModel(resolvedModel);
1094
- if (isImageModel) {
1095
- return {
1096
- actualModel: resolvedModel,
1097
- isThinkingModel: false,
1098
- isImageModel: true,
1099
- quotaPreference,
1100
- explicitQuota
1101
- };
1102
- }
1103
- const isEffectiveGemini3 = resolvedModel.toLowerCase().includes("gemini-3");
1104
- const lowerModelWithoutQuota = modelWithoutQuota.toLowerCase();
1105
- const isClaudeThinking = resolvedModel.toLowerCase().includes("claude") && resolvedModel.toLowerCase().includes("thinking") || lowerModelWithoutQuota.includes("claude") && lowerModelWithoutQuota.includes("thinking") || lowerModelWithoutQuota === "gemini-claude-sonnet-4-6";
1106
- if (!tier) {
1107
- if (isEffectiveGemini3) {
1108
- return {
1109
- actualModel: resolvedModel,
1110
- thinkingLevel: isGemini35Flash ? "medium" : "low",
1111
- isThinkingModel: true,
1112
- quotaPreference,
1113
- explicitQuota
1114
- };
1115
- }
1116
- if (isClaudeThinking) {
1117
- return {
1118
- actualModel: resolvedModel,
1119
- thinkingBudget: 1024,
1120
- isThinkingModel: true,
1121
- quotaPreference,
1122
- explicitQuota
1123
- };
1124
- }
1125
- return { actualModel: resolvedModel, isThinkingModel: isThinking, quotaPreference, explicitQuota };
1126
- }
1127
- if (isEffectiveGemini3) {
1128
- return {
1129
- actualModel: resolvedModel,
1130
- thinkingLevel: tier,
1131
- tier,
1132
- isThinkingModel: true,
1133
- quotaPreference,
1134
- explicitQuota
1135
- };
1136
- }
1137
- if (isClaudeThinking) {
1138
- return {
1139
- actualModel: resolvedModel,
1140
- thinkingBudget: 1024,
1141
- tier,
1142
- isThinkingModel: true,
1143
- quotaPreference,
1144
- explicitQuota
1145
- };
1146
- }
1147
- const budgetFamily = getBudgetFamily(resolvedModel);
1148
- const budgets = THINKING_TIER_BUDGETS[budgetFamily];
1149
- const thinkingBudget = budgets[tier];
1150
- return {
1151
- actualModel: resolvedModel,
1152
- thinkingBudget,
1153
- tier,
1154
- isThinkingModel: isThinking,
1155
- quotaPreference,
1156
- explicitQuota
1157
- };
1158
- }
1159
- function resolveModelForHeaderStyle(requestedModel, headerStyle) {
1160
- const lower = requestedModel.toLowerCase();
1161
- const isGemini3 = lower.includes("gemini-3");
1162
- if (!isGemini3) {
1163
- return resolveModelWithTier(requestedModel);
1164
- }
1165
- if (headerStyle === "antigravity") {
1166
- let transformedModel = requestedModel.replace(/-preview-customtools$/i, "").replace(/-preview$/i, "").replace(/^antigravity-/i, "");
1167
- const isGemini3Pro = isGemini3ProModel(transformedModel);
1168
- const isGemini3Flash = isGemini3FlashModel(transformedModel);
1169
- const hasTierSuffix = /-(minimal|low|medium|high)$/i.test(transformedModel);
1170
- const isImageModel = IMAGE_GENERATION_MODELS.test(transformedModel);
1171
- const isGemini35Flash = isGemini35FlashModel(transformedModel.replace(TIER_REGEX, ""));
1172
- if ((isGemini3Pro || isGemini3Flash) && !isGemini35Flash && !hasTierSuffix && !isImageModel) {
1173
- const defaultTier = isGemini3Pro ? "low" : "medium";
1174
- transformedModel = `${transformedModel}-${defaultTier}`;
1175
- }
1176
- const prefixedModel = `antigravity-${transformedModel}`;
1177
- return resolveModelWithTier(prefixedModel);
1178
- }
1179
- if (headerStyle === "gemini-cli") {
1180
- const requestedTier = extractThinkingTierFromModel(requestedModel.replace(/^antigravity-/i, ""));
1181
- let transformedModel = requestedModel.replace(/^antigravity-/i, "").replace(/-(minimal|low|medium|high)$/i, "");
1182
- const hasPreviewSuffix = /-preview($|-)/i.test(transformedModel);
1183
- const isGemini35Flash = isGemini35FlashModel(transformedModel);
1184
- if (isGemini35Flash) {
1185
- transformedModel = getGemini35FlashGeminiCliFallbackModel();
1186
- } else if (!hasPreviewSuffix) {
1187
- transformedModel = `${transformedModel}-preview`;
1188
- }
1189
- const resolved = resolveModelWithTier(transformedModel, { cli_first: true });
1190
- return {
1191
- ...resolved,
1192
- thinkingLevel: requestedTier ?? resolved.thinkingLevel,
1193
- tier: requestedTier ?? resolved.tier,
1194
- quotaPreference: "gemini-cli"
1195
- };
1196
- }
1197
- return resolveModelWithTier(requestedModel);
1198
- }
1199
-
1200
- // ../core/src/transform/gemini.ts
1201
- var UNSUPPORTED_SCHEMA_FIELDS = /* @__PURE__ */ new Set([
1202
- "additionalProperties",
1203
- "$schema",
1204
- "$id",
1205
- "$comment",
1206
- "$ref",
1207
- "$defs",
1208
- "definitions",
1209
- "const",
1210
- "contentMediaType",
1211
- "contentEncoding",
1212
- "if",
1213
- "then",
1214
- "else",
1215
- "not",
1216
- "patternProperties",
1217
- "unevaluatedProperties",
1218
- "unevaluatedItems",
1219
- "dependentRequired",
1220
- "dependentSchemas",
1221
- "propertyNames",
1222
- "minContains",
1223
- "maxContains"
1224
- ]);
1225
- function toGeminiSchema(schema) {
1226
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
1227
- return schema;
1228
- }
1229
- const inputSchema = schema;
1230
- const result = {};
1231
- const propertyNames = /* @__PURE__ */ new Set();
1232
- if (inputSchema.properties && typeof inputSchema.properties === "object") {
1233
- for (const propName of Object.keys(inputSchema.properties)) {
1234
- propertyNames.add(propName);
1235
- }
1236
- }
1237
- for (const [key, value] of Object.entries(inputSchema)) {
1238
- if (UNSUPPORTED_SCHEMA_FIELDS.has(key)) {
1239
- continue;
1240
- }
1241
- if (key === "type" && typeof value === "string") {
1242
- result[key] = value.toUpperCase();
1243
- } else if (key === "properties" && typeof value === "object" && value !== null) {
1244
- const props = {};
1245
- for (const [propName, propSchema] of Object.entries(value)) {
1246
- props[propName] = toGeminiSchema(propSchema);
1247
- }
1248
- result[key] = props;
1249
- } else if (key === "items" && typeof value === "object") {
1250
- result[key] = toGeminiSchema(value);
1251
- } else if ((key === "anyOf" || key === "oneOf" || key === "allOf") && Array.isArray(value)) {
1252
- result[key] = value.map((item) => toGeminiSchema(item));
1253
- } else if (key === "enum" && Array.isArray(value)) {
1254
- result[key] = value;
1255
- } else if (key === "default" || key === "examples") {
1256
- result[key] = value;
1257
- } else if (key === "required" && Array.isArray(value)) {
1258
- if (propertyNames.size > 0) {
1259
- const validRequired = value.filter(
1260
- (prop) => typeof prop === "string" && propertyNames.has(prop)
1261
- );
1262
- if (validRequired.length > 0) {
1263
- result[key] = validRequired;
1264
- }
1265
- } else {
1266
- result[key] = value;
1267
- }
1268
- } else {
1269
- result[key] = value;
1270
- }
1271
- }
1272
- if (result.type === "ARRAY" && !result.items) {
1273
- result.items = { type: "STRING" };
1274
- }
1275
- return result;
1276
- }
1277
-
1278
- // ../../node_modules/jose/dist/node/esm/runtime/base64url.js
1279
- import { Buffer as Buffer3 } from "node:buffer";
1280
-
1281
- // ../../node_modules/jose/dist/node/esm/lib/buffer_utils.js
1282
- var encoder = new TextEncoder();
1283
- var decoder = new TextDecoder();
1284
- var MAX_INT32 = 2 ** 32;
1285
-
1286
- // ../../node_modules/jose/dist/node/esm/runtime/base64url.js
1287
- function normalize(input) {
1288
- let encoded = input;
1289
- if (encoded instanceof Uint8Array) {
1290
- encoded = decoder.decode(encoded);
1291
- }
1292
- return encoded;
1293
- }
1294
- var encode = (input) => Buffer3.from(input).toString("base64url");
1295
- var decode = (input) => new Uint8Array(Buffer3.from(normalize(input), "base64url"));
1296
-
1297
- // ../../node_modules/jose/dist/node/esm/util/base64url.js
1298
- var base64url_exports = {};
1299
- __export(base64url_exports, {
1300
- decode: () => decode2,
1301
- encode: () => encode2
1302
- });
1303
- var encode2 = encode;
1304
- var decode2 = decode;
1305
-
1306
- // ../../node_modules/@openauthjs/openauth/dist/esm/pkce.js
1307
- function generateVerifier(length) {
1308
- const buffer = new Uint8Array(length);
1309
- crypto.getRandomValues(buffer);
1310
- return base64url_exports.encode(buffer);
1311
- }
1312
- async function generateChallenge(verifier, method) {
1313
- if (method === "plain")
1314
- return verifier;
1315
- const encoder2 = new TextEncoder();
1316
- const data = encoder2.encode(verifier);
1317
- const hash = await crypto.subtle.digest("SHA-256", data);
1318
- return base64url_exports.encode(new Uint8Array(hash));
1319
- }
1320
- async function generatePKCE(length = 64) {
1321
- if (length < 43 || length > 128) {
1322
- throw new Error("Code verifier length must be between 43 and 128 characters");
1323
- }
1324
- const verifier = generateVerifier(length);
1325
- const challenge = await generateChallenge(verifier, "S256");
1326
- return {
1327
- verifier,
1328
- challenge,
1329
- method: "S256"
1330
- };
1331
- }
1332
-
1333
- // ../core/src/antigravity/oauth.ts
1334
- var log2 = createLogger("oauth");
1335
- async function refreshAntigravityToken(refreshToken) {
1336
- const startTime = Date.now();
1337
- const response = await fetch("https://oauth2.googleapis.com/token", {
1338
- method: "POST",
1339
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1340
- body: new URLSearchParams({
1341
- grant_type: "refresh_token",
1342
- refresh_token: refreshToken,
1343
- client_id: ANTIGRAVITY_CLIENT_ID,
1344
- client_secret: ANTIGRAVITY_CLIENT_SECRET
1345
- })
1346
- });
1347
- if (!response.ok) {
1348
- const errorText = await response.text().catch(() => "");
1349
- throw new Error(
1350
- `Antigravity token refresh failed (${response.status} ${response.statusText})${errorText ? ` - ${errorText}` : ""}`
1351
- );
1352
- }
1353
- const payload = await response.json();
1354
- return {
1355
- access: payload.access_token,
1356
- refresh: payload.refresh_token ?? refreshToken,
1357
- expires: calculateTokenExpiry(startTime, payload.expires_in)
1358
- };
1359
- }
1360
- function encodeState(payload) {
1361
- return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
1362
- }
1363
- function decodeState(state) {
1364
- const normalized = state.replace(/-/g, "+").replace(/_/g, "/");
1365
- const padded = normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "=");
1366
- const json = Buffer.from(padded, "base64").toString("utf8");
1367
- const parsed = JSON.parse(json);
1368
- if (typeof parsed.verifier !== "string") {
1369
- throw new Error("Missing PKCE verifier in state");
1370
- }
1371
- return {
1372
- verifier: parsed.verifier,
1373
- projectId: typeof parsed.projectId === "string" ? parsed.projectId : ""
1374
- };
1375
- }
1376
- async function authorizeAntigravity(projectId = "") {
1377
- const pkce = await generatePKCE();
1378
- const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
1379
- url.searchParams.set("client_id", ANTIGRAVITY_CLIENT_ID);
1380
- url.searchParams.set("response_type", "code");
1381
- url.searchParams.set("redirect_uri", ANTIGRAVITY_REDIRECT_URI);
1382
- url.searchParams.set("scope", ANTIGRAVITY_SCOPES.join(" "));
1383
- url.searchParams.set("code_challenge", pkce.challenge);
1384
- url.searchParams.set("code_challenge_method", "S256");
1385
- url.searchParams.set(
1386
- "state",
1387
- encodeState({ verifier: pkce.verifier, projectId: projectId || "" })
1388
- );
1389
- url.searchParams.set("access_type", "offline");
1390
- url.searchParams.set("prompt", "consent");
1391
- return {
1392
- url: url.toString(),
1393
- verifier: pkce.verifier,
1394
- projectId: projectId || ""
1395
- };
1396
- }
1397
- async function fetchProjectID(accessToken) {
1398
- const errors = [];
1399
- const loadHeaders = buildAntigravityHarnessBootstrapHeaders(accessToken);
1400
- const loadEndpoints = Array.from(
1401
- /* @__PURE__ */ new Set([...ANTIGRAVITY_LOAD_ENDPOINTS, ...ANTIGRAVITY_ENDPOINT_FALLBACKS])
1402
- );
1403
- for (const baseEndpoint of loadEndpoints) {
1404
- try {
1405
- const url = `${baseEndpoint}/v1internal:loadCodeAssist`;
1406
- const response = await fetchWithAgyCliTransport(url, {
1407
- method: "POST",
1408
- headers: loadHeaders,
1409
- body: JSON.stringify({ metadata: buildAntigravityLoadCodeAssistMetadata() })
1410
- }, { timeoutMs: 1e4 });
1411
- if (!response.ok) {
1412
- const message = await response.text().catch(() => "");
1413
- errors.push(
1414
- `loadCodeAssist ${response.status} at ${baseEndpoint}${message ? `: ${message}` : ""}`
1415
- );
1416
- continue;
1417
- }
1418
- const data = await response.json();
1419
- if (typeof data.cloudaicompanionProject === "string" && data.cloudaicompanionProject) {
1420
- return data.cloudaicompanionProject;
1421
- }
1422
- if (data.cloudaicompanionProject && typeof data.cloudaicompanionProject.id === "string" && data.cloudaicompanionProject.id) {
1423
- return data.cloudaicompanionProject.id;
1424
- }
1425
- errors.push(`loadCodeAssist missing project id at ${baseEndpoint}`);
1426
- } catch (e) {
1427
- errors.push(
1428
- `loadCodeAssist error at ${baseEndpoint}: ${e instanceof Error ? e.message : String(e)}`
1429
- );
1430
- }
1431
- }
1432
- if (errors.length) {
1433
- log2.warn("Failed to resolve Antigravity project via loadCodeAssist", { errors: errors.join("; ") });
1434
- }
1435
- return "";
1436
- }
1437
- async function exchangeAntigravity(code, state) {
1438
- try {
1439
- const { verifier, projectId } = decodeState(state);
1440
- const startTime = Date.now();
1441
- const tokenResponse = await fetch("https://oauth2.googleapis.com/token", {
1442
- method: "POST",
1443
- headers: {
1444
- "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
1445
- "Accept": "*/*",
1446
- "Accept-Encoding": "gzip, deflate, br",
1447
- "User-Agent": GEMINI_CLI_HEADERS["User-Agent"]
1448
- },
1449
- body: new URLSearchParams({
1450
- client_id: ANTIGRAVITY_CLIENT_ID,
1451
- client_secret: ANTIGRAVITY_CLIENT_SECRET,
1452
- code,
1453
- grant_type: "authorization_code",
1454
- redirect_uri: ANTIGRAVITY_REDIRECT_URI,
1455
- code_verifier: verifier
1456
- })
1457
- });
1458
- if (!tokenResponse.ok) {
1459
- const errorText = await tokenResponse.text();
1460
- return { type: "failed", error: errorText };
1461
- }
1462
- const tokenPayload = await tokenResponse.json();
1463
- const userInfoResponse = await fetch(
1464
- "https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
1465
- {
1466
- headers: {
1467
- Authorization: `Bearer ${tokenPayload.access_token}`,
1468
- "User-Agent": GEMINI_CLI_HEADERS["User-Agent"]
1469
- }
1470
- }
1471
- );
1472
- const userInfo = userInfoResponse.ok ? await userInfoResponse.json() : {};
1473
- const refreshToken = tokenPayload.refresh_token;
1474
- if (!refreshToken) {
1475
- return { type: "failed", error: "Missing refresh token in response" };
1476
- }
1477
- let effectiveProjectId = projectId;
1478
- if (!effectiveProjectId) {
1479
- effectiveProjectId = await fetchProjectID(tokenPayload.access_token);
1480
- }
1481
- const storedRefresh = `${refreshToken}|${effectiveProjectId || ""}`;
1482
- return {
1483
- type: "success",
1484
- refresh: storedRefresh,
1485
- access: tokenPayload.access_token,
1486
- expires: calculateTokenExpiry(startTime, tokenPayload.expires_in),
1487
- email: userInfo.email,
1488
- projectId: effectiveProjectId || ""
1489
- };
1490
- } catch (error) {
1491
- return {
1492
- type: "failed",
1493
- error: error instanceof Error ? error.message : "Unknown error"
1494
- };
1495
- }
1496
- }
1
+ // src/index.ts
2
+ import {
3
+ authorizeAntigravity,
4
+ exchangeAntigravity,
5
+ getPublicModelDefinitions,
6
+ refreshAntigravityToken
7
+ } from "@cortexkit/antigravity-auth-core";
1497
8
 
1498
9
  // src/credential-cache.ts
1499
10
  var packedRefreshByAccessToken = /* @__PURE__ */ new Map();
@@ -1513,12 +24,23 @@ function getPackedRefresh(accessToken) {
1513
24
  }
1514
25
 
1515
26
  // src/stream.ts
27
+ import {
28
+ AgyRequestSessionStore,
29
+ ANTIGRAVITY_ENDPOINT,
30
+ buildAgyAgentRequestMetadata,
31
+ buildAntigravityHarnessUserAgent,
32
+ ensureProjectContext,
33
+ fetchWithAgyCliTransport,
34
+ orderAgyRequestPayloadInPlace,
35
+ resolveModelForHeaderStyle
36
+ } from "@cortexkit/antigravity-auth-core";
1516
37
  import {
1517
38
  calculateCost,
1518
39
  createAssistantMessageEventStream
1519
40
  } from "@earendil-works/pi-ai";
1520
41
 
1521
42
  // src/convert.ts
43
+ import { toGeminiSchema } from "@cortexkit/antigravity-auth-core";
1522
44
  function sanitize(text) {
1523
45
  return text.replace(/[\uD800-\uDFFF]/gu, "\uFFFD");
1524
46
  }
@@ -1533,18 +55,30 @@ function convertUserParts(content) {
1533
55
  }
1534
56
  return parts;
1535
57
  }
1536
- function convertAssistantParts(content) {
58
+ function convertAssistantParts(message, preserveSignedHistory) {
1537
59
  const parts = [];
1538
- for (const block of content) {
1539
- if (block.type === "text" && block.text.trim()) {
1540
- parts.push({ text: sanitize(block.text) });
60
+ for (const block of message.content) {
61
+ if (block.type === "thinking") {
62
+ if (preserveSignedHistory && block.thinking) {
63
+ parts.push({
64
+ text: sanitize(block.thinking),
65
+ thought: true,
66
+ ...block.thinkingSignature ? { thoughtSignature: block.thinkingSignature } : {}
67
+ });
68
+ }
69
+ } else if (block.type === "text" && block.text.trim()) {
70
+ parts.push({
71
+ text: sanitize(block.text),
72
+ ...preserveSignedHistory && block.textSignature ? { thoughtSignature: block.textSignature } : {}
73
+ });
1541
74
  } else if (block.type === "toolCall") {
1542
75
  parts.push({
1543
76
  functionCall: {
1544
77
  name: block.name,
1545
- args: block.arguments ?? {}
78
+ args: block.arguments ?? {},
79
+ id: block.id
1546
80
  },
1547
- ...block.thoughtSignature ? { thoughtSignature: block.thoughtSignature } : {}
81
+ ...preserveSignedHistory && block.thoughtSignature ? { thoughtSignature: block.thoughtSignature } : {}
1548
82
  });
1549
83
  }
1550
84
  }
@@ -1557,32 +91,53 @@ function toolResultResponse(message) {
1557
91
  }
1558
92
  return { output: text };
1559
93
  }
1560
- function convertMessages(messages) {
94
+ function isSameTargetModel(message, options) {
95
+ if (!options?.provider || !options.model) return true;
96
+ return message.provider === options.provider && message.model === options.model;
97
+ }
98
+ function convertMessages(messages, options) {
1561
99
  const contents = [];
100
+ const callMatchesTarget = /* @__PURE__ */ new Map();
101
+ for (const message of messages) {
102
+ if (message?.role !== "assistant") continue;
103
+ const matchesTarget = isSameTargetModel(message, options);
104
+ for (const block of message.content) {
105
+ if (block.type === "toolCall") {
106
+ callMatchesTarget.set(block.id, matchesTarget);
107
+ }
108
+ }
109
+ }
1562
110
  for (const message of messages) {
1563
111
  if (!message) continue;
1564
112
  if (message.role === "user") {
1565
- const parts = typeof message.content === "string" ? message.content.trim() ? [{ text: sanitize(message.content) }] : [] : convertUserParts(message.content);
113
+ const parts = typeof message.content === "string" ? message.content.trim() ? [{ text: sanitize(message.content) }] : [] : convertUserParts(
114
+ message.content
115
+ );
1566
116
  if (parts.length) contents.push({ role: "user", parts });
1567
117
  continue;
1568
118
  }
1569
119
  if (message.role === "assistant") {
1570
- const parts = convertAssistantParts(message.content);
120
+ const parts = convertAssistantParts(
121
+ message,
122
+ isSameTargetModel(message, options)
123
+ );
1571
124
  if (parts.length) contents.push({ role: "model", parts });
1572
125
  continue;
1573
126
  }
1574
127
  if (message.role === "toolResult") {
128
+ const role = callMatchesTarget.get(message.toolCallId) === true ? "model" : "user";
1575
129
  const part = {
1576
130
  functionResponse: {
1577
131
  name: message.toolName,
1578
- response: toolResultResponse(message)
132
+ response: toolResultResponse(message),
133
+ id: message.toolCallId
1579
134
  }
1580
135
  };
1581
136
  const last = contents[contents.length - 1];
1582
- if (last && last.role === "user" && last.parts.every((p) => "functionResponse" in p)) {
137
+ if (last && last.role === role && last.parts.every((p) => "functionResponse" in p)) {
1583
138
  last.parts.push(part);
1584
139
  } else {
1585
- contents.push({ role: "user", parts: [part] });
140
+ contents.push({ role, parts: [part] });
1586
141
  }
1587
142
  }
1588
143
  }
@@ -1603,20 +158,41 @@ function convertTools(tools) {
1603
158
  }
1604
159
  ];
1605
160
  }
1606
- function buildGeminiRequest(context) {
161
+ function buildGeminiRequest(context, options) {
1607
162
  const request = {
1608
- contents: convertMessages(context.messages)
163
+ contents: convertMessages(context.messages, options)
1609
164
  };
1610
165
  const tools = convertTools(context.tools);
1611
166
  if (tools) request.tools = tools;
1612
167
  if (context.systemPrompt?.trim()) {
1613
- request.systemInstruction = { parts: [{ text: sanitize(context.systemPrompt) }] };
168
+ request.systemInstruction = {
169
+ parts: [{ text: sanitize(context.systemPrompt) }]
170
+ };
1614
171
  }
1615
172
  return request;
1616
173
  }
1617
174
 
1618
175
  // src/stream.ts
1619
176
  var STREAM_ACTION = "streamGenerateContent";
177
+ var FALLBACK_SESSION_KEY = "__default__";
178
+ var TRAILING_USAGE_TIMEOUT_MS = 1e3;
179
+ var requestSessions = new AgyRequestSessionStore("");
180
+ async function nextWithTimeout(iterator, timeoutMs, onTimeout) {
181
+ let timer;
182
+ try {
183
+ return await Promise.race([
184
+ iterator.next(),
185
+ new Promise((resolve) => {
186
+ timer = setTimeout(() => {
187
+ onTimeout();
188
+ resolve(void 0);
189
+ }, timeoutMs);
190
+ })
191
+ ]);
192
+ } finally {
193
+ if (timer) clearTimeout(timer);
194
+ }
195
+ }
1620
196
  function mapFinishReason(reason) {
1621
197
  switch (reason) {
1622
198
  case "STOP":
@@ -1655,6 +231,21 @@ function unwrapChunk(raw) {
1655
231
  }
1656
232
  return raw;
1657
233
  }
234
+ function convertGeminiToolCallPart(part, state) {
235
+ if (part.thought && !part.text && part.thoughtSignature) {
236
+ state.pendingThoughtSignature = part.thoughtSignature;
237
+ }
238
+ if (!part.functionCall) return void 0;
239
+ const thoughtSignature = part.thoughtSignature ?? state.pendingThoughtSignature;
240
+ state.pendingThoughtSignature = void 0;
241
+ return {
242
+ type: "toolCall",
243
+ id: part.functionCall.id ?? `call_${crypto.randomUUID()}`,
244
+ name: part.functionCall.name ?? "",
245
+ arguments: part.functionCall.args ?? {},
246
+ ...thoughtSignature ? { thoughtSignature } : {}
247
+ };
248
+ }
1658
249
  function updateUsage(model, output, usage) {
1659
250
  if (!usage) return;
1660
251
  const cacheRead = usage.cachedContentTokenCount ?? output.usage.cacheRead;
@@ -1670,7 +261,7 @@ function updateUsage(model, output, usage) {
1670
261
  async function* parseGeminiSse(response) {
1671
262
  if (!response.body) return;
1672
263
  const reader = response.body.getReader();
1673
- const decoder2 = new TextDecoder();
264
+ const decoder = new TextDecoder();
1674
265
  let buffer = "";
1675
266
  const parseFrame = function* (frame) {
1676
267
  for (const line of frame.split("\n")) {
@@ -1687,7 +278,7 @@ async function* parseGeminiSse(response) {
1687
278
  while (true) {
1688
279
  const { done, value } = await reader.read();
1689
280
  if (done) break;
1690
- buffer += decoder2.decode(value, { stream: true }).replace(/\r\n/g, "\n");
281
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
1691
282
  let boundary = buffer.indexOf("\n\n");
1692
283
  while (boundary !== -1) {
1693
284
  const frame = buffer.slice(0, boundary);
@@ -1703,11 +294,44 @@ async function* parseGeminiSse(response) {
1703
294
  reader.releaseLock();
1704
295
  }
1705
296
  }
1706
- function buildRequestId() {
1707
- return `agent/${crypto.randomUUID()}/${Date.now()}/${crypto.randomUUID()}/2`;
297
+ function getRequestSessionKey(context, options) {
298
+ if (options?.sessionId) {
299
+ return options.sessionId;
300
+ }
301
+ const firstTimestamp = context.messages[0]?.timestamp;
302
+ return firstTimestamp !== void 0 ? `message:${firstTimestamp}` : FALLBACK_SESSION_KEY;
303
+ }
304
+ function finalizePiAntigravityRequest(request, wireModel, scope) {
305
+ if (Array.isArray(request.tools) && request.tools.length > 0) {
306
+ request.toolConfig = { functionCallingConfig: { mode: "VALIDATED" } };
307
+ }
308
+ const metadata = buildAgyAgentRequestMetadata(
309
+ scope.session,
310
+ request,
311
+ wireModel,
312
+ scope.timestamp,
313
+ { stepCountMode: "cli" }
314
+ );
315
+ request.labels = metadata.labels;
316
+ request.sessionId = metadata.sessionId;
317
+ orderAgyRequestPayloadInPlace(request);
318
+ return metadata.requestId;
319
+ }
320
+ function resolvePiAntigravityModel(model, reasoning) {
321
+ const lower = model.id.toLowerCase();
322
+ const supportsAgyTiers = model.reasoning && (lower.includes("gemini-3") || lower.includes("claude") && lower.includes("thinking"));
323
+ if (!supportsAgyTiers || !reasoning) {
324
+ return resolveModelForHeaderStyle(model.id, "antigravity");
325
+ }
326
+ const tier = reasoning === "minimal" ? "low" : reasoning === "xhigh" ? "high" : reasoning;
327
+ const baseModel = model.id.replace(/-(minimal|low|medium|high|xhigh)$/i, "");
328
+ return resolveModelForHeaderStyle(`${baseModel}-${tier}`, "antigravity");
1708
329
  }
1709
330
  async function sendAntigravityRequest(options) {
1710
- const resolved = resolveModelForHeaderStyle(options.model.id, "antigravity");
331
+ const resolved = resolvePiAntigravityModel(
332
+ options.model,
333
+ options.streamOptions?.reasoning
334
+ );
1711
335
  const wireModel = resolved.actualModel;
1712
336
  const packedRefresh = getPackedRefresh(options.accessToken) ?? "";
1713
337
  const projectContext = await ensureProjectContext({
@@ -1716,7 +340,10 @@ async function sendAntigravityRequest(options) {
1716
340
  access: options.accessToken,
1717
341
  expires: Date.now() + 6e4
1718
342
  });
1719
- const request = buildGeminiRequest(options.context);
343
+ const request = buildGeminiRequest(options.context, {
344
+ provider: options.model.provider,
345
+ model: options.model.id
346
+ });
1720
347
  const generationConfig = {};
1721
348
  if (resolved.thinkingLevel) {
1722
349
  generationConfig.thinkingConfig = {
@@ -1736,9 +363,15 @@ async function sendAntigravityRequest(options) {
1736
363
  if (Object.keys(generationConfig).length > 0) {
1737
364
  request.generationConfig = generationConfig;
1738
365
  }
366
+ const requestScope = requestSessions.beginRequest(options.sessionKey);
367
+ const requestId = finalizePiAntigravityRequest(
368
+ request,
369
+ wireModel,
370
+ requestScope
371
+ );
1739
372
  const envelope = {
1740
373
  project: projectContext.effectiveProjectId,
1741
- requestId: buildRequestId(),
374
+ requestId,
1742
375
  request,
1743
376
  model: wireModel,
1744
377
  userAgent: "antigravity",
@@ -1757,7 +390,7 @@ async function sendAntigravityRequest(options) {
1757
390
  },
1758
391
  body: JSON.stringify(envelope)
1759
392
  },
1760
- { signal: options.streamOptions?.signal ?? null }
393
+ { signal: options.signal ?? options.streamOptions?.signal ?? null }
1761
394
  );
1762
395
  }
1763
396
  function streamCortexKitAntigravity(model, context, options) {
@@ -1767,47 +400,155 @@ function streamCortexKitAntigravity(model, context, options) {
1767
400
  stream.push({ type: "start", partial: output });
1768
401
  try {
1769
402
  const accessToken = options?.apiKey ?? "";
1770
- if (!accessToken) throw new Error("Missing Antigravity OAuth access token");
403
+ if (!accessToken)
404
+ throw new Error("Missing Antigravity OAuth access token");
405
+ const sessionKey = getRequestSessionKey(context, options);
406
+ const trailingUsageAbort = new AbortController();
407
+ const requestSignal = options?.signal ? AbortSignal.any([options.signal, trailingUsageAbort.signal]) : trailingUsageAbort.signal;
1771
408
  const response = await sendAntigravityRequest({
1772
409
  model,
1773
410
  context,
1774
411
  streamOptions: options,
1775
- accessToken
412
+ accessToken,
413
+ sessionKey,
414
+ signal: requestSignal
1776
415
  });
1777
416
  if (!response.ok) {
1778
- throw new Error(`Antigravity request failed: HTTP ${response.status} ${await response.text()}`);
417
+ throw new Error(
418
+ `Antigravity request failed: HTTP ${response.status} ${await response.text()}`
419
+ );
1779
420
  }
1780
421
  const content = output.content;
422
+ const toolCallState = {};
1781
423
  let textIndex = -1;
1782
- let finished = false;
1783
- for await (const chunk of parseGeminiSse(response)) {
424
+ let thinkingIndex = -1;
425
+ let terminalSeen = false;
426
+ const closeText = () => {
427
+ if (textIndex === -1) return;
428
+ const block = content[textIndex];
429
+ if (block?.type === "text") {
430
+ stream.push({
431
+ type: "text_end",
432
+ contentIndex: textIndex,
433
+ content: block.text,
434
+ partial: output
435
+ });
436
+ }
437
+ textIndex = -1;
438
+ };
439
+ const closeThinking = () => {
440
+ if (thinkingIndex === -1) return;
441
+ const block = content[thinkingIndex];
442
+ if (block?.type === "thinking") {
443
+ stream.push({
444
+ type: "thinking_end",
445
+ contentIndex: thinkingIndex,
446
+ content: block.thinking,
447
+ partial: output
448
+ });
449
+ }
450
+ thinkingIndex = -1;
451
+ };
452
+ const chunkIterator = parseGeminiSse(response)[Symbol.asyncIterator]();
453
+ while (true) {
454
+ const next = terminalSeen ? await nextWithTimeout(
455
+ chunkIterator,
456
+ TRAILING_USAGE_TIMEOUT_MS,
457
+ () => trailingUsageAbort.abort()
458
+ ) : await chunkIterator.next();
459
+ if (!next) break;
460
+ if (next.done) break;
461
+ const chunk = next.value;
1784
462
  updateUsage(model, output, chunk.usageMetadata);
463
+ if (terminalSeen) {
464
+ if (chunk.usageMetadata) break;
465
+ continue;
466
+ }
1785
467
  const candidate = chunk.candidates?.[0];
1786
468
  const parts = candidate?.content?.parts ?? [];
1787
469
  for (const part of parts) {
1788
- if (part.functionCall) {
1789
- const toolCall = {
1790
- type: "toolCall",
1791
- id: `call_${crypto.randomUUID()}`,
1792
- name: part.functionCall.name ?? "",
1793
- arguments: part.functionCall.args ?? {},
1794
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
1795
- };
470
+ if (!part.thought && !part.functionCall && !part.text && part.thoughtSignature) {
471
+ const block = textIndex === -1 ? void 0 : content[textIndex];
472
+ if (block?.type === "text") {
473
+ block.textSignature = part.thoughtSignature;
474
+ } else {
475
+ toolCallState.pendingThoughtSignature = part.thoughtSignature;
476
+ }
477
+ continue;
478
+ }
479
+ const toolCall = convertGeminiToolCallPart(part, toolCallState);
480
+ if (toolCall) {
481
+ closeText();
482
+ closeThinking();
1796
483
  content.push(toolCall);
1797
484
  const idx = content.length - 1;
1798
- textIndex = -1;
1799
- stream.push({ type: "toolcall_start", contentIndex: idx, partial: output });
1800
- stream.push({ type: "toolcall_end", contentIndex: idx, toolCall, partial: output });
485
+ stream.push({
486
+ type: "toolcall_start",
487
+ contentIndex: idx,
488
+ partial: output
489
+ });
490
+ stream.push({
491
+ type: "toolcall_end",
492
+ contentIndex: idx,
493
+ toolCall,
494
+ partial: output
495
+ });
1801
496
  output.stopReason = "toolUse";
1802
- } else if (typeof part.text === "string" && part.text.length > 0 && !part.thought) {
497
+ continue;
498
+ }
499
+ if (part.thought) {
500
+ if (typeof part.text !== "string" || part.text.length === 0)
501
+ continue;
502
+ closeText();
503
+ if (thinkingIndex === -1) {
504
+ content.push({
505
+ type: "thinking",
506
+ thinking: "",
507
+ ...part.thoughtSignature ? { thinkingSignature: part.thoughtSignature } : {}
508
+ });
509
+ thinkingIndex = content.length - 1;
510
+ stream.push({
511
+ type: "thinking_start",
512
+ contentIndex: thinkingIndex,
513
+ partial: output
514
+ });
515
+ }
516
+ const block = content[thinkingIndex];
517
+ if (block?.type === "thinking") {
518
+ block.thinking += part.text;
519
+ if (part.thoughtSignature)
520
+ block.thinkingSignature = part.thoughtSignature;
521
+ stream.push({
522
+ type: "thinking_delta",
523
+ contentIndex: thinkingIndex,
524
+ delta: part.text,
525
+ partial: output
526
+ });
527
+ }
528
+ continue;
529
+ }
530
+ if (typeof part.text === "string" && part.text.length > 0) {
531
+ closeThinking();
1803
532
  if (textIndex === -1) {
1804
- content.push({ type: "text", text: "" });
533
+ const textSignature = part.thoughtSignature ?? toolCallState.pendingThoughtSignature;
534
+ toolCallState.pendingThoughtSignature = void 0;
535
+ content.push({
536
+ type: "text",
537
+ text: "",
538
+ ...textSignature ? { textSignature } : {}
539
+ });
1805
540
  textIndex = content.length - 1;
1806
- stream.push({ type: "text_start", contentIndex: textIndex, partial: output });
541
+ stream.push({
542
+ type: "text_start",
543
+ contentIndex: textIndex,
544
+ partial: output
545
+ });
1807
546
  }
1808
547
  const block = content[textIndex];
1809
- if (block && block.type === "text") {
548
+ if (block?.type === "text") {
1810
549
  block.text += part.text;
550
+ if (part.thoughtSignature)
551
+ block.textSignature = part.thoughtSignature;
1811
552
  stream.push({
1812
553
  type: "text_delta",
1813
554
  contentIndex: textIndex,
@@ -1818,21 +559,22 @@ function streamCortexKitAntigravity(model, context, options) {
1818
559
  }
1819
560
  }
1820
561
  if (candidate?.finishReason) {
1821
- if (textIndex !== -1) {
1822
- const block = content[textIndex];
1823
- if (block && block.type === "text") {
1824
- stream.push({ type: "text_end", contentIndex: textIndex, content: block.text, partial: output });
1825
- }
1826
- textIndex = -1;
1827
- }
562
+ closeText();
563
+ closeThinking();
1828
564
  if (output.stopReason !== "toolUse") {
1829
565
  output.stopReason = mapFinishReason(candidate.finishReason);
1830
566
  }
1831
- finished = true;
1832
- break;
567
+ terminalSeen = true;
568
+ const needsTrailingUsage = model.id.toLowerCase().includes("gpt-oss") && !chunk.usageMetadata;
569
+ if (!needsTrailingUsage) break;
1833
570
  }
1834
571
  }
1835
- if (finished) {
572
+ if (terminalSeen) {
573
+ try {
574
+ await chunkIterator.return?.(void 0);
575
+ } catch (error) {
576
+ if (!trailingUsageAbort.signal.aborted) throw error;
577
+ }
1836
578
  await response.body?.cancel().catch(() => {
1837
579
  });
1838
580
  }
@@ -1842,6 +584,9 @@ function streamCortexKitAntigravity(model, context, options) {
1842
584
  reason: output.stopReason,
1843
585
  message: output
1844
586
  });
587
+ if (output.stopReason === "stop" || output.stopReason === "length") {
588
+ requestSessions.completeExecution(sessionKey);
589
+ }
1845
590
  stream.end();
1846
591
  } catch (error) {
1847
592
  output.stopReason = options?.signal?.aborted ? "aborted" : "error";
@@ -1896,7 +641,7 @@ async function refreshAntigravityCredentials(credentials) {
1896
641
  };
1897
642
  }
1898
643
  function cortexKitPiAntigravityAuth(pi) {
1899
- const models = Object.values(getPublicModelDefinitions()).map((model) => ({
644
+ const models = Object.values(getPublicModelDefinitions()).filter((model) => !model.modalities.output.includes("image")).map((model) => ({
1900
645
  id: model.id,
1901
646
  name: model.name,
1902
647
  reasoning: model.reasoning,