@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.
Files changed (48) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +91 -0
  4. package/dist/auth/index.d.ts +2 -0
  5. package/dist/auth/index.js +1 -0
  6. package/dist/auth/oauth.d.ts +18 -0
  7. package/dist/auth/oauth.js +374 -0
  8. package/dist/client/client.d.ts +35 -0
  9. package/dist/client/client.js +448 -0
  10. package/dist/client/index.d.ts +1 -0
  11. package/dist/client/index.js +1 -0
  12. package/dist/diagnostics/diagnostics.d.ts +31 -0
  13. package/dist/diagnostics/diagnostics.js +68 -0
  14. package/dist/diagnostics/index.d.ts +1 -0
  15. package/dist/diagnostics/index.js +1 -0
  16. package/dist/image/image.d.ts +62 -0
  17. package/dist/image/image.js +244 -0
  18. package/dist/image/index.d.ts +1 -0
  19. package/dist/image/index.js +1 -0
  20. package/dist/index.d.ts +12 -0
  21. package/dist/index.js +182 -0
  22. package/dist/models/index.d.ts +1 -0
  23. package/dist/models/index.js +1 -0
  24. package/dist/models/models.d.ts +44 -0
  25. package/dist/models/models.js +377 -0
  26. package/dist/stream/index.d.ts +1 -0
  27. package/dist/stream/index.js +1 -0
  28. package/dist/stream/stream.d.ts +24 -0
  29. package/dist/stream/stream.js +879 -0
  30. package/dist/types/enums.d.ts +41 -0
  31. package/dist/types/enums.js +49 -0
  32. package/dist/types/index.d.ts +2 -0
  33. package/dist/types/index.js +2 -0
  34. package/dist/types/types.d.ts +259 -0
  35. package/dist/types/types.js +2 -0
  36. package/dist/usage/index.d.ts +1 -0
  37. package/dist/usage/index.js +1 -0
  38. package/dist/usage/usage.d.ts +8 -0
  39. package/dist/usage/usage.js +388 -0
  40. package/dist/utils/http.d.ts +7 -0
  41. package/dist/utils/http.js +81 -0
  42. package/dist/utils/index.d.ts +3 -0
  43. package/dist/utils/index.js +3 -0
  44. package/dist/utils/security.d.ts +8 -0
  45. package/dist/utils/security.js +60 -0
  46. package/dist/utils/util.d.ts +40 -0
  47. package/dist/utils/util.js +176 -0
  48. package/package.json +73 -0
@@ -0,0 +1,448 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Platform } from "../types/enums.js";
3
+ import { getCurrentAvailableModels, getCurrentEndpoint, getCurrentMatchedModelDebug, setLastAvailableModels, setLastEndpoint, setLastError, setLastMatchedModelDebug, setLastStatus, } from "../diagnostics/diagnostics.js";
4
+ import { assertSafeApiBaseUrl, safeError } from "../utils/security.js";
5
+ import { antigravityEnv, asString, escapeRegExp, isRecord } from "../utils/util.js";
6
+ import { antigravityFetch } from "../utils/http.js";
7
+ export const DEFAULT_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
8
+ export const ENDPOINT_FALLBACKS = [
9
+ DEFAULT_ENDPOINT,
10
+ "https://daily-cloudcode-pa.sandbox.googleapis.com",
11
+ "https://cloudcode-pa.googleapis.com",
12
+ ];
13
+ const PROJECT_CACHE_TTL_MS = 30 * 60 * 1000;
14
+ const projectCache = new Map();
15
+ const MODEL_CACHE_TTL_MS = 30 * 60 * 1000;
16
+ const modelCache = new Map();
17
+ /** Metadata lookups (project/model discovery) must be fast; a stalled endpoint should
18
+ * fall through to the next candidate instead of hanging the whole request. */
19
+ const DISCOVERY_TIMEOUT_MS = 8000;
20
+ /** In-flight de-dupe: concurrent requests for the same (token, project, model) share one probe. */
21
+ const inFlightModelLookups = new Map();
22
+ /** UUID-shaped stable id from a seed (account email preferred over cwd). */
23
+ export function stableProjectId(seed) {
24
+ const bytes = createHash("sha1").update(`antigravity:${seed}`).digest().subarray(0, 16);
25
+ bytes[6] = (bytes[6] & 0x0f) | 0x50;
26
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
27
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
28
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
29
+ }
30
+ /**
31
+ * Fallback project id when discovery fails.
32
+ * Prefer ANTIGRAVITY_PROJECT_ID, then a stable seed (email), never process.cwd().
33
+ */
34
+ export function defaultProjectId(seed = "antigravity-default") {
35
+ return antigravityEnv("PROJECT_ID")?.trim() || stableProjectId(seed);
36
+ }
37
+ /** @deprecated Use defaultProjectId(seed); kept for scripts that imported the old constant. */
38
+ export const DEFAULT_PROJECT_ID = defaultProjectId();
39
+ export function endpointCandidates(preferredEndpoint) {
40
+ const explicit = antigravityEnv("BASE_URL")?.trim();
41
+ if (explicit)
42
+ return [assertSafeApiBaseUrl(explicit)];
43
+ if (preferredEndpoint && ENDPOINT_FALLBACKS.includes(preferredEndpoint)) {
44
+ return [preferredEndpoint, ...ENDPOINT_FALLBACKS.filter((e) => e !== preferredEndpoint)];
45
+ }
46
+ return ENDPOINT_FALLBACKS;
47
+ }
48
+ const DEFAULT_ANTIGRAVITY_VERSION = "2.8.0";
49
+ const DEFAULT_ANTIGRAVITY_CL = "963137146";
50
+ function defaultUserAgent() {
51
+ const version = antigravityEnv("HUB_VERSION") || DEFAULT_ANTIGRAVITY_VERSION;
52
+ const cl = antigravityEnv("HUB_CL") || DEFAULT_ANTIGRAVITY_CL;
53
+ const os = antigravityEnv("HUB_OS") || "darwin";
54
+ const arch = antigravityEnv("HUB_ARCH") || "arm64";
55
+ return `antigravity/hub/${version} (aidev_client; os_type=${os}; arch=${arch}; cl=${cl})`;
56
+ }
57
+ export function antigravityHeaders(token) {
58
+ const platform = process.platform === "darwin"
59
+ ? Platform.Macos
60
+ : process.platform === "win32"
61
+ ? Platform.Windows
62
+ : Platform.Linux;
63
+ return {
64
+ Authorization: `Bearer ${token}`,
65
+ "Content-Type": "application/json",
66
+ Accept: "text/event-stream",
67
+ "User-Agent": antigravityEnv("USER_AGENT") || defaultUserAgent(),
68
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
69
+ "Client-Metadata": JSON.stringify({
70
+ ideType: "ANTIGRAVITY",
71
+ platform,
72
+ pluginType: "GEMINI",
73
+ }),
74
+ };
75
+ }
76
+ export function jsonOrTextError(text) {
77
+ try {
78
+ const parsed = JSON.parse(text);
79
+ if (parsed.error?.message)
80
+ return parsed.error.message;
81
+ }
82
+ catch {
83
+ // not JSON
84
+ }
85
+ return text;
86
+ }
87
+ export function parseApiKey(apiKeyRaw) {
88
+ if (!apiKeyRaw) {
89
+ throw new Error("No Antigravity OAuth credentials. Run /login antigravity.");
90
+ }
91
+ try {
92
+ const parsed = JSON.parse(apiKeyRaw);
93
+ if (!parsed.token || !parsed.projectId)
94
+ throw new Error("missing token or projectId");
95
+ return { token: parsed.token, projectId: parsed.projectId };
96
+ }
97
+ catch (error) {
98
+ throw new Error(`Invalid Antigravity credentials. Run /login antigravity. (${safeError(error)})`, { cause: error });
99
+ }
100
+ }
101
+ export function extractProjectId(data) {
102
+ if (!isRecord(data))
103
+ return undefined;
104
+ const direct = data.antigravityProjectId ??
105
+ data.projectId ??
106
+ data.backendProjectId ??
107
+ data.userDefinedCloudaicompanionProject ??
108
+ data.cloudaicompanionProject ??
109
+ data.project;
110
+ const directId = asString(direct);
111
+ if (directId)
112
+ return directId;
113
+ if (isRecord(direct)) {
114
+ const nestedId = asString(direct.id);
115
+ if (nestedId)
116
+ return nestedId;
117
+ }
118
+ for (const key of ["projects", "projectIds", "cloudaicompanionProjects"]) {
119
+ const value = data[key];
120
+ if (Array.isArray(value)) {
121
+ for (const item of value) {
122
+ const nested = extractProjectId(item);
123
+ if (nested)
124
+ return nested;
125
+ const itemId = asString(item);
126
+ if (itemId)
127
+ return itemId;
128
+ }
129
+ }
130
+ }
131
+ return undefined;
132
+ }
133
+ async function listCloudAICompanionProjects(token) {
134
+ for (const endpoint of endpointCandidates()) {
135
+ try {
136
+ const res = await antigravityFetch(`${endpoint}/v1internal:listCloudAICompanionProjects`, {
137
+ method: "POST",
138
+ headers: antigravityHeaders(token),
139
+ body: JSON.stringify({}),
140
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
141
+ });
142
+ setLastStatus(res.status);
143
+ setLastEndpoint(endpoint);
144
+ if (!res.ok)
145
+ continue;
146
+ return extractProjectId(await res.json());
147
+ }
148
+ catch (error) {
149
+ setLastError(safeError(error));
150
+ }
151
+ }
152
+ return undefined;
153
+ }
154
+ function collectModelLabels(value, out = []) {
155
+ if (!value || out.length > 50)
156
+ return out;
157
+ if (typeof value === "string") {
158
+ if (/gemini|claude|gpt-oss/i.test(value))
159
+ out.push(value);
160
+ return out;
161
+ }
162
+ if (Array.isArray(value)) {
163
+ for (const item of value)
164
+ collectModelLabels(item, out);
165
+ return out;
166
+ }
167
+ if (isRecord(value)) {
168
+ for (const key of ["id", "name", "label", "displayName", "model", "modelId"]) {
169
+ collectModelLabels(value[key], out);
170
+ }
171
+ for (const nested of Object.values(value)) {
172
+ if (nested && typeof nested === "object")
173
+ collectModelLabels(nested, out);
174
+ }
175
+ }
176
+ return out;
177
+ }
178
+ function summarizeModelCandidate(value) {
179
+ if (!isRecord(value))
180
+ return String(value ?? "none");
181
+ const out = {};
182
+ for (const [key, raw] of Object.entries(value)) {
183
+ if (/token|auth|credential|secret|email/i.test(key))
184
+ continue;
185
+ if (raw === null || ["string", "number", "boolean"].includes(typeof raw))
186
+ out[key] = raw;
187
+ else if (Array.isArray(raw))
188
+ out[key] = `[array:${String(raw.length)}]`;
189
+ else if (isRecord(raw)) {
190
+ out[key] = `{${Object.keys(raw).slice(0, 12).join(",")}}`;
191
+ }
192
+ }
193
+ return JSON.stringify(out).slice(0, 1200);
194
+ }
195
+ /** Runtime ids look like gemini-*, claude-*, gpt-oss-*, never MODEL_PLACEHOLDER_* enums. */
196
+ export function isUsableRuntimeModelId(id) {
197
+ return /^(gemini-|claude-|gpt-oss-)/i.test(id) && !/\s/.test(id) && !/^MODEL_/i.test(id);
198
+ }
199
+ function buildModelMatchRegex(requestedId) {
200
+ const req = requestedId.toLowerCase();
201
+ // Display names from fetchAvailableModels (keys are the real runtime ids):
202
+ // gemini-3.8-flash-low → "Gemini 3.8 Flash (Low)"
203
+ // gemini-3.8-flash-medium → "Gemini 3.8 Flash (Medium)"
204
+ // gemini-3.8-flash-high → "Gemini 3.8 Flash (High)"
205
+ // gemini-3.7-flash-low → "Gemini 3.7 Flash (Low)"
206
+ // gemini-3.7-flash-medium → "Gemini 3.7 Flash (Medium)"
207
+ // gemini-3.7-flash-high → "Gemini 3.7 Flash (High)"
208
+ // gemini-3.6-flash-low → "Gemini 3.6 Flash (Low)"
209
+ // gemini-3.6-flash-medium → "Gemini 3.6 Flash (Medium)"
210
+ // gemini-3.6-flash-high → "Gemini 3.6 Flash (High)"
211
+ // gemini-3.5-flash-extra-low → "Gemini 3.5 Flash (Low)"
212
+ // gemini-3.5-flash-low → "Gemini 3.5 Flash (Medium)"
213
+ // gemini-3-flash-agent → "Gemini 3.5 Flash (High)"
214
+ if (req === "gemini-3.8-flash-low")
215
+ return /gemini[- ]3\.8[- ]flash \(low\)/i;
216
+ if (req === "gemini-3.8-flash-medium")
217
+ return /gemini[- ]3\.8[- ]flash \(medium\)/i;
218
+ if (req === "gemini-3.8-flash-high")
219
+ return /gemini[- ]3\.8[- ]flash \(high\)/i;
220
+ if (req === "gemini-3.7-flash-low")
221
+ return /gemini[- ]3\.7[- ]flash \(low\)/i;
222
+ if (req === "gemini-3.7-flash-medium")
223
+ return /gemini[- ]3\.7[- ]flash \(medium\)/i;
224
+ if (req === "gemini-3.7-flash-high")
225
+ return /gemini[- ]3\.7[- ]flash \(high\)/i;
226
+ if (req === "gemini-3.6-flash-low")
227
+ return /gemini[- ]3\.6[- ]flash \(low\)/i;
228
+ if (req === "gemini-3.6-flash-medium")
229
+ return /gemini[- ]3\.6[- ]flash \(medium\)/i;
230
+ if (req === "gemini-3.6-flash-high")
231
+ return /gemini[- ]3\.6[- ]flash \(high\)/i;
232
+ if (req === "gemini-3.5-flash-extra-low")
233
+ return /gemini[- ]3\.5[- ]flash \(low\)/i;
234
+ if (req === "gemini-3.5-flash-low" || req === "gemini-3.5-flash-medium")
235
+ return /gemini[- ]3\.5[- ]flash \(medium\)/i;
236
+ if (req === "gemini-3.5-flash-high" || req === "gemini-3-flash-agent")
237
+ return /gemini[- ]3\.5[- ]flash \(high\)/i;
238
+ if (req.includes("claude-opus-4-6"))
239
+ return /claude.*opus.*4\.6/i;
240
+ if (req.includes("claude-sonnet-4-6"))
241
+ return /claude.*sonnet.*4\.6/i;
242
+ if (req.includes("gpt-oss-120b"))
243
+ return /gpt.*oss.*120b/i;
244
+ if (req === "gemini-3.1-pro-low")
245
+ return /gemini[- ]3\.1[- ]pro \(low\)/i;
246
+ if (req === "gemini-3.1-pro-high" || req === "gemini-pro-agent")
247
+ return /gemini[- ]3\.1[- ]pro \(high\)/i;
248
+ const escaped = escapeRegExp(req).replace(/\\-/g, "[- ]");
249
+ return new RegExp(escaped, "i");
250
+ }
251
+ function dynamicModelFromInfo(modelId, info) {
252
+ if (!isRecord(info))
253
+ return { id: modelId };
254
+ setLastMatchedModelDebug(summarizeModelCandidate({ modelId, ...info }));
255
+ const experiments = Array.isArray(info.modelExperiments)
256
+ ? info.modelExperiments.filter((item) => typeof item === "string")
257
+ : undefined;
258
+ return {
259
+ id: modelId,
260
+ experiments,
261
+ apiProvider: asString(info.apiProvider),
262
+ modelProvider: asString(info.modelProvider),
263
+ };
264
+ }
265
+ /**
266
+ * Resolve a requested runtime model against fetchAvailableModels payload.
267
+ * The real runtime ids are the keys of `data.models`; the nested `model` field is often
268
+ * a MODEL_PLACEHOLDER_* enum that 404s on streamGenerateContent.
269
+ */
270
+ function findDynamicModel(value, requestedId) {
271
+ if (!value)
272
+ return undefined;
273
+ if (isRecord(value) && isRecord(value.models)) {
274
+ const modelsMap = value.models;
275
+ if (isUsableRuntimeModelId(requestedId) && requestedId in modelsMap) {
276
+ return dynamicModelFromInfo(requestedId, modelsMap[requestedId]);
277
+ }
278
+ const targetRegex = buildModelMatchRegex(requestedId);
279
+ for (const [modelId, info] of Object.entries(modelsMap)) {
280
+ if (!isUsableRuntimeModelId(modelId))
281
+ continue;
282
+ if (targetRegex.test(modelId))
283
+ return dynamicModelFromInfo(modelId, info);
284
+ if (isRecord(info)) {
285
+ const label = info.label ?? info.displayName ?? info.name;
286
+ if (typeof label === "string" && targetRegex.test(label)) {
287
+ return dynamicModelFromInfo(modelId, info);
288
+ }
289
+ }
290
+ }
291
+ return undefined;
292
+ }
293
+ const targetRegex = buildModelMatchRegex(requestedId);
294
+ if (typeof value === "string") {
295
+ return targetRegex.test(value) && isUsableRuntimeModelId(value) ? { id: value } : undefined;
296
+ }
297
+ if (Array.isArray(value)) {
298
+ for (const item of value) {
299
+ const found = findDynamicModel(item, requestedId);
300
+ if (found)
301
+ return found;
302
+ }
303
+ return undefined;
304
+ }
305
+ if (isRecord(value)) {
306
+ for (const nested of Object.values(value)) {
307
+ if (nested && typeof nested === "object") {
308
+ const found = findDynamicModel(nested, requestedId);
309
+ if (found)
310
+ return found;
311
+ }
312
+ }
313
+ }
314
+ return undefined;
315
+ }
316
+ async function fetchAvailableRuntimeModelUncached(token, projectId, requestedRuntimeModel) {
317
+ const body = JSON.stringify({ project: projectId });
318
+ const endpoints = endpointCandidates();
319
+ let lastLabels = "";
320
+ // Try endpoints in priority order (production first). If the primary endpoint
321
+ // resolves the model, return immediately without waiting on slower sandbox endpoints.
322
+ for (const endpoint of endpoints) {
323
+ try {
324
+ const res = await antigravityFetch(`${endpoint}/v1internal:fetchAvailableModels`, {
325
+ method: "POST",
326
+ headers: antigravityHeaders(token),
327
+ body,
328
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
329
+ });
330
+ setLastStatus(res.status);
331
+ if (!res.ok)
332
+ continue;
333
+ setLastEndpoint(endpoint);
334
+ const data = await res.json();
335
+ const labels = [...new Set(collectModelLabels(data))].slice(0, 16);
336
+ if (labels.length)
337
+ lastLabels = labels.join(",");
338
+ const found = findDynamicModel(data, requestedRuntimeModel);
339
+ if (found) {
340
+ if (lastLabels)
341
+ setLastAvailableModels(lastLabels);
342
+ return found;
343
+ }
344
+ }
345
+ catch (error) {
346
+ setLastError(safeError(error));
347
+ }
348
+ }
349
+ if (lastLabels)
350
+ setLastAvailableModels(lastLabels);
351
+ return undefined;
352
+ }
353
+ export async function fetchAvailableRuntimeModel(token, projectId, requestedRuntimeModel) {
354
+ const cacheKey = `${token}::${projectId}::${requestedRuntimeModel}`;
355
+ const cached = modelCache.get(cacheKey);
356
+ if (cached && cached.expiresAt > Date.now())
357
+ return cached.result;
358
+ // De-dupe concurrent lookups for the same key (e.g. parallel requests right after
359
+ // startup) so they share one probe instead of each firing their own round-trips.
360
+ const inFlight = inFlightModelLookups.get(cacheKey);
361
+ if (inFlight)
362
+ return inFlight;
363
+ const promise = fetchAvailableRuntimeModelUncached(token, projectId, requestedRuntimeModel).then((result) => {
364
+ modelCache.set(cacheKey, { result, expiresAt: Date.now() + MODEL_CACHE_TTL_MS });
365
+ return result;
366
+ });
367
+ inFlightModelLookups.set(cacheKey, promise);
368
+ try {
369
+ return await promise;
370
+ }
371
+ finally {
372
+ inFlightModelLookups.delete(cacheKey);
373
+ // Evict expired entries; bound map size to avoid unbounded growth.
374
+ if (modelCache.size > 64) {
375
+ const now = Date.now();
376
+ for (const [key, entry] of modelCache) {
377
+ if (entry.expiresAt <= now)
378
+ modelCache.delete(key);
379
+ }
380
+ }
381
+ }
382
+ }
383
+ export function clearModelCache() {
384
+ modelCache.clear();
385
+ }
386
+ async function loadCodeAssistUncached(token) {
387
+ const body = JSON.stringify({
388
+ metadata: {
389
+ ideType: "ANTIGRAVITY",
390
+ platform: "PLATFORM_UNSPECIFIED",
391
+ pluginType: "GEMINI",
392
+ },
393
+ });
394
+ for (const endpoint of endpointCandidates()) {
395
+ try {
396
+ const res = await antigravityFetch(`${endpoint}/v1internal:loadCodeAssist`, {
397
+ method: "POST",
398
+ headers: antigravityHeaders(token),
399
+ body,
400
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
401
+ });
402
+ setLastStatus(res.status);
403
+ setLastEndpoint(endpoint);
404
+ if (!res.ok)
405
+ continue;
406
+ const project = extractProjectId(await res.json());
407
+ if (project)
408
+ return project;
409
+ return await listCloudAICompanionProjects(token);
410
+ }
411
+ catch (error) {
412
+ setLastError(safeError(error));
413
+ }
414
+ }
415
+ return undefined;
416
+ }
417
+ /** Discover project id with a short in-memory LRU cache keyed by access token. */
418
+ export async function loadCodeAssist(token) {
419
+ const cached = projectCache.get(token);
420
+ if (cached && cached.expiresAt > Date.now()) {
421
+ // Refresh LRU order: delete and re-insert so newest is at the end.
422
+ projectCache.delete(token);
423
+ projectCache.set(token, cached);
424
+ return cached.projectId;
425
+ }
426
+ const projectId = await loadCodeAssistUncached(token);
427
+ projectCache.set(token, { projectId, expiresAt: Date.now() + PROJECT_CACHE_TTL_MS });
428
+ // Evict oldest entry when the cache exceeds 32 entries (O(1) — Map preserves insertion order).
429
+ if (projectCache.size > 32) {
430
+ const oldestKey = projectCache.keys().next().value;
431
+ if (oldestKey !== undefined)
432
+ projectCache.delete(oldestKey);
433
+ }
434
+ return projectId;
435
+ }
436
+ export function clearProjectCache() {
437
+ projectCache.clear();
438
+ }
439
+ export function resolveProjectId(opts) {
440
+ return (antigravityEnv("PROJECT_ID")?.trim() ||
441
+ opts.warmedProject ||
442
+ opts.credentialProjectId ||
443
+ defaultProjectId(opts.email || "antigravity-default"));
444
+ }
445
+ /** Build a diagnostic suffix using the active request bag. */
446
+ export function formatRequestDiagnostics(extra) {
447
+ return `endpoint=${getCurrentEndpoint() || "unknown"}, project=${extra.projectId}, runtimeModel=${extra.runtimeModel}, matched=${getCurrentMatchedModelDebug() || "none"}, available=${getCurrentAvailableModels() || "unknown"}`;
448
+ }
@@ -0,0 +1 @@
1
+ export * from "./client.js";
@@ -0,0 +1 @@
1
+ export * from "./client.js";
@@ -0,0 +1,31 @@
1
+ export type DiagnosticsSnapshot = {
2
+ status?: number;
3
+ endpoint?: string;
4
+ error?: string;
5
+ projectId?: string;
6
+ resolvedRuntimeModel?: string;
7
+ availableModels?: string;
8
+ matchedModelDebug?: string;
9
+ latencyMs?: number;
10
+ maskedEmail?: string;
11
+ tokenExpiry?: string;
12
+ };
13
+ /** Run work with an isolated diagnostics bag; commits it to `lastSnapshot` when done. */
14
+ export declare function runWithDiagnostics<T>(fn: () => Promise<T>): Promise<T>;
15
+ export declare function getLastDiagnostics(): Readonly<DiagnosticsSnapshot>;
16
+ /** Read endpoint from the active request bag (or last snapshot outside a request). */
17
+ export declare function getCurrentEndpoint(): string | undefined;
18
+ export declare function getCurrentMatchedModelDebug(): string | undefined;
19
+ export declare function getCurrentAvailableModels(): string | undefined;
20
+ export declare function setLastStatus(status: number | undefined): void;
21
+ export declare function setLastEndpoint(endpoint: string | undefined): void;
22
+ export declare function setLastError(error: string | undefined): void;
23
+ export declare function setLastProjectId(projectId: string | undefined): void;
24
+ export declare function setLastResolvedRuntimeModel(model: string | undefined): void;
25
+ export declare function setLastAvailableModels(models: string | undefined): void;
26
+ export declare function setLastMatchedModelDebug(debug: string | undefined): void;
27
+ export declare function setLastLatencyMs(ms: number | undefined): void;
28
+ export declare function setLastMaskedEmail(email: string | undefined): void;
29
+ export declare function setLastTokenExpiry(expiry: string | undefined): void;
30
+ /** Test helper: reset last snapshot between cases. */
31
+ export declare function resetDiagnosticsForTests(): void;
@@ -0,0 +1,68 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { redactSecrets } from "../utils/security.js";
3
+ const storage = new AsyncLocalStorage();
4
+ /** Last completed request snapshot for `/antigravity.doctor`. */
5
+ let lastSnapshot = {};
6
+ function currentBag() {
7
+ return storage.getStore() ?? lastSnapshot;
8
+ }
9
+ /** Run work with an isolated diagnostics bag; commits it to `lastSnapshot` when done. */
10
+ export async function runWithDiagnostics(fn) {
11
+ const bag = {};
12
+ return storage.run(bag, async () => {
13
+ try {
14
+ return await fn();
15
+ }
16
+ finally {
17
+ lastSnapshot = { ...bag };
18
+ }
19
+ });
20
+ }
21
+ export function getLastDiagnostics() {
22
+ return lastSnapshot;
23
+ }
24
+ /** Read endpoint from the active request bag (or last snapshot outside a request). */
25
+ export function getCurrentEndpoint() {
26
+ return currentBag().endpoint;
27
+ }
28
+ export function getCurrentMatchedModelDebug() {
29
+ return currentBag().matchedModelDebug;
30
+ }
31
+ export function getCurrentAvailableModels() {
32
+ return currentBag().availableModels;
33
+ }
34
+ export function setLastStatus(status) {
35
+ currentBag().status = status;
36
+ }
37
+ export function setLastEndpoint(endpoint) {
38
+ currentBag().endpoint = endpoint;
39
+ }
40
+ export function setLastError(error) {
41
+ currentBag().error = error === undefined ? undefined : redactSecrets(error).slice(0, 800);
42
+ }
43
+ export function setLastProjectId(projectId) {
44
+ currentBag().projectId = projectId;
45
+ }
46
+ export function setLastResolvedRuntimeModel(model) {
47
+ currentBag().resolvedRuntimeModel = model;
48
+ }
49
+ export function setLastAvailableModels(models) {
50
+ currentBag().availableModels = models;
51
+ }
52
+ export function setLastMatchedModelDebug(debug) {
53
+ currentBag().matchedModelDebug =
54
+ debug === undefined ? undefined : redactSecrets(debug).slice(0, 1200);
55
+ }
56
+ export function setLastLatencyMs(ms) {
57
+ currentBag().latencyMs = ms;
58
+ }
59
+ export function setLastMaskedEmail(email) {
60
+ currentBag().maskedEmail = email;
61
+ }
62
+ export function setLastTokenExpiry(expiry) {
63
+ currentBag().tokenExpiry = expiry;
64
+ }
65
+ /** Test helper: reset last snapshot between cases. */
66
+ export function resetDiagnosticsForTests() {
67
+ lastSnapshot = {};
68
+ }
@@ -0,0 +1 @@
1
+ export * from "./diagnostics.js";
@@ -0,0 +1 @@
1
+ export * from "./diagnostics.js";
@@ -0,0 +1,62 @@
1
+ import { AntigravityRequestType, AntigravityUserAgent, GeminiRole } from "../types/enums.js";
2
+ export declare const DEFAULT_IMAGE_MODEL = "gemini-3-pro-image";
3
+ export declare const IMAGE_ASPECT_RATIOS: readonly ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
4
+ export type ImageAspectRatio = (typeof IMAGE_ASPECT_RATIOS)[number];
5
+ export type GeneratedImage = {
6
+ data: string;
7
+ mimeType: string;
8
+ };
9
+ export type ImageGenerateRequest = {
10
+ project: string;
11
+ model: string;
12
+ request: {
13
+ contents: Array<{
14
+ role: GeminiRole.User;
15
+ parts: Array<{
16
+ text: string;
17
+ }>;
18
+ }>;
19
+ systemInstruction: {
20
+ role: GeminiRole.User;
21
+ parts: Array<{
22
+ text: string;
23
+ }>;
24
+ };
25
+ generationConfig: {
26
+ imageConfig: {
27
+ aspectRatio: string;
28
+ };
29
+ candidateCount: number;
30
+ };
31
+ };
32
+ requestType: AntigravityRequestType.Agent;
33
+ userAgent: AntigravityUserAgent.Antigravity;
34
+ requestId: string;
35
+ };
36
+ export type ImageCommandArgs = {
37
+ prompt: string;
38
+ aspectRatio?: string;
39
+ model?: string;
40
+ path?: string;
41
+ };
42
+ export type GenerateImageOptions = ImageCommandArgs & {
43
+ apiKey: string;
44
+ cwd: string;
45
+ signal?: AbortSignal;
46
+ };
47
+ export type GenerateImageResult = {
48
+ images: GeneratedImage[];
49
+ savedPaths: string[];
50
+ text: string[];
51
+ model: string;
52
+ };
53
+ export declare function assertSafeImageModel(modelId: string): string;
54
+ export declare function assertSafeAspectRatio(ratio: string): ImageAspectRatio;
55
+ export declare function parseImageCommandArgs(args: string): ImageCommandArgs;
56
+ export declare function resolveImageSavePath(cwd: string, requested?: string, mimeType?: string, index?: number): string;
57
+ export declare function buildImageGenerateRequest(prompt: string, model: string, projectId: string, aspectRatio: string): ImageGenerateRequest;
58
+ export declare function collectImagesFromSse(response: Response, signal?: AbortSignal): Promise<{
59
+ images: GeneratedImage[];
60
+ text: string[];
61
+ }>;
62
+ export declare function generateAntigravityImage(options: GenerateImageOptions): Promise<GenerateImageResult>;