tuxevil-rotator 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +773 -0
- package/LICENSE +21 -0
- package/README.md +341 -0
- package/bin/pi-antigravity-rotator.js +27 -0
- package/bin/tuxevil-rotator.js +5 -0
- package/package.json +63 -0
- package/src/account-store.ts +542 -0
- package/src/admin-auth.ts +126 -0
- package/src/body-limit.ts +52 -0
- package/src/cli.ts +293 -0
- package/src/compat/cache.ts +38 -0
- package/src/compat/model-specs.ts +82 -0
- package/src/compat/schema-sanitizer.ts +284 -0
- package/src/compat.ts +2357 -0
- package/src/compression/index.ts +92 -0
- package/src/compression/lite.ts +210 -0
- package/src/compression/preservation.ts +183 -0
- package/src/compression/rtk/command-detector.ts +170 -0
- package/src/compression/rtk/deduplicator.ts +39 -0
- package/src/compression/rtk/filter-loader.ts +84 -0
- package/src/compression/rtk/filter-types.ts +25 -0
- package/src/compression/rtk/filters/aws.json +34 -0
- package/src/compression/rtk/filters/biome.json +35 -0
- package/src/compression/rtk/filters/build-eslint.json +37 -0
- package/src/compression/rtk/filters/build-typescript.json +33 -0
- package/src/compression/rtk/filters/build-vite.json +41 -0
- package/src/compression/rtk/filters/build-webpack.json +34 -0
- package/src/compression/rtk/filters/bundle-install.json +35 -0
- package/src/compression/rtk/filters/composer.json +81 -0
- package/src/compression/rtk/filters/curl.json +34 -0
- package/src/compression/rtk/filters/df.json +34 -0
- package/src/compression/rtk/filters/docker-build.json +78 -0
- package/src/compression/rtk/filters/docker-logs.json +42 -0
- package/src/compression/rtk/filters/docker-ps.json +33 -0
- package/src/compression/rtk/filters/dotnet.json +47 -0
- package/src/compression/rtk/filters/du.json +33 -0
- package/src/compression/rtk/filters/error-stacktrace.json +41 -0
- package/src/compression/rtk/filters/gcloud.json +34 -0
- package/src/compression/rtk/filters/generic-output.json +32 -0
- package/src/compression/rtk/filters/gh.json +98 -0
- package/src/compression/rtk/filters/git-branch.json +45 -0
- package/src/compression/rtk/filters/git-diff.json +33 -0
- package/src/compression/rtk/filters/git-log.json +33 -0
- package/src/compression/rtk/filters/git-status.json +40 -0
- package/src/compression/rtk/filters/golangci-lint.json +34 -0
- package/src/compression/rtk/filters/gradle.json +47 -0
- package/src/compression/rtk/filters/json-output.json +40 -0
- package/src/compression/rtk/filters/kubectl.json +99 -0
- package/src/compression/rtk/filters/make.json +38 -0
- package/src/compression/rtk/filters/mypy.json +34 -0
- package/src/compression/rtk/filters/npm-audit.json +43 -0
- package/src/compression/rtk/filters/npm-install.json +41 -0
- package/src/compression/rtk/filters/nx.json +34 -0
- package/src/compression/rtk/filters/pip.json +41 -0
- package/src/compression/rtk/filters/playwright.json +42 -0
- package/src/compression/rtk/filters/poetry-install.json +35 -0
- package/src/compression/rtk/filters/prettier.json +40 -0
- package/src/compression/rtk/filters/ps.json +34 -0
- package/src/compression/rtk/filters/rsync.json +33 -0
- package/src/compression/rtk/filters/rubocop.json +34 -0
- package/src/compression/rtk/filters/ruff.json +40 -0
- package/src/compression/rtk/filters/shell-find.json +33 -0
- package/src/compression/rtk/filters/shell-grep.json +37 -0
- package/src/compression/rtk/filters/shell-ls.json +33 -0
- package/src/compression/rtk/filters/ssh.json +43 -0
- package/src/compression/rtk/filters/systemctl-status.json +43 -0
- package/src/compression/rtk/filters/terraform-plan.json +34 -0
- package/src/compression/rtk/filters/test-cargo.json +42 -0
- package/src/compression/rtk/filters/test-go.json +41 -0
- package/src/compression/rtk/filters/test-jest.json +43 -0
- package/src/compression/rtk/filters/test-pytest.json +41 -0
- package/src/compression/rtk/filters/test-vitest.json +43 -0
- package/src/compression/rtk/filters/tofu-plan.json +34 -0
- package/src/compression/rtk/filters/turbo.json +34 -0
- package/src/compression/rtk/filters/uv-sync.json +35 -0
- package/src/compression/rtk/filters/wget.json +34 -0
- package/src/compression/rtk/index.ts +103 -0
- package/src/compression/rtk/line-filter.ts +124 -0
- package/src/compression/rtk/smart-truncate.ts +71 -0
- package/src/config-defaults.ts +93 -0
- package/src/config-normalize.ts +48 -0
- package/src/config-storage.ts +21 -0
- package/src/dashboard.ts +1169 -0
- package/src/db-store.ts +188 -0
- package/src/doctor.ts +115 -0
- package/src/env.ts +15 -0
- package/src/exposure.ts +17 -0
- package/src/fetch-with-retry.ts +93 -0
- package/src/idempotency.ts +137 -0
- package/src/index.ts +267 -0
- package/src/key-auth.ts +159 -0
- package/src/key-migrations.ts +84 -0
- package/src/logger.ts +92 -0
- package/src/login.ts +48 -0
- package/src/notification-poller.ts +155 -0
- package/src/onboarding.ts +754 -0
- package/src/paths.ts +153 -0
- package/src/providers/adapter.ts +131 -0
- package/src/providers/credential-helpers.ts +72 -0
- package/src/providers/google-antigravity/code-assist.ts +161 -0
- package/src/providers/google-antigravity/credentials.ts +24 -0
- package/src/providers/google-antigravity/forward.ts +424 -0
- package/src/providers/google-antigravity/index.ts +168 -0
- package/src/providers/google-antigravity/login.ts +285 -0
- package/src/providers/google-antigravity/oauth.ts +314 -0
- package/src/providers/google-antigravity/quota.ts +152 -0
- package/src/providers/google-antigravity/translators.ts +1663 -0
- package/src/providers/ollama/api-key-validation.ts +59 -0
- package/src/providers/ollama/credentials.ts +28 -0
- package/src/providers/ollama/forward.ts +306 -0
- package/src/providers/ollama/index.ts +85 -0
- package/src/providers/ollama/login.ts +55 -0
- package/src/providers/ollama/prediction.ts +188 -0
- package/src/providers/ollama/quota-poll-store.ts +160 -0
- package/src/providers/ollama/quota.ts +189 -0
- package/src/providers/ollama/translators.ts +256 -0
- package/src/providers/ollama/usage-windows.ts +48 -0
- package/src/providers/proxy-dispatcher.ts +269 -0
- package/src/providers/registry.ts +70 -0
- package/src/proxy.ts +2446 -0
- package/src/rate-limit-parser.ts +126 -0
- package/src/response-headers.ts +98 -0
- package/src/responses-store.ts +159 -0
- package/src/rotator.ts +3614 -0
- package/src/settings-repository.ts +327 -0
- package/src/spend-logger.ts +696 -0
- package/src/static/dashboard-keys.js +384 -0
- package/src/static/dashboard-logs.js +797 -0
- package/src/static/dashboard.css +2740 -0
- package/src/static/dashboard.js +3177 -0
- package/src/storage.ts +105 -0
- package/src/systemd-env.ts +214 -0
- package/src/telemetry.ts +384 -0
- package/src/token-encryption.ts +199 -0
- package/src/types.ts +897 -0
- package/src/validators.ts +218 -0
- package/src/version-check.ts +225 -0
- package/src/virtual-keys.ts +312 -0
- package/tools/telemetry-receiver/README.md +147 -0
- package/tools/telemetry-receiver/package.json +13 -0
- package/tools/telemetry-receiver/receiver.js +2334 -0
- package/tuxevil-rotator_logo.png +0 -0
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,2446 @@
|
|
|
1
|
+
// HTTP reverse proxy - forwards requests to Antigravity with credential rotation
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
buildRotatorResponseHeaders,
|
|
5
|
+
maskAccountLabel,
|
|
6
|
+
} from "./response-headers.js";
|
|
7
|
+
import {
|
|
8
|
+
createServer,
|
|
9
|
+
type IncomingMessage,
|
|
10
|
+
type Server,
|
|
11
|
+
type ServerResponse,
|
|
12
|
+
} from "node:http";
|
|
13
|
+
import { Readable } from "node:stream";
|
|
14
|
+
import {
|
|
15
|
+
resolveQuotaModelKey,
|
|
16
|
+
resolveDisplayModelKey,
|
|
17
|
+
} from "./types.js";
|
|
18
|
+
import type { AccountRuntime } from "./types.js";
|
|
19
|
+
import type { AccountRotator } from "./rotator.js";
|
|
20
|
+
import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount } from "./providers/registry.js";
|
|
21
|
+
import { isRecord } from "./compat/schema-sanitizer.js";
|
|
22
|
+
import type { ProviderAdapter, StreamAccumulator } from "./providers/adapter.js";
|
|
23
|
+
import {
|
|
24
|
+
isCodeAssistAction,
|
|
25
|
+
validateCodeAssistPayload,
|
|
26
|
+
type CodeAssistAction,
|
|
27
|
+
} from "./providers/google-antigravity/code-assist.js";
|
|
28
|
+
import {
|
|
29
|
+
forwardRequest,
|
|
30
|
+
SseEventAccumulator,
|
|
31
|
+
extractUsageFromSseEvent,
|
|
32
|
+
GOOGLE_BENCHMARK_CONSTANTS,
|
|
33
|
+
} from "./providers/google-antigravity/forward.js";
|
|
34
|
+
export { forwardRequest, SseEventAccumulator, extractUsageFromSseEvent };
|
|
35
|
+
import {
|
|
36
|
+
serveDashboard,
|
|
37
|
+
serveStatusApi,
|
|
38
|
+
serveConfigApi,
|
|
39
|
+
serveConfigExportApi,
|
|
40
|
+
serveConfigImportApi,
|
|
41
|
+
serveEnableApi,
|
|
42
|
+
serveDisableApi,
|
|
43
|
+
serveQuarantineApi,
|
|
44
|
+
serveRestoreApi,
|
|
45
|
+
serveRemoveAccountApi,
|
|
46
|
+
serveSetTierApi,
|
|
47
|
+
serveFreshWindowStartsApi,
|
|
48
|
+
serveAccountFreshWindowStartsApi,
|
|
49
|
+
serveClearInFlightApi,
|
|
50
|
+
serveClearBreakerApi,
|
|
51
|
+
serveKickstartApi,
|
|
52
|
+
serveAutoWarmupApi,
|
|
53
|
+
serveGenerateVirtualKeyApi,
|
|
54
|
+
serveListVirtualKeysApi,
|
|
55
|
+
serveGetVirtualKeyApi,
|
|
56
|
+
serveUpdateVirtualKeyApi,
|
|
57
|
+
serveDeleteVirtualKeyApi,
|
|
58
|
+
serveGetSpendLogsApi,
|
|
59
|
+
serveGetSpendSummaryApi,
|
|
60
|
+
serveGetSpendByKeyApi,
|
|
61
|
+
serveDashboardKeys,
|
|
62
|
+
serveDashboardLogs,
|
|
63
|
+
serveStaticKeysJs,
|
|
64
|
+
serveStaticLogsJs,
|
|
65
|
+
serveStaticCss,
|
|
66
|
+
serveStaticJs,
|
|
67
|
+
} from "./dashboard.js";
|
|
68
|
+
import {
|
|
69
|
+
handleHostedCallback,
|
|
70
|
+
serveLoginLanding,
|
|
71
|
+
startHostedLogin,
|
|
72
|
+
serveCliLogin,
|
|
73
|
+
handleCliLoginApi,
|
|
74
|
+
} from "./onboarding.js";
|
|
75
|
+
import { requireAdmin } from "./admin-auth.js";
|
|
76
|
+
import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
|
|
77
|
+
import { validateConfig, validateProxyRequestBody } from "./validators.js";
|
|
78
|
+
import { logger } from "./logger.js";
|
|
79
|
+
import {
|
|
80
|
+
trackFeature,
|
|
81
|
+
reportFlagEvent,
|
|
82
|
+
FLAG_PATTERNS,
|
|
83
|
+
type FlagPattern,
|
|
84
|
+
} from "./telemetry.js";
|
|
85
|
+
import type { FlagEventData } from "./telemetry.js";
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Provider adapter for a request on a (possibly multi-provider) account.
|
|
89
|
+
* The destination model decides the adapter: if the model is in the
|
|
90
|
+
* Ollama catalog (tracked on the rotator), it goes through the Ollama
|
|
91
|
+
* adapter; otherwise the account's primary provider is used. This avoids
|
|
92
|
+
* the broken heuristic of relying on `:` in the model name (some Ollama
|
|
93
|
+
* models like `minimax-m3`, `kimi-k3`, `glm-5.1` have no tag, and some
|
|
94
|
+
* Google model aliases do).
|
|
95
|
+
*
|
|
96
|
+
* The rotator is required only when it exposes `getOllamaModels()`; test
|
|
97
|
+
* stubs that omit it fall back to the credentials-only dispatch.
|
|
98
|
+
*/
|
|
99
|
+
function providerAdapterForModel(
|
|
100
|
+
account: AccountRuntime,
|
|
101
|
+
model: string | undefined,
|
|
102
|
+
rotator?: { getOllamaModels?: () => string[] },
|
|
103
|
+
): ProviderAdapter {
|
|
104
|
+
const creds = account.config.credentials ?? [];
|
|
105
|
+
if (creds.length > 0) {
|
|
106
|
+
const onlyOllama = creds.every((c) => c.provider === "ollama");
|
|
107
|
+
const onlyGoogle = creds.every((c) => c.provider !== "ollama");
|
|
108
|
+
if (onlyOllama) return getProviderAdapter("ollama");
|
|
109
|
+
if (onlyGoogle) return getProviderAdapter(DEFAULT_PROVIDER);
|
|
110
|
+
}
|
|
111
|
+
let isOllamaModel = false;
|
|
112
|
+
try {
|
|
113
|
+
const ollamaList = rotator?.getOllamaModels?.() ?? [];
|
|
114
|
+
if (ollamaList.length > 0 && model) {
|
|
115
|
+
isOllamaModel = ollamaList.includes(model);
|
|
116
|
+
}
|
|
117
|
+
} catch {
|
|
118
|
+
// ignore — fall through to primary dispatch
|
|
119
|
+
}
|
|
120
|
+
if (isOllamaModel) {
|
|
121
|
+
return getProviderAdapter("ollama");
|
|
122
|
+
}
|
|
123
|
+
return getProviderForAccount(account.config);
|
|
124
|
+
}
|
|
125
|
+
import { startVersionChecker, performSelfUpdate } from "./version-check.js";
|
|
126
|
+
import { startNotificationPoller } from "./notification-poller.js";
|
|
127
|
+
import {
|
|
128
|
+
handleAnthropicMessages,
|
|
129
|
+
handleGeminiGenerateContent,
|
|
130
|
+
handleOpenAIChatCompletions,
|
|
131
|
+
handleOpenAIResponsesCancel,
|
|
132
|
+
handleOpenAIResponsesCreate,
|
|
133
|
+
handleOpenAIResponsesDelete,
|
|
134
|
+
handleOpenAIResponsesInputItems,
|
|
135
|
+
handleOpenAIResponsesRetrieve,
|
|
136
|
+
serveGeminiModels,
|
|
137
|
+
serveOpenAIModels,
|
|
138
|
+
} from "./compat.js";
|
|
139
|
+
import { applyConfigDefaults } from "./account-store.js";
|
|
140
|
+
import {
|
|
141
|
+
classifyRateLimitReason,
|
|
142
|
+
parseRetryAfterMs,
|
|
143
|
+
} from "./rate-limit-parser.js";
|
|
144
|
+
import { authenticateVirtualKey, sendAuthErrorResponse } from "./key-auth.js";
|
|
145
|
+
import { logSpend } from "./spend-logger.js";
|
|
146
|
+
import { hashKey } from "./virtual-keys.js";
|
|
147
|
+
|
|
148
|
+
const proxyLogger = logger.child("proxy");
|
|
149
|
+
const GENERIC_UPSTREAM_ERROR = "Upstream request failed";
|
|
150
|
+
|
|
151
|
+
const DEFAULT_STREAM_RECOVERY_MAX_RETRIES = 2;
|
|
152
|
+
const MAX_COOLDOWN_MS = 30 * 60 * 1000; // 30 minutes max cooldown
|
|
153
|
+
const RESOURCE_EXHAUSTED_COOLDOWN_MS = 30 * 60 * 1000; // Stop hammering provider-side daily/request buckets
|
|
154
|
+
const STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1000; // Release account if a stream goes silent.
|
|
155
|
+
const LARGE_CONTEXT_WARN_BYTES = 1 * 1024 * 1024;
|
|
156
|
+
|
|
157
|
+
function sleep(ms: number): Promise<void> {
|
|
158
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export class PreFlushStreamError extends Error {
|
|
162
|
+
constructor(cause: unknown) {
|
|
163
|
+
super(`Upstream stream failed before response flush: ${formatError(cause)}`, {
|
|
164
|
+
cause,
|
|
165
|
+
});
|
|
166
|
+
this.name = "PreFlushStreamError";
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function getStreamRecoveryMaxRetries(rotator: AccountRotator): number {
|
|
171
|
+
const configured = rotator.getConfig?.().streamRecoveryMaxRetries;
|
|
172
|
+
if (configured === undefined || !Number.isInteger(configured) || configured < 0) {
|
|
173
|
+
return DEFAULT_STREAM_RECOVERY_MAX_RETRIES;
|
|
174
|
+
}
|
|
175
|
+
return configured;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export interface RequestBody {
|
|
179
|
+
project: string;
|
|
180
|
+
model: string;
|
|
181
|
+
request: unknown;
|
|
182
|
+
requestType?: string;
|
|
183
|
+
userAgent?: string;
|
|
184
|
+
requestId?: string;
|
|
185
|
+
displayModel?: string;
|
|
186
|
+
[key: string]: unknown;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface ForwardedResponse {
|
|
190
|
+
response: Response;
|
|
191
|
+
endpoint: string;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export type BenchmarkResultStatus = "success" | "failed" | "skipped";
|
|
195
|
+
|
|
196
|
+
export interface BenchmarkResult {
|
|
197
|
+
account: string;
|
|
198
|
+
status: BenchmarkResultStatus;
|
|
199
|
+
latencyMs: number | null;
|
|
200
|
+
ttfbMs: number | null;
|
|
201
|
+
outputTokens: number | null;
|
|
202
|
+
tokensPerSecond: number | null;
|
|
203
|
+
error?: string;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface BenchmarkSummary {
|
|
207
|
+
total: number;
|
|
208
|
+
succeeded: number;
|
|
209
|
+
failed: number;
|
|
210
|
+
skipped: number;
|
|
211
|
+
successRate: number;
|
|
212
|
+
averageLatencyMs: number | null;
|
|
213
|
+
averageTtfbMs: number | null;
|
|
214
|
+
averageTokensPerSecond: number | null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export interface RotationAttemptContext {
|
|
218
|
+
account: AccountRuntime;
|
|
219
|
+
label: string;
|
|
220
|
+
modelKey: string;
|
|
221
|
+
displayModelKey: string;
|
|
222
|
+
requestId: string;
|
|
223
|
+
requestStartMs: number;
|
|
224
|
+
endpoint: string;
|
|
225
|
+
retries: number;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export type RotationOutcome<T> =
|
|
229
|
+
| { ok: true; result: T; endpoint: string; context?: RotationAttemptContext }
|
|
230
|
+
| {
|
|
231
|
+
ok: false;
|
|
232
|
+
status: number;
|
|
233
|
+
errorText: string;
|
|
234
|
+
retryAfterMs?: number;
|
|
235
|
+
endpoint?: string;
|
|
236
|
+
context?: RotationAttemptContext;
|
|
237
|
+
totalMs?: number;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Discriminated union describing what should happen after inspecting an
|
|
242
|
+
* upstream response. Used by both withRotation (which translates into a
|
|
243
|
+
* RotationOutcome) and handleProxyRequest (which translates into HTTP) to
|
|
244
|
+
* keep the status-code branching in one place.
|
|
245
|
+
*/
|
|
246
|
+
export type UpstreamAction =
|
|
247
|
+
| {
|
|
248
|
+
kind: "rate-limited";
|
|
249
|
+
cooldownMs: number;
|
|
250
|
+
providerResourceExhausted: boolean;
|
|
251
|
+
errorText: string;
|
|
252
|
+
endpoint: string;
|
|
253
|
+
}
|
|
254
|
+
| { kind: "flagged-401"; errorText: string; endpoint: string }
|
|
255
|
+
| { kind: "flagged-403"; errorText: string; endpoint: string }
|
|
256
|
+
| { kind: "forbidden"; errorText: string; endpoint: string }
|
|
257
|
+
| { kind: "not-found"; errorText: string; endpoint: string }
|
|
258
|
+
| { kind: "bad-request"; errorText: string; endpoint: string }
|
|
259
|
+
| { kind: "server-error-503"; errorText: string; endpoint: string }
|
|
260
|
+
| {
|
|
261
|
+
kind: "rotate-on-5xx";
|
|
262
|
+
httpStatus: number;
|
|
263
|
+
errorText: string;
|
|
264
|
+
endpoint: string;
|
|
265
|
+
}
|
|
266
|
+
| { kind: "success" };
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Inspect an upstream response and return a tag describing what to do next.
|
|
270
|
+
* Shared between withRotation and handleProxyRequest so the status-code
|
|
271
|
+
* classification logic lives in one place.
|
|
272
|
+
*/
|
|
273
|
+
export async function classifyUpstreamResponse(
|
|
274
|
+
response: Response,
|
|
275
|
+
endpoint: string,
|
|
276
|
+
account: AccountRuntime,
|
|
277
|
+
model: string,
|
|
278
|
+
modelKey: string,
|
|
279
|
+
): Promise<UpstreamAction> {
|
|
280
|
+
if (response.status === 429) {
|
|
281
|
+
const errorText = await response.text().catch(() => "");
|
|
282
|
+
const rateLimitReason = classifyRateLimitReason(errorText, response.status);
|
|
283
|
+
const providerResourceExhausted = rateLimitReason === "quota-exhausted";
|
|
284
|
+
const cooldownMs = providerResourceExhausted
|
|
285
|
+
? RESOURCE_EXHAUSTED_COOLDOWN_MS
|
|
286
|
+
: capCooldown(parseRetryAfterMs(errorText, response.headers));
|
|
287
|
+
return {
|
|
288
|
+
kind: "rate-limited",
|
|
289
|
+
cooldownMs,
|
|
290
|
+
providerResourceExhausted,
|
|
291
|
+
errorText,
|
|
292
|
+
endpoint,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (response.status === 401) {
|
|
297
|
+
const errorText = await response.text().catch(() => "");
|
|
298
|
+
return { kind: "flagged-401", errorText, endpoint };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (response.status === 403) {
|
|
302
|
+
const errorText = await response.text().catch(() => "");
|
|
303
|
+
const lower = errorText.toLowerCase();
|
|
304
|
+
const flagPatternsLocal = [
|
|
305
|
+
"infring",
|
|
306
|
+
"suspend",
|
|
307
|
+
"abus",
|
|
308
|
+
"terminat",
|
|
309
|
+
"violat",
|
|
310
|
+
"banned",
|
|
311
|
+
"policy",
|
|
312
|
+
"forbidden",
|
|
313
|
+
"verif",
|
|
314
|
+
];
|
|
315
|
+
const isFlagged = flagPatternsLocal.some((p) => lower.includes(p));
|
|
316
|
+
if (isFlagged) {
|
|
317
|
+
return { kind: "flagged-403", errorText, endpoint };
|
|
318
|
+
}
|
|
319
|
+
return { kind: "forbidden", errorText, endpoint };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (response.status === 404) {
|
|
323
|
+
const errorText = await response.text().catch(() => "");
|
|
324
|
+
return { kind: "not-found", errorText, endpoint };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (response.status === 400) {
|
|
328
|
+
const errorText = await response.text().catch(() => "");
|
|
329
|
+
return { kind: "bad-request", errorText, endpoint };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (response.status === 503) {
|
|
333
|
+
const errorText = await response.text().catch(() => "");
|
|
334
|
+
return { kind: "server-error-503", errorText, endpoint };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (response.status >= 500) {
|
|
338
|
+
const errorText = await response.text().catch(() => "");
|
|
339
|
+
return {
|
|
340
|
+
kind: "rotate-on-5xx",
|
|
341
|
+
httpStatus: response.status,
|
|
342
|
+
errorText,
|
|
343
|
+
endpoint,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Reference parameters to satisfy "all parameters are used" without changing behavior.
|
|
348
|
+
void account;
|
|
349
|
+
void model;
|
|
350
|
+
void modelKey;
|
|
351
|
+
return { kind: "success" };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function capCooldown(ms: number): number {
|
|
355
|
+
return Math.min(ms, MAX_COOLDOWN_MS);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
type UpstreamActionDecision =
|
|
359
|
+
| { kind: "retry" }
|
|
360
|
+
| {
|
|
361
|
+
kind: "fail";
|
|
362
|
+
status: number;
|
|
363
|
+
errorText: string;
|
|
364
|
+
retryAfterMs?: number;
|
|
365
|
+
endpoint?: string;
|
|
366
|
+
context: RotationAttemptContext;
|
|
367
|
+
totalMs: number;
|
|
368
|
+
actionKind: Exclude<UpstreamAction["kind"], "success">;
|
|
369
|
+
providerResourceExhausted?: boolean;
|
|
370
|
+
noReplacementReason?: string;
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
type UpstreamFailureDecision = Extract<UpstreamActionDecision, { kind: "fail" }>;
|
|
374
|
+
type UpstreamFailureExtra = Partial<
|
|
375
|
+
Pick<
|
|
376
|
+
UpstreamFailureDecision,
|
|
377
|
+
| "retryAfterMs"
|
|
378
|
+
| "endpoint"
|
|
379
|
+
| "providerResourceExhausted"
|
|
380
|
+
| "noReplacementReason"
|
|
381
|
+
>
|
|
382
|
+
>;
|
|
383
|
+
|
|
384
|
+
type UpstreamActionHandlerOptions = {
|
|
385
|
+
action: Exclude<UpstreamAction, { kind: "success" }>;
|
|
386
|
+
provider: ProviderAdapter;
|
|
387
|
+
rotator: AccountRotator;
|
|
388
|
+
account: AccountRuntime;
|
|
389
|
+
model: string;
|
|
390
|
+
modelKey: string;
|
|
391
|
+
label: string;
|
|
392
|
+
context: RotationAttemptContext;
|
|
393
|
+
logRequestEnd: (status: string | number, extra?: string) => void;
|
|
394
|
+
rotateAndRelease: () => Promise<AccountRuntime | null>;
|
|
395
|
+
canRetry: boolean;
|
|
396
|
+
writeLog: (message: string, level?: "info" | "warn" | "error") => void;
|
|
397
|
+
recordFailureAttempt?: (statusCode: number) => void;
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
function buildFailureDecision(
|
|
401
|
+
options: UpstreamActionHandlerOptions,
|
|
402
|
+
status: number,
|
|
403
|
+
errorText: string,
|
|
404
|
+
extra: UpstreamFailureExtra = {},
|
|
405
|
+
): UpstreamFailureDecision {
|
|
406
|
+
return {
|
|
407
|
+
kind: "fail",
|
|
408
|
+
status,
|
|
409
|
+
errorText,
|
|
410
|
+
context: options.context,
|
|
411
|
+
totalMs: Date.now() - options.context.requestStartMs,
|
|
412
|
+
actionKind: options.action.kind,
|
|
413
|
+
endpoint: "endpoint" in options.action ? options.action.endpoint : undefined,
|
|
414
|
+
...extra,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function buildNoReplacementDecision(
|
|
419
|
+
options: UpstreamActionHandlerOptions,
|
|
420
|
+
reason: string,
|
|
421
|
+
): UpstreamFailureDecision {
|
|
422
|
+
const retryAfterMs = options.rotator.getRetryAfterMs(options.model);
|
|
423
|
+
if (retryAfterMs > 0) {
|
|
424
|
+
return buildFailureDecision(
|
|
425
|
+
options,
|
|
426
|
+
429,
|
|
427
|
+
`All accounts cooling down or model circuit breaker active: ${reason}`,
|
|
428
|
+
{ retryAfterMs, noReplacementReason: reason },
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
return buildFailureDecision(
|
|
432
|
+
options,
|
|
433
|
+
503,
|
|
434
|
+
`All accounts exhausted or disabled: ${reason}`,
|
|
435
|
+
{ noReplacementReason: reason },
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async function handleUpstreamAccountAction(
|
|
440
|
+
options: UpstreamActionHandlerOptions,
|
|
441
|
+
): Promise<UpstreamActionDecision> {
|
|
442
|
+
const {
|
|
443
|
+
action,
|
|
444
|
+
provider,
|
|
445
|
+
rotator,
|
|
446
|
+
account,
|
|
447
|
+
model,
|
|
448
|
+
modelKey,
|
|
449
|
+
label,
|
|
450
|
+
logRequestEnd,
|
|
451
|
+
rotateAndRelease,
|
|
452
|
+
writeLog,
|
|
453
|
+
recordFailureAttempt,
|
|
454
|
+
} = options;
|
|
455
|
+
|
|
456
|
+
if (action.kind === "rate-limited") {
|
|
457
|
+
writeLog(
|
|
458
|
+
`[${label}] 429 rate limited${action.providerResourceExhausted ? " (RESOURCE_EXHAUSTED)" : ""}, cooldown ${Math.ceil(action.cooldownMs / 1000)}s. Error text: ${action.errorText.slice(0, 300)}`,
|
|
459
|
+
"warn",
|
|
460
|
+
);
|
|
461
|
+
recordFailureAttempt?.(429);
|
|
462
|
+
rotator.markExhausted(
|
|
463
|
+
account,
|
|
464
|
+
model,
|
|
465
|
+
action.cooldownMs,
|
|
466
|
+
action.errorText.slice(0, 300),
|
|
467
|
+
);
|
|
468
|
+
rotator.recordProvider429(
|
|
469
|
+
account,
|
|
470
|
+
model,
|
|
471
|
+
action.cooldownMs,
|
|
472
|
+
action.providerResourceExhausted,
|
|
473
|
+
);
|
|
474
|
+
logRequestEnd(
|
|
475
|
+
429,
|
|
476
|
+
`cooldownMs=${action.cooldownMs}${action.providerResourceExhausted ? " resourceExhausted=true" : ""} endpoint=${action.endpoint}`,
|
|
477
|
+
);
|
|
478
|
+
|
|
479
|
+
if (
|
|
480
|
+
action.providerResourceExhausted &&
|
|
481
|
+
options.canRetry &&
|
|
482
|
+
provider.shouldRetryOnQuotaExhaustion(account, model, action.errorText)
|
|
483
|
+
) {
|
|
484
|
+
const nextAccount = await rotateAndRelease();
|
|
485
|
+
if (nextAccount) {
|
|
486
|
+
writeLog(
|
|
487
|
+
`[${label}] RESOURCE_EXHAUSTED is account-scoped; retrying with the next eligible account`,
|
|
488
|
+
"warn",
|
|
489
|
+
);
|
|
490
|
+
return { kind: "retry" };
|
|
491
|
+
}
|
|
492
|
+
writeLog(
|
|
493
|
+
`[${label}] RESOURCE_EXHAUSTED has no eligible replacement account; returning the provider error`,
|
|
494
|
+
"warn",
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
return buildFailureDecision(options, 429, action.errorText, {
|
|
499
|
+
retryAfterMs: action.cooldownMs,
|
|
500
|
+
providerResourceExhausted: action.providerResourceExhausted,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (action.kind === "flagged-401") {
|
|
505
|
+
writeLog(
|
|
506
|
+
`[${label}] BLOCKED (401): ${action.errorText.slice(0, 200)}`,
|
|
507
|
+
"error",
|
|
508
|
+
);
|
|
509
|
+
const lower401 = action.errorText.toLowerCase();
|
|
510
|
+
const matched401 = FLAG_PATTERNS.filter((p) => lower401.includes(p));
|
|
511
|
+
const ctx401 = rotator.getFlagContext(account, modelKey);
|
|
512
|
+
reportFlagEvent({
|
|
513
|
+
flagHttpStatus: 401,
|
|
514
|
+
flagPatternsMatched:
|
|
515
|
+
matched401.length > 0 ? matched401 : ["blocked_401" as FlagPattern],
|
|
516
|
+
model: modelKey,
|
|
517
|
+
timerType: ctx401.timerType as FlagEventData["timerType"],
|
|
518
|
+
accountQuotaPercent: ctx401.accountQuotaPercent,
|
|
519
|
+
wasProAccount: ctx401.wasProAccount,
|
|
520
|
+
accountTotalRequests: account.totalRequests,
|
|
521
|
+
accountRequestsLastHour: ctx401.accountRequestsLastHour,
|
|
522
|
+
accountConcurrentAtFlag: account.inFlightRequests,
|
|
523
|
+
poolSize: ctx401.poolSize,
|
|
524
|
+
poolHealthyCount: ctx401.poolHealthyCount,
|
|
525
|
+
protectivePauseTriggered: false,
|
|
526
|
+
uptimeSeconds: ctx401.uptimeSeconds,
|
|
527
|
+
timeSinceLastFlagSeconds: -1,
|
|
528
|
+
});
|
|
529
|
+
rotator.markFlagged(
|
|
530
|
+
account,
|
|
531
|
+
`Account blocked (401): ${action.errorText.slice(0, 300)}`,
|
|
532
|
+
);
|
|
533
|
+
logRequestEnd(401, `endpoint=${action.endpoint}`);
|
|
534
|
+
if (!options.canRetry) {
|
|
535
|
+
return buildFailureDecision(options, 401, action.errorText);
|
|
536
|
+
}
|
|
537
|
+
const nextAccount = await rotateAndRelease();
|
|
538
|
+
if (!nextAccount) {
|
|
539
|
+
return buildNoReplacementDecision(
|
|
540
|
+
options,
|
|
541
|
+
`no replacement account remained after ${label} was flagged with 401`,
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
return { kind: "retry" };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
if (action.kind === "flagged-403") {
|
|
548
|
+
writeLog(`[${label}] FLAGGED: ${action.errorText.slice(0, 200)}`, "error");
|
|
549
|
+
recordFailureAttempt?.(403);
|
|
550
|
+
logRequestEnd(403, `endpoint=${action.endpoint}`);
|
|
551
|
+
const lower = action.errorText.toLowerCase();
|
|
552
|
+
const matchedPatterns = FLAG_PATTERNS.filter((p) => lower.includes(p));
|
|
553
|
+
const ctx403 = rotator.getFlagContext(account, modelKey);
|
|
554
|
+
reportFlagEvent({
|
|
555
|
+
flagHttpStatus: 403,
|
|
556
|
+
flagPatternsMatched: matchedPatterns,
|
|
557
|
+
model: modelKey,
|
|
558
|
+
timerType: ctx403.timerType as FlagEventData["timerType"],
|
|
559
|
+
accountQuotaPercent: ctx403.accountQuotaPercent,
|
|
560
|
+
wasProAccount: ctx403.wasProAccount,
|
|
561
|
+
accountTotalRequests: account.totalRequests,
|
|
562
|
+
accountRequestsLastHour: ctx403.accountRequestsLastHour,
|
|
563
|
+
accountConcurrentAtFlag: account.inFlightRequests,
|
|
564
|
+
poolSize: ctx403.poolSize,
|
|
565
|
+
poolHealthyCount: ctx403.poolHealthyCount,
|
|
566
|
+
protectivePauseTriggered: false,
|
|
567
|
+
uptimeSeconds: ctx403.uptimeSeconds,
|
|
568
|
+
timeSinceLastFlagSeconds: -1,
|
|
569
|
+
});
|
|
570
|
+
rotator.markFlagged(account, action.errorText.slice(0, 300));
|
|
571
|
+
if (!options.canRetry) {
|
|
572
|
+
return buildFailureDecision(options, 403, action.errorText);
|
|
573
|
+
}
|
|
574
|
+
const nextAccount = await rotateAndRelease();
|
|
575
|
+
if (!nextAccount) {
|
|
576
|
+
return buildNoReplacementDecision(
|
|
577
|
+
options,
|
|
578
|
+
`no replacement account remained after ${label} was flagged with 403`,
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
return { kind: "retry" };
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (action.kind === "forbidden") {
|
|
585
|
+
writeLog(`[${label}] 403: ${action.errorText.slice(0, 200)}`, "warn");
|
|
586
|
+
logRequestEnd(403, `endpoint=${action.endpoint}`);
|
|
587
|
+
return buildFailureDecision(options, 403, action.errorText);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
if (action.kind === "not-found") {
|
|
591
|
+
writeLog(
|
|
592
|
+
`[${label}] 404 from ${action.endpoint}: ${action.errorText.slice(0, 200)}`,
|
|
593
|
+
"warn",
|
|
594
|
+
);
|
|
595
|
+
logRequestEnd(404, `endpoint=${action.endpoint}`);
|
|
596
|
+
return buildFailureDecision(options, 404, action.errorText);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
if (action.kind === "bad-request") {
|
|
600
|
+
writeLog(
|
|
601
|
+
`[${label}] 400 Bad Request from ${action.endpoint}: ${action.errorText.slice(0, 500)}`,
|
|
602
|
+
"warn",
|
|
603
|
+
);
|
|
604
|
+
logRequestEnd(400, `endpoint=${action.endpoint}`);
|
|
605
|
+
return buildFailureDecision(options, 400, action.errorText);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (action.kind === "server-error-503") {
|
|
609
|
+
writeLog(
|
|
610
|
+
`[${label}] Server error 503: ${action.errorText.slice(0, 200)}`,
|
|
611
|
+
"warn",
|
|
612
|
+
);
|
|
613
|
+
recordFailureAttempt?.(503);
|
|
614
|
+
logRequestEnd(503, `endpoint=${action.endpoint}`);
|
|
615
|
+
rotator.markError(account, `503: ${action.errorText.slice(0, 200)}`);
|
|
616
|
+
if (!options.canRetry) {
|
|
617
|
+
return buildFailureDecision(options, 503, action.errorText);
|
|
618
|
+
}
|
|
619
|
+
const nextAccount = await rotateAndRelease();
|
|
620
|
+
if (!nextAccount) {
|
|
621
|
+
return buildNoReplacementDecision(
|
|
622
|
+
options,
|
|
623
|
+
`no replacement account remained after ${label} failed with 503`,
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
return { kind: "retry" };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
writeLog(
|
|
630
|
+
`[${label}] Server error ${action.httpStatus}: ${action.errorText.slice(0, 200)}`,
|
|
631
|
+
"warn",
|
|
632
|
+
);
|
|
633
|
+
recordFailureAttempt?.(action.httpStatus);
|
|
634
|
+
logRequestEnd(action.httpStatus, `endpoint=${action.endpoint}`);
|
|
635
|
+
rotator.markError(
|
|
636
|
+
account,
|
|
637
|
+
`${action.httpStatus}: ${action.errorText.slice(0, 200)}`,
|
|
638
|
+
);
|
|
639
|
+
if (!options.canRetry) {
|
|
640
|
+
return buildFailureDecision(options, action.httpStatus, action.errorText);
|
|
641
|
+
}
|
|
642
|
+
const nextAccount = await rotateAndRelease();
|
|
643
|
+
if (!nextAccount) {
|
|
644
|
+
return buildNoReplacementDecision(
|
|
645
|
+
options,
|
|
646
|
+
`no replacement account remained after ${label} failed with ${action.httpStatus}`,
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
return { kind: "retry" };
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function failureDecisionToOutcome<T>(
|
|
653
|
+
decision: UpstreamFailureDecision,
|
|
654
|
+
): RotationOutcome<T> {
|
|
655
|
+
return {
|
|
656
|
+
ok: false,
|
|
657
|
+
status: decision.status,
|
|
658
|
+
errorText: decision.errorText,
|
|
659
|
+
retryAfterMs: decision.retryAfterMs,
|
|
660
|
+
endpoint: decision.endpoint,
|
|
661
|
+
context: decision.context,
|
|
662
|
+
totalMs: decision.totalMs,
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function formatError(err: unknown): string {
|
|
667
|
+
if (!(err instanceof Error)) return String(err);
|
|
668
|
+
const cause = err.cause;
|
|
669
|
+
if (cause && typeof cause === "object") {
|
|
670
|
+
const code = "code" in cause ? String(cause.code) : null;
|
|
671
|
+
const message = "message" in cause ? String(cause.message) : null;
|
|
672
|
+
if (code || message) {
|
|
673
|
+
return `${err.name}: ${err.message} (${[code, message].filter(Boolean).join(": ")})`;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return `${err.name}: ${err.message}`;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function isFetchTransportError(err: unknown): boolean {
|
|
680
|
+
if (err instanceof PreFlushStreamError) return true;
|
|
681
|
+
if (err instanceof TypeError && /^(fetch failed|terminated)$/i.test(err.message)) {
|
|
682
|
+
return true;
|
|
683
|
+
}
|
|
684
|
+
if (err && typeof err === "object" && "code" in err) {
|
|
685
|
+
return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(
|
|
686
|
+
String(err.code),
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
return false;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
async function readJsonRequest(req: IncomingMessage): Promise<unknown> {
|
|
693
|
+
const body = await readLimitedBody(req);
|
|
694
|
+
return body.length === 0 ? {} : JSON.parse(body.toString("utf-8"));
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async function streamResponseBody(
|
|
698
|
+
body: Response["body"],
|
|
699
|
+
req: IncomingMessage,
|
|
700
|
+
res: ServerResponse,
|
|
701
|
+
label: string,
|
|
702
|
+
proxyLog: (msg: string, level?: "info" | "warn" | "error") => void,
|
|
703
|
+
responseStatus: number,
|
|
704
|
+
responseHeaders: Record<string, string>,
|
|
705
|
+
accumulator: StreamAccumulator = new SseEventAccumulator(),
|
|
706
|
+
): Promise<{
|
|
707
|
+
inputTokens: number;
|
|
708
|
+
outputTokens: number;
|
|
709
|
+
firstByteMs: number;
|
|
710
|
+
responseText?: string;
|
|
711
|
+
streamError?: string;
|
|
712
|
+
} | null> {
|
|
713
|
+
if (!body) {
|
|
714
|
+
if (!res.headersSent && !res.destroyed) {
|
|
715
|
+
res.writeHead(responseStatus, responseHeaders);
|
|
716
|
+
}
|
|
717
|
+
return null;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const nodeStream = Readable.fromWeb(
|
|
721
|
+
body as import("node:stream/web").ReadableStream,
|
|
722
|
+
);
|
|
723
|
+
const eventAccumulator = accumulator;
|
|
724
|
+
let firstUsage: { inputTokens: number; outputTokens: number } | null = null;
|
|
725
|
+
let streamError: string | undefined;
|
|
726
|
+
const streamStartMs = Date.now();
|
|
727
|
+
let firstByteMs = 0;
|
|
728
|
+
let hasForwardedBytes = false;
|
|
729
|
+
|
|
730
|
+
const usage = await new Promise<{
|
|
731
|
+
inputTokens: number;
|
|
732
|
+
outputTokens: number;
|
|
733
|
+
firstByteMs: number;
|
|
734
|
+
responseText?: string;
|
|
735
|
+
streamError?: string;
|
|
736
|
+
} | null>((resolve, reject) => {
|
|
737
|
+
let settled = false;
|
|
738
|
+
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
739
|
+
|
|
740
|
+
const cleanup = (): void => {
|
|
741
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
742
|
+
nodeStream.off("data", onData);
|
|
743
|
+
nodeStream.off("end", onEnd);
|
|
744
|
+
nodeStream.off("error", onError);
|
|
745
|
+
nodeStream.off("close", onClose);
|
|
746
|
+
req.off("close", onClientClose);
|
|
747
|
+
res.off("close", onResponseClose);
|
|
748
|
+
res.off("error", onResponseError);
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
const finish = (reason?: string): void => {
|
|
752
|
+
if (settled) return;
|
|
753
|
+
settled = true;
|
|
754
|
+
if (reason) proxyLog(`[${label}] Stream closed: ${reason}`, "warn");
|
|
755
|
+
cleanup();
|
|
756
|
+
// Drain any partial event that didn't end with \n\n
|
|
757
|
+
if (!firstUsage) firstUsage = eventAccumulator.final();
|
|
758
|
+
if (firstUsage || streamError) {
|
|
759
|
+
resolve({
|
|
760
|
+
...(firstUsage || { inputTokens: 0, outputTokens: 0 }),
|
|
761
|
+
firstByteMs,
|
|
762
|
+
responseText: eventAccumulator.getText(),
|
|
763
|
+
streamError,
|
|
764
|
+
});
|
|
765
|
+
} else {
|
|
766
|
+
resolve(null);
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
|
|
770
|
+
const failBeforeFlush = (err: unknown): void => {
|
|
771
|
+
if (settled) return;
|
|
772
|
+
settled = true;
|
|
773
|
+
cleanup();
|
|
774
|
+
reject(new PreFlushStreamError(err));
|
|
775
|
+
};
|
|
776
|
+
|
|
777
|
+
const emitStreamError = (err: unknown): void => {
|
|
778
|
+
streamError = formatError(err).slice(0, 200);
|
|
779
|
+
if (res.destroyed || res.writableEnded) return;
|
|
780
|
+
res.write(
|
|
781
|
+
`data: ${JSON.stringify({ error: { code: 502, status: "BAD_GATEWAY", message: streamError } })}\n\n`,
|
|
782
|
+
);
|
|
783
|
+
};
|
|
784
|
+
|
|
785
|
+
const resetIdleTimer = (): void => {
|
|
786
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
787
|
+
idleTimer = setTimeout(() => {
|
|
788
|
+
const error = new Error(
|
|
789
|
+
`idle timeout after ${Math.round(STREAM_IDLE_TIMEOUT_MS / 1000)}s`,
|
|
790
|
+
);
|
|
791
|
+
if (hasForwardedBytes) emitStreamError(error);
|
|
792
|
+
finish(
|
|
793
|
+
error.message,
|
|
794
|
+
);
|
|
795
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
796
|
+
}, STREAM_IDLE_TIMEOUT_MS);
|
|
797
|
+
};
|
|
798
|
+
|
|
799
|
+
const onData = (chunk: Buffer): void => {
|
|
800
|
+
if (firstByteMs === 0) firstByteMs = Date.now() - streamStartMs;
|
|
801
|
+
resetIdleTimer();
|
|
802
|
+
// Forward to client immediately (real-time streaming preserved)
|
|
803
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
804
|
+
if (!res.headersSent) res.writeHead(responseStatus, responseHeaders);
|
|
805
|
+
hasForwardedBytes = true;
|
|
806
|
+
res.write(chunk);
|
|
807
|
+
}
|
|
808
|
+
// Extract usage from any newly-completed SSE events
|
|
809
|
+
if (!firstUsage) {
|
|
810
|
+
const usage = eventAccumulator.append(chunk.toString());
|
|
811
|
+
if (usage) firstUsage = usage;
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
const onEnd = (): void => finish();
|
|
815
|
+
const onError = (err: Error): void => {
|
|
816
|
+
if (!hasForwardedBytes) {
|
|
817
|
+
failBeforeFlush(err);
|
|
818
|
+
} else {
|
|
819
|
+
emitStreamError(err);
|
|
820
|
+
finish(String(err));
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
const onClose = (): void => {
|
|
824
|
+
if (!hasForwardedBytes) {
|
|
825
|
+
failBeforeFlush(new Error("upstream stream closed before response data"));
|
|
826
|
+
} else {
|
|
827
|
+
emitStreamError(new Error("upstream stream closed before response completion"));
|
|
828
|
+
finish();
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
// req.aborted is deprecated and unreliable since Node 18+.
|
|
832
|
+
// req.on("close") is the correct signal for client disconnect in Node 22.
|
|
833
|
+
const onClientClose = (): void => {
|
|
834
|
+
// Always destroy when the client disconnects — regardless of writableEnded.
|
|
835
|
+
// The upstream stream from Google may still be open even if res finished writing,
|
|
836
|
+
// which would leave the account stuck in-flight until the idle timeout.
|
|
837
|
+
if (!settled) {
|
|
838
|
+
nodeStream.destroy();
|
|
839
|
+
finish("client closed connection");
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
const onResponseClose = (): void => {
|
|
843
|
+
if (!settled) {
|
|
844
|
+
nodeStream.destroy();
|
|
845
|
+
finish("response closed before completion");
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
const onResponseError = (err: Error): void => {
|
|
849
|
+
nodeStream.destroy(err);
|
|
850
|
+
finish(String(err));
|
|
851
|
+
};
|
|
852
|
+
|
|
853
|
+
nodeStream.on("data", onData);
|
|
854
|
+
nodeStream.once("end", onEnd);
|
|
855
|
+
nodeStream.once("error", onError);
|
|
856
|
+
nodeStream.once("close", onClose);
|
|
857
|
+
req.once("close", onClientClose);
|
|
858
|
+
res.once("close", onResponseClose);
|
|
859
|
+
res.once("error", onResponseError);
|
|
860
|
+
resetIdleTimer();
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
if (!res.headersSent && !res.destroyed) {
|
|
864
|
+
res.writeHead(responseStatus, responseHeaders);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
return usage;
|
|
868
|
+
}function benchmarkFailure(
|
|
869
|
+
account: AccountRuntime,
|
|
870
|
+
startedAt: number,
|
|
871
|
+
error: string,
|
|
872
|
+
ttfbMs: number | null = null,
|
|
873
|
+
): BenchmarkResult {
|
|
874
|
+
return {
|
|
875
|
+
account: maskAccountLabel(account.config.label || account.config.email),
|
|
876
|
+
status: "failed",
|
|
877
|
+
latencyMs: Date.now() - startedAt,
|
|
878
|
+
ttfbMs,
|
|
879
|
+
outputTokens: null,
|
|
880
|
+
tokensPerSecond: null,
|
|
881
|
+
error: error.slice(0, 240),
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
export async function benchmarkAccount(
|
|
886
|
+
rotator: AccountRotator,
|
|
887
|
+
account: AccountRuntime,
|
|
888
|
+
sharedSignal?: AbortSignal,
|
|
889
|
+
): Promise<BenchmarkResult> {
|
|
890
|
+
const label = maskAccountLabel(account.config.label || account.config.email);
|
|
891
|
+
const startedAt = Date.now();
|
|
892
|
+
const maxConcurrent = Math.max(
|
|
893
|
+
1,
|
|
894
|
+
rotator.getConfig().maxConcurrentRequestsPerAccount ?? 1,
|
|
895
|
+
);
|
|
896
|
+
if (account.inFlightRequests >= maxConcurrent) {
|
|
897
|
+
return {
|
|
898
|
+
account: label,
|
|
899
|
+
status: "skipped",
|
|
900
|
+
latencyMs: null,
|
|
901
|
+
ttfbMs: null,
|
|
902
|
+
outputTokens: null,
|
|
903
|
+
tokensPerSecond: null,
|
|
904
|
+
error: "Account already has the maximum number of in-flight requests",
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const benchmarkSpec = getProviderForAccount(account.config).getBenchmark(account);
|
|
909
|
+
rotator.startRequest(account, benchmarkSpec.body.model);
|
|
910
|
+
const timeoutController = new AbortController();
|
|
911
|
+
const timeout = setTimeout(
|
|
912
|
+
() => timeoutController.abort(new Error("Benchmark timeout")),
|
|
913
|
+
GOOGLE_BENCHMARK_CONSTANTS.timeoutMs,
|
|
914
|
+
);
|
|
915
|
+
const signal = sharedSignal
|
|
916
|
+
? AbortSignal.any([timeoutController.signal, sharedSignal])
|
|
917
|
+
: timeoutController.signal;
|
|
918
|
+
let ttfbMs: number | null = null;
|
|
919
|
+
|
|
920
|
+
try {
|
|
921
|
+
await rotator.ensureValidToken(account);
|
|
922
|
+
const forwarded = await providerAdapterForModel(
|
|
923
|
+
account,
|
|
924
|
+
benchmarkSpec.body.model,
|
|
925
|
+
rotator,
|
|
926
|
+
).forwardRequest(account, benchmarkSpec.body, {}, signal);
|
|
927
|
+
ttfbMs = Date.now() - startedAt;
|
|
928
|
+
const raw = await forwarded.response.text();
|
|
929
|
+
const latencyMs = Date.now() - startedAt;
|
|
930
|
+
if (!forwarded.response.ok) {
|
|
931
|
+
return benchmarkFailure(
|
|
932
|
+
account,
|
|
933
|
+
startedAt,
|
|
934
|
+
`HTTP ${forwarded.response.status}: ${raw || forwarded.response.statusText}`,
|
|
935
|
+
ttfbMs,
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const usage = benchmarkSpec.parseUsage(raw);
|
|
940
|
+
const outputTokens = usage?.outputTokens ?? Math.max(1, Math.ceil(raw.length / 4));
|
|
941
|
+
return {
|
|
942
|
+
account: label,
|
|
943
|
+
status: "success",
|
|
944
|
+
latencyMs,
|
|
945
|
+
ttfbMs,
|
|
946
|
+
outputTokens,
|
|
947
|
+
tokensPerSecond: outputTokens / Math.max(latencyMs / 1000, 0.001),
|
|
948
|
+
};
|
|
949
|
+
} catch (err) {
|
|
950
|
+
return benchmarkFailure(account, startedAt, formatError(err), ttfbMs);
|
|
951
|
+
} finally {
|
|
952
|
+
clearTimeout(timeout);
|
|
953
|
+
rotator.finishRequest(account, benchmarkSpec.body.model);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function averageBenchmarkMetric(
|
|
958
|
+
results: BenchmarkResult[],
|
|
959
|
+
metric: "latencyMs" | "ttfbMs" | "tokensPerSecond",
|
|
960
|
+
): number | null {
|
|
961
|
+
const values = results
|
|
962
|
+
.filter((result) => result.status === "success")
|
|
963
|
+
.map((result) => result[metric])
|
|
964
|
+
.filter((value): value is number => value !== null);
|
|
965
|
+
if (values.length === 0) return null;
|
|
966
|
+
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
export function summarizeBenchmarkResults(
|
|
970
|
+
results: BenchmarkResult[],
|
|
971
|
+
): BenchmarkSummary {
|
|
972
|
+
const succeeded = results.filter((result) => result.status === "success").length;
|
|
973
|
+
const failed = results.filter((result) => result.status === "failed").length;
|
|
974
|
+
const skipped = results.filter((result) => result.status === "skipped").length;
|
|
975
|
+
return {
|
|
976
|
+
total: results.length,
|
|
977
|
+
succeeded,
|
|
978
|
+
failed,
|
|
979
|
+
skipped,
|
|
980
|
+
successRate: results.length > 0 ? (succeeded / results.length) * 100 : 0,
|
|
981
|
+
averageLatencyMs: averageBenchmarkMetric(results, "latencyMs"),
|
|
982
|
+
averageTtfbMs: averageBenchmarkMetric(results, "ttfbMs"),
|
|
983
|
+
averageTokensPerSecond: averageBenchmarkMetric(results, "tokensPerSecond"),
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function sortBenchmarkResults(results: BenchmarkResult[]): BenchmarkResult[] {
|
|
988
|
+
const rank: Record<BenchmarkResultStatus, number> = {
|
|
989
|
+
success: 0,
|
|
990
|
+
failed: 1,
|
|
991
|
+
skipped: 2,
|
|
992
|
+
};
|
|
993
|
+
return results.sort((a, b) => {
|
|
994
|
+
if (rank[a.status] !== rank[b.status]) return rank[a.status] - rank[b.status];
|
|
995
|
+
if (a.status === "success" && b.status === "success") {
|
|
996
|
+
return (b.tokensPerSecond ?? 0) - (a.tokensPerSecond ?? 0);
|
|
997
|
+
}
|
|
998
|
+
return a.account.localeCompare(b.account);
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
function writeBenchmarkEvent(
|
|
1003
|
+
res: ServerResponse,
|
|
1004
|
+
payload: Record<string, unknown>,
|
|
1005
|
+
): boolean {
|
|
1006
|
+
if (res.writableEnded || res.destroyed) return false;
|
|
1007
|
+
try {
|
|
1008
|
+
res.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
1009
|
+
return true;
|
|
1010
|
+
} catch {
|
|
1011
|
+
return false;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
export async function serveBenchmarkApi(
|
|
1016
|
+
res: ServerResponse,
|
|
1017
|
+
rotator: AccountRotator,
|
|
1018
|
+
): Promise<void> {
|
|
1019
|
+
res.writeHead(200, {
|
|
1020
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
1021
|
+
"Cache-Control": "no-cache, no-store",
|
|
1022
|
+
Connection: "keep-alive",
|
|
1023
|
+
"X-Accel-Buffering": "no",
|
|
1024
|
+
});
|
|
1025
|
+
res.write(": benchmark\n\n");
|
|
1026
|
+
|
|
1027
|
+
const accounts = rotator.getBenchmarkAccounts();
|
|
1028
|
+
const clientController = new AbortController();
|
|
1029
|
+
const onClose = (): void => clientController.abort();
|
|
1030
|
+
res.once("close", onClose);
|
|
1031
|
+
const results: BenchmarkResult[] = [];
|
|
1032
|
+
|
|
1033
|
+
try {
|
|
1034
|
+
writeBenchmarkEvent(res, {
|
|
1035
|
+
type: "start",
|
|
1036
|
+
total: accounts.length,
|
|
1037
|
+
model: GOOGLE_BENCHMARK_CONSTANTS.model,
|
|
1038
|
+
});
|
|
1039
|
+
await Promise.all(
|
|
1040
|
+
accounts.map(async (account) => {
|
|
1041
|
+
const result = await benchmarkAccount(
|
|
1042
|
+
rotator,
|
|
1043
|
+
account,
|
|
1044
|
+
clientController.signal,
|
|
1045
|
+
);
|
|
1046
|
+
results.push(result);
|
|
1047
|
+
writeBenchmarkEvent(res, {
|
|
1048
|
+
type: "progress",
|
|
1049
|
+
completed: results.length,
|
|
1050
|
+
total: accounts.length,
|
|
1051
|
+
result,
|
|
1052
|
+
});
|
|
1053
|
+
}),
|
|
1054
|
+
);
|
|
1055
|
+
const sortedResults = sortBenchmarkResults(results);
|
|
1056
|
+
writeBenchmarkEvent(res, {
|
|
1057
|
+
type: "complete",
|
|
1058
|
+
summary: summarizeBenchmarkResults(sortedResults),
|
|
1059
|
+
results: sortedResults,
|
|
1060
|
+
});
|
|
1061
|
+
} catch (err) {
|
|
1062
|
+
const details = formatError(err);
|
|
1063
|
+
proxyLogger.error(`Benchmark failed: ${details}`);
|
|
1064
|
+
writeBenchmarkEvent(res, {
|
|
1065
|
+
type: "error",
|
|
1066
|
+
error: "Benchmark failed",
|
|
1067
|
+
});
|
|
1068
|
+
} finally {
|
|
1069
|
+
res.off("close", onClose);
|
|
1070
|
+
if (!res.writableEnded) res.end();
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
export async function withRotation<T>(
|
|
1075
|
+
rotator: AccountRotator,
|
|
1076
|
+
model: string,
|
|
1077
|
+
originalHeaders: Record<string, string>,
|
|
1078
|
+
body: RequestBody,
|
|
1079
|
+
onSuccess: (
|
|
1080
|
+
response: Response,
|
|
1081
|
+
context: RotationAttemptContext,
|
|
1082
|
+
) => Promise<T>,
|
|
1083
|
+
): Promise<RotationOutcome<T>> {
|
|
1084
|
+
const sendNoAccountsAvailable = (
|
|
1085
|
+
reason: string,
|
|
1086
|
+
context?: RotationAttemptContext,
|
|
1087
|
+
): RotationOutcome<T> => {
|
|
1088
|
+
log(`[${model}] No healthy account available: ${reason}`, rotator, "warn");
|
|
1089
|
+
const retryAfterMs = rotator.getRetryAfterMs(model);
|
|
1090
|
+
const contextFields = context
|
|
1091
|
+
? { context, totalMs: Date.now() - context.requestStartMs }
|
|
1092
|
+
: {};
|
|
1093
|
+
if (retryAfterMs > 0) {
|
|
1094
|
+
return {
|
|
1095
|
+
ok: false,
|
|
1096
|
+
status: 429,
|
|
1097
|
+
errorText: `All accounts cooling down or model circuit breaker active: ${reason}`,
|
|
1098
|
+
retryAfterMs,
|
|
1099
|
+
...contextFields,
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
return {
|
|
1103
|
+
ok: false,
|
|
1104
|
+
status: 503,
|
|
1105
|
+
errorText: `All accounts exhausted or disabled: ${reason}`,
|
|
1106
|
+
...contextFields,
|
|
1107
|
+
};
|
|
1108
|
+
};
|
|
1109
|
+
|
|
1110
|
+
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1111
|
+
const nextAccount = await rotator.rotateToNext(model);
|
|
1112
|
+
if (nextAccount) {
|
|
1113
|
+
rotator.finishRequest(
|
|
1114
|
+
nextAccount,
|
|
1115
|
+
resolveQuotaModelKey(model) ?? undefined,
|
|
1116
|
+
);
|
|
1117
|
+
}
|
|
1118
|
+
return nextAccount;
|
|
1119
|
+
};
|
|
1120
|
+
|
|
1121
|
+
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1122
|
+
const maxAttempts = maxRetries + 1;
|
|
1123
|
+
|
|
1124
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1125
|
+
const account = await rotator.getActiveAccount(model);
|
|
1126
|
+
if (!account) {
|
|
1127
|
+
return sendNoAccountsAvailable("rotation returned no available account");
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
const label = account.config.label || account.config.email;
|
|
1131
|
+
const modelKey = resolveQuotaModelKey(model) ?? model;
|
|
1132
|
+
const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
|
|
1133
|
+
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1134
|
+
const requestStartMs = Date.now();
|
|
1135
|
+
const logRequestEnd = (status: string | number, extra = ""): void => {
|
|
1136
|
+
log(
|
|
1137
|
+
`[${requestId}] END account=${label} model=${model} status=${status}${extra ? ` ${extra}` : ""} totalMs=${Date.now() - requestStartMs}`,
|
|
1138
|
+
rotator,
|
|
1139
|
+
status === 200 || status === 0 ? "info" : "warn",
|
|
1140
|
+
);
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
log(
|
|
1144
|
+
`[${requestId}] START account=${label} model=${model} attempt=${attempt + 1}`,
|
|
1145
|
+
rotator,
|
|
1146
|
+
);
|
|
1147
|
+
|
|
1148
|
+
try {
|
|
1149
|
+
const jitterMs = rotator.getSafetyJitterMs(account);
|
|
1150
|
+
const globalDelayMs = rotator.getGlobalDelayMs();
|
|
1151
|
+
const totalDelayMs = jitterMs + globalDelayMs;
|
|
1152
|
+
if (totalDelayMs > 0) {
|
|
1153
|
+
if (jitterMs > 0) {
|
|
1154
|
+
log(
|
|
1155
|
+
`[${requestId}] Safety slow-mode jitter ${jitterMs}ms for account/project daily budget pressure`,
|
|
1156
|
+
rotator,
|
|
1157
|
+
"warn",
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
if (globalDelayMs > 0) {
|
|
1161
|
+
log(
|
|
1162
|
+
`[${requestId}] Global request delay ${globalDelayMs}ms applied to slow down requests`,
|
|
1163
|
+
rotator,
|
|
1164
|
+
"info",
|
|
1165
|
+
);
|
|
1166
|
+
}
|
|
1167
|
+
await sleep(totalDelayMs);
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
rotator.recordUpstreamAttempt(account);
|
|
1171
|
+
const provider = providerAdapterForModel(
|
|
1172
|
+
account,
|
|
1173
|
+
model,
|
|
1174
|
+
rotator,
|
|
1175
|
+
);
|
|
1176
|
+
const forwarded = await provider.forwardRequest(
|
|
1177
|
+
account,
|
|
1178
|
+
{ ...body },
|
|
1179
|
+
originalHeaders,
|
|
1180
|
+
);
|
|
1181
|
+
const { response, endpoint } = forwarded;
|
|
1182
|
+
const context: RotationAttemptContext = {
|
|
1183
|
+
account,
|
|
1184
|
+
label,
|
|
1185
|
+
modelKey,
|
|
1186
|
+
displayModelKey,
|
|
1187
|
+
requestId,
|
|
1188
|
+
requestStartMs,
|
|
1189
|
+
endpoint,
|
|
1190
|
+
retries: attempt,
|
|
1191
|
+
};
|
|
1192
|
+
|
|
1193
|
+
const action = await classifyUpstreamResponse(
|
|
1194
|
+
response,
|
|
1195
|
+
endpoint,
|
|
1196
|
+
account,
|
|
1197
|
+
model,
|
|
1198
|
+
modelKey,
|
|
1199
|
+
);
|
|
1200
|
+
|
|
1201
|
+
if (action.kind !== "success") {
|
|
1202
|
+
const decision = await handleUpstreamAccountAction({
|
|
1203
|
+
action,
|
|
1204
|
+
provider,
|
|
1205
|
+
rotator,
|
|
1206
|
+
account,
|
|
1207
|
+
model,
|
|
1208
|
+
modelKey,
|
|
1209
|
+
label,
|
|
1210
|
+
context,
|
|
1211
|
+
logRequestEnd,
|
|
1212
|
+
rotateAndRelease,
|
|
1213
|
+
canRetry: attempt < maxRetries,
|
|
1214
|
+
writeLog: (message, level = "info") => log(message, rotator, level),
|
|
1215
|
+
});
|
|
1216
|
+
if (decision.kind === "retry") continue;
|
|
1217
|
+
return failureDecisionToOutcome(decision);
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
// success
|
|
1221
|
+
const result = await onSuccess(response, context);
|
|
1222
|
+
const shouldRotate = rotator.recordRequest(account, model);
|
|
1223
|
+
logRequestEnd(response.status, `endpoint=${endpoint}`);
|
|
1224
|
+
if (shouldRotate) {
|
|
1225
|
+
await rotateAndRelease();
|
|
1226
|
+
}
|
|
1227
|
+
return { ok: true, result, endpoint, context };
|
|
1228
|
+
} catch (err) {
|
|
1229
|
+
const formattedError = formatError(err);
|
|
1230
|
+
log(
|
|
1231
|
+
`[${label}] Request failed: ${formattedError}`,
|
|
1232
|
+
rotator,
|
|
1233
|
+
isFetchTransportError(err) ? "warn" : "error",
|
|
1234
|
+
);
|
|
1235
|
+
logRequestEnd(
|
|
1236
|
+
isFetchTransportError(err) ? "fetch-error" : 500,
|
|
1237
|
+
`error=${formattedError.slice(0, 120)}`,
|
|
1238
|
+
);
|
|
1239
|
+
if (!isFetchTransportError(err)) {
|
|
1240
|
+
rotator.markError(account, formattedError);
|
|
1241
|
+
return {
|
|
1242
|
+
ok: false,
|
|
1243
|
+
status: 502,
|
|
1244
|
+
errorText: GENERIC_UPSTREAM_ERROR,
|
|
1245
|
+
context: {
|
|
1246
|
+
account,
|
|
1247
|
+
label,
|
|
1248
|
+
modelKey,
|
|
1249
|
+
displayModelKey,
|
|
1250
|
+
requestId,
|
|
1251
|
+
requestStartMs,
|
|
1252
|
+
endpoint: "unknown",
|
|
1253
|
+
retries: attempt,
|
|
1254
|
+
},
|
|
1255
|
+
totalMs: Date.now() - requestStartMs,
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
if (attempt >= maxRetries) {
|
|
1259
|
+
return {
|
|
1260
|
+
ok: false,
|
|
1261
|
+
status: 502,
|
|
1262
|
+
errorText: "All retry attempts failed",
|
|
1263
|
+
context: {
|
|
1264
|
+
account,
|
|
1265
|
+
label,
|
|
1266
|
+
modelKey,
|
|
1267
|
+
displayModelKey,
|
|
1268
|
+
requestId,
|
|
1269
|
+
requestStartMs,
|
|
1270
|
+
endpoint: "unknown",
|
|
1271
|
+
retries: attempt,
|
|
1272
|
+
},
|
|
1273
|
+
totalMs: Date.now() - requestStartMs,
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
const nextAccount = await rotateAndRelease();
|
|
1277
|
+
if (!nextAccount) {
|
|
1278
|
+
return sendNoAccountsAvailable(
|
|
1279
|
+
`no replacement account remained after ${label} request error`,
|
|
1280
|
+
);
|
|
1281
|
+
}
|
|
1282
|
+
continue;
|
|
1283
|
+
} finally {
|
|
1284
|
+
rotator.finishRequest(account, resolveQuotaModelKey(model) ?? undefined);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
return { ok: false, status: 502, errorText: "All retry attempts failed" };
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
function log(
|
|
1292
|
+
msg: string,
|
|
1293
|
+
rotator?: AccountRotator,
|
|
1294
|
+
level: "info" | "warn" | "error" = "info",
|
|
1295
|
+
): void {
|
|
1296
|
+
proxyLogger.log(level, msg);
|
|
1297
|
+
rotator?.recordProxyEvent(msg, level);
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
function isGeminiGenerateContentPath(pathname: string): boolean {
|
|
1301
|
+
const prefix = "/v1beta/models/";
|
|
1302
|
+
if (!pathname.startsWith(prefix)) return false;
|
|
1303
|
+
|
|
1304
|
+
const separator = pathname.lastIndexOf(":");
|
|
1305
|
+
if (separator <= prefix.length || separator === pathname.length - 1) {
|
|
1306
|
+
return false;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
const operation = pathname.slice(separator + 1);
|
|
1310
|
+
return operation === "generateContent" || operation === "streamGenerateContent";
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* Handle a proxied API request.
|
|
1315
|
+
*/
|
|
1316
|
+
async function handleProxyRequest(
|
|
1317
|
+
req: IncomingMessage,
|
|
1318
|
+
res: ServerResponse,
|
|
1319
|
+
rotator: AccountRotator,
|
|
1320
|
+
onComplete?: () => void,
|
|
1321
|
+
nativeOllamaChat = false,
|
|
1322
|
+
): Promise<void> {
|
|
1323
|
+
let bodyBuffer: Buffer;
|
|
1324
|
+
try {
|
|
1325
|
+
bodyBuffer = await readLimitedBody(req);
|
|
1326
|
+
} catch (err) {
|
|
1327
|
+
if (err instanceof PayloadTooLargeError) {
|
|
1328
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
1329
|
+
res.end(
|
|
1330
|
+
JSON.stringify({
|
|
1331
|
+
error: "Payload too large",
|
|
1332
|
+
limitBytes: err.limitBytes,
|
|
1333
|
+
}),
|
|
1334
|
+
);
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
throw err;
|
|
1338
|
+
}
|
|
1339
|
+
let body: RequestBody;
|
|
1340
|
+
if (nativeOllamaChat) {
|
|
1341
|
+
// Native /api/chat payload ({model, messages, stream, options}) is
|
|
1342
|
+
// translated to the internal body shape; the internal validator expects
|
|
1343
|
+
// the wrapped format, so parse the native shape first.
|
|
1344
|
+
let raw: Record<string, unknown>;
|
|
1345
|
+
try {
|
|
1346
|
+
const parsed: unknown = JSON.parse(bodyBuffer.toString("utf-8"));
|
|
1347
|
+
raw = isRecord(parsed) ? parsed : {};
|
|
1348
|
+
} catch {
|
|
1349
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1350
|
+
res.end(JSON.stringify({ error: "Invalid JSON body" }));
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
if (typeof raw.model !== "string" || raw.model === "") {
|
|
1354
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1355
|
+
res.end(JSON.stringify({ error: "Invalid request body: model required" }));
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (!Array.isArray(raw.messages) || raw.messages.length === 0) {
|
|
1359
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1360
|
+
res.end(
|
|
1361
|
+
JSON.stringify({ error: "Invalid request body: messages required" }),
|
|
1362
|
+
);
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
body = {
|
|
1366
|
+
project: "",
|
|
1367
|
+
model: raw.model,
|
|
1368
|
+
request: raw,
|
|
1369
|
+
displayModel: raw.model,
|
|
1370
|
+
requestType: "ollama-chat",
|
|
1371
|
+
};
|
|
1372
|
+
} else {
|
|
1373
|
+
try {
|
|
1374
|
+
const parsed: unknown = JSON.parse(bodyBuffer.toString("utf-8"));
|
|
1375
|
+
const validation = validateProxyRequestBody(parsed);
|
|
1376
|
+
if (!validation.ok || !validation.value) {
|
|
1377
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1378
|
+
res.end(
|
|
1379
|
+
JSON.stringify({
|
|
1380
|
+
error: "Invalid request body",
|
|
1381
|
+
details: validation.errors,
|
|
1382
|
+
}),
|
|
1383
|
+
);
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
body = validation.value as RequestBody;
|
|
1387
|
+
} catch {
|
|
1388
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1389
|
+
res.end(JSON.stringify({ error: "Invalid JSON body" }));
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
const auth = await authenticateVirtualKey(req, body.model);
|
|
1395
|
+
if (!auth.authenticated) {
|
|
1396
|
+
sendAuthErrorResponse(res, auth);
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
1400
|
+
|
|
1401
|
+
const proxyLog = (
|
|
1402
|
+
msg: string,
|
|
1403
|
+
level: "info" | "warn" | "error" = "info",
|
|
1404
|
+
): void => {
|
|
1405
|
+
log(msg, rotator, level);
|
|
1406
|
+
};
|
|
1407
|
+
if (bodyBuffer.length > LARGE_CONTEXT_WARN_BYTES) {
|
|
1408
|
+
proxyLog(
|
|
1409
|
+
`[${body.model}] Large request body ${bodyBuffer.length} bytes; high context pressure increases rate-limit/flag risk`,
|
|
1410
|
+
"warn",
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
const sendNoAccountsAvailable = (reason: string): void => {
|
|
1415
|
+
proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
|
|
1416
|
+
const retryAfterMs = rotator.getRetryAfterMs(body.model);
|
|
1417
|
+
if (retryAfterMs > 0) {
|
|
1418
|
+
res.writeHead(429, {
|
|
1419
|
+
"Content-Type": "application/json",
|
|
1420
|
+
"Retry-After": String(Math.ceil(retryAfterMs / 1000)),
|
|
1421
|
+
});
|
|
1422
|
+
res.end(
|
|
1423
|
+
JSON.stringify({
|
|
1424
|
+
error: "All accounts cooling down or model circuit breaker active",
|
|
1425
|
+
reason,
|
|
1426
|
+
model: body.model,
|
|
1427
|
+
retryAfterMs,
|
|
1428
|
+
}),
|
|
1429
|
+
);
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
res.writeHead(503, { "Content-Type": "application/json" });
|
|
1433
|
+
res.end(
|
|
1434
|
+
JSON.stringify({
|
|
1435
|
+
error: "All accounts exhausted or disabled",
|
|
1436
|
+
reason,
|
|
1437
|
+
model: body.model,
|
|
1438
|
+
retryable: false,
|
|
1439
|
+
}),
|
|
1440
|
+
);
|
|
1441
|
+
};
|
|
1442
|
+
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1443
|
+
const nextAccount = await rotator.rotateToNext(body.model);
|
|
1444
|
+
if (nextAccount) {
|
|
1445
|
+
rotator.finishRequest(
|
|
1446
|
+
nextAccount,
|
|
1447
|
+
resolveQuotaModelKey(body.model) ?? undefined,
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
return nextAccount;
|
|
1451
|
+
};
|
|
1452
|
+
const sendFailureDecision = (decision: UpstreamFailureDecision): void => {
|
|
1453
|
+
if (decision.noReplacementReason) {
|
|
1454
|
+
sendNoAccountsAvailable(decision.noReplacementReason);
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
const label = decision.context.label;
|
|
1459
|
+
if (decision.actionKind === "rate-limited") {
|
|
1460
|
+
const retryAfterMs = decision.retryAfterMs ?? 0;
|
|
1461
|
+
res.writeHead(429, {
|
|
1462
|
+
"Content-Type": "application/json",
|
|
1463
|
+
"Retry-After": String(Math.ceil(retryAfterMs / 1000)),
|
|
1464
|
+
});
|
|
1465
|
+
res.end(
|
|
1466
|
+
JSON.stringify({
|
|
1467
|
+
error: decision.providerResourceExhausted
|
|
1468
|
+
? "Resource exhausted"
|
|
1469
|
+
: "Rate limited",
|
|
1470
|
+
reason: decision.providerResourceExhausted
|
|
1471
|
+
? `${label} hit provider RESOURCE_EXHAUSTED; not retrying another account to avoid pool-wide hammering`
|
|
1472
|
+
: `${label} was rate limited; not retrying another account for account-safety`,
|
|
1473
|
+
model: body.model,
|
|
1474
|
+
account: label,
|
|
1475
|
+
retryAfterMs,
|
|
1476
|
+
}),
|
|
1477
|
+
);
|
|
1478
|
+
return;
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
if (decision.actionKind === "forbidden") {
|
|
1482
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
1483
|
+
res.end(decision.errorText || JSON.stringify({ error: "Forbidden" }));
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
if (decision.actionKind === "not-found") {
|
|
1488
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1489
|
+
res.end(decision.errorText || JSON.stringify({ error: "Not found" }));
|
|
1490
|
+
return;
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
if (decision.actionKind === "bad-request") {
|
|
1494
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1495
|
+
res.end(decision.errorText || JSON.stringify({ error: "Bad request" }));
|
|
1496
|
+
return;
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
if (decision.actionKind === "server-error-503") {
|
|
1500
|
+
res.writeHead(503, { "Content-Type": "application/json" });
|
|
1501
|
+
res.end(
|
|
1502
|
+
decision.errorText ||
|
|
1503
|
+
JSON.stringify({
|
|
1504
|
+
error: "Server unavailable",
|
|
1505
|
+
account: label,
|
|
1506
|
+
model: body.model,
|
|
1507
|
+
}),
|
|
1508
|
+
);
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
res.writeHead(decision.status, { "Content-Type": "application/json" });
|
|
1513
|
+
res.end(decision.errorText || JSON.stringify({ error: "Upstream error" }));
|
|
1514
|
+
};
|
|
1515
|
+
|
|
1516
|
+
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1517
|
+
const maxAttempts = maxRetries + 1;
|
|
1518
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1519
|
+
const account = await rotator.getActiveAccount(body.model);
|
|
1520
|
+
if (!account) {
|
|
1521
|
+
sendNoAccountsAvailable("rotation returned no available account");
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
const label = account.config.label || account.config.email;
|
|
1526
|
+
const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
|
|
1527
|
+
const displayModelKey = resolveDisplayModelKey(body.model); // metrics/logs
|
|
1528
|
+
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1529
|
+
proxyLog(
|
|
1530
|
+
`[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
|
|
1531
|
+
);
|
|
1532
|
+
const requestStartMs = Date.now();
|
|
1533
|
+
const logRequestEnd = (status: string | number, extra = ""): void => {
|
|
1534
|
+
proxyLog(
|
|
1535
|
+
`[${requestId}] END account=${label} model=${body.model} status=${status}${extra ? ` ${extra}` : ""} totalMs=${Date.now() - requestStartMs}`,
|
|
1536
|
+
status === 200 || status === 0 ? "info" : "warn",
|
|
1537
|
+
);
|
|
1538
|
+
};
|
|
1539
|
+
const recordOutcome = (
|
|
1540
|
+
statusCode: number,
|
|
1541
|
+
ttfbMs = 0,
|
|
1542
|
+
totalMs = Date.now() - requestStartMs,
|
|
1543
|
+
inputTokens = 0,
|
|
1544
|
+
outputTokens = 0,
|
|
1545
|
+
): void => {
|
|
1546
|
+
rotator.recordRequestLog({
|
|
1547
|
+
model: modelKey,
|
|
1548
|
+
account: label,
|
|
1549
|
+
statusCode,
|
|
1550
|
+
ttfbMs,
|
|
1551
|
+
totalMs,
|
|
1552
|
+
inputTokens,
|
|
1553
|
+
outputTokens,
|
|
1554
|
+
});
|
|
1555
|
+
};
|
|
1556
|
+
|
|
1557
|
+
try {
|
|
1558
|
+
const jitterMs = rotator.getSafetyJitterMs(account);
|
|
1559
|
+
const globalDelayMs = rotator.getGlobalDelayMs();
|
|
1560
|
+
const totalDelayMs = jitterMs + globalDelayMs;
|
|
1561
|
+
if (totalDelayMs > 0) {
|
|
1562
|
+
if (jitterMs > 0) {
|
|
1563
|
+
proxyLog(
|
|
1564
|
+
`[${requestId}] Safety slow-mode jitter ${jitterMs}ms for account/project daily budget pressure`,
|
|
1565
|
+
"warn",
|
|
1566
|
+
);
|
|
1567
|
+
}
|
|
1568
|
+
if (globalDelayMs > 0) {
|
|
1569
|
+
proxyLog(
|
|
1570
|
+
`[${requestId}] Global request delay ${globalDelayMs}ms applied to slow down requests`,
|
|
1571
|
+
"info",
|
|
1572
|
+
);
|
|
1573
|
+
}
|
|
1574
|
+
await sleep(totalDelayMs);
|
|
1575
|
+
}
|
|
1576
|
+
rotator.recordUpstreamAttempt(account);
|
|
1577
|
+
const provider = providerAdapterForModel(
|
|
1578
|
+
account,
|
|
1579
|
+
body.model,
|
|
1580
|
+
rotator,
|
|
1581
|
+
);
|
|
1582
|
+
const forwarded = await provider.forwardRequest(
|
|
1583
|
+
account,
|
|
1584
|
+
{ ...body },
|
|
1585
|
+
flattenHeaders(req.headers),
|
|
1586
|
+
);
|
|
1587
|
+
const { response, endpoint } = forwarded;
|
|
1588
|
+
const context: RotationAttemptContext = {
|
|
1589
|
+
account,
|
|
1590
|
+
label,
|
|
1591
|
+
modelKey,
|
|
1592
|
+
displayModelKey,
|
|
1593
|
+
requestId,
|
|
1594
|
+
requestStartMs,
|
|
1595
|
+
endpoint,
|
|
1596
|
+
retries: attempt,
|
|
1597
|
+
};
|
|
1598
|
+
|
|
1599
|
+
const action = await classifyUpstreamResponse(
|
|
1600
|
+
response,
|
|
1601
|
+
endpoint,
|
|
1602
|
+
account,
|
|
1603
|
+
body.model,
|
|
1604
|
+
modelKey,
|
|
1605
|
+
);
|
|
1606
|
+
|
|
1607
|
+
if (action.kind !== "success") {
|
|
1608
|
+
const decision = await handleUpstreamAccountAction({
|
|
1609
|
+
action,
|
|
1610
|
+
provider,
|
|
1611
|
+
rotator,
|
|
1612
|
+
account,
|
|
1613
|
+
model: body.model,
|
|
1614
|
+
modelKey,
|
|
1615
|
+
label,
|
|
1616
|
+
context,
|
|
1617
|
+
logRequestEnd,
|
|
1618
|
+
rotateAndRelease,
|
|
1619
|
+
canRetry: attempt < maxRetries,
|
|
1620
|
+
writeLog: proxyLog,
|
|
1621
|
+
recordFailureAttempt: recordOutcome,
|
|
1622
|
+
});
|
|
1623
|
+
if (decision.kind === "retry") continue;
|
|
1624
|
+
sendFailureDecision(decision);
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
// Success or non-error client response
|
|
1629
|
+
const shouldRotate = rotator.recordRequest(account, body.model);
|
|
1630
|
+
|
|
1631
|
+
const responseHeaders: Record<string, string> = {};
|
|
1632
|
+
response.headers.forEach((value, key) => {
|
|
1633
|
+
if (
|
|
1634
|
+
key.toLowerCase() !== "transfer-encoding" &&
|
|
1635
|
+
key.toLowerCase() !== "connection"
|
|
1636
|
+
) {
|
|
1637
|
+
responseHeaders[key] = value;
|
|
1638
|
+
}
|
|
1639
|
+
});
|
|
1640
|
+
|
|
1641
|
+
const rotatorHeaders = buildRotatorResponseHeaders({
|
|
1642
|
+
accountLabel: label,
|
|
1643
|
+
model: displayModelKey || body.displayModel || body.model,
|
|
1644
|
+
ttfbMs: Date.now() - requestStartMs,
|
|
1645
|
+
healthScore: account.healthScore,
|
|
1646
|
+
routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
|
|
1647
|
+
retries: attempt,
|
|
1648
|
+
});
|
|
1649
|
+
Object.assign(responseHeaders, rotatorHeaders);
|
|
1650
|
+
|
|
1651
|
+
try {
|
|
1652
|
+
const usage = await streamResponseBody(
|
|
1653
|
+
response.body,
|
|
1654
|
+
req,
|
|
1655
|
+
res,
|
|
1656
|
+
label,
|
|
1657
|
+
proxyLog,
|
|
1658
|
+
response.status,
|
|
1659
|
+
responseHeaders,
|
|
1660
|
+
provider.createStreamAccumulator(),
|
|
1661
|
+
);
|
|
1662
|
+
const totalMs = Date.now() - requestStartMs;
|
|
1663
|
+
const ttfbMs = usage?.firstByteMs ?? totalMs;
|
|
1664
|
+
const outcomeStatus = usage?.streamError ? 502 : response.status;
|
|
1665
|
+
rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
|
|
1666
|
+
logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} endpoint=${endpoint}`);
|
|
1667
|
+
rotator.recordRequestLog({
|
|
1668
|
+
model: displayModelKey,
|
|
1669
|
+
account: label,
|
|
1670
|
+
statusCode: outcomeStatus,
|
|
1671
|
+
ttfbMs,
|
|
1672
|
+
totalMs,
|
|
1673
|
+
inputTokens: usage?.inputTokens ?? 0,
|
|
1674
|
+
outputTokens: usage?.outputTokens ?? 0,
|
|
1675
|
+
});
|
|
1676
|
+
logSpend({
|
|
1677
|
+
requestId,
|
|
1678
|
+
apiKeyHash,
|
|
1679
|
+
model: displayModelKey,
|
|
1680
|
+
accountEmail: label,
|
|
1681
|
+
callType: "native",
|
|
1682
|
+
status: outcomeStatus >= 200 && outcomeStatus < 300 ? "success" : "failure",
|
|
1683
|
+
promptTokens: usage?.inputTokens ?? 0,
|
|
1684
|
+
completionTokens: usage?.outputTokens ?? 0,
|
|
1685
|
+
totalTokens: (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0),
|
|
1686
|
+
startTime: new Date(requestStartMs).toISOString(),
|
|
1687
|
+
endTime: new Date().toISOString(),
|
|
1688
|
+
ttfbMs,
|
|
1689
|
+
durationMs: totalMs,
|
|
1690
|
+
requestMessages: body.request || body,
|
|
1691
|
+
responseContent: usage?.responseText
|
|
1692
|
+
? { candidates: [{ content: { parts: [{ text: usage.responseText }] }, finishReason: "STOP" }] }
|
|
1693
|
+
: null,
|
|
1694
|
+
requesterIp: req.socket?.remoteAddress || null,
|
|
1695
|
+
});
|
|
1696
|
+
if (usage && (usage.inputTokens > 0 || usage.outputTokens > 0)) {
|
|
1697
|
+
rotator.recordTokenUsage(
|
|
1698
|
+
body.displayModel || body.model,
|
|
1699
|
+
usage.inputTokens,
|
|
1700
|
+
usage.outputTokens,
|
|
1701
|
+
);
|
|
1702
|
+
}
|
|
1703
|
+
} catch (err) {
|
|
1704
|
+
proxyLog(`[${label}] Stream setup error: ${err}`, "warn");
|
|
1705
|
+
if (err instanceof PreFlushStreamError) throw err;
|
|
1706
|
+
}
|
|
1707
|
+
res.end();
|
|
1708
|
+
|
|
1709
|
+
if (shouldRotate) {
|
|
1710
|
+
await rotateAndRelease();
|
|
1711
|
+
}
|
|
1712
|
+
return;
|
|
1713
|
+
} catch (err) {
|
|
1714
|
+
const formattedError = formatError(err);
|
|
1715
|
+
proxyLog(
|
|
1716
|
+
`[${label}] Request failed: ${formattedError}`,
|
|
1717
|
+
isFetchTransportError(err) ? "warn" : "error",
|
|
1718
|
+
);
|
|
1719
|
+
recordOutcome(isFetchTransportError(err) ? 0 : 500);
|
|
1720
|
+
logRequestEnd(
|
|
1721
|
+
isFetchTransportError(err) ? "fetch-error" : 500,
|
|
1722
|
+
`error=${formattedError.slice(0, 120)}`,
|
|
1723
|
+
);
|
|
1724
|
+
if (!isFetchTransportError(err)) {
|
|
1725
|
+
rotator.markError(account, formattedError);
|
|
1726
|
+
}
|
|
1727
|
+
if (res.headersSent || res.destroyed) {
|
|
1728
|
+
res.end();
|
|
1729
|
+
return;
|
|
1730
|
+
}
|
|
1731
|
+
if (!isFetchTransportError(err) || attempt >= maxRetries) {
|
|
1732
|
+
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1733
|
+
res.end(JSON.stringify({ error: GENERIC_UPSTREAM_ERROR }));
|
|
1734
|
+
return;
|
|
1735
|
+
}
|
|
1736
|
+
const nextAccount = await rotateAndRelease();
|
|
1737
|
+
if (!nextAccount) {
|
|
1738
|
+
sendNoAccountsAvailable(
|
|
1739
|
+
`no replacement account remained after ${label} request error`,
|
|
1740
|
+
);
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
continue;
|
|
1744
|
+
} finally {
|
|
1745
|
+
rotator.finishRequest(
|
|
1746
|
+
account,
|
|
1747
|
+
resolveQuotaModelKey(body.model) ?? undefined,
|
|
1748
|
+
);
|
|
1749
|
+
if (onComplete) onComplete();
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
if (!res.headersSent) {
|
|
1754
|
+
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1755
|
+
}
|
|
1756
|
+
res.end(JSON.stringify({ error: "All retry attempts failed" }));
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
const CODE_ASSIST_ROUTING_MODEL = "gemini-3-flash";
|
|
1760
|
+
|
|
1761
|
+
async function handleCodeAssistPassthrough(
|
|
1762
|
+
req: IncomingMessage,
|
|
1763
|
+
res: ServerResponse,
|
|
1764
|
+
rotator: AccountRotator,
|
|
1765
|
+
action: CodeAssistAction,
|
|
1766
|
+
): Promise<void> {
|
|
1767
|
+
let bodyBuffer: Buffer;
|
|
1768
|
+
try {
|
|
1769
|
+
bodyBuffer = await readLimitedBody(req);
|
|
1770
|
+
} catch (err) {
|
|
1771
|
+
if (err instanceof PayloadTooLargeError) {
|
|
1772
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
1773
|
+
res.end(JSON.stringify({ error: "Payload too large", limitBytes: err.limitBytes }));
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
throw err;
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
let body: unknown;
|
|
1780
|
+
try {
|
|
1781
|
+
body = JSON.parse(bodyBuffer.toString("utf-8")) as unknown;
|
|
1782
|
+
validateCodeAssistPayload(action, body);
|
|
1783
|
+
} catch (err) {
|
|
1784
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1785
|
+
res.end(JSON.stringify({
|
|
1786
|
+
error: err instanceof Error ? err.message : "Invalid Code Assist request",
|
|
1787
|
+
}));
|
|
1788
|
+
return;
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1791
|
+
const provider = getProviderAdapter(DEFAULT_PROVIDER);
|
|
1792
|
+
if (!provider.forwardCodeAssistRequest) {
|
|
1793
|
+
res.writeHead(501, { "Content-Type": "application/json" });
|
|
1794
|
+
res.end(JSON.stringify({ error: "Code Assist passthrough is unavailable" }));
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1799
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1800
|
+
let account: AccountRuntime | null;
|
|
1801
|
+
try {
|
|
1802
|
+
account = await rotator.getActiveAccount(CODE_ASSIST_ROUTING_MODEL);
|
|
1803
|
+
} catch {
|
|
1804
|
+
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1805
|
+
res.end(JSON.stringify({ error: "Account token refresh failed" }));
|
|
1806
|
+
return;
|
|
1807
|
+
}
|
|
1808
|
+
if (!account) {
|
|
1809
|
+
res.writeHead(503, { "Content-Type": "application/json" });
|
|
1810
|
+
res.end(JSON.stringify({ error: "All Google accounts exhausted or disabled" }));
|
|
1811
|
+
return;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
try {
|
|
1815
|
+
// getActiveAccount performs the normal account lifecycle check, but the
|
|
1816
|
+
// explicit provider call is required for dual Google+Ollama accounts.
|
|
1817
|
+
await provider.ensureValidToken(account);
|
|
1818
|
+
rotator.recordUpstreamAttempt(account);
|
|
1819
|
+
const forwarded = await provider.forwardCodeAssistRequest(
|
|
1820
|
+
account,
|
|
1821
|
+
action,
|
|
1822
|
+
body,
|
|
1823
|
+
flattenHeaders(req.headers),
|
|
1824
|
+
);
|
|
1825
|
+
const responseBody = await forwarded.response.text();
|
|
1826
|
+
res.writeHead(forwarded.response.status, {
|
|
1827
|
+
"Content-Type": forwarded.response.headers.get("content-type") || "application/json",
|
|
1828
|
+
});
|
|
1829
|
+
res.end(responseBody);
|
|
1830
|
+
return;
|
|
1831
|
+
} catch (err) {
|
|
1832
|
+
if (!isFetchTransportError(err) || attempt >= maxRetries) {
|
|
1833
|
+
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1834
|
+
res.end(JSON.stringify({ error: "Code Assist upstream request failed" }));
|
|
1835
|
+
return;
|
|
1836
|
+
}
|
|
1837
|
+
const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL);
|
|
1838
|
+
if (nextAccount) {
|
|
1839
|
+
rotator.finishRequest(
|
|
1840
|
+
nextAccount,
|
|
1841
|
+
resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
|
|
1842
|
+
);
|
|
1843
|
+
continue;
|
|
1844
|
+
}
|
|
1845
|
+
res.writeHead(503, { "Content-Type": "application/json" });
|
|
1846
|
+
res.end(JSON.stringify({ error: "No replacement Google account available" }));
|
|
1847
|
+
return;
|
|
1848
|
+
} finally {
|
|
1849
|
+
rotator.finishRequest(
|
|
1850
|
+
account,
|
|
1851
|
+
resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
|
|
1852
|
+
);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
export function flattenHeaders(
|
|
1858
|
+
headers: IncomingMessage["headers"],
|
|
1859
|
+
): Record<string, string> {
|
|
1860
|
+
const flat: Record<string, string> = {};
|
|
1861
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
1862
|
+
if (value) {
|
|
1863
|
+
flat[key] = Array.isArray(value) ? value.join(", ") : value;
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
return flat;
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
export function startProxy(
|
|
1870
|
+
rotator: AccountRotator,
|
|
1871
|
+
port: number,
|
|
1872
|
+
bindHost = "0.0.0.0",
|
|
1873
|
+
): Server {
|
|
1874
|
+
startVersionChecker();
|
|
1875
|
+
startNotificationPoller();
|
|
1876
|
+
const sseClients = new Set<ServerResponse>();
|
|
1877
|
+
let sseBroadcastTimer: ReturnType<typeof setTimeout> | null = null;
|
|
1878
|
+
let benchmarkRunning = false;
|
|
1879
|
+
const SSE_THROTTLE_MS = 1000; // max 1 push/second
|
|
1880
|
+
|
|
1881
|
+
const scheduleSseBroadcast = (): void => {
|
|
1882
|
+
if (sseBroadcastTimer) return; // already scheduled
|
|
1883
|
+
sseBroadcastTimer = setTimeout(() => {
|
|
1884
|
+
sseBroadcastTimer = null;
|
|
1885
|
+
if (sseClients.size === 0) return;
|
|
1886
|
+
const data = JSON.stringify(rotator.getStatus());
|
|
1887
|
+
for (const client of sseClients) {
|
|
1888
|
+
try {
|
|
1889
|
+
client.write(`data: ${data}\n\n`);
|
|
1890
|
+
} catch {
|
|
1891
|
+
sseClients.delete(client);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
}, SSE_THROTTLE_MS);
|
|
1895
|
+
};
|
|
1896
|
+
|
|
1897
|
+
// Hook into rotator state changes to trigger SSE
|
|
1898
|
+
const origSaveState = rotator.saveState.bind(rotator);
|
|
1899
|
+
rotator.saveState = (): Promise<void> => {
|
|
1900
|
+
const write = origSaveState();
|
|
1901
|
+
scheduleSseBroadcast();
|
|
1902
|
+
return write;
|
|
1903
|
+
};
|
|
1904
|
+
|
|
1905
|
+
const server = createServer((req, res) => {
|
|
1906
|
+
const method = req.method?.toUpperCase();
|
|
1907
|
+
const url = req.url || "";
|
|
1908
|
+
const pathname = url.split("?")[0];
|
|
1909
|
+
|
|
1910
|
+
if (method === "GET" && (pathname === "/" || pathname === "/dashboard")) {
|
|
1911
|
+
if (!requireAdmin(req, res)) return;
|
|
1912
|
+
trackFeature("dashboard");
|
|
1913
|
+
serveDashboard(res);
|
|
1914
|
+
return;
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
if (method === "GET" && pathname === "/dashboard/keys") {
|
|
1918
|
+
if (!requireAdmin(req, res)) return;
|
|
1919
|
+
serveDashboardKeys(res);
|
|
1920
|
+
return;
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
if (method === "GET" && pathname === "/dashboard/logs") {
|
|
1924
|
+
if (!requireAdmin(req, res)) return;
|
|
1925
|
+
serveDashboardLogs(res);
|
|
1926
|
+
return;
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
if (method === "GET" && pathname === "/favicon.ico") {
|
|
1930
|
+
res.writeHead(204);
|
|
1931
|
+
res.end();
|
|
1932
|
+
return;
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
if (method === "GET" && pathname === "/static/dashboard.css") {
|
|
1936
|
+
serveStaticCss(res);
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
if (method === "GET" && pathname === "/static/dashboard.js") {
|
|
1941
|
+
serveStaticJs(res);
|
|
1942
|
+
return;
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
if (method === "GET" && pathname === "/static/dashboard-keys.js") {
|
|
1946
|
+
serveStaticKeysJs(res);
|
|
1947
|
+
return;
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
if (method === "GET" && pathname === "/static/dashboard-logs.js") {
|
|
1951
|
+
serveStaticLogsJs(res);
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
if (method === "GET" && pathname === "/login") {
|
|
1956
|
+
if (!requireAdmin(req, res)) return;
|
|
1957
|
+
trackFeature("hostedLogin");
|
|
1958
|
+
serveLoginLanding(res);
|
|
1959
|
+
return;
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
if (method === "GET" && pathname === "/login-cli") {
|
|
1963
|
+
if (!requireAdmin(req, res)) return;
|
|
1964
|
+
trackFeature("cliLogin");
|
|
1965
|
+
serveCliLogin(res);
|
|
1966
|
+
return;
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
if (method === "POST" && pathname === "/api/cli-login") {
|
|
1970
|
+
if (!requireAdmin(req, res)) return;
|
|
1971
|
+
handleCliLoginApi(req, res, rotator).catch((err) => {
|
|
1972
|
+
log(`CLI login error: ${err}`, rotator, "error");
|
|
1973
|
+
if (!res.headersSent) {
|
|
1974
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
1975
|
+
}
|
|
1976
|
+
res.end(JSON.stringify({ ok: false, error: "Internal login error" }));
|
|
1977
|
+
});
|
|
1978
|
+
return;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
if (method === "GET" && pathname === "/auth/antigravity/start") {
|
|
1982
|
+
if (!requireAdmin(req, res)) return;
|
|
1983
|
+
startHostedLogin(req, res);
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
if (method === "GET" && pathname === "/auth/antigravity/callback") {
|
|
1988
|
+
handleHostedCallback(req, res, rotator).catch((err) => {
|
|
1989
|
+
log(`Hosted callback error: ${err}`, rotator, "error");
|
|
1990
|
+
if (!res.headersSent) {
|
|
1991
|
+
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
1992
|
+
}
|
|
1993
|
+
res.end("<h1>Internal login error</h1>");
|
|
1994
|
+
});
|
|
1995
|
+
return;
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
if (method === "GET" && pathname === "/api/status") {
|
|
1999
|
+
if (!requireAdmin(req, res)) return;
|
|
2000
|
+
serveStatusApi(res, rotator);
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
if (method === "GET" && pathname === "/api/config") {
|
|
2005
|
+
if (!requireAdmin(req, res)) return;
|
|
2006
|
+
serveConfigApi(res, rotator);
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
if (method === "GET" && pathname === "/api/config/export") {
|
|
2011
|
+
if (!requireAdmin(req, res)) return;
|
|
2012
|
+
serveConfigExportApi(res, rotator);
|
|
2013
|
+
return;
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
if (method === "POST" && pathname === "/api/benchmark") {
|
|
2017
|
+
if (!requireAdmin(req, res)) return;
|
|
2018
|
+
if (benchmarkRunning) {
|
|
2019
|
+
res.writeHead(409, { "Content-Type": "application/json" });
|
|
2020
|
+
res.end(JSON.stringify({ ok: false, error: "Benchmark already running" }));
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
benchmarkRunning = true;
|
|
2024
|
+
void serveBenchmarkApi(res, rotator).finally(() => {
|
|
2025
|
+
benchmarkRunning = false;
|
|
2026
|
+
});
|
|
2027
|
+
return;
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
if (
|
|
2031
|
+
(method === "PUT" && pathname === "/api/config") ||
|
|
2032
|
+
(method === "POST" && pathname === "/api/config/import")
|
|
2033
|
+
) {
|
|
2034
|
+
if (!requireAdmin(req, res)) return;
|
|
2035
|
+
readJsonRequest(req)
|
|
2036
|
+
.then((parsed) => {
|
|
2037
|
+
const candidate =
|
|
2038
|
+
parsed &&
|
|
2039
|
+
typeof parsed === "object" &&
|
|
2040
|
+
"config" in (parsed as Record<string, unknown>)
|
|
2041
|
+
? (parsed as { config: unknown }).config
|
|
2042
|
+
: parsed;
|
|
2043
|
+
const validation = validateConfig(candidate);
|
|
2044
|
+
if (!validation.ok || !validation.value) {
|
|
2045
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
2046
|
+
res.end(JSON.stringify({ ok: false, errors: validation.errors }));
|
|
2047
|
+
return;
|
|
2048
|
+
}
|
|
2049
|
+
return serveConfigImportApi(
|
|
2050
|
+
res,
|
|
2051
|
+
rotator,
|
|
2052
|
+
applyConfigDefaults(validation.value),
|
|
2053
|
+
);
|
|
2054
|
+
})
|
|
2055
|
+
.catch((err) => {
|
|
2056
|
+
const isPayloadTooLarge = err instanceof PayloadTooLargeError;
|
|
2057
|
+
proxyLogger.warn(`Config import request failed: ${formatError(err)}`);
|
|
2058
|
+
res.writeHead(isPayloadTooLarge ? 413 : 400, {
|
|
2059
|
+
"Content-Type": "application/json",
|
|
2060
|
+
});
|
|
2061
|
+
res.end(
|
|
2062
|
+
JSON.stringify({
|
|
2063
|
+
ok: false,
|
|
2064
|
+
error: isPayloadTooLarge
|
|
2065
|
+
? "Payload too large"
|
|
2066
|
+
: "Invalid config request",
|
|
2067
|
+
}),
|
|
2068
|
+
);
|
|
2069
|
+
});
|
|
2070
|
+
return;
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
if (method === "GET" && pathname === "/api/events") {
|
|
2074
|
+
if (!requireAdmin(req, res)) return;
|
|
2075
|
+
// Server-Sent Events for live dashboard
|
|
2076
|
+
res.writeHead(200, {
|
|
2077
|
+
"Content-Type": "text/event-stream",
|
|
2078
|
+
"Cache-Control": "no-cache",
|
|
2079
|
+
Connection: "keep-alive",
|
|
2080
|
+
"X-Accel-Buffering": "no",
|
|
2081
|
+
});
|
|
2082
|
+
res.write(":\n\n"); // keepalive comment
|
|
2083
|
+
sseClients.add(res);
|
|
2084
|
+
req.on("close", () => sseClients.delete(res));
|
|
2085
|
+
return;
|
|
2086
|
+
}
|
|
2087
|
+
|
|
2088
|
+
if (method === "POST" && pathname.startsWith("/api/enable/")) {
|
|
2089
|
+
if (!requireAdmin(req, res)) return;
|
|
2090
|
+
const email = decodeURIComponent(pathname.slice("/api/enable/".length));
|
|
2091
|
+
void serveEnableApi(res, rotator, email);
|
|
2092
|
+
return;
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
if (method === "POST" && pathname.startsWith("/api/disable/")) {
|
|
2096
|
+
if (!requireAdmin(req, res)) return;
|
|
2097
|
+
const email = decodeURIComponent(pathname.slice("/api/disable/".length));
|
|
2098
|
+
void serveDisableApi(res, rotator, email);
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
if (method === "POST" && pathname.startsWith("/api/quarantine/")) {
|
|
2103
|
+
if (!requireAdmin(req, res)) return;
|
|
2104
|
+
const email = decodeURIComponent(pathname.slice("/api/quarantine/".length));
|
|
2105
|
+
void serveQuarantineApi(res, rotator, email);
|
|
2106
|
+
return;
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
if (method === "POST" && pathname.startsWith("/api/restore/")) {
|
|
2110
|
+
if (!requireAdmin(req, res)) return;
|
|
2111
|
+
const email = decodeURIComponent(pathname.slice("/api/restore/".length));
|
|
2112
|
+
void serveRestoreApi(res, rotator, email);
|
|
2113
|
+
return;
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
if (method === "POST" && pathname.startsWith("/api/remove-account/")) {
|
|
2117
|
+
if (!requireAdmin(req, res)) return;
|
|
2118
|
+
const email = decodeURIComponent(
|
|
2119
|
+
pathname.slice("/api/remove-account/".length),
|
|
2120
|
+
);
|
|
2121
|
+
void serveRemoveAccountApi(res, rotator, email);
|
|
2122
|
+
return;
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
if (method === "POST" && pathname.startsWith("/api/set-tier/")) {
|
|
2126
|
+
if (!requireAdmin(req, res)) return;
|
|
2127
|
+
const rest = pathname.slice("/api/set-tier/".length);
|
|
2128
|
+
const lastSlash = rest.lastIndexOf("/");
|
|
2129
|
+
if (lastSlash < 0) {
|
|
2130
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
2131
|
+
res.end(
|
|
2132
|
+
JSON.stringify({
|
|
2133
|
+
ok: false,
|
|
2134
|
+
error: "Missing tier. Use /api/set-tier/:email/:tier",
|
|
2135
|
+
}),
|
|
2136
|
+
);
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
const email = decodeURIComponent(rest.slice(0, lastSlash));
|
|
2140
|
+
const tier = decodeURIComponent(rest.slice(lastSlash + 1));
|
|
2141
|
+
void serveSetTierApi(res, rotator, email, tier);
|
|
2142
|
+
return;
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
if (method === "POST" && pathname.startsWith("/api/clear-inflight/")) {
|
|
2146
|
+
if (!requireAdmin(req, res)) return;
|
|
2147
|
+
const rest = pathname.slice("/api/clear-inflight/".length);
|
|
2148
|
+
const firstSlash = rest.indexOf("/");
|
|
2149
|
+
const email = decodeURIComponent(
|
|
2150
|
+
firstSlash >= 0 ? rest.slice(0, firstSlash) : rest,
|
|
2151
|
+
);
|
|
2152
|
+
const modelKey =
|
|
2153
|
+
firstSlash >= 0
|
|
2154
|
+
? decodeURIComponent(rest.slice(firstSlash + 1))
|
|
2155
|
+
: undefined;
|
|
2156
|
+
serveClearInFlightApi(res, rotator, email, modelKey);
|
|
2157
|
+
return;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
if (method === "POST" && pathname.startsWith("/api/clear-breaker/")) {
|
|
2161
|
+
if (!requireAdmin(req, res)) return;
|
|
2162
|
+
const rest = pathname.slice("/api/clear-breaker/".length);
|
|
2163
|
+
const modelKey =
|
|
2164
|
+
rest && rest !== "all" ? decodeURIComponent(rest) : undefined;
|
|
2165
|
+
void serveClearBreakerApi(res, rotator, modelKey);
|
|
2166
|
+
return;
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
if (
|
|
2170
|
+
method === "POST" &&
|
|
2171
|
+
(pathname === "/api/settings/fresh-window-starts/on" ||
|
|
2172
|
+
pathname === "/api/settings/fresh-window-starts/off")
|
|
2173
|
+
) {
|
|
2174
|
+
if (!requireAdmin(req, res)) return;
|
|
2175
|
+
trackFeature("freshWindowToggle");
|
|
2176
|
+
void serveFreshWindowStartsApi(res, rotator, pathname.endsWith("/on"));
|
|
2177
|
+
return;
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
if (
|
|
2181
|
+
method === "POST" &&
|
|
2182
|
+
pathname.startsWith("/api/account-fresh-window-starts/") &&
|
|
2183
|
+
(pathname.endsWith("/on") || pathname.endsWith("/off"))
|
|
2184
|
+
) {
|
|
2185
|
+
if (!requireAdmin(req, res)) return;
|
|
2186
|
+
const rest = pathname.slice("/api/account-fresh-window-starts/".length);
|
|
2187
|
+
const lastSlash = rest.lastIndexOf("/");
|
|
2188
|
+
const email = decodeURIComponent(rest.slice(0, lastSlash));
|
|
2189
|
+
const enabled = rest.slice(lastSlash + 1) === "on";
|
|
2190
|
+
void serveAccountFreshWindowStartsApi(res, rotator, email, enabled);
|
|
2191
|
+
return;
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
if (method === "POST" && pathname.startsWith("/api/kickstart/")) {
|
|
2195
|
+
if (!requireAdmin(req, res)) return;
|
|
2196
|
+
const rest = pathname.slice("/api/kickstart/".length);
|
|
2197
|
+
const firstSlash = rest.indexOf("/");
|
|
2198
|
+
if (firstSlash >= 0) {
|
|
2199
|
+
// /api/kickstart/:email/:modelKey
|
|
2200
|
+
const email = decodeURIComponent(rest.slice(0, firstSlash));
|
|
2201
|
+
const modelKey = decodeURIComponent(rest.slice(firstSlash + 1));
|
|
2202
|
+
serveKickstartApi(res, rotator, email, modelKey);
|
|
2203
|
+
} else {
|
|
2204
|
+
// /api/kickstart/:email — kickstart all fresh timers
|
|
2205
|
+
const email = decodeURIComponent(rest);
|
|
2206
|
+
serveKickstartApi(res, rotator, email);
|
|
2207
|
+
}
|
|
2208
|
+
return;
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
if (
|
|
2212
|
+
method === "POST" &&
|
|
2213
|
+
(pathname === "/api/settings/auto-warmup/on" ||
|
|
2214
|
+
pathname === "/api/settings/auto-warmup/off")
|
|
2215
|
+
) {
|
|
2216
|
+
if (!requireAdmin(req, res)) return;
|
|
2217
|
+
void serveAutoWarmupApi(res, rotator, pathname.endsWith("/on"));
|
|
2218
|
+
return;
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
if (method === "POST" && pathname === "/api/self-update") {
|
|
2222
|
+
if (!requireAdmin(req, res)) return;
|
|
2223
|
+
trackFeature("selfUpdate");
|
|
2224
|
+
try {
|
|
2225
|
+
const result = performSelfUpdate();
|
|
2226
|
+
res.writeHead(result.ok ? 200 : 500, {
|
|
2227
|
+
"Content-Type": "application/json",
|
|
2228
|
+
});
|
|
2229
|
+
res.end(JSON.stringify(result));
|
|
2230
|
+
} catch {
|
|
2231
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2232
|
+
res.end(
|
|
2233
|
+
JSON.stringify({
|
|
2234
|
+
ok: false,
|
|
2235
|
+
message: "Self-update failed. Check the server logs and try again.",
|
|
2236
|
+
}),
|
|
2237
|
+
);
|
|
2238
|
+
}
|
|
2239
|
+
return;
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
// ── Virtual Keys & Spend Logs API routes ──
|
|
2243
|
+
if (method === "POST" && pathname === "/api/keys/generate") {
|
|
2244
|
+
if (!requireAdmin(req, res)) return;
|
|
2245
|
+
void serveGenerateVirtualKeyApi(req, res);
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
if (method === "GET" && pathname === "/api/keys") {
|
|
2250
|
+
if (!requireAdmin(req, res)) return;
|
|
2251
|
+
void serveListVirtualKeysApi(res);
|
|
2252
|
+
return;
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
if (pathname.startsWith("/api/keys/")) {
|
|
2256
|
+
if (!requireAdmin(req, res)) return;
|
|
2257
|
+
const hash = decodeURIComponent(pathname.slice("/api/keys/".length));
|
|
2258
|
+
if (method === "GET") {
|
|
2259
|
+
void serveGetVirtualKeyApi(res, hash);
|
|
2260
|
+
return;
|
|
2261
|
+
}
|
|
2262
|
+
if (method === "PUT") {
|
|
2263
|
+
void serveUpdateVirtualKeyApi(req, res, hash);
|
|
2264
|
+
return;
|
|
2265
|
+
}
|
|
2266
|
+
if (method === "DELETE") {
|
|
2267
|
+
void serveDeleteVirtualKeyApi(res, hash);
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
if (method === "GET" && pathname === "/api/spend/logs") {
|
|
2273
|
+
if (!requireAdmin(req, res)) return;
|
|
2274
|
+
void serveGetSpendLogsApi(req, res);
|
|
2275
|
+
return;
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
if (method === "GET" && pathname === "/api/spend/summary") {
|
|
2279
|
+
if (!requireAdmin(req, res)) return;
|
|
2280
|
+
void serveGetSpendSummaryApi(req, res);
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
if (method === "GET" && pathname === "/api/spend/by-key") {
|
|
2285
|
+
if (!requireAdmin(req, res)) return;
|
|
2286
|
+
void serveGetSpendByKeyApi(req, res);
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
// OpenAI-compatible adapter route (additive; does not affect native v1internal route)
|
|
2291
|
+
if (method === "GET" && pathname === "/v1/models") {
|
|
2292
|
+
serveOpenAIModels(res, rotator);
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
if (method === "GET" && pathname === "/v1beta/models") {
|
|
2297
|
+
serveGeminiModels(res);
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
if (method === "POST" && pathname === "/v1/chat/completions") {
|
|
2302
|
+
handleOpenAIChatCompletions(req, res, rotator).catch((err) => {
|
|
2303
|
+
log(`OpenAI compat error: ${err}`, rotator, "error");
|
|
2304
|
+
if (!res.headersSent)
|
|
2305
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2306
|
+
res.end(
|
|
2307
|
+
JSON.stringify({
|
|
2308
|
+
error: {
|
|
2309
|
+
message: "Internal OpenAI compat error",
|
|
2310
|
+
type: "server_error",
|
|
2311
|
+
},
|
|
2312
|
+
}),
|
|
2313
|
+
);
|
|
2314
|
+
});
|
|
2315
|
+
return;
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
if (method === "POST" && pathname === "/v1/responses") {
|
|
2319
|
+
handleOpenAIResponsesCreate(req, res, rotator).catch((err) => {
|
|
2320
|
+
log(`OpenAI responses compat error: ${err}`, rotator, "error");
|
|
2321
|
+
if (!res.headersSent)
|
|
2322
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2323
|
+
res.end(
|
|
2324
|
+
JSON.stringify({
|
|
2325
|
+
error: {
|
|
2326
|
+
message: "Internal OpenAI responses compat error",
|
|
2327
|
+
type: "server_error",
|
|
2328
|
+
},
|
|
2329
|
+
}),
|
|
2330
|
+
);
|
|
2331
|
+
});
|
|
2332
|
+
return;
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
const responseMatch = pathname.match(
|
|
2336
|
+
/^\/v1\/responses\/([^/]+)(?:\/(cancel|input_items))?$/,
|
|
2337
|
+
);
|
|
2338
|
+
if (responseMatch) {
|
|
2339
|
+
const responseId = decodeURIComponent(responseMatch[1]);
|
|
2340
|
+
const action = responseMatch[2] || "";
|
|
2341
|
+
if (method === "GET" && !action)
|
|
2342
|
+
return handleOpenAIResponsesRetrieve(req, res, responseId);
|
|
2343
|
+
if (method === "DELETE" && !action)
|
|
2344
|
+
return handleOpenAIResponsesDelete(req, res, responseId);
|
|
2345
|
+
if (method === "POST" && action === "cancel")
|
|
2346
|
+
return handleOpenAIResponsesCancel(req, res, responseId);
|
|
2347
|
+
if (method === "GET" && action === "input_items")
|
|
2348
|
+
return handleOpenAIResponsesInputItems(req, res, responseId);
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
// Anthropic-compatible adapter route (additive; does not affect native v1internal route)
|
|
2352
|
+
if (method === "POST" && pathname === "/v1/messages") {
|
|
2353
|
+
handleAnthropicMessages(req, res, rotator).catch((err) => {
|
|
2354
|
+
log(`Anthropic compat error: ${err}`, rotator, "error");
|
|
2355
|
+
if (!res.headersSent)
|
|
2356
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2357
|
+
res.end(
|
|
2358
|
+
JSON.stringify({
|
|
2359
|
+
type: "error",
|
|
2360
|
+
error: {
|
|
2361
|
+
type: "server_error",
|
|
2362
|
+
message: "Internal Anthropic compat error",
|
|
2363
|
+
},
|
|
2364
|
+
}),
|
|
2365
|
+
);
|
|
2366
|
+
});
|
|
2367
|
+
return;
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
if (method === "POST" && isGeminiGenerateContentPath(pathname)) {
|
|
2371
|
+
handleGeminiGenerateContent(req, res, rotator).catch((err) => {
|
|
2372
|
+
log(`Gemini compat error: ${err}`, rotator, "error");
|
|
2373
|
+
if (!res.headersSent)
|
|
2374
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2375
|
+
res.end(
|
|
2376
|
+
JSON.stringify({
|
|
2377
|
+
error: {
|
|
2378
|
+
message: "Internal Gemini compat error",
|
|
2379
|
+
status: "INTERNAL",
|
|
2380
|
+
},
|
|
2381
|
+
}),
|
|
2382
|
+
);
|
|
2383
|
+
});
|
|
2384
|
+
return;
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
// Native Ollama chat route (additive; /api/chat payload shape)
|
|
2388
|
+
if (method === "POST" && pathname === "/api/chat") {
|
|
2389
|
+
handleProxyRequest(req, res, rotator, scheduleSseBroadcast, true).catch(
|
|
2390
|
+
(err) => {
|
|
2391
|
+
log(`Unhandled error: ${err}`, rotator, "error");
|
|
2392
|
+
if (!res.headersSent) {
|
|
2393
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2394
|
+
}
|
|
2395
|
+
res.end(JSON.stringify({ error: "Internal proxy error" }));
|
|
2396
|
+
},
|
|
2397
|
+
);
|
|
2398
|
+
return;
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2401
|
+
// Proxy route (native Antigravity v1internal)
|
|
2402
|
+
if (method === "POST" && url.includes("v1internal")) {
|
|
2403
|
+
const operation = pathname.split(":").pop() || "";
|
|
2404
|
+
if (isCodeAssistAction(operation)) {
|
|
2405
|
+
handleCodeAssistPassthrough(req, res, rotator, operation).catch(
|
|
2406
|
+
(err) => {
|
|
2407
|
+
log(`Unhandled Code Assist passthrough error: ${err}`, rotator, "error");
|
|
2408
|
+
if (!res.headersSent) {
|
|
2409
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2410
|
+
}
|
|
2411
|
+
res.end(JSON.stringify({ error: "Internal Code Assist proxy error" }));
|
|
2412
|
+
},
|
|
2413
|
+
);
|
|
2414
|
+
return;
|
|
2415
|
+
}
|
|
2416
|
+
if (
|
|
2417
|
+
operation !== "streamGenerateContent" &&
|
|
2418
|
+
operation !== "generateContent"
|
|
2419
|
+
) {
|
|
2420
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
2421
|
+
res.end(JSON.stringify({ error: "Unsupported v1internal operation" }));
|
|
2422
|
+
return;
|
|
2423
|
+
}
|
|
2424
|
+
handleProxyRequest(req, res, rotator, scheduleSseBroadcast).catch(
|
|
2425
|
+
(err) => {
|
|
2426
|
+
log(`Unhandled error: ${err}`, rotator, "error");
|
|
2427
|
+
if (!res.headersSent) {
|
|
2428
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2429
|
+
}
|
|
2430
|
+
res.end(JSON.stringify({ error: "Internal proxy error" }));
|
|
2431
|
+
},
|
|
2432
|
+
);
|
|
2433
|
+
return;
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
2437
|
+
res.end(JSON.stringify({ error: "Not found" }));
|
|
2438
|
+
});
|
|
2439
|
+
|
|
2440
|
+
server.listen(port, bindHost, () => {
|
|
2441
|
+
log(`Listening on ${bindHost}:${port}`, rotator);
|
|
2442
|
+
log(`Dashboard: http://localhost:${port}/dashboard`, rotator);
|
|
2443
|
+
log(`Hosted login: http://localhost:${port}/login`, rotator);
|
|
2444
|
+
});
|
|
2445
|
+
return server;
|
|
2446
|
+
}
|