tuxevil-rotator 4.4.9 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +2 -1
- package/package.json +1 -1
- package/src/access-probe.ts +1 -1
- package/src/account-store.ts +14 -2
- package/src/audio-transcription.ts +1 -0
- package/src/auto-model-access.ts +22 -0
- package/src/compat/model-specs.ts +7 -0
- package/src/compat/schema-sanitizer.ts +420 -287
- package/src/compat.ts +110 -66
- package/src/config-defaults.ts +7 -0
- package/src/fetch-with-retry.ts +294 -16
- package/src/idempotency.ts +3 -1
- package/src/model-access-api.ts +9 -1
- package/src/model-access.ts +2 -2
- package/src/notification-poller.ts +9 -1
- package/src/provider-catalog-evidence.ts +18 -1
- package/src/providers/adapter.ts +5 -0
- package/src/providers/credential-helpers.ts +34 -0
- package/src/providers/google-antigravity/aicode-eligibility.ts +256 -0
- package/src/providers/google-antigravity/aicode-forward.ts +381 -0
- package/src/providers/google-antigravity/aicode.ts +478 -0
- package/src/providers/google-antigravity/catalog.ts +6 -0
- package/src/providers/google-antigravity/code-assist.ts +53 -41
- package/src/providers/google-antigravity/dynamic-catalog.ts +72 -7
- package/src/providers/google-antigravity/forward.ts +309 -86
- package/src/providers/google-antigravity/index.ts +67 -6
- package/src/providers/google-antigravity/oauth.ts +22 -12
- package/src/providers/google-antigravity/quota.ts +781 -34
- package/src/providers/google-antigravity/translators.ts +55 -46
- package/src/providers/google-antigravity/twin-payload.ts +231 -0
- package/src/providers/ollama/quota.ts +6 -4
- package/src/providers/openai-codex/compat.ts +11 -2
- package/src/providers/openai-codex/quota.ts +2 -1
- package/src/providers/opencode-zen/catalog.ts +159 -13
- package/src/providers/opencode-zen/discovery.ts +50 -0
- package/src/providers/opencode-zen/index.ts +7 -2
- package/src/providers/opencode-zen/quota.ts +14 -1
- package/src/proxy.ts +570 -87
- package/src/quota-pools.ts +76 -1
- package/src/rate-limit-parser.ts +239 -19
- package/src/rotator.ts +602 -138
- package/src/stream-guards.ts +87 -1
- package/src/telemetry.ts +17 -3
- package/src/types.ts +168 -9
- package/src/validators.ts +3 -0
- package/src/web/lib/accounts.ts +2 -0
- package/src/web/lib/attention.ts +19 -0
- package/src/web/lib/models.ts +6 -1
- package/src/web/lib/status.ts +22 -4
- package/src/web/pages/AccountDetail.tsx +49 -2
- package/src/web/pages/Accounts.tsx +38 -3
- package/src/web/pages/ModelAccess.tsx +4 -0
- package/src/web/pages/Models.tsx +2 -1
- package/src/web/pages/Overview.tsx +15 -1
- package/src/web/styles/app.css +73 -3
- package/tools/telemetry-receiver/receiver.js +444 -243
|
@@ -268,6 +268,7 @@ export class DynamicModelRegistry {
|
|
|
268
268
|
accountId = DEFAULT_ACCOUNT_KEY,
|
|
269
269
|
credentialGeneration?: string,
|
|
270
270
|
accountEpoch?: number,
|
|
271
|
+
poolOverrides?: ReadonlyMap<string, string>,
|
|
271
272
|
): number {
|
|
272
273
|
const data = parseGoogleQuotaResponse(value);
|
|
273
274
|
if (!data) return 0;
|
|
@@ -293,7 +294,16 @@ export class DynamicModelRegistry {
|
|
|
293
294
|
const lowerId = normalizedId.toLowerCase();
|
|
294
295
|
if (!isDiscoverableModelId(normalizedId)) continue;
|
|
295
296
|
|
|
296
|
-
const { family, quotaPool } = DynamicModelRegistry.inferFamilyAndPool(normalizedId);
|
|
297
|
+
const { family, quotaPool: inferredPool } = DynamicModelRegistry.inferFamilyAndPool(normalizedId);
|
|
298
|
+
const overridePool = poolOverrides?.get(lowerId);
|
|
299
|
+
const quotaPool =
|
|
300
|
+
overridePool &&
|
|
301
|
+
overridePool !== "__proto__" &&
|
|
302
|
+
overridePool !== "constructor" &&
|
|
303
|
+
overridePool !== "prototype" &&
|
|
304
|
+
/^[a-z0-9][a-z0-9._:-]{0,63}$/.test(overridePool)
|
|
305
|
+
? overridePool
|
|
306
|
+
: inferredPool;
|
|
297
307
|
const familySpec = familyDefaults(family);
|
|
298
308
|
const staticSpec = getStaticModelSpec(normalizedId);
|
|
299
309
|
const defaults = previous?.get(lowerId) ?? {
|
|
@@ -543,9 +553,21 @@ export class DynamicModelRegistry {
|
|
|
543
553
|
const models = new Map<string, DynamicModelEntry>();
|
|
544
554
|
let valid = true;
|
|
545
555
|
for (const raw of snapshot.models) {
|
|
546
|
-
if (!isRecord(raw)
|
|
556
|
+
if (!isRecord(raw)) {
|
|
557
|
+
valid = false;
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
const validPool =
|
|
561
|
+
typeof raw.quotaPool === "string" &&
|
|
562
|
+
raw.quotaPool.length > 0 &&
|
|
563
|
+
raw.quotaPool.length <= 64 &&
|
|
564
|
+
/^[a-z0-9][a-z0-9._:-]*$/.test(raw.quotaPool) &&
|
|
565
|
+
raw.quotaPool !== "__proto__" &&
|
|
566
|
+
raw.quotaPool !== "constructor" &&
|
|
567
|
+
raw.quotaPool !== "prototype";
|
|
568
|
+
if (typeof raw.id !== "string" || !isDiscoverableModelId(raw.id) ||
|
|
547
569
|
typeof raw.family !== "string" || !isSafeModelId(raw.family) ||
|
|
548
|
-
|
|
570
|
+
!validPool ||
|
|
549
571
|
!["ctx", "maxOutputTokens"].every((key) => typeof raw[key] === "number" && Number.isFinite(raw[key]) && raw[key] > 0) ||
|
|
550
572
|
typeof raw.thinkingBudget !== "number" || !Number.isFinite(raw.thinkingBudget) || raw.thinkingBudget < -1 ||
|
|
551
573
|
(raw.thinkingBudget < 0 && raw.thinkingBudget !== -1) ||
|
|
@@ -662,10 +684,14 @@ export class DynamicModelRegistry {
|
|
|
662
684
|
const quotaPool = typeof rawPool === "string"
|
|
663
685
|
? rawPool.trim().toLowerCase()
|
|
664
686
|
: "";
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
687
|
+
const validPool =
|
|
688
|
+
quotaPool.length > 0 &&
|
|
689
|
+
quotaPool.length <= 64 &&
|
|
690
|
+
/^[a-z0-9][a-z0-9._:-]*$/.test(quotaPool) &&
|
|
691
|
+
quotaPool !== "__proto__" &&
|
|
692
|
+
quotaPool !== "constructor" &&
|
|
693
|
+
quotaPool !== "prototype";
|
|
694
|
+
if (!isDiscoverableModelId(id) || !validPool) continue;
|
|
669
695
|
this.discoveredModels.set(id.toLowerCase(), { id, quotaPool });
|
|
670
696
|
}
|
|
671
697
|
}
|
|
@@ -699,6 +725,45 @@ export class DynamicModelRegistry {
|
|
|
699
725
|
this.discoveredModels.get(lowerId)?.quotaPool;
|
|
700
726
|
}
|
|
701
727
|
|
|
728
|
+
resolveQuotaPoolForAccount(accountId: string, id: string): string | undefined {
|
|
729
|
+
const lowerId = id.trim().toLowerCase();
|
|
730
|
+
return this.accountModels.get(accountKey(accountId))?.get(lowerId)?.quotaPool ??
|
|
731
|
+
this.resolveQuotaPool(lowerId);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
hasQuotaPool(poolKey: string, accountId?: string): boolean {
|
|
735
|
+
const targetPool = poolKey.trim().toLowerCase();
|
|
736
|
+
if (!targetPool) return false;
|
|
737
|
+
if (accountId) {
|
|
738
|
+
const scoped = this.accountModels.get(accountKey(accountId));
|
|
739
|
+
if (scoped) {
|
|
740
|
+
for (const entry of scoped.values()) {
|
|
741
|
+
if (entry.quotaPool === targetPool) return true;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
for (const accountCatalog of this.accountModels.values()) {
|
|
746
|
+
for (const entry of accountCatalog.values()) {
|
|
747
|
+
if (entry.quotaPool === targetPool) return true;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
for (const entry of this.discoveredModels.values()) {
|
|
751
|
+
if (entry.quotaPool === targetPool) return true;
|
|
752
|
+
}
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
getModelsForQuotaPool(quotaPool: string, accountId?: string): DynamicModelEntry[] {
|
|
757
|
+
const targetPool = quotaPool.trim().toLowerCase();
|
|
758
|
+
if (accountId) {
|
|
759
|
+
const scoped = this.accountModels.get(accountKey(accountId));
|
|
760
|
+
return scoped
|
|
761
|
+
? Array.from(scoped.values()).filter((entry) => entry.quotaPool === targetPool)
|
|
762
|
+
: [];
|
|
763
|
+
}
|
|
764
|
+
return this.getAllModels().filter((entry) => entry.quotaPool === targetPool);
|
|
765
|
+
}
|
|
766
|
+
|
|
702
767
|
getDefaultAgentModelId(): string | null {
|
|
703
768
|
return Array.from(this.defaultAgentModelIds.values()).at(-1) ?? null;
|
|
704
769
|
}
|
|
@@ -4,8 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
import {
|
|
6
6
|
ANTIGRAVITY_ENDPOINTS,
|
|
7
|
-
REQUEST_CLIENT_METADATA,
|
|
8
|
-
REQUEST_GOOG_API_CLIENT,
|
|
9
7
|
REQUEST_USER_AGENT,
|
|
10
8
|
applyModelAlias,
|
|
11
9
|
} from "../../types.js";
|
|
@@ -16,9 +14,22 @@ import type { TokenUsage } from "../adapter.js";
|
|
|
16
14
|
import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
|
|
17
15
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
18
16
|
import {
|
|
17
|
+
ANTIGRAVITY_HEADERS_TIMEOUT_MS,
|
|
19
18
|
fetchWithHeadersTimeout,
|
|
19
|
+
isRetryableFetchError,
|
|
20
|
+
runWithAntigravityApiRetry,
|
|
21
|
+
type AntigravityApiRetryOptions,
|
|
20
22
|
type RequestInitWithDispatcher,
|
|
21
23
|
} from "../../fetch-with-retry.js";
|
|
24
|
+
import {
|
|
25
|
+
extractRetryDelayMs,
|
|
26
|
+
isAntigravityRetryableError,
|
|
27
|
+
} from "../../rate-limit-parser.js";
|
|
28
|
+
import { applyAntigravityTwinPayload } from "./twin-payload.js";
|
|
29
|
+
import {
|
|
30
|
+
forwardAicodeRequestOnce,
|
|
31
|
+
resolveAicodeTarget,
|
|
32
|
+
} from "./aicode-forward.js";
|
|
22
33
|
|
|
23
34
|
const forwardLogger = logger.child("google-forward");
|
|
24
35
|
|
|
@@ -261,7 +272,7 @@ const BENCHMARK_MAX_OUTPUT_TOKENS = 16;
|
|
|
261
272
|
const BENCHMARK_TIMEOUT_MS = 30_000;
|
|
262
273
|
|
|
263
274
|
function benchmarkRequestBody(account: AccountRuntime): RequestBody {
|
|
264
|
-
return {
|
|
275
|
+
return applyAntigravityTwinPayload({
|
|
265
276
|
project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
|
|
266
277
|
model: BENCHMARK_MODEL,
|
|
267
278
|
request: {
|
|
@@ -275,7 +286,7 @@ function benchmarkRequestBody(account: AccountRuntime): RequestBody {
|
|
|
275
286
|
maxOutputTokens: BENCHMARK_MAX_OUTPUT_TOKENS,
|
|
276
287
|
},
|
|
277
288
|
},
|
|
278
|
-
};
|
|
289
|
+
});
|
|
279
290
|
}
|
|
280
291
|
|
|
281
292
|
function benchmarkUsage(raw: string): { outputTokens: number } | null {
|
|
@@ -316,89 +327,79 @@ export const GOOGLE_BENCHMARK_CONSTANTS = {
|
|
|
316
327
|
timeoutMs: BENCHMARK_TIMEOUT_MS,
|
|
317
328
|
} as const;
|
|
318
329
|
|
|
330
|
+
export interface ForwardRequestOptions {
|
|
331
|
+
/**
|
|
332
|
+
* Controls Antigravity single-account / non-rotating retry handling via
|
|
333
|
+
* `runWithAntigravityApiRetry`. Defaults to true for standalone calls; pass
|
|
334
|
+
* `{ apiRetry: false }` when an outer multi-account rotation loop owns retries.
|
|
335
|
+
*/
|
|
336
|
+
apiRetry?:
|
|
337
|
+
| boolean
|
|
338
|
+
| Partial<Omit<AntigravityApiRetryOptions<ForwardedResponse>, "fn">>;
|
|
339
|
+
}
|
|
340
|
+
|
|
319
341
|
/**
|
|
320
|
-
*
|
|
342
|
+
* Strict Antigravity CCPA wire header allowlist (twin to `ccpahttp` +
|
|
343
|
+
* `codeassistclient.setHeaders`): never leak third-party SDK or proxy headers.
|
|
321
344
|
*/
|
|
322
|
-
export
|
|
345
|
+
export function buildAntigravityWireHeaders(
|
|
323
346
|
account: AccountRuntime,
|
|
324
|
-
body: RequestBody,
|
|
325
347
|
originalHeaders: Record<string, string>,
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
// Swap credentials
|
|
329
|
-
body.project = getProviderProjectId(account.config, DEFAULT_PROVIDER);
|
|
330
|
-
|
|
331
|
-
// Map internal display/compat names to Google upstream names (single source
|
|
332
|
-
// of truth: src/types.ts:applyModelAlias)
|
|
333
|
-
body.model = applyModelAlias(body.model);
|
|
334
|
-
|
|
335
|
-
const {
|
|
336
|
-
displayModel: _displayModel,
|
|
337
|
-
requestedModel: _requestedModel,
|
|
338
|
-
catalogModel: _catalogModel,
|
|
339
|
-
providerId: _providerId,
|
|
340
|
-
selectionMode: _selectionMode,
|
|
341
|
-
selectionConfidence: _selectionConfidence,
|
|
342
|
-
selectionReason: _selectionReason,
|
|
343
|
-
...bodyToForward
|
|
344
|
-
} = body;
|
|
345
|
-
const requestBody = JSON.stringify(bodyToForward);
|
|
346
|
-
|
|
347
|
-
// Build headers: keep originals but swap Authorization
|
|
348
|
-
const forwardHeaders: Record<string, string> = {
|
|
349
|
-
...originalHeaders,
|
|
348
|
+
): Record<string, string> {
|
|
349
|
+
const headers: Record<string, string> = {
|
|
350
350
|
"Content-Type": "application/json",
|
|
351
|
-
|
|
351
|
+
Authorization: `Bearer ${account.accessToken ?? ""}`,
|
|
352
|
+
"User-Agent": REQUEST_USER_AGENT,
|
|
352
353
|
};
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
"
|
|
360
|
-
|
|
361
|
-
"proxy-authorization",
|
|
362
|
-
"te",
|
|
363
|
-
"trailers",
|
|
364
|
-
"transfer-encoding",
|
|
365
|
-
"upgrade",
|
|
366
|
-
// Forwarding / proxying artefacts that should never reach the upstream
|
|
367
|
-
"x-forwarded-for",
|
|
368
|
-
"x-forwarded-host",
|
|
369
|
-
"x-forwarded-proto",
|
|
370
|
-
"x-forwarded-port",
|
|
371
|
-
"x-real-ip",
|
|
372
|
-
"forwarded",
|
|
373
|
-
"via",
|
|
374
|
-
]);
|
|
375
|
-
for (const key of Object.keys(forwardHeaders)) {
|
|
376
|
-
const lowerKey = key.toLowerCase();
|
|
377
|
-
if (
|
|
378
|
-
HOP_BY_HOP.has(lowerKey) ||
|
|
379
|
-
lowerKey === "authorization" ||
|
|
380
|
-
lowerKey === "user-agent" ||
|
|
381
|
-
lowerKey === "x-goog-api-client" ||
|
|
382
|
-
lowerKey === "client-metadata"
|
|
383
|
-
) {
|
|
384
|
-
delete forwardHeaders[key];
|
|
354
|
+
let requestReason = "";
|
|
355
|
+
let userProjectHeader = "";
|
|
356
|
+
for (const [key, value] of Object.entries(originalHeaders)) {
|
|
357
|
+
const lower = key.toLowerCase();
|
|
358
|
+
if (lower === "x-goog-request-reason" && typeof value === "string" && value.trim()) {
|
|
359
|
+
requestReason = value.trim();
|
|
360
|
+
} else if (lower === "x-goog-user-project" && typeof value === "string" && value.trim()) {
|
|
361
|
+
userProjectHeader = value.trim();
|
|
385
362
|
}
|
|
386
363
|
}
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
if (/^claude-/i.test(body.model)) {
|
|
394
|
-
forwardHeaders["anthropic-beta"] = "interleaved-thinking-2025-05-14";
|
|
364
|
+
requestReason ||= process.env.GOOG_REQUEST_REASON?.trim() || "";
|
|
365
|
+
// Never default to the account projectId: Google-managed Antigravity projects
|
|
366
|
+
// lack the Cloud Code Private API for billing and answer 403 PERMISSION_DENIED.
|
|
367
|
+
userProjectHeader ||= process.env.GOOG_USER_PROJECT?.trim() || "";
|
|
368
|
+
if (requestReason) {
|
|
369
|
+
headers["X-Goog-Request-Reason"] = requestReason;
|
|
395
370
|
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
371
|
+
if (userProjectHeader) {
|
|
372
|
+
headers["X-Goog-User-Project"] = userProjectHeader;
|
|
373
|
+
}
|
|
374
|
+
return headers;
|
|
375
|
+
}
|
|
400
376
|
|
|
401
|
-
|
|
377
|
+
class RetryableAntigravityHttpError extends Error {
|
|
378
|
+
readonly status: number;
|
|
379
|
+
readonly serverRetryDelayMs?: number;
|
|
380
|
+
readonly fallbackResult: ForwardedResponse;
|
|
381
|
+
|
|
382
|
+
constructor(
|
|
383
|
+
status: number,
|
|
384
|
+
message: string,
|
|
385
|
+
serverRetryDelayMs: number | undefined,
|
|
386
|
+
fallbackResult: ForwardedResponse,
|
|
387
|
+
) {
|
|
388
|
+
super(message);
|
|
389
|
+
this.name = "RetryableAntigravityHttpError";
|
|
390
|
+
this.status = status;
|
|
391
|
+
this.serverRetryDelayMs = serverRetryDelayMs;
|
|
392
|
+
this.fallbackResult = fallbackResult;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function forwardRequestOnce(
|
|
397
|
+
account: AccountRuntime,
|
|
398
|
+
forwardHeaders: Record<string, string>,
|
|
399
|
+
requestBody: string,
|
|
400
|
+
signal?: AbortSignal,
|
|
401
|
+
): Promise<ForwardedResponse> {
|
|
402
|
+
// Try endpoints with cascade only on 404 (missing route), never replaying 401/403
|
|
402
403
|
for (
|
|
403
404
|
let endpointIdx = 0;
|
|
404
405
|
endpointIdx < ANTIGRAVITY_ENDPOINTS.length;
|
|
@@ -408,11 +409,11 @@ export async function forwardRequest(
|
|
|
408
409
|
const url = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
|
|
409
410
|
const isProd = endpointIdx === ANTIGRAVITY_ENDPOINTS.length - 1;
|
|
410
411
|
|
|
412
|
+
const controller = !isProd ? new AbortController() : undefined;
|
|
413
|
+
const timeout = controller
|
|
414
|
+
? setTimeout(() => controller.abort(), 10_000)
|
|
415
|
+
: undefined;
|
|
411
416
|
try {
|
|
412
|
-
const controller = !isProd ? new AbortController() : undefined;
|
|
413
|
-
const timeout = controller
|
|
414
|
-
? setTimeout(() => controller.abort(), 10_000)
|
|
415
|
-
: undefined;
|
|
416
417
|
const requestSignal =
|
|
417
418
|
controller?.signal && signal
|
|
418
419
|
? AbortSignal.any([controller.signal, signal])
|
|
@@ -423,20 +424,18 @@ export async function forwardRequest(
|
|
|
423
424
|
headers: forwardHeaders,
|
|
424
425
|
body: requestBody,
|
|
425
426
|
signal: requestSignal,
|
|
427
|
+
timeoutMs: ANTIGRAVITY_HEADERS_TIMEOUT_MS,
|
|
426
428
|
dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
|
|
427
429
|
} as RequestInitWithDispatcher);
|
|
428
|
-
if (timeout) clearTimeout(timeout);
|
|
429
430
|
|
|
430
431
|
if (
|
|
431
|
-
|
|
432
|
-
response.status === 403 ||
|
|
433
|
-
response.status === 404) &&
|
|
432
|
+
response.status === 404 &&
|
|
434
433
|
endpointIdx < ANTIGRAVITY_ENDPOINTS.length - 1
|
|
435
434
|
) {
|
|
436
435
|
forwardLogger.log("info",
|
|
437
436
|
`Endpoint ${endpoint} returned ${response.status}, cascading...`,
|
|
438
437
|
);
|
|
439
|
-
response.
|
|
438
|
+
await response.body?.cancel().catch(() => undefined);
|
|
440
439
|
continue;
|
|
441
440
|
}
|
|
442
441
|
|
|
@@ -452,12 +451,236 @@ export async function forwardRequest(
|
|
|
452
451
|
continue;
|
|
453
452
|
}
|
|
454
453
|
throw err;
|
|
454
|
+
} finally {
|
|
455
|
+
if (timeout) clearTimeout(timeout);
|
|
455
456
|
}
|
|
456
457
|
}
|
|
457
458
|
|
|
458
459
|
throw new Error("All endpoints failed");
|
|
459
460
|
}
|
|
460
461
|
|
|
462
|
+
const ERROR_BODY_READ_TIMEOUT_MS = 500;
|
|
463
|
+
const ERROR_BODY_MAX_BYTES = 262_144;
|
|
464
|
+
|
|
465
|
+
async function readBoundedErrorResponseText(
|
|
466
|
+
response: Response,
|
|
467
|
+
signal?: AbortSignal,
|
|
468
|
+
timeoutMs = ERROR_BODY_READ_TIMEOUT_MS,
|
|
469
|
+
maxBytes = ERROR_BODY_MAX_BYTES,
|
|
470
|
+
): Promise<{ text: string; truncatedOrTimedOut: boolean }> {
|
|
471
|
+
const cloned = response.clone();
|
|
472
|
+
if (!cloned.body) {
|
|
473
|
+
const text = await cloned.text().catch(() => "");
|
|
474
|
+
return { text, truncatedOrTimedOut: false };
|
|
475
|
+
}
|
|
476
|
+
const reader = cloned.body.getReader();
|
|
477
|
+
const decoder = new TextDecoder();
|
|
478
|
+
let text = "";
|
|
479
|
+
let totalBytes = 0;
|
|
480
|
+
let truncatedOrTimedOut = false;
|
|
481
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
482
|
+
let onAbort: (() => void) | undefined;
|
|
483
|
+
|
|
484
|
+
const deadline = new Promise<"timeout">((resolve) => {
|
|
485
|
+
timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
486
|
+
timer.unref?.();
|
|
487
|
+
});
|
|
488
|
+
const aborted = signal
|
|
489
|
+
? new Promise<"abort">((resolve) => {
|
|
490
|
+
if (signal.aborted) {
|
|
491
|
+
resolve("abort");
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
onAbort = () => resolve("abort");
|
|
495
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
496
|
+
})
|
|
497
|
+
: null;
|
|
498
|
+
|
|
499
|
+
try {
|
|
500
|
+
while (true) {
|
|
501
|
+
const racers: Array<Promise<ReadableStreamReadResult<Uint8Array> | "timeout" | "abort">> = [
|
|
502
|
+
reader.read(),
|
|
503
|
+
deadline,
|
|
504
|
+
];
|
|
505
|
+
if (aborted) racers.push(aborted);
|
|
506
|
+
const step = await Promise.race(racers);
|
|
507
|
+
if (step === "timeout" || step === "abort") {
|
|
508
|
+
truncatedOrTimedOut = true;
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
if (step.done) break;
|
|
512
|
+
const chunk = step.value;
|
|
513
|
+
if (chunk.byteLength > 0) {
|
|
514
|
+
const remaining = maxBytes - totalBytes;
|
|
515
|
+
if (remaining <= 0) {
|
|
516
|
+
truncatedOrTimedOut = true;
|
|
517
|
+
break;
|
|
518
|
+
}
|
|
519
|
+
const slice = chunk.byteLength > remaining ? chunk.subarray(0, remaining) : chunk;
|
|
520
|
+
totalBytes += slice.byteLength;
|
|
521
|
+
text += decoder.decode(slice, { stream: true });
|
|
522
|
+
if (totalBytes >= maxBytes) {
|
|
523
|
+
truncatedOrTimedOut = true;
|
|
524
|
+
break;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
text += decoder.decode();
|
|
529
|
+
} catch {
|
|
530
|
+
// Ignore stream read errors on error payloads; return whatever was buffered.
|
|
531
|
+
} finally {
|
|
532
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
533
|
+
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
|
534
|
+
// Do not await branch cancel before the caller cancels the original body;
|
|
535
|
+
// in WHATWG ReadableStream tee(), awaiting one branch can wait for the other.
|
|
536
|
+
void reader.cancel().catch(() => undefined);
|
|
537
|
+
}
|
|
538
|
+
return { text, truncatedOrTimedOut };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Forward a request to the real Antigravity endpoint with credential swapping.
|
|
543
|
+
*/
|
|
544
|
+
export async function forwardRequest(
|
|
545
|
+
account: AccountRuntime,
|
|
546
|
+
body: RequestBody,
|
|
547
|
+
originalHeaders: Record<string, string>,
|
|
548
|
+
signal?: AbortSignal,
|
|
549
|
+
options?: ForwardRequestOptions,
|
|
550
|
+
): Promise<ForwardedResponse> {
|
|
551
|
+
// Swap credentials
|
|
552
|
+
body.project = getProviderProjectId(account.config, DEFAULT_PROVIDER);
|
|
553
|
+
|
|
554
|
+
// Map internal display/compat names to Google upstream names (single source
|
|
555
|
+
// of truth: src/types.ts:applyModelAlias)
|
|
556
|
+
body.model = applyModelAlias(body.model);
|
|
557
|
+
|
|
558
|
+
const {
|
|
559
|
+
displayModel: _displayModel,
|
|
560
|
+
requestedModel: _requestedModel,
|
|
561
|
+
catalogModel: _catalogModel,
|
|
562
|
+
providerId: _providerId,
|
|
563
|
+
selectionMode: _selectionMode,
|
|
564
|
+
selectionConfidence: _selectionConfidence,
|
|
565
|
+
selectionReason: _selectionReason,
|
|
566
|
+
preservePrompt,
|
|
567
|
+
...strippedBody
|
|
568
|
+
} = body;
|
|
569
|
+
const bodyToForward = applyAntigravityTwinPayload(strippedBody, {
|
|
570
|
+
skipPromptInjection: preservePrompt === true,
|
|
571
|
+
});
|
|
572
|
+
const requestBody = JSON.stringify(bodyToForward);
|
|
573
|
+
const forwardHeaders = buildAntigravityWireHeaders(account, originalHeaders);
|
|
574
|
+
|
|
575
|
+
const executeOnce = async (): Promise<ForwardedResponse> => {
|
|
576
|
+
const aicodeTarget = await resolveAicodeTarget(
|
|
577
|
+
account,
|
|
578
|
+
body.model,
|
|
579
|
+
originalHeaders,
|
|
580
|
+
signal,
|
|
581
|
+
);
|
|
582
|
+
if (aicodeTarget) {
|
|
583
|
+
const { result, scopeInsufficientFallback } = await forwardAicodeRequestOnce(
|
|
584
|
+
account,
|
|
585
|
+
aicodeTarget,
|
|
586
|
+
bodyToForward,
|
|
587
|
+
originalHeaders,
|
|
588
|
+
signal,
|
|
589
|
+
readBoundedErrorResponseText,
|
|
590
|
+
);
|
|
591
|
+
if (!scopeInsufficientFallback) {
|
|
592
|
+
return result;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return forwardRequestOnce(account, forwardHeaders, requestBody, signal);
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
const retrySpec = options?.apiRetry;
|
|
599
|
+
if (retrySpec === false) {
|
|
600
|
+
return executeOnce();
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const retryOptions =
|
|
604
|
+
typeof retrySpec === "object" && retrySpec !== null ? retrySpec : {};
|
|
605
|
+
const label = account.config.label || account.config.email;
|
|
606
|
+
|
|
607
|
+
try {
|
|
608
|
+
return await runWithAntigravityApiRetry({
|
|
609
|
+
...retryOptions,
|
|
610
|
+
signal: retryOptions.signal ?? signal,
|
|
611
|
+
classifyError: (error) => {
|
|
612
|
+
if (error instanceof RetryableAntigravityHttpError) {
|
|
613
|
+
return {
|
|
614
|
+
retryable: true,
|
|
615
|
+
serverRetryDelayMs: error.serverRetryDelayMs,
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
return { retryable: isRetryableFetchError(error) };
|
|
619
|
+
},
|
|
620
|
+
onRetry: (info) => {
|
|
621
|
+
forwardLogger.log(
|
|
622
|
+
"warn",
|
|
623
|
+
`[${label}] Single-account Antigravity retry #${info.attempt + 1} in ${info.delayMs}ms`,
|
|
624
|
+
);
|
|
625
|
+
retryOptions.onRetry?.(info);
|
|
626
|
+
},
|
|
627
|
+
fn: async () => {
|
|
628
|
+
const result = await executeOnce();
|
|
629
|
+
const status = result.response.status;
|
|
630
|
+
if (status === 408 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
|
|
631
|
+
const { text: errorText, truncatedOrTimedOut } = await readBoundedErrorResponseText(
|
|
632
|
+
result.response,
|
|
633
|
+
signal,
|
|
634
|
+
);
|
|
635
|
+
if (signal?.aborted) {
|
|
636
|
+
await result.response.body?.cancel().catch(() => undefined);
|
|
637
|
+
throw signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
638
|
+
}
|
|
639
|
+
if (
|
|
640
|
+
isAntigravityRetryableError({
|
|
641
|
+
status,
|
|
642
|
+
errorText,
|
|
643
|
+
headers: result.response.headers,
|
|
644
|
+
})
|
|
645
|
+
) {
|
|
646
|
+
const serverRetryDelayMs =
|
|
647
|
+
extractRetryDelayMs(errorText, result.response.headers) ?? undefined;
|
|
648
|
+
const fallbackResponse = new Response(errorText, {
|
|
649
|
+
status: result.response.status,
|
|
650
|
+
statusText: result.response.statusText,
|
|
651
|
+
headers: result.response.headers,
|
|
652
|
+
});
|
|
653
|
+
await result.response.body?.cancel().catch(() => undefined);
|
|
654
|
+
throw new RetryableAntigravityHttpError(
|
|
655
|
+
status,
|
|
656
|
+
errorText || `HTTP ${status}`,
|
|
657
|
+
serverRetryDelayMs,
|
|
658
|
+
{ response: fallbackResponse, endpoint: result.endpoint },
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
if (truncatedOrTimedOut) {
|
|
662
|
+
await result.response.body?.cancel().catch(() => undefined);
|
|
663
|
+
return {
|
|
664
|
+
endpoint: result.endpoint,
|
|
665
|
+
response: new Response(errorText, {
|
|
666
|
+
status: result.response.status,
|
|
667
|
+
statusText: result.response.statusText,
|
|
668
|
+
headers: result.response.headers,
|
|
669
|
+
}),
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return result;
|
|
674
|
+
},
|
|
675
|
+
});
|
|
676
|
+
} catch (err) {
|
|
677
|
+
if (err instanceof RetryableAntigravityHttpError) {
|
|
678
|
+
return err.fallbackResult;
|
|
679
|
+
}
|
|
680
|
+
throw err;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
461
684
|
export function createGoogleStreamAccumulator(): SseEventAccumulator {
|
|
462
685
|
return new SseEventAccumulator();
|
|
463
686
|
}
|