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
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { getCredentialGeneration } from "../../account-identity.js";
|
|
2
|
+
import { fetchWithRetry } from "../../fetch-with-retry.js";
|
|
3
|
+
import type { AccountAuthWarning, AccountRuntime } from "../../types.js";
|
|
4
|
+
import {
|
|
5
|
+
AICODE_SCOPE,
|
|
6
|
+
ANTIGRAVITY_CLIENT_METADATA,
|
|
7
|
+
LIST_EXPERIMENTS_URL,
|
|
8
|
+
LOAD_CODE_ASSIST_URL,
|
|
9
|
+
} from "../../types.js";
|
|
10
|
+
import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
|
|
11
|
+
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
12
|
+
|
|
13
|
+
const AICODE_ELIGIBILITY_TTL_MS = 6 * 60 * 60 * 1000;
|
|
14
|
+
const AICODE_ELIGIBILITY_RETRY_MS = 15 * 60 * 1000;
|
|
15
|
+
|
|
16
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function hasGoogleAntigravityCredential(account: AccountRuntime): boolean {
|
|
21
|
+
if (account.config.credentials && account.config.credentials.length > 0) {
|
|
22
|
+
return account.config.credentials.some((c) => c.provider === DEFAULT_PROVIDER);
|
|
23
|
+
}
|
|
24
|
+
return !account.config.provider || account.config.provider === DEFAULT_PROVIDER;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function hasTokenScopes(account: AccountRuntime): boolean {
|
|
28
|
+
return Array.isArray(account.tokenScopes) && account.tokenScopes.length > 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function hasAicodeScope(account: AccountRuntime): boolean {
|
|
32
|
+
return hasTokenScopes(account) && account.tokenScopes!.includes(AICODE_SCOPE);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function hasMissingAicodeScope(account: AccountRuntime): boolean {
|
|
36
|
+
return hasTokenScopes(account) && !account.tokenScopes!.includes(AICODE_SCOPE);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function parseLoadCodeAssistPersonalConsumer(raw: unknown): {
|
|
40
|
+
personalConsumer: boolean | null;
|
|
41
|
+
userTierId: string | null;
|
|
42
|
+
} {
|
|
43
|
+
if (!isRecord(raw)) {
|
|
44
|
+
return { personalConsumer: null, userTierId: null };
|
|
45
|
+
}
|
|
46
|
+
const currentTier = isRecord(raw.currentTier) ? raw.currentTier : null;
|
|
47
|
+
const paidTier = isRecord(raw.paidTier) ? raw.paidTier : null;
|
|
48
|
+
const paidId = typeof paidTier?.id === "string" ? paidTier.id.trim() : "";
|
|
49
|
+
const currentId = typeof currentTier?.id === "string" ? currentTier.id.trim() : "";
|
|
50
|
+
const userTierId = paidId || currentId || null;
|
|
51
|
+
|
|
52
|
+
if (raw.gcpManaged === true) {
|
|
53
|
+
return { personalConsumer: false, userTierId };
|
|
54
|
+
}
|
|
55
|
+
if (
|
|
56
|
+
/enterprise|business/i.test(currentId) ||
|
|
57
|
+
/enterprise|business/i.test(paidId)
|
|
58
|
+
) {
|
|
59
|
+
return { personalConsumer: false, userTierId };
|
|
60
|
+
}
|
|
61
|
+
if (userTierId || raw.gcpManaged === false) {
|
|
62
|
+
return { personalConsumer: true, userTierId };
|
|
63
|
+
}
|
|
64
|
+
return { personalConsumer: null, userTierId: null };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const USE_AICODE_MENDEL_FLAG = "use-aicode-mendel";
|
|
68
|
+
// Antigravity.app (2.34.0–2.35.2) only routes generation to AICode when this
|
|
69
|
+
// Mendel flag feeds SetUseAICodePredictionFlow; use-aicode-mendel only moves
|
|
70
|
+
// ListExperiments to fetchConfig.
|
|
71
|
+
export const INFERENCE_TRAFFIC_MIGRATION_FLAG = "enable-inference-traffic-migration";
|
|
72
|
+
export const DARK_LAUNCH_AICODE_QUOTA_STATUS_FLAG = "dark-launch-aicode-quota-status";
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Read a boolean experiment flag from a `listExperiments` (`{ flags }`) or
|
|
76
|
+
* `fetchConfig.experimentConfig` (`{ experimentFlags }`) payload. Returns
|
|
77
|
+
* null when the payload is not a flag list, false when the flag is absent.
|
|
78
|
+
*/
|
|
79
|
+
export function parseExperimentBoolFlag(raw: unknown, name: string): boolean | null {
|
|
80
|
+
if (!isRecord(raw)) return null;
|
|
81
|
+
const flags = Array.isArray(raw.flags)
|
|
82
|
+
? raw.flags
|
|
83
|
+
: Array.isArray(raw.experimentFlags)
|
|
84
|
+
? raw.experimentFlags
|
|
85
|
+
: null;
|
|
86
|
+
if (!flags) return null;
|
|
87
|
+
for (const entry of flags) {
|
|
88
|
+
if (!isRecord(entry)) continue;
|
|
89
|
+
if (entry.name === name && typeof entry.boolValue === "boolean") {
|
|
90
|
+
return entry.boolValue;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function parseUseAicodeMendel(raw: unknown): boolean | null {
|
|
97
|
+
return parseExperimentBoolFlag(raw, USE_AICODE_MENDEL_FLAG);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function refreshAicodeEligibilityIfNeeded(
|
|
101
|
+
account: AccountRuntime,
|
|
102
|
+
headers: Record<string, string>,
|
|
103
|
+
isCurrentGeneration: () => boolean,
|
|
104
|
+
): Promise<void> {
|
|
105
|
+
if (
|
|
106
|
+
!hasGoogleAntigravityCredential(account) ||
|
|
107
|
+
!hasTokenScopes(account) ||
|
|
108
|
+
!account.accessToken
|
|
109
|
+
) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const gen = getCredentialGeneration(account, DEFAULT_PROVIDER);
|
|
114
|
+
const now = Date.now();
|
|
115
|
+
const prev =
|
|
116
|
+
account.aicodeEligibility?.credentialGeneration === gen
|
|
117
|
+
? account.aicodeEligibility
|
|
118
|
+
: undefined;
|
|
119
|
+
|
|
120
|
+
const isComplete =
|
|
121
|
+
prev !== undefined &&
|
|
122
|
+
prev.personalConsumer !== null &&
|
|
123
|
+
prev.useAicodeMendel !== null &&
|
|
124
|
+
prev.inferenceTrafficMigration !== undefined &&
|
|
125
|
+
prev.inferenceTrafficMigration !== null;
|
|
126
|
+
const ttl = isComplete ? AICODE_ELIGIBILITY_TTL_MS : AICODE_ELIGIBILITY_RETRY_MS;
|
|
127
|
+
if (prev && now - prev.checkedAt < ttl) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let personalConsumer = prev?.personalConsumer ?? null;
|
|
132
|
+
let userTierId = prev?.userTierId ?? null;
|
|
133
|
+
let useAicodeMendel = prev?.useAicodeMendel ?? null;
|
|
134
|
+
let inferenceTrafficMigration = prev?.inferenceTrafficMigration ?? null;
|
|
135
|
+
let darkLaunchAicodeQuotaStatus = prev?.darkLaunchAicodeQuotaStatus ?? null;
|
|
136
|
+
const dispatcher = getAccountProxyDispatcher(account, DEFAULT_PROVIDER);
|
|
137
|
+
|
|
138
|
+
if (personalConsumer === null || now - (prev?.checkedAt ?? 0) >= AICODE_ELIGIBILITY_TTL_MS) {
|
|
139
|
+
try {
|
|
140
|
+
const lcRes = await fetchWithRetry(LOAD_CODE_ASSIST_URL, {
|
|
141
|
+
method: "POST",
|
|
142
|
+
headers,
|
|
143
|
+
body: JSON.stringify({ metadata: ANTIGRAVITY_CLIENT_METADATA }),
|
|
144
|
+
timeoutMs: 8000,
|
|
145
|
+
retries: 0,
|
|
146
|
+
dispatcher,
|
|
147
|
+
});
|
|
148
|
+
if (!isCurrentGeneration()) return;
|
|
149
|
+
if (lcRes.ok) {
|
|
150
|
+
const parsed = parseLoadCodeAssistPersonalConsumer(
|
|
151
|
+
await lcRes.json().catch(() => null),
|
|
152
|
+
);
|
|
153
|
+
if (parsed.personalConsumer !== null) {
|
|
154
|
+
personalConsumer = parsed.personalConsumer;
|
|
155
|
+
}
|
|
156
|
+
if (parsed.userTierId !== null) {
|
|
157
|
+
userTierId = parsed.userTierId;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
} catch {
|
|
161
|
+
// Non-fatal: keep cached/partial value and retry on next cycle.
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const projectId = getProviderProjectId(account.config, DEFAULT_PROVIDER);
|
|
166
|
+
if (
|
|
167
|
+
projectId &&
|
|
168
|
+
(useAicodeMendel === null ||
|
|
169
|
+
inferenceTrafficMigration === null ||
|
|
170
|
+
now - (prev?.checkedAt ?? 0) >= AICODE_ELIGIBILITY_TTL_MS)
|
|
171
|
+
) {
|
|
172
|
+
try {
|
|
173
|
+
const expRes = await fetchWithRetry(LIST_EXPERIMENTS_URL, {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers,
|
|
176
|
+
body: JSON.stringify({
|
|
177
|
+
project: projectId,
|
|
178
|
+
metadata: ANTIGRAVITY_CLIENT_METADATA,
|
|
179
|
+
}),
|
|
180
|
+
timeoutMs: 8000,
|
|
181
|
+
retries: 0,
|
|
182
|
+
dispatcher,
|
|
183
|
+
});
|
|
184
|
+
if (!isCurrentGeneration()) return;
|
|
185
|
+
if (expRes.ok) {
|
|
186
|
+
const raw: unknown = await expRes.json().catch(() => null);
|
|
187
|
+
const mendel = parseUseAicodeMendel(raw);
|
|
188
|
+
if (mendel !== null) {
|
|
189
|
+
useAicodeMendel = mendel;
|
|
190
|
+
}
|
|
191
|
+
const migration = parseExperimentBoolFlag(raw, INFERENCE_TRAFFIC_MIGRATION_FLAG);
|
|
192
|
+
if (migration !== null) {
|
|
193
|
+
inferenceTrafficMigration = migration;
|
|
194
|
+
}
|
|
195
|
+
const darkLaunch = parseExperimentBoolFlag(raw, DARK_LAUNCH_AICODE_QUOTA_STATUS_FLAG);
|
|
196
|
+
if (darkLaunch !== null) {
|
|
197
|
+
darkLaunchAicodeQuotaStatus = darkLaunch;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
} catch {
|
|
201
|
+
// Non-fatal: keep cached/partial value and retry on next cycle.
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (!isCurrentGeneration()) return;
|
|
206
|
+
account.aicodeEligibility = {
|
|
207
|
+
credentialGeneration: gen,
|
|
208
|
+
checkedAt: Date.now(),
|
|
209
|
+
personalConsumer,
|
|
210
|
+
useAicodeMendel,
|
|
211
|
+
inferenceTrafficMigration,
|
|
212
|
+
darkLaunchAicodeQuotaStatus,
|
|
213
|
+
userTierId,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function buildAccountAuthWarning(
|
|
218
|
+
account: AccountRuntime,
|
|
219
|
+
): AccountAuthWarning | null {
|
|
220
|
+
if (
|
|
221
|
+
!hasGoogleAntigravityCredential(account) ||
|
|
222
|
+
account.disabled ||
|
|
223
|
+
account.flagged ||
|
|
224
|
+
account.invalidProviders?.[DEFAULT_PROVIDER] ||
|
|
225
|
+
account.disabledProviders?.includes(DEFAULT_PROVIDER)
|
|
226
|
+
) {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const gen = getCredentialGeneration(account, DEFAULT_PROVIDER);
|
|
231
|
+
const eligibility = account.aicodeEligibility;
|
|
232
|
+
if (!eligibility || eligibility.credentialGeneration !== gen) {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Only warn once Google moves the account's generation to AICode
|
|
237
|
+
// (enable-inference-traffic-migration); use-aicode-mendel alone does not.
|
|
238
|
+
const personalConsumer = eligibility.personalConsumer === true;
|
|
239
|
+
const inferenceTrafficMigration = eligibility.inferenceTrafficMigration === true;
|
|
240
|
+
const missingAicodeScope = hasMissingAicodeScope(account);
|
|
241
|
+
|
|
242
|
+
if (!personalConsumer || !inferenceTrafficMigration || !missingAicodeScope) {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
code: "missing-aicode-scope",
|
|
248
|
+
message:
|
|
249
|
+
"Re-authenticate required: Google moved this personal account to AICode (enable-inference-traffic-migration) and it is missing the aicode OAuth scope.",
|
|
250
|
+
rules: {
|
|
251
|
+
personalConsumer: true,
|
|
252
|
+
inferenceTrafficMigration: true,
|
|
253
|
+
missingAicodeScope: true,
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
// Google AICode (aicode.googleapis.com / v1alpha) request forwarding:
|
|
2
|
+
// eligibility gating, v1internal -> google.gca.aicode.v1main payload conversion,
|
|
3
|
+
// flat SSE -> { response } wrapper, and 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT fallback.
|
|
4
|
+
|
|
5
|
+
import { getCredentialGeneration } from "../../account-identity.js";
|
|
6
|
+
import {
|
|
7
|
+
ANTIGRAVITY_HEADERS_TIMEOUT_MS,
|
|
8
|
+
fetchWithHeadersTimeout,
|
|
9
|
+
type RequestInitWithDispatcher,
|
|
10
|
+
} from "../../fetch-with-retry.js";
|
|
11
|
+
import type { ForwardedResponse, RequestBody } from "../../proxy.js";
|
|
12
|
+
import type { AccountRuntime } from "../../types.js";
|
|
13
|
+
import { DEFAULT_PROVIDER } from "../credential-helpers.js";
|
|
14
|
+
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
15
|
+
import { hasAicodeScope } from "./aicode-eligibility.js";
|
|
16
|
+
import {
|
|
17
|
+
buildAicodeWireHeaders,
|
|
18
|
+
fetchAicodeConfig,
|
|
19
|
+
fetchAicodeLicenses,
|
|
20
|
+
isAicodeInsufficientScopeError,
|
|
21
|
+
isInAicodeScopeCooldown,
|
|
22
|
+
markAicodeScopeMissing,
|
|
23
|
+
resolveAicodeEndpoint,
|
|
24
|
+
resolveAicodeExperience,
|
|
25
|
+
} from "./aicode.js";
|
|
26
|
+
|
|
27
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
28
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type AicodeMode = "off" | "on" | "auto";
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* `USE_AICODE` (alias `TUXEVIL_ROTATOR_USE_AICODE`):
|
|
35
|
+
* - `false`/`0`/`no`/`off`: never use aicode.googleapis.com.
|
|
36
|
+
* - `true`/`1`/`yes`/`on`: force AICode for eligible personal accounts.
|
|
37
|
+
* - unset or `auto` (default): off unless Google turns on
|
|
38
|
+
* `enable-inference-traffic-migration` for the account, which is when
|
|
39
|
+
* Antigravity.app itself moves generation to AICode.
|
|
40
|
+
*/
|
|
41
|
+
export function resolveAicodeMode(): AicodeMode {
|
|
42
|
+
const raw = (process.env.USE_AICODE ?? process.env.TUXEVIL_ROTATOR_USE_AICODE)
|
|
43
|
+
?.trim()
|
|
44
|
+
.toLowerCase();
|
|
45
|
+
if (!raw || raw === "auto") return "auto";
|
|
46
|
+
if (raw === "true" || raw === "1" || raw === "yes" || raw === "on") return "on";
|
|
47
|
+
if (raw === "false" || raw === "0" || raw === "no" || raw === "off") return "off";
|
|
48
|
+
return "auto";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseUseAicodeEnvOverride(): boolean | null {
|
|
52
|
+
const mode = resolveAicodeMode();
|
|
53
|
+
if (mode === "on") return true;
|
|
54
|
+
if (mode === "off") return false;
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function shouldAttemptAicodeRouting(
|
|
59
|
+
account: AccountRuntime,
|
|
60
|
+
now = Date.now(),
|
|
61
|
+
): boolean {
|
|
62
|
+
const envOverride = parseUseAicodeEnvOverride();
|
|
63
|
+
if (envOverride === false) return false;
|
|
64
|
+
if (!account.accessToken) return false;
|
|
65
|
+
if (!hasAicodeScope(account)) return false;
|
|
66
|
+
if (isInAicodeScopeCooldown(account, now)) return false;
|
|
67
|
+
|
|
68
|
+
const gen = getCredentialGeneration(account, DEFAULT_PROVIDER);
|
|
69
|
+
const elig =
|
|
70
|
+
account.aicodeEligibility?.credentialGeneration === gen
|
|
71
|
+
? account.aicodeEligibility
|
|
72
|
+
: undefined;
|
|
73
|
+
const cachedConfig =
|
|
74
|
+
account.aicodeState?.credentialGeneration === gen
|
|
75
|
+
? account.aicodeState.config
|
|
76
|
+
: undefined;
|
|
77
|
+
|
|
78
|
+
if (elig?.personalConsumer !== true) {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (envOverride === true) {
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Default/auto mode stays off until Google enables the same flag that drives
|
|
87
|
+
// Antigravity.app useAICodePredictionFlow(); `use-aicode-mendel` never routes.
|
|
88
|
+
const migration = elig.inferenceTrafficMigration ?? null;
|
|
89
|
+
return (
|
|
90
|
+
migration === true ||
|
|
91
|
+
(migration === null && cachedConfig?.inferenceTrafficMigration === true)
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Antigravity.app keeps CCPA `retrieveUserQuotaSummary` as the quota source and
|
|
97
|
+
* only calls AICode `fetchQuotaStatus` as a shadow eval while
|
|
98
|
+
* `dark-launch-aicode-quota-status` is on. `USE_AICODE=false` also disables it.
|
|
99
|
+
*/
|
|
100
|
+
export function shouldShadowAicodeQuotaStatus(
|
|
101
|
+
account: AccountRuntime,
|
|
102
|
+
now = Date.now(),
|
|
103
|
+
): boolean {
|
|
104
|
+
if (parseUseAicodeEnvOverride() === false) return false;
|
|
105
|
+
if (!account.accessToken) return false;
|
|
106
|
+
if (!hasAicodeScope(account)) return false;
|
|
107
|
+
if (isInAicodeScopeCooldown(account, now)) return false;
|
|
108
|
+
const gen = getCredentialGeneration(account, DEFAULT_PROVIDER);
|
|
109
|
+
const elig =
|
|
110
|
+
account.aicodeEligibility?.credentialGeneration === gen
|
|
111
|
+
? account.aicodeEligibility
|
|
112
|
+
: undefined;
|
|
113
|
+
return elig?.personalConsumer === true && elig.darkLaunchAicodeQuotaStatus === true;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface ResolvedAicodeTarget {
|
|
117
|
+
endpoint: string;
|
|
118
|
+
experience: string;
|
|
119
|
+
userTier: string;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function resolveAicodeTarget(
|
|
123
|
+
account: AccountRuntime,
|
|
124
|
+
model: string,
|
|
125
|
+
originalHeaders: Record<string, string>,
|
|
126
|
+
signal?: AbortSignal,
|
|
127
|
+
): Promise<ResolvedAicodeTarget | null> {
|
|
128
|
+
if (!shouldAttemptAicodeRouting(account)) return null;
|
|
129
|
+
|
|
130
|
+
const [config, licenses] = await Promise.all([
|
|
131
|
+
fetchAicodeConfig(account, originalHeaders, signal),
|
|
132
|
+
fetchAicodeLicenses(account, originalHeaders, signal),
|
|
133
|
+
]);
|
|
134
|
+
|
|
135
|
+
if (isInAicodeScopeCooldown(account)) return null;
|
|
136
|
+
if (!config) return null;
|
|
137
|
+
|
|
138
|
+
const envOverride = parseUseAicodeEnvOverride();
|
|
139
|
+
if (envOverride !== true && config.inferenceTrafficMigration === false) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const experience = resolveAicodeExperience(config, model);
|
|
144
|
+
if (!experience) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const gen = getCredentialGeneration(account, DEFAULT_PROVIDER);
|
|
149
|
+
const eligTier =
|
|
150
|
+
account.aicodeEligibility?.credentialGeneration === gen
|
|
151
|
+
? account.aicodeEligibility.userTierId?.trim() || null
|
|
152
|
+
: null;
|
|
153
|
+
const userTier =
|
|
154
|
+
licenses?.userTier ||
|
|
155
|
+
(eligTier && eligTier.toLowerCase() !== "free-tier" ? eligTier : null);
|
|
156
|
+
if (!userTier) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
endpoint: resolveAicodeEndpoint(),
|
|
162
|
+
experience,
|
|
163
|
+
userTier,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Translate a twin-normalized `v1internal` request body into a flat
|
|
169
|
+
* `google.gca.aicode.v1main.GenerateContentRequest` payload.
|
|
170
|
+
*/
|
|
171
|
+
export function buildAicodeGenerateContentRequest(
|
|
172
|
+
twinBody: RequestBody,
|
|
173
|
+
experience: string,
|
|
174
|
+
userTier: string,
|
|
175
|
+
): Record<string, unknown> {
|
|
176
|
+
const inner = isRecord(twinBody.request) ? twinBody.request : {};
|
|
177
|
+
const out: Record<string, unknown> = {
|
|
178
|
+
aicode: { experience },
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
if (Array.isArray(inner.contents)) {
|
|
182
|
+
out.contents = inner.contents;
|
|
183
|
+
}
|
|
184
|
+
if (isRecord(inner.systemInstruction) || typeof inner.systemInstruction === "string") {
|
|
185
|
+
out.systemInstruction = inner.systemInstruction;
|
|
186
|
+
}
|
|
187
|
+
if (Array.isArray(inner.tools)) {
|
|
188
|
+
out.tools = inner.tools;
|
|
189
|
+
}
|
|
190
|
+
if (isRecord(inner.toolConfig)) {
|
|
191
|
+
out.toolConfig = inner.toolConfig;
|
|
192
|
+
}
|
|
193
|
+
if (isRecord(inner.labels)) {
|
|
194
|
+
out.labels = inner.labels;
|
|
195
|
+
}
|
|
196
|
+
if (Array.isArray(inner.safetySettings)) {
|
|
197
|
+
out.safetySettings = inner.safetySettings;
|
|
198
|
+
}
|
|
199
|
+
if (isRecord(inner.generationConfig)) {
|
|
200
|
+
out.generationConfig = inner.generationConfig;
|
|
201
|
+
}
|
|
202
|
+
if (typeof inner.sessionId === "string" && inner.sessionId.trim()) {
|
|
203
|
+
out.sessionId = inner.sessionId;
|
|
204
|
+
}
|
|
205
|
+
if (userTier.trim()) {
|
|
206
|
+
out.entitlement = { userTier: userTier.trim() };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return out;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function transformSseBlock(block: string): string {
|
|
213
|
+
const normalized = block.replace(/\r\n/g, "\n");
|
|
214
|
+
const lines = normalized.split("\n");
|
|
215
|
+
const otherLines: string[] = [];
|
|
216
|
+
const dataLines: string[] = [];
|
|
217
|
+
|
|
218
|
+
for (const line of lines) {
|
|
219
|
+
if (line.startsWith("data:")) {
|
|
220
|
+
dataLines.push(line.slice(5).trimStart());
|
|
221
|
+
} else {
|
|
222
|
+
otherLines.push(line);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (dataLines.length === 0) {
|
|
227
|
+
return `${normalized}\n\n`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const payload = dataLines.join("\n").trim();
|
|
231
|
+
if (!payload || payload === "[DONE]") {
|
|
232
|
+
return `${normalized}\n\n`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
try {
|
|
236
|
+
const parsed: unknown = JSON.parse(payload);
|
|
237
|
+
if (isRecord(parsed) && !("response" in parsed)) {
|
|
238
|
+
const wrapped = `data: ${JSON.stringify({ response: parsed })}`;
|
|
239
|
+
const prefix = otherLines.length > 0 ? `${otherLines.join("\n")}\n` : "";
|
|
240
|
+
return `${prefix}${wrapped}\n\n`;
|
|
241
|
+
}
|
|
242
|
+
} catch {
|
|
243
|
+
// Pass unparseable/partial payloads through unchanged.
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return `${normalized}\n\n`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Wrap flat AICode SSE `GenerateContentResponse` events into `{ response: ... }`
|
|
251
|
+
* frames matching `v1internal:streamGenerateContent?alt=sse`.
|
|
252
|
+
*/
|
|
253
|
+
export function wrapAicodeSseResponse(response: Response): Response {
|
|
254
|
+
if (!response.ok || !response.body) {
|
|
255
|
+
return response;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const decoder = new TextDecoder();
|
|
259
|
+
const encoder = new TextEncoder();
|
|
260
|
+
let buffer = "";
|
|
261
|
+
// A CRLF can be split across chunks: hold a trailing CR until the next
|
|
262
|
+
// chunk shows whether it starts with LF.
|
|
263
|
+
let pendingCr = false;
|
|
264
|
+
const normalizeChunk = (text: string, final: boolean): string => {
|
|
265
|
+
let input = pendingCr ? `\r${text}` : text;
|
|
266
|
+
pendingCr = false;
|
|
267
|
+
if (!final && input.endsWith("\r")) {
|
|
268
|
+
pendingCr = true;
|
|
269
|
+
input = input.slice(0, -1);
|
|
270
|
+
}
|
|
271
|
+
return input.replace(/\r\n?/g, "\n");
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const transform = new TransformStream<Uint8Array, Uint8Array>({
|
|
275
|
+
transform(chunk, controller) {
|
|
276
|
+
buffer += normalizeChunk(decoder.decode(chunk, { stream: true }), false);
|
|
277
|
+
let boundary = buffer.indexOf("\n\n");
|
|
278
|
+
while (boundary !== -1) {
|
|
279
|
+
const block = buffer.slice(0, boundary);
|
|
280
|
+
buffer = buffer.slice(boundary + 2);
|
|
281
|
+
if (block.length > 0) {
|
|
282
|
+
controller.enqueue(encoder.encode(transformSseBlock(block)));
|
|
283
|
+
} else {
|
|
284
|
+
controller.enqueue(encoder.encode("\n\n"));
|
|
285
|
+
}
|
|
286
|
+
boundary = buffer.indexOf("\n\n");
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
flush(controller) {
|
|
290
|
+
buffer += normalizeChunk(decoder.decode(), true);
|
|
291
|
+
let boundary = buffer.indexOf("\n\n");
|
|
292
|
+
while (boundary !== -1) {
|
|
293
|
+
const block = buffer.slice(0, boundary);
|
|
294
|
+
buffer = buffer.slice(boundary + 2);
|
|
295
|
+
if (block.length > 0) {
|
|
296
|
+
controller.enqueue(encoder.encode(transformSseBlock(block)));
|
|
297
|
+
}
|
|
298
|
+
boundary = buffer.indexOf("\n\n");
|
|
299
|
+
}
|
|
300
|
+
if (buffer.trim().length > 0) {
|
|
301
|
+
controller.enqueue(encoder.encode(transformSseBlock(buffer)));
|
|
302
|
+
}
|
|
303
|
+
buffer = "";
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
const headers = new Headers(response.headers);
|
|
308
|
+
headers.delete("content-length");
|
|
309
|
+
headers.delete("content-encoding");
|
|
310
|
+
|
|
311
|
+
return new Response(response.body.pipeThrough(transform), {
|
|
312
|
+
status: response.status,
|
|
313
|
+
statusText: response.statusText,
|
|
314
|
+
headers,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function forwardAicodeRequestOnce(
|
|
319
|
+
account: AccountRuntime,
|
|
320
|
+
target: ResolvedAicodeTarget,
|
|
321
|
+
twinBody: RequestBody,
|
|
322
|
+
originalHeaders: Record<string, string>,
|
|
323
|
+
signal: AbortSignal | undefined,
|
|
324
|
+
readErrorBody: (
|
|
325
|
+
response: Response,
|
|
326
|
+
signal?: AbortSignal,
|
|
327
|
+
) => Promise<{ text: string; truncatedOrTimedOut: boolean }>,
|
|
328
|
+
): Promise<{ result: ForwardedResponse; scopeInsufficientFallback: boolean }> {
|
|
329
|
+
const url = `${target.endpoint}/v1alpha:streamGenerateContent?alt=sse`;
|
|
330
|
+
const payload = buildAicodeGenerateContentRequest(
|
|
331
|
+
twinBody,
|
|
332
|
+
target.experience,
|
|
333
|
+
target.userTier,
|
|
334
|
+
);
|
|
335
|
+
const response = await fetchWithHeadersTimeout(url, {
|
|
336
|
+
method: "POST",
|
|
337
|
+
headers: buildAicodeWireHeaders(account, originalHeaders),
|
|
338
|
+
body: JSON.stringify(payload),
|
|
339
|
+
signal,
|
|
340
|
+
timeoutMs: ANTIGRAVITY_HEADERS_TIMEOUT_MS,
|
|
341
|
+
dispatcher: getAccountProxyDispatcher(account, DEFAULT_PROVIDER),
|
|
342
|
+
} as RequestInitWithDispatcher);
|
|
343
|
+
|
|
344
|
+
if (response.status === 403) {
|
|
345
|
+
const { text: errorText } = await readErrorBody(response, signal);
|
|
346
|
+
await response.body?.cancel().catch(() => undefined);
|
|
347
|
+
if (isAicodeInsufficientScopeError(403, errorText)) {
|
|
348
|
+
markAicodeScopeMissing(account);
|
|
349
|
+
return {
|
|
350
|
+
result: {
|
|
351
|
+
endpoint: target.endpoint,
|
|
352
|
+
response: new Response(errorText, {
|
|
353
|
+
status: 403,
|
|
354
|
+
statusText: response.statusText,
|
|
355
|
+
headers: response.headers,
|
|
356
|
+
}),
|
|
357
|
+
},
|
|
358
|
+
scopeInsufficientFallback: true,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
return {
|
|
362
|
+
result: {
|
|
363
|
+
endpoint: target.endpoint,
|
|
364
|
+
response: new Response(errorText, {
|
|
365
|
+
status: response.status,
|
|
366
|
+
statusText: response.statusText,
|
|
367
|
+
headers: response.headers,
|
|
368
|
+
}),
|
|
369
|
+
},
|
|
370
|
+
scopeInsufficientFallback: false,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
return {
|
|
375
|
+
result: {
|
|
376
|
+
endpoint: target.endpoint,
|
|
377
|
+
response: wrapAicodeSseResponse(response),
|
|
378
|
+
},
|
|
379
|
+
scopeInsufficientFallback: false,
|
|
380
|
+
};
|
|
381
|
+
}
|