lemma-agent 1.0.0 → 1.1.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/dist/proxy.js ADDED
@@ -0,0 +1,858 @@
1
+ import { createServer } from "node:http";
2
+ import { randomUUID } from "node:crypto";
3
+ import { claudeSettingsEnv } from "./config.js";
4
+ import { readCredential, readCredentials } from "./credentials.js";
5
+ import { Redactor, StreamUnredactor } from "./redact.js";
6
+ function calculateUsageCost(price, usage) {
7
+ if (!price)
8
+ return undefined;
9
+ const fresh = Math.max(0, usage.input - (usage.cacheRead ?? 0));
10
+ return (fresh * price.input + (usage.cacheRead ?? 0) * (price.cacheRead ?? price.input) + usage.output * price.output) / 1_000_000;
11
+ }
12
+ const MAX_REQUEST_BYTES = 16 * 1024 * 1024;
13
+ const HOP_BY_HOP_HEADERS = new Set([
14
+ "host",
15
+ "connection",
16
+ "keep-alive",
17
+ "proxy-authenticate",
18
+ "proxy-authorization",
19
+ "te",
20
+ "trailer",
21
+ "transfer-encoding",
22
+ "upgrade",
23
+ "content-length",
24
+ "accept-encoding",
25
+ ]);
26
+ /** 解析 API 成员或协议通道的密钥池(去重保序,兼容环境变量与本机凭据库) */
27
+ export function resolveKeyPool(source) {
28
+ const raw = [];
29
+ if (source.apiKeys?.length)
30
+ raw.push(...source.apiKeys);
31
+ if (source.credentials?.length)
32
+ raw.push(...readCredentials(source.credentials));
33
+ for (const envName of source.apiKeyEnv ?? []) {
34
+ const v = process.env[envName];
35
+ if (v)
36
+ raw.push(...v.split(/[\r\n,]+/));
37
+ }
38
+ if (source.credential) {
39
+ const c = readCredential(source.credential);
40
+ if (c)
41
+ raw.push(c);
42
+ }
43
+ for (const k of source.extraKeys ?? [])
44
+ if (k)
45
+ raw.push(k);
46
+ const seen = new Set();
47
+ const out = [];
48
+ for (const item of raw) {
49
+ const trimmed = item.trim();
50
+ if (trimmed && !seen.has(trimmed)) {
51
+ seen.add(trimmed);
52
+ out.push(trimmed);
53
+ }
54
+ }
55
+ return out;
56
+ }
57
+ /** 拼接上游 baseUrl 与子路径,自动消除常见的重复 `/v1` 或 `/v1beta` 前缀 */
58
+ export function joinUpstreamUrl(baseUrl, subpath, search) {
59
+ const cleanBase = baseUrl.replace(/\/+$/, "");
60
+ let cleanSub = subpath.startsWith("/") ? subpath : `/${subpath}`;
61
+ try {
62
+ const basePath = new URL(cleanBase).pathname.replace(/\/+$/, "");
63
+ if (basePath && (cleanSub === basePath || cleanSub.startsWith(`${basePath}/`))) {
64
+ cleanSub = cleanSub.slice(basePath.length) || "/";
65
+ }
66
+ }
67
+ catch {
68
+ /* 已在上游配置校验过 URL */
69
+ }
70
+ return `${cleanBase}${cleanSub}${search}`;
71
+ }
72
+ export function parseRetryAfterMs(headers, bodyText, defaultSeconds, now) {
73
+ const raw = headers.get("retry-after");
74
+ if (raw) {
75
+ const sec = Number(raw);
76
+ if (Number.isFinite(sec) && sec > 0)
77
+ return Math.min(sec * 1000, 3600_000);
78
+ const at = Date.parse(raw);
79
+ if (Number.isFinite(at) && at > now)
80
+ return Math.min(at - now, 3600_000);
81
+ }
82
+ const m = bodyText.match(/retry[-_\s]*after[^0-9]*([0-9]+(?:\.[0-9]+)?)\s*(s|sec|seconds|ms)?/i);
83
+ if (m) {
84
+ const n = Number(m[1]);
85
+ if (Number.isFinite(n) && n > 0) {
86
+ return Math.min((m[2]?.toLowerCase() === "ms" ? n : n * 1000), 3600_000);
87
+ }
88
+ }
89
+ return Math.max(1000, defaultSeconds * 1000);
90
+ }
91
+ export function shouldFailoverStatus(status, bodyText) {
92
+ if (status === 429 || status === 503 || status === 529)
93
+ return true;
94
+ if (status === 402 || status === 403 || status === 401) {
95
+ return /insufficient[_\s-]?(?:quota|balance|credit)|rate[_\s-]?limit|quota[_\s-]?exceeded|exceeded your current quota|余额不足/i.test(bodyText);
96
+ }
97
+ return false;
98
+ }
99
+ /** 粘性 Key 池管理器:常规平滑轮转 + Prompt Cache 粘性优先 + 429 冷却退避 */
100
+ export class StickyKeyPool {
101
+ sticky = new Map();
102
+ cooldown = new Map();
103
+ rrCursor = new Map();
104
+ now;
105
+ constructor(now = () => Date.now()) {
106
+ this.now = now;
107
+ }
108
+ cooldownKey(poolId, key) {
109
+ return `${poolId}\0${key}`;
110
+ }
111
+ pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
112
+ if (!keys.length)
113
+ return [];
114
+ const t = this.now();
115
+ const healthy = [];
116
+ const resting = [];
117
+ for (const key of keys) {
118
+ const until = this.cooldown.get(this.cooldownKey(poolId, key)) ?? 0;
119
+ if (until <= t) {
120
+ if (until > 0)
121
+ this.cooldown.delete(this.cooldownKey(poolId, key));
122
+ healthy.push(key);
123
+ }
124
+ else {
125
+ resting.push({ key, until });
126
+ }
127
+ }
128
+ // 若池内全部 Key 都在冷却,按最早解禁时间兜底放行,避免假死
129
+ const baseList = healthy.length
130
+ ? healthy
131
+ : resting.sort((a, b) => a.until - b.until).map((r) => r.key);
132
+ const ordered = [];
133
+ if (stickyEnabled && sessionKey) {
134
+ const stickKey = `${poolId}\0${sessionKey}`;
135
+ const hit = this.sticky.get(stickKey);
136
+ if (hit && hit.expiresAt > t && baseList.includes(hit.key)) {
137
+ ordered.push(hit.key);
138
+ }
139
+ else if (hit && hit.expiresAt <= t) {
140
+ this.sticky.delete(stickKey);
141
+ }
142
+ }
143
+ const cursor = this.rrCursor.get(poolId) ?? 0;
144
+ const rotated = baseList.map((_, idx) => baseList[(cursor + idx) % baseList.length]);
145
+ this.rrCursor.set(poolId, (cursor + 1) % Math.max(1, baseList.length));
146
+ for (const key of rotated) {
147
+ if (!ordered.includes(key))
148
+ ordered.push(key);
149
+ }
150
+ return ordered;
151
+ }
152
+ markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
153
+ this.cooldown.delete(this.cooldownKey(poolId, key));
154
+ if (stickyEnabled && sessionKey && ttlSeconds > 0) {
155
+ this.sticky.set(`${poolId}\0${sessionKey}`, { key, expiresAt: this.now() + ttlSeconds * 1000 });
156
+ }
157
+ }
158
+ markFailed(poolId, sessionKey, key, cooldownMs) {
159
+ this.cooldown.set(this.cooldownKey(poolId, key), this.now() + cooldownMs);
160
+ if (sessionKey) {
161
+ const stickKey = `${poolId}\0${sessionKey}`;
162
+ if (this.sticky.get(stickKey)?.key === key)
163
+ this.sticky.delete(stickKey);
164
+ }
165
+ }
166
+ }
167
+ /** 旁路解析非流式 JSON 或 SSE 流中各厂商的 Token 用量与模型 ID */
168
+ export class UsageSniffer {
169
+ protocol;
170
+ sse;
171
+ lineBuf = "";
172
+ dataLines = [];
173
+ model;
174
+ inputTokens = 0;
175
+ outputTokens = 0;
176
+ cacheReadTokens = 0;
177
+ cacheWriteTokens = 0;
178
+ seenMessageStart = false;
179
+ constructor(protocol, contentType) {
180
+ this.protocol = protocol;
181
+ this.sse = (contentType ?? "").toLowerCase().includes("text/event-stream");
182
+ }
183
+ push(chunkText) {
184
+ if (!this.sse) {
185
+ this.lineBuf += chunkText;
186
+ return;
187
+ }
188
+ this.lineBuf += chunkText;
189
+ for (;;) {
190
+ const nl = this.lineBuf.indexOf("\n");
191
+ if (nl < 0)
192
+ break;
193
+ const rawLine = this.lineBuf.slice(0, nl).replace(/\r$/, "");
194
+ this.lineBuf = this.lineBuf.slice(nl + 1);
195
+ this.processSseLine(rawLine);
196
+ }
197
+ }
198
+ finish() {
199
+ if (!this.sse) {
200
+ const raw = this.lineBuf.trim();
201
+ this.lineBuf = "";
202
+ if (raw)
203
+ this.parsePayload(raw);
204
+ return;
205
+ }
206
+ if (this.lineBuf.trim()) {
207
+ this.processSseLine(this.lineBuf.replace(/\r$/, ""));
208
+ this.lineBuf = "";
209
+ }
210
+ this.flushSseEvent();
211
+ }
212
+ processSseLine(line) {
213
+ if (line === "") {
214
+ this.flushSseEvent();
215
+ return;
216
+ }
217
+ if (line.startsWith("data:")) {
218
+ this.dataLines.push(line.slice(5).trimStart());
219
+ }
220
+ }
221
+ flushSseEvent() {
222
+ if (!this.dataLines.length)
223
+ return;
224
+ const payload = this.dataLines.join("\n").trim();
225
+ this.dataLines = [];
226
+ if (payload && payload !== "[DONE]")
227
+ this.parsePayload(payload);
228
+ }
229
+ parsePayload(jsonText) {
230
+ let obj;
231
+ try {
232
+ obj = JSON.parse(jsonText);
233
+ }
234
+ catch {
235
+ return;
236
+ }
237
+ if (!obj || typeof obj !== "object")
238
+ return;
239
+ if (typeof obj.model === "string" && obj.model)
240
+ this.model = obj.model;
241
+ if (typeof obj.message?.model === "string" && obj.message.model)
242
+ this.model = obj.message.model;
243
+ if (typeof obj.response?.model === "string" && obj.response.model)
244
+ this.model = obj.response.model;
245
+ if (typeof obj.modelVersion === "string" && obj.modelVersion)
246
+ this.model = obj.modelVersion;
247
+ if (this.protocol === "anthropic") {
248
+ const u = obj.message?.usage ?? obj.usage;
249
+ if (!u || typeof u !== "object")
250
+ return;
251
+ if (obj.type === "message_start" || !this.sse) {
252
+ this.seenMessageStart = true;
253
+ if (typeof u.input_tokens === "number")
254
+ this.inputTokens = u.input_tokens;
255
+ if (typeof u.cache_read_input_tokens === "number")
256
+ this.cacheReadTokens = u.cache_read_input_tokens;
257
+ if (typeof u.cache_creation_input_tokens === "number")
258
+ this.cacheWriteTokens = u.cache_creation_input_tokens;
259
+ if (typeof u.output_tokens === "number")
260
+ this.outputTokens = Math.max(this.outputTokens, u.output_tokens);
261
+ }
262
+ else {
263
+ // message_delta 等增量事件报告最终累计 output_tokens
264
+ if (!this.seenMessageStart && typeof u.input_tokens === "number")
265
+ this.inputTokens = Math.max(this.inputTokens, u.input_tokens);
266
+ if (typeof u.cache_read_input_tokens === "number")
267
+ this.cacheReadTokens = Math.max(this.cacheReadTokens, u.cache_read_input_tokens);
268
+ if (typeof u.cache_creation_input_tokens === "number")
269
+ this.cacheWriteTokens = Math.max(this.cacheWriteTokens, u.cache_creation_input_tokens);
270
+ if (typeof u.output_tokens === "number")
271
+ this.outputTokens = Math.max(this.outputTokens, u.output_tokens);
272
+ }
273
+ return;
274
+ }
275
+ if (this.protocol === "openai") {
276
+ const u = obj.response?.usage ?? obj.usage;
277
+ if (!u || typeof u !== "object")
278
+ return;
279
+ const input = u.input_tokens ?? u.prompt_tokens;
280
+ const output = u.output_tokens ?? u.completion_tokens;
281
+ const cached = u.input_tokens_details?.cached_tokens ?? u.prompt_tokens_details?.cached_tokens;
282
+ if (typeof input === "number")
283
+ this.inputTokens = Math.max(this.inputTokens, input);
284
+ if (typeof output === "number")
285
+ this.outputTokens = Math.max(this.outputTokens, output);
286
+ if (typeof cached === "number")
287
+ this.cacheReadTokens = Math.max(this.cacheReadTokens, cached);
288
+ return;
289
+ }
290
+ if (this.protocol === "gemini") {
291
+ const m = obj.usageMetadata ?? obj.response?.usageMetadata;
292
+ if (!m || typeof m !== "object")
293
+ return;
294
+ const cached = typeof m.cachedContentTokenCount === "number" ? m.cachedContentTokenCount : 0;
295
+ const prompt = typeof m.promptTokenCount === "number" ? m.promptTokenCount : 0;
296
+ const candidates = typeof m.candidatesTokenCount === "number" ? m.candidatesTokenCount : 0;
297
+ const thoughts = typeof m.thoughtsTokenCount === "number" ? m.thoughtsTokenCount : 0;
298
+ if (prompt > 0)
299
+ this.inputTokens = Math.max(this.inputTokens, Math.max(0, prompt - cached));
300
+ if (cached > 0)
301
+ this.cacheReadTokens = Math.max(this.cacheReadTokens, cached);
302
+ if (candidates + thoughts > 0)
303
+ this.outputTokens = Math.max(this.outputTokens, candidates + thoughts);
304
+ }
305
+ }
306
+ toTokenUsage() {
307
+ return {
308
+ input: this.inputTokens,
309
+ output: this.outputTokens,
310
+ ...(this.cacheReadTokens > 0 ? { cacheRead: this.cacheReadTokens } : {}),
311
+ ...(this.cacheWriteTokens > 0 ? { cacheWrite: this.cacheWriteTokens } : {}),
312
+ };
313
+ }
314
+ }
315
+ function protocolErrorBody(protocol, message, code = "budget_exceeded") {
316
+ if (protocol === "anthropic") {
317
+ return JSON.stringify({ type: "error", error: { type: "rate_limit_error", message } });
318
+ }
319
+ if (protocol === "gemini") {
320
+ return JSON.stringify({ error: { code: 429, message, status: "RESOURCE_EXHAUSTED" } });
321
+ }
322
+ return JSON.stringify({ error: { message, type: "insufficient_quota", code } });
323
+ }
324
+ function extractClientToken(req, url) {
325
+ const auth = req.headers.authorization;
326
+ if (typeof auth === "string" && /^Bearer\s+/i.test(auth))
327
+ return auth.replace(/^Bearer\s+/i, "").trim();
328
+ const anthropicKey = req.headers["x-api-key"];
329
+ if (typeof anthropicKey === "string" && anthropicKey.trim())
330
+ return anthropicKey.trim();
331
+ const googKey = req.headers["x-goog-api-key"];
332
+ if (typeof googKey === "string" && googKey.trim())
333
+ return googKey.trim();
334
+ const queryKey = url.searchParams.get("key");
335
+ if (queryKey?.trim())
336
+ return queryKey.trim();
337
+ return undefined;
338
+ }
339
+ async function readRequestBody(req) {
340
+ const chunks = [];
341
+ let total = 0;
342
+ for await (const chunk of req) {
343
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
344
+ total += buf.length;
345
+ if (total > MAX_REQUEST_BYTES)
346
+ throw new Error("代理请求体超过 16MB 限制");
347
+ chunks.push(buf);
348
+ }
349
+ return Buffer.concat(chunks);
350
+ }
351
+ function parseProxyRoute(pathname, config) {
352
+ const memberMatch = pathname.match(/^\/proxy\/member\/([a-z0-9_]+)(\/.*)?$/);
353
+ if (memberMatch) {
354
+ const kind = memberMatch[1];
355
+ const agent = config.agents[kind];
356
+ if (!agent?.api)
357
+ return undefined;
358
+ const protocol = agent.api.type === "anthropic-compatible" ? "anthropic" : "openai";
359
+ return {
360
+ protocol,
361
+ subpath: memberMatch[2] || "/",
362
+ poolId: `member:${kind}`,
363
+ memberKind: kind,
364
+ memberApi: agent.api,
365
+ };
366
+ }
367
+ const protoMatch = pathname.match(/^\/proxy\/(anthropic|openai|gemini)(\/.*)?$/);
368
+ if (!protoMatch)
369
+ return undefined;
370
+ const protocol = protoMatch[1];
371
+ return {
372
+ protocol,
373
+ subpath: protoMatch[2] || "/",
374
+ poolId: `proto:${protocol}`,
375
+ };
376
+ }
377
+ export class LocalProxy {
378
+ deps;
379
+ tokens = new Map();
380
+ memberTokens = new Map();
381
+ keyPool;
382
+ redactor;
383
+ lastRedactConfigKey = "";
384
+ listenUrl;
385
+ onUrlChange = new Set();
386
+ activeUsage = new Map();
387
+ constructor(deps) {
388
+ this.deps = deps;
389
+ const now = deps.now ?? (() => Date.now());
390
+ this.keyPool = new StickyKeyPool(now);
391
+ this.redactor = new Redactor();
392
+ }
393
+ baseUrl() {
394
+ return this.listenUrl;
395
+ }
396
+ setListenUrl(url) {
397
+ const normalized = url ? url.replace(/\/+$/, "") : undefined;
398
+ if (this.listenUrl === normalized)
399
+ return;
400
+ this.listenUrl = normalized;
401
+ for (const listener of this.onUrlChange) {
402
+ try {
403
+ listener(normalized);
404
+ }
405
+ catch { }
406
+ }
407
+ }
408
+ subscribeUrl(listener) {
409
+ this.onUrlChange.add(listener);
410
+ return () => this.onUrlChange.delete(listener);
411
+ }
412
+ /** 判断给定本机 CLI 成员是否应被代理接管 */
413
+ shouldCaptureCli(kind) {
414
+ const cfg = this.deps.getConfig().proxy;
415
+ if (!cfg?.enabled)
416
+ return false;
417
+ if (kind === "claude" || kind === "codex" || kind === "gemini") {
418
+ return cfg.captureCli[kind] !== false;
419
+ }
420
+ return true;
421
+ }
422
+ /** 判断 API 成员是否应经过代理(全局启用代理 或 自身配置了多 Key 池) */
423
+ shouldRouteApiMember(api) {
424
+ const cfg = this.deps.getConfig().proxy;
425
+ if (cfg?.enabled)
426
+ return true;
427
+ return Boolean((api.apiKeys?.length ?? 0) > 1 || (api.credentials?.length ?? 0) > 1);
428
+ }
429
+ issueToken(meta) {
430
+ const token = `lemma-${randomUUID().replace(/-/g, "")}`;
431
+ this.tokens.set(token, { ...meta, token });
432
+ if (meta.callId && !this.activeUsage.has(meta.callId)) {
433
+ this.activeUsage.set(meta.callId, { costUsd: 0, events: 0 });
434
+ }
435
+ return token;
436
+ }
437
+ /** 为 API 成员复用一个稳定的本地代理占位令牌,避免反复生成泄漏 */
438
+ memberTokenFor(agent, protocol) {
439
+ const key = `${agent}:${protocol}`;
440
+ const existing = this.memberTokens.get(key);
441
+ if (existing && this.tokens.has(existing))
442
+ return existing;
443
+ const token = this.issueToken({ agent, protocol });
444
+ this.memberTokens.set(key, token);
445
+ return token;
446
+ }
447
+ revokeToken(token) {
448
+ if (!token)
449
+ return;
450
+ this.tokens.delete(token);
451
+ }
452
+ /** 供 dispatch 结算前查询本次 callId 是否已经由代理累加花费(避免与退出总结算重复扣减) */
453
+ consumeCallReport(callId) {
454
+ const rec = this.activeUsage.get(callId);
455
+ if (rec)
456
+ this.activeUsage.delete(callId);
457
+ return rec;
458
+ }
459
+ /** 构建注入到 CLI 子进程环境变量中的代理覆写项 */
460
+ cliEnvFor(kind, meta) {
461
+ const base = this.listenUrl;
462
+ if (!base || !this.shouldCaptureCli(kind))
463
+ return undefined;
464
+ const protocol = kind === "codex" ? "openai" : kind === "gemini" ? "gemini" : "anthropic";
465
+ const token = this.issueToken({ agent: kind, protocol, ...meta });
466
+ if (kind === "claude") {
467
+ return {
468
+ token,
469
+ env: {
470
+ ANTHROPIC_BASE_URL: `${base}/proxy/anthropic`,
471
+ ANTHROPIC_API_KEY: token,
472
+ ANTHROPIC_AUTH_TOKEN: token,
473
+ },
474
+ };
475
+ }
476
+ if (kind === "codex") {
477
+ return {
478
+ token,
479
+ env: {
480
+ OPENAI_BASE_URL: `${base}/proxy/openai/v1`,
481
+ OPENAI_API_KEY: token,
482
+ },
483
+ };
484
+ }
485
+ if (kind === "gemini") {
486
+ return {
487
+ token,
488
+ env: {
489
+ GOOGLE_GEMINI_BASE_URL: `${base}/proxy/gemini`,
490
+ GEMINI_API_KEY: token,
491
+ },
492
+ };
493
+ }
494
+ return undefined;
495
+ }
496
+ ensureRedactor(config) {
497
+ const r = config.proxy?.redact;
498
+ const key = JSON.stringify({ allowlist: r?.allowlist ?? [], customPatterns: r?.customPatterns ?? [] });
499
+ if (key !== this.lastRedactConfigKey) {
500
+ this.lastRedactConfigKey = key;
501
+ this.redactor = new Redactor({
502
+ allowlist: r?.allowlist,
503
+ customPatterns: r?.customPatterns,
504
+ });
505
+ }
506
+ return this.redactor;
507
+ }
508
+ resolveRelayToken(config) {
509
+ const relay = config.proxy?.relay;
510
+ if (!relay)
511
+ return undefined;
512
+ for (const envName of relay.tokenEnv) {
513
+ const v = process.env[envName];
514
+ if (v?.trim())
515
+ return v.trim();
516
+ }
517
+ return readCredential(relay.credential);
518
+ }
519
+ resolveUpstream(route, config) {
520
+ if (route.memberApi) {
521
+ return {
522
+ baseUrl: route.memberApi.baseUrl,
523
+ keys: resolveKeyPool(route.memberApi),
524
+ };
525
+ }
526
+ const upstream = config.proxy?.upstreams[route.protocol] ?? {};
527
+ if (route.protocol === "anthropic") {
528
+ const explicitKeys = resolveKeyPool(upstream);
529
+ const claude = !upstream.baseUrl || !explicitKeys.length ? claudeSettingsEnv() : {};
530
+ const baseUrl = upstream.baseUrl ?? claude.baseUrl ?? "https://api.anthropic.com";
531
+ const keys = explicitKeys.length ? explicitKeys : resolveKeyPool({ ...upstream, extraKeys: [claude.token] });
532
+ return { baseUrl, keys };
533
+ }
534
+ if (route.protocol === "openai") {
535
+ return {
536
+ baseUrl: upstream.baseUrl ?? "https://api.openai.com",
537
+ keys: resolveKeyPool(upstream),
538
+ };
539
+ }
540
+ return {
541
+ baseUrl: upstream.baseUrl ?? "https://generativelanguage.googleapis.com",
542
+ keys: resolveKeyPool(upstream),
543
+ };
544
+ }
545
+ priceFor(meta, modelId, config) {
546
+ const agent = config.agents[meta.agent];
547
+ if (!agent)
548
+ return undefined;
549
+ const target = modelId ?? meta.model ?? agent.defaultModel;
550
+ if (target) {
551
+ const matched = agent.models.find((m) => m.id === target)?.price;
552
+ if (matched)
553
+ return matched;
554
+ }
555
+ return agent.models[0]?.price;
556
+ }
557
+ /**
558
+ * 处理 `/proxy/*` 请求;若路径不是 `/proxy/*` 返回 `false` 交由外层路由继续处理。
559
+ */
560
+ async handle(req, res) {
561
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "127.0.0.1"}`);
562
+ if (!url.pathname.startsWith("/proxy/"))
563
+ return false;
564
+ const config = this.deps.getConfig();
565
+ const route = parseProxyRoute(url.pathname, config);
566
+ if (!route) {
567
+ res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
568
+ res.end(JSON.stringify({ error: "未知代理路由" }));
569
+ return true;
570
+ }
571
+ const clientToken = extractClientToken(req, url);
572
+ const meta = clientToken ? this.tokens.get(clientToken) : undefined;
573
+ if (!meta) {
574
+ res.writeHead(401, { "content-type": "application/json; charset=utf-8" });
575
+ res.end(protocolErrorBody(route.protocol, "无效的本地代理令牌", "invalid_proxy_token"));
576
+ return true;
577
+ }
578
+ if (this.deps.checkBudget) {
579
+ const check = await this.deps.checkBudget(meta);
580
+ if (!check.allowed) {
581
+ res.writeHead(429, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
582
+ res.end(protocolErrorBody(route.protocol, check.message ?? "当前运行已达到预算上限,代理已熔断。", "budget_exceeded"));
583
+ return true;
584
+ }
585
+ }
586
+ const proxyCfg = config.proxy;
587
+ const rawBody = await readRequestBody(req);
588
+ let outboundBody = rawBody;
589
+ let redactedCount = 0;
590
+ const requestVault = new Map();
591
+ const reqContentType = String(req.headers["content-type"] ?? "");
592
+ let requestedModel = meta.model;
593
+ if (rawBody.length > 0 && reqContentType.toLowerCase().includes("application/json")) {
594
+ try {
595
+ const parsed = JSON.parse(rawBody.toString("utf8"));
596
+ if (typeof parsed.model === "string" && parsed.model)
597
+ requestedModel = parsed.model;
598
+ if (proxyCfg?.redact.enabled) {
599
+ const redacted = this.ensureRedactor(config).redactJson(parsed, requestVault);
600
+ redactedCount = redacted.count;
601
+ if (redactedCount > 0)
602
+ outboundBody = Buffer.from(JSON.stringify(redacted.value), "utf8");
603
+ }
604
+ }
605
+ catch {
606
+ /* 非法或非 JSON 原样透传 */
607
+ }
608
+ }
609
+ // Gemini CLI 可能把 ?key=<localToken> 放在 query 上,转发上游前剥离本地占位 key
610
+ const searchParams = new URLSearchParams(url.search);
611
+ if (searchParams.get("key") === clientToken)
612
+ searchParams.delete("key");
613
+ const cleanSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
614
+ const useRelay = proxyCfg?.mode === "relay" && Boolean(proxyCfg.relay.url) && !route.memberApi;
615
+ const stickyCfg = proxyCfg?.sticky ?? { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 };
616
+ const sessionKey = meta.sessionId ||
617
+ meta.taskId ||
618
+ (typeof req.headers["x-lemma-session-id"] === "string" ? req.headers["x-lemma-session-id"] : undefined) ||
619
+ (typeof req.headers["x-codex-window-id"] === "string" ? req.headers["x-codex-window-id"] : undefined) ||
620
+ meta.callId ||
621
+ meta.agent;
622
+ let targetUrl;
623
+ let candidates;
624
+ if (useRelay) {
625
+ const relayUrl = proxyCfg.relay.url;
626
+ targetUrl = joinUpstreamUrl(relayUrl, `/${route.protocol}${route.subpath}`, cleanSearch);
627
+ const relayToken = this.resolveRelayToken(config);
628
+ if (!relayToken) {
629
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
630
+ res.end(protocolErrorBody(route.protocol, "托管中转模式缺少 relay token,请检查环境变量或本机凭据。", "missing_relay_token"));
631
+ return true;
632
+ }
633
+ candidates = [relayToken];
634
+ }
635
+ else {
636
+ const upstream = this.resolveUpstream(route, config);
637
+ targetUrl = joinUpstreamUrl(upstream.baseUrl, route.subpath, cleanSearch);
638
+ candidates = this.keyPool.pickCandidates(route.poolId, upstream.keys, sessionKey, stickyCfg.enabled);
639
+ if (!candidates.length) {
640
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
641
+ res.end(protocolErrorBody(route.protocol, `上游 ${route.poolId} 未配置可用 API Key。`, "missing_api_key"));
642
+ return true;
643
+ }
644
+ }
645
+ const fetchFn = this.deps.fetchImpl ?? fetch;
646
+ const now = this.deps.now ?? (() => Date.now());
647
+ const controller = new AbortController();
648
+ const onClientAbort = () => controller.abort();
649
+ req.once("aborted", onClientAbort);
650
+ res.once("close", onClientAbort);
651
+ const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 3);
652
+ let finalResponse;
653
+ let retries = 0;
654
+ try {
655
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
656
+ const apiKey = candidates[attempt];
657
+ const headers = new Headers();
658
+ for (const [k, v] of Object.entries(req.headers)) {
659
+ const lower = k.toLowerCase();
660
+ if (HOP_BY_HOP_HEADERS.has(lower))
661
+ continue;
662
+ if (lower === "authorization" || lower === "x-api-key" || lower === "x-goog-api-key")
663
+ continue;
664
+ if (Array.isArray(v))
665
+ headers.set(k, v.join(", "));
666
+ else if (typeof v === "string")
667
+ headers.set(k, v);
668
+ }
669
+ if (useRelay) {
670
+ headers.set("authorization", `Bearer ${apiKey}`);
671
+ if (meta.taskId)
672
+ headers.set("x-lemma-task-id", meta.taskId);
673
+ if (meta.sessionId)
674
+ headers.set("x-lemma-session-id", meta.sessionId);
675
+ headers.set("x-lemma-member", meta.agent);
676
+ }
677
+ else if (route.protocol === "anthropic") {
678
+ headers.set("x-api-key", apiKey);
679
+ }
680
+ else if (route.protocol === "gemini") {
681
+ headers.set("x-goog-api-key", apiKey);
682
+ }
683
+ else {
684
+ headers.set("authorization", `Bearer ${apiKey}`);
685
+ }
686
+ const upstreamRes = await fetchFn(targetUrl, {
687
+ method: req.method ?? "POST",
688
+ headers,
689
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(outboundBody),
690
+ signal: controller.signal,
691
+ });
692
+ // 若响应为错误且仍有备用 Key 可切换:先读错误体判断是否触发 cooldown + failover
693
+ if (!upstreamRes.ok && attempt + 1 < maxAttempts) {
694
+ const errText = await upstreamRes.text();
695
+ if (shouldFailoverStatus(upstreamRes.status, errText)) {
696
+ const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
697
+ this.keyPool.markFailed(route.poolId, sessionKey, apiKey, cooldownMs);
698
+ retries++;
699
+ continue;
700
+ }
701
+ finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
702
+ break;
703
+ }
704
+ if (upstreamRes.ok && !useRelay) {
705
+ this.keyPool.markSuccess(route.poolId, sessionKey, apiKey, stickyCfg.ttlSeconds, stickyCfg.enabled);
706
+ }
707
+ else if (!upstreamRes.ok && !useRelay && shouldFailoverStatus(upstreamRes.status, "")) {
708
+ const cooldownMs = parseRetryAfterMs(upstreamRes.headers, "", stickyCfg.cooldownSeconds, now());
709
+ this.keyPool.markFailed(route.poolId, sessionKey, apiKey, cooldownMs);
710
+ }
711
+ finalResponse = upstreamRes;
712
+ break;
713
+ }
714
+ }
715
+ catch (error) {
716
+ if (!controller.signal.aborted && !res.headersSent) {
717
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
718
+ res.end(protocolErrorBody(route.protocol, `上游请求失败:${error instanceof Error ? error.message : String(error)}`, "upstream_error"));
719
+ }
720
+ return true;
721
+ }
722
+ finally {
723
+ req.off("aborted", onClientAbort);
724
+ res.off("close", onClientAbort);
725
+ }
726
+ if (!finalResponse) {
727
+ if (!res.headersSent) {
728
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
729
+ res.end(protocolErrorBody(route.protocol, "未收到上游响应。", "upstream_error"));
730
+ }
731
+ return true;
732
+ }
733
+ const outHeaders = {};
734
+ finalResponse.headers.forEach((v, k) => {
735
+ const lower = k.toLowerCase();
736
+ if (lower === "content-length" || lower === "content-encoding" || lower === "transfer-encoding" || lower === "connection")
737
+ return;
738
+ outHeaders[k] = v;
739
+ });
740
+ res.writeHead(finalResponse.status, outHeaders);
741
+ const resContentType = finalResponse.headers.get("content-type");
742
+ const sniffer = new UsageSniffer(route.protocol, resContentType);
743
+ const restore = Boolean(proxyCfg?.redact.restoreInResponse && redactedCount > 0);
744
+ const redactor = this.ensureRedactor(config);
745
+ const unredactor = restore ? new StreamUnredactor((t) => redactor.restoreText(t, requestVault)) : undefined;
746
+ if (finalResponse.body) {
747
+ const decoder = new TextDecoder();
748
+ const reader = finalResponse.body.getReader();
749
+ try {
750
+ for (;;) {
751
+ const { done, value } = await reader.read();
752
+ if (done)
753
+ break;
754
+ const text = decoder.decode(value, { stream: true });
755
+ if (text) {
756
+ sniffer.push(text);
757
+ const emit = unredactor ? unredactor.push(text) : text;
758
+ if (emit && !res.destroyed)
759
+ res.write(emit);
760
+ }
761
+ }
762
+ const tail = decoder.decode();
763
+ if (tail) {
764
+ sniffer.push(tail);
765
+ const emit = unredactor ? unredactor.push(tail) : tail;
766
+ if (emit && !res.destroyed)
767
+ res.write(emit);
768
+ }
769
+ if (unredactor) {
770
+ const rem = unredactor.flush();
771
+ if (rem && !res.destroyed)
772
+ res.write(rem);
773
+ }
774
+ }
775
+ catch {
776
+ /* 流中断时仍尽量提交已嗅探到的部分用量 */
777
+ }
778
+ }
779
+ sniffer.finish();
780
+ if (!res.writableEnded)
781
+ res.end();
782
+ const usage = sniffer.toTokenUsage();
783
+ const usedModel = sniffer.model ?? requestedModel;
784
+ const hasTokens = usage.input > 0 || usage.output > 0 || (usage.cacheRead ?? 0) > 0;
785
+ const costUsd = hasTokens ? calculateUsageCost(this.priceFor(meta, usedModel, config), usage) : undefined;
786
+ if (meta.callId && costUsd !== undefined && costUsd > 0) {
787
+ const prev = this.activeUsage.get(meta.callId) ?? { costUsd: 0, events: 0 };
788
+ prev.costUsd += costUsd;
789
+ prev.events++;
790
+ this.activeUsage.set(meta.callId, prev);
791
+ }
792
+ if (this.deps.onUsage && (hasTokens || costUsd !== undefined)) {
793
+ await Promise.resolve(this.deps.onUsage({
794
+ agent: meta.agent,
795
+ protocol: route.protocol,
796
+ taskId: meta.taskId,
797
+ sessionId: meta.sessionId,
798
+ callId: meta.callId,
799
+ model: usedModel,
800
+ usage,
801
+ costUsd,
802
+ status: finalResponse.status,
803
+ redactedCount,
804
+ retries,
805
+ })).catch(() => { });
806
+ }
807
+ return true;
808
+ }
809
+ }
810
+ /** 仅启动代理路由的轻量本地 HTTP 服务(用于 `--no-web`、单轮或离线测试场景) */
811
+ export async function startProxyServer(proxy, preferredPort = 8787) {
812
+ let port = preferredPort;
813
+ const server = createServer((req, res) => {
814
+ const host = String(req.headers.host ?? "");
815
+ if (host && !host.startsWith(`127.0.0.1:${port}`) && !host.startsWith(`localhost:${port}`)) {
816
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
817
+ res.end(JSON.stringify({ error: "bad host" }));
818
+ return;
819
+ }
820
+ void proxy.handle(req, res).then((handled) => {
821
+ if (!handled && !res.headersSent) {
822
+ res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
823
+ res.end(JSON.stringify({ error: "not found" }));
824
+ }
825
+ }).catch((err) => {
826
+ if (!res.headersSent && !res.destroyed) {
827
+ res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
828
+ res.end(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }));
829
+ }
830
+ });
831
+ });
832
+ for (let attempt = 0;; attempt++) {
833
+ try {
834
+ await new Promise((resolve, reject) => {
835
+ server.once("error", reject);
836
+ server.listen(port, "127.0.0.1", () => { server.off("error", reject); resolve(); });
837
+ });
838
+ port = server.address().port;
839
+ break;
840
+ }
841
+ catch (error) {
842
+ if (error?.code !== "EADDRINUSE" || attempt >= 9 || port === 0)
843
+ throw error;
844
+ port++;
845
+ }
846
+ }
847
+ const url = `http://127.0.0.1:${port}`;
848
+ proxy.setListenUrl(url);
849
+ return {
850
+ url,
851
+ async close() {
852
+ proxy.setListenUrl(undefined);
853
+ const stopped = new Promise((resolve) => server.close(() => resolve()));
854
+ server.closeAllConnections();
855
+ await stopped;
856
+ },
857
+ };
858
+ }