tuxevil-rotator 3.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
@@ -0,0 +1,424 @@
1
+ // Google Antigravity request forwarding: build the upstream v1internal SSE
2
+ // request with credential swapping + endpoint cascade, and parse the SSE
3
+ // stream events (usage + visible text).
4
+
5
+ import {
6
+ ANTIGRAVITY_ENDPOINTS,
7
+ REQUEST_CLIENT_METADATA,
8
+ REQUEST_GOOG_API_CLIENT,
9
+ REQUEST_USER_AGENT,
10
+ applyModelAlias,
11
+ } from "../../types.js";
12
+ import type { AccountRuntime } from "../../types.js";
13
+ import type { RequestBody, ForwardedResponse } from "../../proxy.js";
14
+ import { logger } from "../../logger.js";
15
+ import type { TokenUsage } from "../adapter.js";
16
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
17
+ import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
18
+
19
+ const forwardLogger = logger.child("google-forward");
20
+
21
+ /** Max bytes kept in the SSE event buffer. A single event is rarely >1MB;
22
+ * if it is, we keep the last 1MB which is still enough to find usage. */
23
+ const SSE_EVENT_BUFFER_MAX = 1024 * 1024;
24
+
25
+ function isRecord(value: unknown): value is Record<string, unknown> {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+
29
+ /** Recursively search a parsed JSON value for the first usage block we
30
+ * recognise. Supports Gemini (usageMetadata), OpenAI (usage with
31
+ * prompt_tokens/completion_tokens), and Anthropic (usage with
32
+ * input_tokens/output_tokens). */
33
+ function findUsageInJson(
34
+ value: unknown,
35
+ ): TokenUsage | null {
36
+ if (!isRecord(value)) return null;
37
+
38
+ // Gemini format
39
+ const usageMetadata = isRecord(value.usageMetadata)
40
+ ? value.usageMetadata
41
+ : null;
42
+ if (usageMetadata) {
43
+ const input =
44
+ typeof usageMetadata.promptTokenCount === "number"
45
+ ? usageMetadata.promptTokenCount
46
+ : typeof usageMetadata.inputTokenCount === "number"
47
+ ? usageMetadata.inputTokenCount
48
+ : 0;
49
+ const output =
50
+ typeof usageMetadata.candidatesTokenCount === "number"
51
+ ? usageMetadata.candidatesTokenCount
52
+ : typeof usageMetadata.outputTokenCount === "number"
53
+ ? usageMetadata.outputTokenCount
54
+ : 0;
55
+ if (input > 0 || output > 0)
56
+ return { inputTokens: input, outputTokens: output };
57
+ }
58
+ // OpenAI / Anthropic format
59
+ const usage = value.usage;
60
+ if (isRecord(usage)) {
61
+ const input =
62
+ typeof usage.prompt_tokens === "number"
63
+ ? usage.prompt_tokens
64
+ : typeof usage.input_tokens === "number"
65
+ ? usage.input_tokens
66
+ : 0;
67
+ const output =
68
+ typeof usage.completion_tokens === "number"
69
+ ? usage.completion_tokens
70
+ : typeof usage.output_tokens === "number"
71
+ ? usage.output_tokens
72
+ : 0;
73
+ if (input > 0 || output > 0)
74
+ return { inputTokens: input, outputTokens: output };
75
+ }
76
+ // Recurse into common nesting locations.
77
+ for (const key of ["candidates", "output", "response", "message"]) {
78
+ const child = value[key];
79
+ if (Array.isArray(child)) {
80
+ for (const item of child) {
81
+ const found = findUsageInJson(item);
82
+ if (found) return found;
83
+ }
84
+ } else if (isRecord(child)) {
85
+ const found = findUsageInJson(child);
86
+ if (found) return found;
87
+ }
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /** Extract usage from a single complete SSE event (one or more `data:` lines
93
+ * separated by newlines, terminated by a blank line). The last successful
94
+ * extraction wins (callers should stop scanning once they find usage). */
95
+ export function extractUsageFromSseEvent(
96
+ eventText: string,
97
+ ): TokenUsage | null {
98
+ const dataLines: string[] = [];
99
+ for (const raw of eventText.split("\n")) {
100
+ if (raw.startsWith("data:")) {
101
+ dataLines.push(raw.slice(5).trim());
102
+ }
103
+ }
104
+ if (dataLines.length === 0) return null;
105
+ const payload = dataLines.join("\n");
106
+ if (payload === "[DONE]" || payload === "") return null;
107
+ let parsed: unknown;
108
+ try {
109
+ parsed = JSON.parse(payload);
110
+ } catch {
111
+ // Fall back to regex on the raw event text. This handles non-standard
112
+ // streams that don't quite produce valid JSON per event.
113
+ return regexExtractUsage(payload);
114
+ }
115
+ return findUsageInJson(parsed);
116
+ }
117
+
118
+ /** Last-resort regex extraction for streams that don't yield parseable JSON. */
119
+ function regexExtractUsage(buffer: string): TokenUsage | null {
120
+ try {
121
+ const patterns = [
122
+ /"promptTokenCount"\s*:\s*(\d+).*?"candidatesTokenCount"\s*:\s*(\d+)/s,
123
+ /"input_tokens"\s*:\s*(\d+).*?"output_tokens"\s*:\s*(\d+)/s,
124
+ ];
125
+ for (const pattern of patterns) {
126
+ const match = buffer.match(pattern);
127
+ if (match) {
128
+ return {
129
+ inputTokens: parseInt(match[1], 10),
130
+ outputTokens: parseInt(match[2], 10),
131
+ };
132
+ }
133
+ }
134
+ } catch {
135
+ /* extraction failed */
136
+ }
137
+ return null;
138
+ }
139
+
140
+ function extractTextFromSseEvent(eventText: string): string | null {
141
+ const dataLines: string[] = [];
142
+ for (const raw of eventText.split("\n")) {
143
+ if (raw.startsWith("data:")) {
144
+ dataLines.push(raw.slice(5).trim());
145
+ }
146
+ }
147
+ if (dataLines.length === 0) return null;
148
+ const payload = dataLines.join("\n");
149
+ if (payload === "[DONE]" || payload === "") return null;
150
+ try {
151
+ const parsed = JSON.parse(payload);
152
+ if (parsed && typeof parsed === "object") {
153
+ const p = parsed as Record<string, unknown>;
154
+ if (
155
+ Array.isArray(p.candidates) &&
156
+ p.candidates[0] &&
157
+ typeof p.candidates[0] === "object"
158
+ ) {
159
+ const cand = p.candidates[0] as Record<string, unknown>;
160
+ if (cand.content && typeof cand.content === "object") {
161
+ const content = cand.content as Record<string, unknown>;
162
+ if (Array.isArray(content.parts)) {
163
+ return content.parts
164
+ .map((part) =>
165
+ part &&
166
+ typeof part === "object" &&
167
+ typeof (part as Record<string, unknown>).text === "string"
168
+ ? (part as Record<string, unknown>).text
169
+ : "",
170
+ )
171
+ .join("");
172
+ }
173
+ }
174
+ }
175
+ }
176
+ } catch {
177
+ /* ignore */
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /** State for the SSE event accumulator used by streamResponseBody. */
183
+ export class SseEventAccumulator {
184
+ private buffer = "";
185
+ private accumulatedText = "";
186
+ private readonly maxBytes: number;
187
+ constructor(maxBytes: number = SSE_EVENT_BUFFER_MAX) {
188
+ this.maxBytes = maxBytes;
189
+ }
190
+
191
+ /** Append a chunk, return any usage extracted from newly-completed events. */
192
+ append(chunkText: string): TokenUsage | null {
193
+ this.buffer += chunkText;
194
+ if (this.buffer.length > this.maxBytes) {
195
+ this.buffer = this.buffer.slice(-this.maxBytes);
196
+ }
197
+ let extracted: TokenUsage | null = null;
198
+ let boundary = this.buffer.indexOf("\n\n");
199
+ while (boundary !== -1) {
200
+ const eventText = this.buffer.slice(0, boundary);
201
+ this.buffer = this.buffer.slice(boundary + 2);
202
+ const usage = extractUsageFromSseEvent(eventText);
203
+ if (usage && !extracted) extracted = usage;
204
+ const text = extractTextFromSseEvent(eventText);
205
+ if (text && this.accumulatedText.length < 100000) {
206
+ this.accumulatedText += text;
207
+ }
208
+ boundary = this.buffer.indexOf("\n\n");
209
+ }
210
+ return extracted;
211
+ }
212
+
213
+ getText(): string {
214
+ return this.accumulatedText;
215
+ }
216
+
217
+ /** Flush any partial event at end-of-stream. */
218
+ final(): TokenUsage | null {
219
+ if (!this.buffer) return null;
220
+ const usage = extractUsageFromSseEvent(this.buffer);
221
+ const text = extractTextFromSseEvent(this.buffer);
222
+ if (text && this.accumulatedText.length < 100000) {
223
+ this.accumulatedText += text;
224
+ }
225
+ this.buffer = "";
226
+ return usage;
227
+ }
228
+ }
229
+
230
+ const BENCHMARK_MODEL = "gemini-3-flash";
231
+ const BENCHMARK_PROMPT = "Reply with exactly: OK";
232
+ const BENCHMARK_MAX_OUTPUT_TOKENS = 16;
233
+ const BENCHMARK_TIMEOUT_MS = 30_000;
234
+
235
+ function benchmarkRequestBody(account: AccountRuntime): RequestBody {
236
+ return {
237
+ project: account.config.projectId as string,
238
+ model: BENCHMARK_MODEL,
239
+ request: {
240
+ contents: [
241
+ {
242
+ role: "user",
243
+ parts: [{ text: BENCHMARK_PROMPT }],
244
+ },
245
+ ],
246
+ generationConfig: {
247
+ maxOutputTokens: BENCHMARK_MAX_OUTPUT_TOKENS,
248
+ },
249
+ },
250
+ };
251
+ }
252
+
253
+ function benchmarkUsage(raw: string): { outputTokens: number } | null {
254
+ let outputTokens = 0;
255
+ for (const event of raw.split(/\r?\n\r?\n/)) {
256
+ const usage = extractUsageFromSseEvent(event);
257
+ if (usage) {
258
+ outputTokens += usage.outputTokens;
259
+ }
260
+ }
261
+ return { outputTokens };
262
+ }
263
+
264
+ export function getBenchmarkSpec(account: AccountRuntime): {
265
+ body: RequestBody;
266
+ parseUsage(raw: string): { outputTokens: number } | null;
267
+ parseText(raw: string): string;
268
+ } {
269
+ return {
270
+ body: benchmarkRequestBody(account),
271
+ parseUsage: benchmarkUsage,
272
+ parseText: (raw: string) => {
273
+ const lines: string[] = [];
274
+ for (const event of raw.split(/\r?\n\r?\n/)) {
275
+ const text = extractTextFromSseEvent(event);
276
+ if (text) lines.push(text);
277
+ }
278
+ return lines.join("");
279
+ },
280
+ };
281
+ }
282
+
283
+ export const GOOGLE_BENCHMARK_CONSTANTS = {
284
+ model: BENCHMARK_MODEL,
285
+ prompt: BENCHMARK_PROMPT,
286
+ maxOutputTokens: BENCHMARK_MAX_OUTPUT_TOKENS,
287
+ timeoutMs: BENCHMARK_TIMEOUT_MS,
288
+ } as const;
289
+
290
+ /**
291
+ * Forward a request to the real Antigravity endpoint with credential swapping.
292
+ */
293
+ export async function forwardRequest(
294
+ account: AccountRuntime,
295
+ body: RequestBody,
296
+ originalHeaders: Record<string, string>,
297
+ signal?: AbortSignal,
298
+ ): Promise<ForwardedResponse> {
299
+ // Swap credentials
300
+ body.project = account.config.projectId ?? "";
301
+
302
+ // Map internal display/compat names to Google upstream names (single source
303
+ // of truth: src/types.ts:applyModelAlias)
304
+ body.model = applyModelAlias(body.model);
305
+
306
+ const { displayModel: _displayModel, ...bodyToForward } = body;
307
+ const requestBody = JSON.stringify(bodyToForward);
308
+
309
+ // Build headers: keep originals but swap Authorization
310
+ const forwardHeaders: Record<string, string> = {
311
+ ...originalHeaders,
312
+ "Content-Type": "application/json",
313
+ Accept: "text/event-stream",
314
+ };
315
+ // Remove original authorization (any case), provider-set headers, and
316
+ // hop-by-hop headers per RFC 7230 §6.1. The hop-by-hop list prevents
317
+ // leaking client IP (X-Forwarded-For) and prevents IP spoofing in
318
+ // upstream logs (Via).
319
+ const HOP_BY_HOP = new Set([
320
+ "connection",
321
+ "keep-alive",
322
+ "proxy-authenticate",
323
+ "proxy-authorization",
324
+ "te",
325
+ "trailers",
326
+ "transfer-encoding",
327
+ "upgrade",
328
+ // Forwarding / proxying artefacts that should never reach the upstream
329
+ "x-forwarded-for",
330
+ "x-forwarded-host",
331
+ "x-forwarded-proto",
332
+ "x-forwarded-port",
333
+ "x-real-ip",
334
+ "forwarded",
335
+ "via",
336
+ ]);
337
+ for (const key of Object.keys(forwardHeaders)) {
338
+ const lowerKey = key.toLowerCase();
339
+ if (
340
+ HOP_BY_HOP.has(lowerKey) ||
341
+ lowerKey === "authorization" ||
342
+ lowerKey === "user-agent" ||
343
+ lowerKey === "x-goog-api-client" ||
344
+ lowerKey === "client-metadata"
345
+ ) {
346
+ delete forwardHeaders[key];
347
+ }
348
+ }
349
+ forwardHeaders["Authorization"] = `Bearer ${account.accessToken}`;
350
+ forwardHeaders["User-Agent"] = REQUEST_USER_AGENT;
351
+ forwardHeaders["X-Goog-Api-Client"] = REQUEST_GOOG_API_CLIENT;
352
+ forwardHeaders["Client-Metadata"] = REQUEST_CLIENT_METADATA;
353
+ // Claude models on Cloud Code Assist (Antigravity) require this beta header to
354
+ // return interleaved thinking blocks. Mirrors pi-mono's needsClaudeThinkingBetaHeader.
355
+ if (/^claude-/i.test(body.model)) {
356
+ forwardHeaders["anthropic-beta"] = "interleaved-thinking-2025-05-14";
357
+ }
358
+ delete forwardHeaders["host"];
359
+ delete forwardHeaders["connection"];
360
+ delete forwardHeaders["transfer-encoding"];
361
+ delete forwardHeaders["content-length"];
362
+
363
+ // Try endpoints with cascade on 401/403/404
364
+ for (
365
+ let endpointIdx = 0;
366
+ endpointIdx < ANTIGRAVITY_ENDPOINTS.length;
367
+ endpointIdx++
368
+ ) {
369
+ const endpoint = ANTIGRAVITY_ENDPOINTS[endpointIdx];
370
+ const url = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
371
+ const isProd = endpointIdx === ANTIGRAVITY_ENDPOINTS.length - 1;
372
+
373
+ try {
374
+ const controller = !isProd ? new AbortController() : undefined;
375
+ const timeout = controller
376
+ ? setTimeout(() => controller.abort(), 10_000)
377
+ : undefined;
378
+ const requestSignal =
379
+ controller?.signal && signal
380
+ ? AbortSignal.any([controller.signal, signal])
381
+ : signal ?? controller?.signal;
382
+
383
+ const response = await fetch(url, {
384
+ method: "POST",
385
+ headers: forwardHeaders,
386
+ body: requestBody,
387
+ signal: requestSignal,
388
+ dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
389
+ } as RequestInitWithDispatcher);
390
+ if (timeout) clearTimeout(timeout);
391
+
392
+ if (
393
+ (response.status === 401 ||
394
+ response.status === 403 ||
395
+ response.status === 404) &&
396
+ endpointIdx < ANTIGRAVITY_ENDPOINTS.length - 1
397
+ ) {
398
+ forwardLogger.log("info",
399
+ `Endpoint ${endpoint} returned ${response.status}, cascading...`,
400
+ );
401
+ response.text().catch(() => {});
402
+ continue;
403
+ }
404
+
405
+ return { response, endpoint };
406
+ } catch (err) {
407
+ if (endpointIdx < ANTIGRAVITY_ENDPOINTS.length - 1) {
408
+ forwardLogger.log("info",
409
+ `Endpoint ${endpoint} failed: ${
410
+ err instanceof Error ? err.message : err
411
+ }, cascading...`,
412
+ );
413
+ continue;
414
+ }
415
+ throw err;
416
+ }
417
+ }
418
+
419
+ throw new Error("All endpoints failed");
420
+ }
421
+
422
+ export function createGoogleStreamAccumulator(): SseEventAccumulator {
423
+ return new SseEventAccumulator();
424
+ }
@@ -0,0 +1,168 @@
1
+ // Google Antigravity provider adapter.
2
+ //
3
+ // Implements the ProviderAdapter contract for Google's Cloud Code Assist
4
+ // (Antigravity) endpoints: OAuth2 credential lifecycle, per-model quota
5
+ // polling, v1internal SSE forwarding, and the Gemini-native request/response
6
+ // translation used by the compat layer.
7
+
8
+ import type {
9
+ ProviderAdapter,
10
+ QuotaFetchContext,
11
+ } from "../adapter.js";
12
+ import { fetchProviderQuota } from "./quota.js";
13
+ import {
14
+ forwardRequest,
15
+ createGoogleStreamAccumulator,
16
+ getBenchmarkSpec,
17
+ } from "./forward.js";
18
+ import {
19
+ forwardCodeAssistRequest,
20
+ isCodeAssistAction,
21
+ } from "./code-assist.js";
22
+ import { runLogin } from "./login.js";
23
+ import { validateCredentials } from "./credentials.js";
24
+ import {
25
+ getOAuthClientConfig,
26
+ isHostedOAuthConfigured,
27
+ } from "./oauth.js";
28
+ import {
29
+ TOKEN_URL,
30
+ KICKSTART_MODEL_FOR_QUOTA_POOL,
31
+ } from "../../types.js";
32
+ import type { AccountRuntime } from "../../types.js";
33
+ import { fetchWithRetry } from "../../fetch-with-retry.js";
34
+ import { logger } from "../../logger.js";
35
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
36
+
37
+ const providerLog = logger.child("provider/google");
38
+
39
+ /**
40
+ * Refresh the OAuth access token for a Google account if it is missing or
41
+ * about to expire. Throws on unrecoverable refresh failures.
42
+ */
43
+ async function ensureGoogleToken(account: AccountRuntime): Promise<void> {
44
+ const now = Date.now();
45
+ if (account.accessToken && account.tokenExpires > now) {
46
+ return;
47
+ }
48
+ if (!account.config.refreshToken) {
49
+ throw new Error(
50
+ `Account ${account.config.email} has no refreshToken; re-run login`,
51
+ );
52
+ }
53
+ const oauth = getOAuthClientConfig();
54
+ const response = await fetchWithRetry(TOKEN_URL, {
55
+ method: "POST",
56
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
57
+ body: new URLSearchParams({
58
+ client_id: oauth.clientId,
59
+ client_secret: oauth.clientSecret,
60
+ refresh_token: account.config.refreshToken,
61
+ grant_type: "refresh_token",
62
+ }),
63
+ dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
64
+ });
65
+ if (!response.ok) {
66
+ const errorText = await response.text();
67
+ throw new Error(`Token refresh failed (${response.status}): ${errorText}`);
68
+ }
69
+ const data = (await response.json()) as {
70
+ access_token: string;
71
+ expires_in: number;
72
+ };
73
+ account.accessToken = data.access_token;
74
+ account.tokenExpires = now + data.expires_in * 1000 - 5 * 60 * 1000;
75
+ account.consecutiveErrors = 0;
76
+ }
77
+
78
+ export const googleAntigravityAdapter: ProviderAdapter = {
79
+ id: "google-antigravity",
80
+ displayName: "Google Antigravity",
81
+ credentialKind: "oauth",
82
+ tierRanking: {
83
+ ultra: 0,
84
+ pro: 1,
85
+ plus: 2,
86
+ free: 3,
87
+ unknown: 4,
88
+ },
89
+ features: {
90
+ circuitBreakers: true,
91
+ concurrencyLimits: true,
92
+ proactiveRotation: false,
93
+ },
94
+
95
+ runLogin,
96
+ validateCredentials,
97
+
98
+ hasValidCredentials(account: AccountRuntime): boolean {
99
+ if (account.accessToken && account.tokenExpires > Date.now()) {
100
+ return true;
101
+ }
102
+ return typeof account.config.refreshToken === "string" &&
103
+ account.config.refreshToken.length > 0;
104
+ },
105
+
106
+ async ensureValidToken(account: AccountRuntime): Promise<void> {
107
+ try {
108
+ await ensureGoogleToken(account);
109
+ } catch (err) {
110
+ providerLog.log(
111
+ "warn",
112
+ `Token refresh failed for ${account.config.email}: ${
113
+ err instanceof Error ? err.message : String(err)
114
+ }`,
115
+ );
116
+ throw err;
117
+ }
118
+ },
119
+
120
+ getAuthHeader(account: AccountRuntime): string {
121
+ return `Bearer ${account.accessToken}`;
122
+ },
123
+
124
+ shouldRetryOnQuotaExhaustion(): boolean {
125
+ // Antigravity quota buckets are attached to the OAuth account/project
126
+ // being used. A different eligible account has an independent bucket.
127
+ return true;
128
+ },
129
+
130
+ async fetchQuota(
131
+ account: AccountRuntime,
132
+ ctx: QuotaFetchContext,
133
+ ): Promise<void> {
134
+ await fetchProviderQuota(account, ctx);
135
+ },
136
+
137
+ forwardRequest,
138
+ async forwardCodeAssistRequest(
139
+ account,
140
+ action,
141
+ body,
142
+ originalHeaders,
143
+ signal,
144
+ ) {
145
+ if (!isCodeAssistAction(action)) {
146
+ throw new Error(`Unsupported Code Assist action: ${action}`);
147
+ }
148
+ return forwardCodeAssistRequest(
149
+ account,
150
+ action,
151
+ body,
152
+ originalHeaders,
153
+ signal,
154
+ );
155
+ },
156
+ createStreamAccumulator: createGoogleStreamAccumulator,
157
+
158
+ getKickstartModelForPool(quotaModelKey: string): string | undefined {
159
+ return KICKSTART_MODEL_FOR_QUOTA_POOL[quotaModelKey];
160
+ },
161
+
162
+ getBenchmark(account: AccountRuntime) {
163
+ return getBenchmarkSpec(account);
164
+ },
165
+ };
166
+
167
+ export type { TokenExchangeResult, OAuthClientConfig } from "./oauth.js";
168
+ export { isHostedOAuthConfigured, getOAuthClientConfig };