-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathantigravity.ts
More file actions
1663 lines (1513 loc) · 63.3 KB
/
Copy pathantigravity.ts
File metadata and controls
1663 lines (1513 loc) · 63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto, { randomUUID } from "crypto";
import {
BaseExecutor,
mergeUpstreamExtraHeaders,
type ExecuteInput,
type ExecutorLog,
type ProviderCredentials,
} from "./base.ts";
import { PROVIDERS, OAUTH_ENDPOINTS, HTTP_STATUS, FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { scrubProxyAndFingerprintHeaders } from "../services/antigravityHeaderScrub.ts";
import {
getAntigravityContentHeaders,
getAntigravityOAuthUserAgent,
} from "../services/antigravityHeaders.ts";
import { classify429, decide429, type Decision } from "../services/antigravity429Engine.ts";
import {
parseRetryFromErrorText,
type RetryHintProvenance,
} from "../services/accountFallback.ts";
import { parseDetailedRetryHintFromJsonBody } from "../services/retryAfterJson.ts";
import {
shouldRetryWithCredits,
shouldUseCreditsFirst,
getCreditsMode,
handleCreditsFailure,
} from "../services/antigravityCredits.ts";
import { persistCreditBalance, getAllPersistedCreditBalances } from "@/lib/db/creditBalance";
import { setConnectionRateLimitUntil } from "@/lib/db/providers";
import { markAntigravityModelQuotaExhausted } from "../services/antigravityFamilyCooldown.ts";
import { getMitmAlias } from "@/lib/db/models";
import {
MAX_ANTIGRAVITY_OUTPUT_TOKENS,
resolveAntigravityOutputCap,
} from "./antigravityOutputCap.ts";
export { MAX_ANTIGRAVITY_OUTPUT_TOKENS } from "./antigravityOutputCap.ts";
import {
ensureAntigravityProjectAssigned,
ANTIGRAVITY_REQUIRES_MANUAL_PROJECT,
} from "../services/antigravityProjectBootstrap.ts";
import { persistDiscoveredAntigravityProjectId } from "../services/antigravityProjectPersist.ts";
import { markAntigravityMissingCloudCodeProject } from "../services/antigravityProjectPersistence.ts";
import {
resolveAntigravityModelId,
getAntigravityModelFallbacks,
} from "../config/antigravityModelAliases.ts";
import {
shouldStripCloudCodeThinking,
stripCloudCodeThinkingConfig,
} from "../services/cloudCodeThinking.ts";
import { buildGeminiTools } from "../translator/helpers/geminiToolsSanitizer.ts";
import {
type AntigravityCollectedStream,
processAntigravitySSEText,
flushAntigravitySSEText,
} from "./antigravity/sseCollect.ts";
// processAntigravitySSEPayload re-exported for external importers (tests).
export { processAntigravitySSEPayload } from "./antigravity/sseCollect.ts";
import {
createCreditsExtractionTransform as createCreditsExtractionTransformImpl,
type SsePassthroughResult,
} from "./antigravity/streamingPassthrough.ts";
import {
toSafeAntigravityLog,
finalizeAntigravityRequestBody,
sendAntigravityRequest,
tryCreditsRetry,
tryEmbedLongRetryAfter,
buildFinalAntigravityResult,
buildAntigravity429ErrorMessage,
markCreditsExhausted,
isAbortError,
type SafeAntigravityLog,
} from "./antigravity/executeAttempt.ts";
import {
handleAntigravityFallbackChainError,
handleAntigravityFallback400,
} from "./antigravity/proFallbackChain.ts";
import {
getAntigravityClientProfile,
resolveAntigravityClientVersion,
} from "../services/antigravityClientProfile.ts";
import {
generateAntigravityRequestId,
getAntigravityEnvelopeUserAgent,
getAntigravitySessionId,
} from "../services/antigravityIdentity.ts";
const MAX_RETRY_AFTER_MS = 60_000;
const LONG_RETRY_THRESHOLD_MS = 60_000;
// Cap for transient 5xx backoff — shorter than the 429 cap to avoid long stalls on
// infra hiccups ("Agent execution terminated", "high traffic", capacity errors).
const ANTIGRAVITY_TRANSIENT_RETRY_MAX_MS = 15_000;
// Bounded per-URL auto-retry count for both the Retry-After-driven short retry and
// the no-Retry-After transient/429 backoff loop in executeOnce().
const MAX_AUTO_RETRIES = 3;
export function resolveAntigravityBodyRetryHint(
body: string,
errorMessage: string
): { retryMs: number; source: RetryHintProvenance } | null {
const structured = parseDetailedRetryHintFromJsonBody(body, Number.MAX_SAFE_INTEGER);
if (structured) {
return {
retryMs: structured.retryAfterMs,
source: structured.provenance,
};
}
const retryMs = parseRetryFromErrorText(errorMessage);
return retryMs ? { retryMs, source: "body" } : null;
}
const ANTIGRAVITY_TRANSIENT_ERROR_PATTERNS: RegExp[] = [
/high\s+traffic/i,
/agent\s+(execution\s+)?terminated\s+due\s+to\s+error/i,
/capacity/i,
/temporarily\s+unavailable/i,
/timeout/i,
/stream\s+(ended|closed|terminated|interrupted)/i,
/empty\s+response/i,
];
const ANTIGRAVITY_TRANSIENT_STATUSES = new Set([
HTTP_STATUS.SERVER_ERROR,
HTTP_STATUS.BAD_GATEWAY,
HTTP_STATUS.SERVICE_UNAVAILABLE,
HTTP_STATUS.GATEWAY_TIMEOUT,
]);
const ANTIGRAVITY_UNSUPPORTED_SAFETY_CATEGORIES = new Set<string>([
"HARM_CATEGORY_CIVIC_INTEGRITY",
]);
// The upstream API uses plain model IDs (no -high/-low suffix).
// Tier suffixes were speculative and caused 404 for gemini-3.x models — the
// bare-Pro→Low normalization was retired (the set stayed empty, making the guard
// dead code). Only keep models that are live-proven via streamGenerateContent.
interface AntigravityContent {
role: string;
parts: unknown[];
[key: string]: unknown;
}
export type AntigravityCredentials = ProviderCredentials & {
projectId?: string | null;
expiresIn?: number;
};
type AntigravityChunkContent = Record<string, unknown> & {
role?: string;
parts?: Array<
Record<string, unknown> & {
text?: unknown;
functionCall?: Record<string, unknown>;
functionResponse?: unknown;
thought?: unknown;
thoughtSignature?: unknown;
}
>;
};
type AntigravityRequestEnvelope = Record<string, unknown> & {
project: string;
model?: string;
userAgent: "antigravity";
requestType: "agent" | "image_gen";
requestId: string;
request: Record<string, unknown>;
enabledCreditTypes?: string[];
};
const MAX_CREDIT_BALANCE_ENTRIES = 50;
const CREDIT_BALANCE_TTL_MS = 5 * 60 * 1000;
const creditBalanceCache = new Map<string, { balance: number; updatedAt: number }>();
let creditCacheHydrated = false;
function hydrateCreditCacheFromDb(): void {
if (creditCacheHydrated) return;
creditCacheHydrated = true;
try {
const persisted = getAllPersistedCreditBalances();
for (const [accountId, balance] of persisted) {
if (!creditBalanceCache.has(accountId)) {
creditBalanceCache.set(accountId, { balance, updatedAt: Date.now() });
}
}
} catch {}
}
function evictStaleCreditBalanceEntries(): void {
const now = Date.now();
for (const [key, entry] of creditBalanceCache) {
if (now - entry.updatedAt > CREDIT_BALANCE_TTL_MS) {
creditBalanceCache.delete(key);
}
}
while (creditBalanceCache.size > MAX_CREDIT_BALANCE_ENTRIES) {
const oldestKey = creditBalanceCache.keys().next().value;
if (oldestKey !== undefined) creditBalanceCache.delete(oldestKey);
else break;
}
}
const _creditBalanceSweep = setInterval(evictStaleCreditBalanceEntries, 60_000);
if (typeof _creditBalanceSweep === "object" && "unref" in _creditBalanceSweep) {
(_creditBalanceSweep as { unref?: () => void }).unref?.();
}
export function getAntigravityRemainingCredits(accountId: string): number | null {
hydrateCreditCacheFromDb();
const entry = creditBalanceCache.get(accountId);
if (!entry) return null;
if (Date.now() - entry.updatedAt > CREDIT_BALANCE_TTL_MS) {
creditBalanceCache.delete(accountId);
return null;
}
return entry.balance;
}
export function updateAntigravityRemainingCredits(accountId: string, balance: number): void {
if (creditBalanceCache.size >= MAX_CREDIT_BALANCE_ENTRIES && !creditBalanceCache.has(accountId)) {
const oldestKey = creditBalanceCache.keys().next().value;
if (oldestKey !== undefined) creditBalanceCache.delete(oldestKey);
}
creditBalanceCache.set(accountId, { balance, updatedAt: Date.now() });
try {
persistCreditBalance(accountId, balance);
} catch {}
}
/**
* Pass-through TransformStream that extracts `remainingCredits` from SSE
* data without consuming the stream (the downstream client receives the
* unmodified bytes). Thin wrapper around the pure implementation in
* streamingPassthrough.ts, injecting this executor's credit-balance cache
* writer so the two modules don't import each other. See that module's
* doc comment for the full parameter behavior.
* @internal Exported for unit testing only.
*/
export function createCreditsExtractionTransform(
accountId: string,
bufferSize = 0
): TransformStream<Uint8Array, Uint8Array> {
return createCreditsExtractionTransformImpl(
accountId,
updateAntigravityRemainingCredits,
bufferSize
);
}
export function markConnectionQuotaExhausted(
connectionId: string,
retryAfterMs: number,
model?: string | null
): void {
try {
if (markAntigravityModelQuotaExhausted(connectionId, retryAfterMs, model)) return;
setConnectionRateLimitUntil(connectionId, Date.now() + retryAfterMs);
} catch {}
}
/**
* Accumulate one Antigravity SSE `data:` payload into `collected`. Exported for unit
* tests (the markdown / candidate-parts extraction branches). @internal
*/
/**
* Strip provider prefixes (e.g. "antigravity/model" → "model").
* Ensures the model name sent to the upstream API never contains a routing prefix.
*
* `modelIdOverride` (#3786): when the per-request Pro-family fallback chain forces a
* specific upstream id, pass it here. It is an ALREADY-RESOLVED upstream id, so it bypasses
* the MITM/static alias resolution and is used verbatim (after prefix stripping).
*/
async function cleanModelName(model: string, modelIdOverride?: string): Promise<string> {
if (modelIdOverride) {
return modelIdOverride.includes("/") ? modelIdOverride.split("/").pop()! : modelIdOverride;
}
if (!model) return model;
const stripped = model.includes("/") ? model.split("/").pop()! : model;
let clean = stripped;
// 1. Check dynamic MITM aliases first (authoritative after first sync).
// Built during model sync — contains ONLY currently-available models.
// Obsolete/removed models are automatically excluded.
try {
const mitmAliases = await getMitmAlias("antigravity");
if (mitmAliases && typeof mitmAliases === "object") {
const aliases = mitmAliases as Record<string, unknown>;
const raw = aliases[stripped];
// Only honor string aliases; corrupted/non-string DB values fall through
// to the static alias resolution below (never return undefined here).
if (typeof raw === "string" && raw) {
// Strip the "antigravity/" prefix if present; use the raw model ID otherwise.
const PREFIX = "antigravity/";
clean = raw.startsWith(PREFIX) ? raw.slice(PREFIX.length) : raw;
}
}
} catch {
// DB not available (build phase, transient error) — fall through to static aliases
}
// 2. Fall back to static aliases if MITM didn't resolve
if (clean === stripped) {
clean = resolveAntigravityModelId(clean);
}
return clean;
}
function applyAntigravityGenerationDefaults(
request: Record<string, unknown>,
modelId?: string | null
): void {
const generationConfig =
request.generationConfig && typeof request.generationConfig === "object"
? (request.generationConfig as Record<string, unknown>)
: {};
if (generationConfig.topK === undefined) {
generationConfig.topK = 40;
}
if (generationConfig.topP === undefined) {
generationConfig.topP = 1.0;
}
const thinkingConfig =
generationConfig.thinkingConfig && typeof generationConfig.thinkingConfig === "object"
? (generationConfig.thinkingConfig as Record<string, unknown>)
: null;
const thinkingBudget = Number(thinkingConfig?.thinkingBudget);
const maxOutputTokens = Number(generationConfig.maxOutputTokens);
if (
Number.isFinite(thinkingBudget) &&
thinkingBudget > 0 &&
(!Number.isFinite(maxOutputTokens) || maxOutputTokens <= thinkingBudget)
) {
generationConfig.maxOutputTokens = Math.floor(thinkingBudget) + 1;
}
// Final cap (after the thinkingBudget bump may have raised the value):
// GitHub Copilot Agent envelopes commonly carry oversized maxOutputTokens
// (32K–65K) that trigger upstream 400 "Invalid Argument". Clamp silently
// — the cap is provider-driven, not client-driven, and only matters when
// the request would otherwise be rejected outright.
const cap = resolveAntigravityOutputCap(modelId);
const finalMax = Number(generationConfig.maxOutputTokens);
if (Number.isFinite(finalMax) && finalMax > cap) {
generationConfig.maxOutputTokens = cap;
}
request.generationConfig = generationConfig;
}
// Test-only export so the unit suite can exercise the cap logic in isolation
// without spinning up the full executor.
export const __test_applyAntigravityGenerationDefaults = applyAntigravityGenerationDefaults;
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
/**
* Known competing-agent identity sentences that Antigravity's server-side
* filter flags, answering with a 429 RESOURCE_EXHAUSTED (port of
* decolua/9router b566b20, generalized). Only the identity sentence is
* removed — surrounding instruction text is untouched.
*/
const COMPETITIVE_AGENT_PROMPT_PATTERNS: RegExp[] = [
/\byou are a claude agent\b[^\n]*/i,
/\bbuilt on anthropic's claude agent sdk\b[^\n]*/i,
/\byou are claude code\b[^\n]*/i,
/\byou are an ai assistant created by anthropic\b[^\n]*/i,
];
/**
* Strip competing-agent identity sentences from systemInstruction.parts.
* Returns the original reference when nothing matched (no allocation).
*/
export function stripCompetitiveAgentPrompts(systemInstruction: unknown): unknown {
const record = asRecord(systemInstruction);
const parts = Array.isArray(record?.parts) ? (record.parts as Array<Record<string, unknown>>) : [];
if (parts.length === 0) return systemInstruction;
let changed = false;
const newParts = parts.map((part) => {
if (typeof part.text !== "string" || part.text.length === 0) return part;
let text = part.text;
for (const pattern of COMPETITIVE_AGENT_PROMPT_PATTERNS) {
const stripped = text.replace(pattern, "").replace(/\n{3,}/g, "\n\n").trimStart();
if (stripped !== text) {
changed = true;
text = stripped;
}
}
return text === part.text ? part : { ...part, text };
});
return changed ? { ...record, parts: newParts } : systemInstruction;
}
function getAntigravitySafetySettings(safetySettings: unknown): unknown[] | undefined {
if (!Array.isArray(safetySettings)) return undefined;
return safetySettings.filter((setting) => {
const category = asRecord(setting)?.category;
return typeof category !== "string" || !ANTIGRAVITY_UNSUPPORTED_SAFETY_CATEGORIES.has(category);
});
}
function sanitizeAntigravityGeminiRequest(
request: Record<string, unknown>
): Record<string, unknown> {
const clean: Record<string, unknown> = {};
if (Array.isArray(request.contents)) {
clean.contents = request.contents;
}
if (asRecord(request.systemInstruction)) {
// #10420: strip competing-agent identity sentences (e.g. "You are a
// Claude agent, built on Anthropic's Claude Agent SDK.") that Antigravity
// flags and answers with 429 RESOURCE_EXHAUSTED.
clean.systemInstruction = stripCompetitiveAgentPrompts(request.systemInstruction);
}
clean.generationConfig = asRecord(request.generationConfig)
? { ...(request.generationConfig as Record<string, unknown>) }
: {};
const geminiTools = buildGeminiTools(request.tools);
if (geminiTools) {
clean.tools = geminiTools;
clean.toolConfig = { functionCallingConfig: { mode: "VALIDATED" } };
} else if (asRecord(request.toolConfig)) {
clean.toolConfig = request.toolConfig;
}
if (typeof request.sessionId === "string") {
clean.sessionId = request.sessionId;
}
// Preserve only caller-supplied safetySettings through the Claude-path whitelist.
// Missing settings stay absent so OmniRoute does not silently weaken upstream safety.
if (Array.isArray(request.safetySettings)) {
clean.safetySettings = request.safetySettings;
}
return clean;
}
/**
* Ported from decolua/9router#2321 (anki1kr): Vertex AI (used by Antigravity for
* Claude-branded models) rejects a conversation ending on an assistant turn —
* "This model does not support assistant message prefill" — so the request must
* always end on a user turn. Upstream patched `openaiToClaudeRequestForAntigravity`
* (dead code here, zero callers — see `open-sse/translator/request/openai-to-claude.ts`);
* this relocates the same strip to the LIVE Antigravity dispatch path, where Claude
* requests are converted to Gemini `contents` (assistant role is `"model"`, not
* `"assistant"`). Mirrors the trailing-strip pop-loop already used for Mistral
* (#3396), Copilot (#5802), and the CC-bridge in `claudeCodeCompatible.ts`.
*
* Wired in by the caller for both the Claude path (`isClaude`) and native Gemini
* models (`isGemini`, #10104) — newer Gemini endpoints reject a trailing `model` turn
* with the same "ending with a model turn" class of 400 that Claude hits via Vertex.
* Other model families routed through Antigravity are left untouched.
*
* Guard: never strip `contents` down to empty — an empty `contents` array is itself
* an invalid request, so at least one entry (even a lone trailing "model" turn) is
* always preserved.
*/
function stripTrailingAntigravityAssistantTurn(
request: Record<string, unknown>
): Record<string, unknown> {
const contents = request.contents;
if (!Array.isArray(contents) || contents.length === 0) {
return request;
}
while (
contents.length > 1 &&
(contents[contents.length - 1] as AntigravityContent)?.role === "model"
) {
contents.pop();
}
return request;
}
/**
* Newer Antigravity Gemini chat families reject a request ending on a model turn.
* Keep this explicit rather than matching every model containing "gemini": image
* generation has a separate request contract, and the older 2.5 family is not part
* of the rejection evidence for #10104.
*/
function isAntigravityGeminiChatModel(upstreamModel: string): boolean {
const normalizedModel = upstreamModel.toLowerCase();
if (/(?:^|-)image(?:-|$)/.test(normalizedModel)) {
return false;
}
return /^gemini-(?:3(?:\.\d+)?(?:-[a-z0-9-]+)?|pro-agent)$/.test(normalizedModel);
}
// Test-only export so the unit suite can exercise the strip logic directly.
export const __test_stripTrailingAntigravityAssistantTurn = stripTrailingAntigravityAssistantTurn;
type AntigravityCreditsRetryState = { attempted: boolean };
/** Base per-url-index attempt context, before the request has been sent. */
type AntigravityAttemptContext = {
url: string;
model: string;
/** Pre-serialization headers (built by buildHeaders + mergeUpstreamExtraHeaders) — the
* credits-retry re-serializes from these, NOT from `finalHeaders` (already fingerprinted). */
headers: Record<string, string>;
transformedBody: Record<string, unknown>;
credentials: AntigravityCredentials;
stream: boolean;
signal: AbortSignal | null | undefined;
log: SafeAntigravityLog;
accountId: string;
creditsMode: ReturnType<typeof getCreditsMode>;
creditsRetryState: AntigravityCreditsRetryState;
urlIndex: number;
retryAttemptsByUrl: Record<number, number>;
fallbackCount: number;
};
/** Context threaded through the 429/503 handling helpers — adds the sent response. */
type AntigravityRateLimitContext = AntigravityAttemptContext & {
response: Response;
finalHeaders: Record<string, string>;
};
/**
* Outcome of handling a 429/503 response — tells executeOnce()'s loop what to do next.
* `lastStatus` mirrors the original inline code, which only updated the outer
* `lastStatus` variable when NOT retrying the same url (i.e. on retryNextUrl/fallthrough,
* never on the bounded-short-retry or transient-auto-retry same-url paths).
*/
type AntigravityRateLimitOutcome =
| { action: "return"; result: SsePassthroughResult }
| { action: "retrySameUrl" }
| { action: "retryNextUrl"; lastStatus: number }
| { action: "fallthrough"; retryMs: number | null; lastStatus: number };
/** Outcome of one full per-url attempt in executeOnce() — return a result, or retry. */
type AntigravityAttemptOutcome =
| { action: "return"; result: SsePassthroughResult }
| { action: "retry"; sameUrl: boolean; lastStatus?: number };
export class AntigravityExecutor extends BaseExecutor {
constructor() {
super("antigravity", PROVIDERS.antigravity);
}
override shouldRetry(status: number, urlIndex: number): boolean {
return (
(status === HTTP_STATUS.RATE_LIMITED ||
status === HTTP_STATUS.NOT_FOUND ||
status === HTTP_STATUS.BAD_GATEWAY ||
status === HTTP_STATUS.SERVICE_UNAVAILABLE ||
status === HTTP_STATUS.GATEWAY_TIMEOUT) &&
urlIndex + 1 < this.getFallbackCount()
);
}
buildUrl(model: string, _stream: boolean, urlIndex = 0): string {
void model;
const baseUrls = this.getBaseUrls();
const baseUrl = baseUrls[urlIndex] || baseUrls[0];
// Always use streaming endpoint — the non-streaming `generateContent` causes
// upstream 400 errors for some models (e.g. gpt-oss-120b-medium) because the
// Cloud Code API internally converts to OpenAI format and injects
// stream_options without setting stream=true. chatCore already handles
// SSE→JSON conversion for non-streaming client requests.
return `${baseUrl}/v1internal:streamGenerateContent?alt=sse`;
}
buildHeaders(credentials: AntigravityCredentials, _stream = true): Record<string, string> {
const clientProfile = getAntigravityClientProfile(credentials);
const raw = {
...getAntigravityContentHeaders(clientProfile, credentials.accessToken),
Accept: "text/event-stream",
};
// Scrub proxy/fingerprint headers that reveal non-native traffic
return scrubProxyAndFingerprintHeaders(raw);
}
async transformRequest(
model: string,
body: unknown,
_stream: boolean,
credentials: AntigravityCredentials,
modelIdOverride?: string,
signal?: AbortSignal
): Promise<AntigravityRequestEnvelope | Response> {
// Project ID resolution: prefer OAuth-stored projectId over incoming body.project
// to avoid stale/wrong client-side values causing 404/403 from Cloud Code endpoints.
// Opt-in escape hatch: set OMNIROUTER_ALLOW_BODY_PROJECT_OVERRIDE=1.
const normalizeProjectId = (value: unknown): string | null => {
if (typeof value !== "string") return null;
const trimmedValue = value.trim();
return trimmedValue ? trimmedValue : null;
};
const bodyRecord = asRecord(body) ?? {};
const bodyProjectId = normalizeProjectId(bodyRecord.project);
const credentialsProjectId = normalizeProjectId(credentials?.projectId);
const providerSpecificProjectId = normalizeProjectId(
(credentials?.providerSpecificData as Record<string, unknown> | undefined)?.projectId
);
const allowBodyProjectOverride = process.env.OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE === "1";
// Default: prefer OAuth-stored projectId over incoming body.project to avoid
// stale/wrong client-side values causing 404/403 from Cloud Code endpoints.
// Opt-in escape hatch: set OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE=1.
let projectId =
allowBodyProjectOverride && bodyProjectId
? bodyProjectId
: credentialsProjectId || providerSpecificProjectId || bodyProjectId;
// Auto-discover a missing projectId via loadCodeAssist before failing (#2334/#2541).
// A freshly re-added Antigravity account can have an empty stored projectId even when
// its Google account already owns a Cloud Code project (the OAuth-time loadCodeAssist
// returned empty/transiently failed). Mirror the Cloud Code bootstrap to recover it
// here — the helper memoizes per access-token, so this is a one-time round-trip.
let requiresManualProject = false;
if (!projectId && credentials?.accessToken) {
const discovered = await ensureAntigravityProjectAssigned(
credentials.accessToken,
fetch,
getAntigravityClientProfile(credentials),
signal
);
if (discovered && discovered !== ANTIGRAVITY_REQUIRES_MANUAL_PROJECT) {
projectId = discovered;
// #8491: persist the recovered id so it survives the next token refresh
// or process restart instead of being silently rediscovered every time.
await persistDiscoveredAntigravityProjectId(
credentials.connectionId,
discovered,
credentials.providerSpecificData
);
}
requiresManualProject = discovered === ANTIGRAVITY_REQUIRES_MANUAL_PROJECT;
}
if (!projectId) {
markAntigravityMissingCloudCodeProject(credentials?.connectionId);
if (requiresManualProject) {
// Google no longer auto-creates GCP projects for standard-tier
// accounts (tracked in #8491): fail fast with a clear instruction
// instead of the generic 422 — a fabricated/omitted id only earns a
// delayed 429 RESOURCE_EXHAUSTED from Google's quota check.
const errorBody = {
error: {
message:
"GCP_PROJECT_REQUIRED: Google Antigravity now requires a free GCP Project ID. " +
"Create one at console.cloud.google.com and enter it in Providers → Antigravity " +
"(connection settings → Project ID). Automatic project creation is no longer " +
"available for personal accounts.",
type: "gcp_project_required",
code: "gcp_project_required",
},
};
// 422, not 403: chatCore's generic "401/403 → refresh credentials and
// retry" path would otherwise hit Google's OAuth token endpoint on
// every request from an affected account — pointless, since refreshing
// the token cannot create a GCP project. 422 also matches the sibling
// missing_project_id error, which the client already maps to a clear
// "action needed" prompt.
const resp = new Response(JSON.stringify(errorBody), {
status: 422,
headers: { "Content-Type": "application/json" },
});
// Returning a Response object signals the executor to stop and forward it
return resp as unknown as never;
}
// (#489) Return a structured error instead of throwing — gives the client a clear signal
// to show a "Reconnect OAuth" prompt rather than an opaque "Internal Server Error".
const errorMsg =
"Missing Google projectId for Antigravity account. Auto-discovery via loadCodeAssist " +
"found no Cloud Code project. Please reconnect OAuth in Providers → Antigravity (and " +
"ensure the Google account has completed Gemini Code Assist onboarding).";
const errorBody = {
error: {
message: errorMsg,
type: "oauth_missing_project_id",
code: "missing_project_id",
},
};
const resp = new Response(JSON.stringify(errorBody), {
status: 422,
headers: { "Content-Type": "application/json" },
});
// Returning a Response object signals the executor to stop and forward it
return resp as unknown as never;
}
// Validate projectId is non-empty and not just whitespace
const trimmedProjectId = typeof projectId === "string" ? projectId.trim() : projectId;
if (!trimmedProjectId) {
const resp = new Response(
JSON.stringify({
error: {
message:
"Invalid (empty) Google projectId for Antigravity account. " +
"Please reconnect OAuth in Providers → Antigravity.",
type: "oauth_missing_project_id",
code: "missing_project_id",
},
}),
{ status: 422, headers: { "Content-Type": "application/json" } }
);
return resp as unknown as never;
}
const upstreamModel = await cleanModelName(model, modelIdOverride);
const isClaude = upstreamModel.toLowerCase().includes("claude");
// #10104: newer Gemini endpoints reject a request ending on a `model` turn with
// HTTP 400 "Requests ending with a model turn are not supported" — the same
// rejection surface Claude hits via Vertex (see stripTrailingAntigravityAssistantTurn's
// doc comment above). Native Gemini models routed through Antigravity (`agy/gemini-*`,
// e.g. the Gemini 3.x Flash/Pro tiers from PR #8013's catalog) need the same guarded
// strip. Scoped to models whose id names Gemini so unrelated model families are
// untouched; the strip itself never empties `contents` (see the guard above).
const isGemini = isAntigravityGeminiChatModel(upstreamModel);
const baseBody = bodyRecord;
const normalizedBody = shouldStripCloudCodeThinking(this.provider, upstreamModel)
? stripCloudCodeThinkingConfig(baseBody)
: baseBody;
const normalizedRequest = asRecord(normalizedBody.request);
const rawContents = Array.isArray(normalizedRequest?.contents)
? normalizedRequest.contents
: [];
// Fix contents for Gemini-compatible Cloud Code requests via Antigravity.
// Claude-branded Antigravity models use the same streamGenerateContent schema.
const normalizedContents: AntigravityContent[] =
rawContents.map((content): AntigravityContent => {
const c = content as AntigravityChunkContent;
let role = typeof c.role === "string" ? c.role : "user";
if (c.parts?.some((p) => p.functionResponse)) {
role = "user";
}
const hasFunctionCall = c.parts?.some((p) => p.functionCall) || false;
const parts =
c.parts?.filter((p) => {
if (typeof p.text === "string" && p.text === "") return false;
if (p.functionCall && !p.functionCall.name) return false;
// Only strip if it's NOT our bypass sentinel.
// Antigravity models (like Gemini) need this sentinel to bypass 400 errors.
return (
!p.thought &&
(hasFunctionCall ||
!p.thoughtSignature ||
p.thoughtSignature === "skip_thought_signature_validator")
);
}) || [];
return { ...c, role, parts };
}) || [];
const contents: AntigravityContent[] = [];
for (const c of normalizedContents) {
if (!Array.isArray(c.parts) || c.parts.length === 0) continue;
if (contents.length > 0 && contents[contents.length - 1].role === c.role) {
contents[contents.length - 1].parts.push(...c.parts);
} else {
contents.push(c);
}
}
const safetySettings = getAntigravitySafetySettings(normalizedRequest?.safetySettings);
const rawTransformedRequest = {
...normalizedRequest,
...(contents.length > 0 && { contents }),
sessionId: getAntigravitySessionId(
credentials,
typeof normalizedRequest?.sessionId === "string" ? normalizedRequest.sessionId : undefined
),
...(safetySettings !== undefined && { safetySettings }),
toolConfig:
Array.isArray(normalizedRequest?.tools) && normalizedRequest.tools.length > 0
? { functionCallingConfig: { mode: "VALIDATED" } }
: normalizedRequest?.toolConfig,
};
// Note: sanitizeAntigravityGeminiRequest() applies a Claude-only field whitelist
// (dropping fields native Gemini requests may legitimately carry), so the Gemini
// branch only runs the trailing-turn strip — never the sanitize/whitelist step.
const transformedRequest = isClaude
? stripTrailingAntigravityAssistantTurn(
sanitizeAntigravityGeminiRequest(rawTransformedRequest)
)
: isGemini
? stripTrailingAntigravityAssistantTurn(rawTransformedRequest)
: rawTransformedRequest;
applyAntigravityGenerationDefaults(transformedRequest, upstreamModel);
const {
project: _project,
model: _model,
userAgent: _userAgent,
requestType: _requestType,
requestId: _requestId,
request: _request,
// #1944: output_config (and the legacy output_format) are Anthropic/Claude-Code-only
// fields. Google's Cloud Code envelope rejects unknown top-level fields with a 400
// ("Invalid JSON payload received. Unknown name \"output_config\""), which broke every
// Claude model served via Antigravity. Drop them so they never reach the envelope.
output_config: _outputConfig,
output_format: _outputFormat,
// #1926: the unified thinking adapter can also set Claude/OpenAI-native thinking fields
// at the body root. Google rejects them with `400 Bad input: oneOf at '/' not met`
// (or `Unknown name "thinking"`), breaking every reasoning/thinking model served via
// Antigravity (e.g. claude-opus-4-x-thinking). Strip the whole thinking family too.
thinking: _thinking,
reasoning_effort: _reasoningEffort,
reasoning: _reasoning,
enable_thinking: _enableThinking,
thinking_budget: _thinkingBudget,
enabledCreditTypes: _enabledCreditTypes,
...passthroughFields
} = normalizedBody;
const requestType = _requestType === "image_gen" ? "image_gen" : "agent";
const envelope: AntigravityRequestEnvelope = {
project: projectId,
requestId: generateAntigravityRequestId(),
request: transformedRequest,
model: upstreamModel,
userAgent: getAntigravityEnvelopeUserAgent(credentials),
requestType,
...passthroughFields,
};
return envelope;
}
async refreshCredentials(
credentials: AntigravityCredentials,
log?: ExecutorLog | null
): Promise<AntigravityCredentials | null> {
if (!credentials.refreshToken) return null;
try {
const bodyParams: Record<string, string> = {
grant_type: "refresh_token",
refresh_token: credentials.refreshToken,
};
// Only include non-empty client_id/client_secret — Google OAuth rejects
// empty params which raw URLSearchParams produces (buildFormParams semantics).
if (this.config.clientId) bodyParams.client_id = this.config.clientId;
if (this.config.clientSecret) bodyParams.client_secret = this.config.clientSecret;
const response = await fetch(OAUTH_ENDPOINTS.google.token, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
"User-Agent": getAntigravityOAuthUserAgent(getAntigravityClientProfile(credentials)),
},
body: new URLSearchParams(bodyParams),
});
if (!response.ok) {
// Detect unrecoverable token (invalid_grant = revoked / expired refresh token)
try {
const errorBody = (await response.json()) as Record<string, unknown>;
if (errorBody.error === "invalid_grant") {
log?.error?.("TOKEN", "Antigravity refresh token revoked. Re-authentication required.");
return { error: "unrecoverable_refresh_error" } as unknown as AntigravityCredentials;
}
} catch {
// not JSON — fall through
}
return null;
}
const tokens = (await response.json()) as Record<string, unknown>;
log?.info?.("TOKEN", "Antigravity refreshed");
const newAccessToken =
typeof tokens.access_token === "string" ? tokens.access_token : undefined;
// Discover projectId if the stored value is empty. The initial OAuth exchange
// may have failed to populate it (network timeout, account not yet onboarded to
// Gemini Code Assist). The runtime transformRequest path already does this, but
// a proactive discovery here prevents 422 errors on the next request when the
// per-token memoization cache is invalidated by the new access token.
let projectId = credentials.projectId?.trim() || "";
if (!projectId && newAccessToken) {
try {
const discovered = await ensureAntigravityProjectAssigned(
newAccessToken,
fetch,
getAntigravityClientProfile(credentials),
AbortSignal.timeout(8_000)
);
if (discovered) {
projectId = discovered;
await persistDiscoveredAntigravityProjectId(
credentials.connectionId,
discovered,
credentials.providerSpecificData
);
const okMsg = `Antigravity projectId discovered during refresh: ${discovered}`;
log?.info?.("TOKEN", okMsg);
}
} catch (discoveryError) {
// Best-effort: if discovery fails, the runtime path will retry on next request.
const msg =
discoveryError instanceof Error ? discoveryError.message : String(discoveryError);
log?.warn?.("TOKEN", `Antigravity projectId discovery during refresh failed: ${msg}`);
}
}
return {
accessToken: newAccessToken,
refreshToken:
typeof tokens.refresh_token === "string" && tokens.refresh_token
? tokens.refresh_token
: credentials.refreshToken,
expiresIn: typeof tokens.expires_in === "number" ? tokens.expires_in : undefined,
projectId,
// Preserve providerSpecificData so a projectId stored there survives the refresh
// (the onCredentialsRefreshed DB write) instead of being dropped → 422 (#2480).
providerSpecificData: credentials.providerSpecificData,
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
log?.error?.("TOKEN", `Antigravity refresh error: ${message}`);
return null;
}
}
generateSessionId(): string {
return `-${parseInt(randomUUID().replace(/-/g, "").substring(0, 8), 16) % 9_000_000_000_000_000_000}`;
}
parseRetryHeaders(headers: Headers | null | undefined): number | null {
if (!headers?.get) return null;
const retryAfter = headers.get("retry-after");
if (retryAfter) {
const seconds = parseInt(retryAfter, 10);
if (!isNaN(seconds) && seconds > 0) return seconds * 1000;
const date = new Date(retryAfter);
if (!isNaN(date.getTime())) {
const diff = date.getTime() - Date.now();
return diff > 0 ? diff : null;
}
}
const resetAfter = headers.get("x-ratelimit-reset-after");
if (resetAfter) {
const seconds = parseInt(resetAfter, 10);
if (!isNaN(seconds) && seconds > 0) return seconds * 1000;
}
const resetTimestamp = headers.get("x-ratelimit-reset");
if (resetTimestamp) {
const ts = parseInt(resetTimestamp, 10) * 1000;
const diff = ts - Date.now();
return diff > 0 ? diff : null;
}
return null;
}
// Parse retry time from Antigravity error message body
// Format: "Your quota will reset after 2h7m23s" or "Resets in 160h27m24s" or
// "1h30m" or "45m" or "30s". The optional plural ("resets in") must match too (#1308).
parseRetryFromErrorMessage(errorMessage: unknown): number | null {
if (!errorMessage || typeof errorMessage !== "string") return null;
const match = errorMessage.match(/resets? (?:after|in) (\d+h)?(\d+m)?(\d+s)?/i);
if (!match) return null;
let totalMs = 0;
if (match[1]) totalMs += parseInt(match[1]) * 3600 * 1000; // hours
if (match[2]) totalMs += parseInt(match[2]) * 60 * 1000; // minutes
if (match[3]) totalMs += parseInt(match[3]) * 1000; // seconds
// "reset after 0s" = burst/RPM limit, not quota exhaustion.
// Return a minimum backoff so the auto-retry loop handles it
// instead of falling through to the 24h exhaustion classifier.
if (totalMs === 0) return 2_000; // 2s minimum burst-limit backoff
return totalMs;
}
/**
* Flatten an Antigravity error JSON + raw body text into a single string so
* isTransientAntigravityError can match against body patterns.