lemma-agent 1.0.1 → 1.1.1
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/README.md +29 -0
- package/dist/account-discovery.js +159 -0
- package/dist/admin.js +20 -1
- package/dist/api-member.js +18 -5
- package/dist/app.js +45 -6
- package/dist/bridge.js +341 -0
- package/dist/config.js +157 -0
- package/dist/credentials.js +11 -0
- package/dist/dispatch.js +37 -23
- package/dist/main.js +34 -1
- package/dist/proxy.js +1251 -0
- package/dist/redact.js +185 -0
- package/dist/tools.js +2 -2
- package/package.json +3 -2
- package/web/js/views.js +40 -0
package/dist/proxy.js
ADDED
|
@@ -0,0 +1,1251 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import { claudeSettingsEnv } from "./config.js";
|
|
6
|
+
import { readCredential, readCredentials } from "./credentials.js";
|
|
7
|
+
import { anthropicToOpenAiRequest, OpenAiToAnthropicSseTranslator, openAiToAnthropicJsonResponse } from "./bridge.js";
|
|
8
|
+
import { Redactor, StreamUnredactor } from "./redact.js";
|
|
9
|
+
function calculateUsageCost(price, usage) {
|
|
10
|
+
if (!price)
|
|
11
|
+
return undefined;
|
|
12
|
+
const fresh = Math.max(0, usage.input - (usage.cacheRead ?? 0));
|
|
13
|
+
return (fresh * price.input + (usage.cacheRead ?? 0) * (price.cacheRead ?? price.input) + usage.output * price.output) / 1_000_000;
|
|
14
|
+
}
|
|
15
|
+
const MAX_REQUEST_BYTES = 16 * 1024 * 1024;
|
|
16
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
17
|
+
"host",
|
|
18
|
+
"connection",
|
|
19
|
+
"keep-alive",
|
|
20
|
+
"proxy-authenticate",
|
|
21
|
+
"proxy-authorization",
|
|
22
|
+
"te",
|
|
23
|
+
"trailer",
|
|
24
|
+
"transfer-encoding",
|
|
25
|
+
"upgrade",
|
|
26
|
+
"content-length",
|
|
27
|
+
"accept-encoding",
|
|
28
|
+
]);
|
|
29
|
+
/** 解析 API 成员或协议通道的密钥池(去重保序,兼容环境变量与本机凭据库) */
|
|
30
|
+
export function resolveKeyPool(source) {
|
|
31
|
+
const raw = [];
|
|
32
|
+
if (source.apiKeys?.length)
|
|
33
|
+
raw.push(...source.apiKeys);
|
|
34
|
+
if (source.credentials?.length)
|
|
35
|
+
raw.push(...readCredentials(source.credentials));
|
|
36
|
+
for (const envName of source.apiKeyEnv ?? []) {
|
|
37
|
+
const v = process.env[envName];
|
|
38
|
+
if (v)
|
|
39
|
+
raw.push(...v.split(/[\r\n,]+/));
|
|
40
|
+
}
|
|
41
|
+
if (source.credential) {
|
|
42
|
+
const c = readCredential(source.credential);
|
|
43
|
+
if (c)
|
|
44
|
+
raw.push(c);
|
|
45
|
+
}
|
|
46
|
+
for (const k of source.extraKeys ?? [])
|
|
47
|
+
if (k)
|
|
48
|
+
raw.push(k);
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
const out = [];
|
|
51
|
+
for (const item of raw) {
|
|
52
|
+
const trimmed = item.trim();
|
|
53
|
+
if (trimmed && !seen.has(trimmed)) {
|
|
54
|
+
seen.add(trimmed);
|
|
55
|
+
out.push(trimmed);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/** 拼接上游 baseUrl 与子路径,自动消除常见的重复 `/v1` 或 `/v1beta` 前缀 */
|
|
61
|
+
export function joinUpstreamUrl(baseUrl, subpath, search) {
|
|
62
|
+
const cleanBase = baseUrl.replace(/\/+$/, "");
|
|
63
|
+
let cleanSub = subpath.startsWith("/") ? subpath : `/${subpath}`;
|
|
64
|
+
try {
|
|
65
|
+
const basePath = new URL(cleanBase).pathname.replace(/\/+$/, "");
|
|
66
|
+
if (basePath && (cleanSub === basePath || cleanSub.startsWith(`${basePath}/`))) {
|
|
67
|
+
cleanSub = cleanSub.slice(basePath.length) || "/";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
/* 已在上游配置校验过 URL */
|
|
72
|
+
}
|
|
73
|
+
return `${cleanBase}${cleanSub}${search}`;
|
|
74
|
+
}
|
|
75
|
+
export function parseRetryAfterMs(headers, bodyText, defaultSeconds, now) {
|
|
76
|
+
const raw = headers.get("retry-after");
|
|
77
|
+
if (raw) {
|
|
78
|
+
const sec = Number(raw);
|
|
79
|
+
if (Number.isFinite(sec) && sec > 0)
|
|
80
|
+
return Math.min(sec * 1000, 3600_000);
|
|
81
|
+
const at = Date.parse(raw);
|
|
82
|
+
if (Number.isFinite(at) && at > now)
|
|
83
|
+
return Math.min(at - now, 3600_000);
|
|
84
|
+
}
|
|
85
|
+
const m = bodyText.match(/retry[-_\s]*after[^0-9]*([0-9]+(?:\.[0-9]+)?)\s*(s|sec|seconds|ms)?/i);
|
|
86
|
+
if (m) {
|
|
87
|
+
const n = Number(m[1]);
|
|
88
|
+
if (Number.isFinite(n) && n > 0) {
|
|
89
|
+
return Math.min((m[2]?.toLowerCase() === "ms" ? n : n * 1000), 3600_000);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return Math.max(1000, defaultSeconds * 1000);
|
|
93
|
+
}
|
|
94
|
+
export function shouldFailoverStatus(status, bodyText) {
|
|
95
|
+
if (status === 429 || status === 503 || status === 529)
|
|
96
|
+
return true;
|
|
97
|
+
if (status === 402 || status === 403 || status === 401) {
|
|
98
|
+
return /insufficient[_\s-]?(?:quota|balance|credit)|rate[_\s-]?limit|quota[_\s-]?exceeded|exceeded your current quota|余额不足/i.test(bodyText);
|
|
99
|
+
}
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
/** 识别上游因跨渠道/跨账号思考块签名不匹配而拒收历史消息的 400 错误(不应拉黑当前健康 Key) */
|
|
103
|
+
export function isSignatureRefused(status, bodyText) {
|
|
104
|
+
if (status !== 400 || !bodyText)
|
|
105
|
+
return false;
|
|
106
|
+
return /invalid[^"\n]*signature|thought[_ ]?signature|signature[^"\n]*(?:invalid|mismatch|expired|verify|unrecognized)|redacted_thinking|encrypted_content/i.test(bodyText);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* 在不改动本地持久化历史的前提下,仅为当前这一次出站请求剥离不兼容的思考签名块,
|
|
110
|
+
* 避免切换上游通道或账号后因签名域不同而反复 400 失败。
|
|
111
|
+
*/
|
|
112
|
+
export function stripIncompatibleSignatures(protocol, body) {
|
|
113
|
+
if (!body.length)
|
|
114
|
+
return { body, stripped: false };
|
|
115
|
+
let parsed;
|
|
116
|
+
try {
|
|
117
|
+
parsed = JSON.parse(body.toString("utf8"));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return { body, stripped: false };
|
|
121
|
+
}
|
|
122
|
+
if (!parsed || typeof parsed !== "object")
|
|
123
|
+
return { body, stripped: false };
|
|
124
|
+
let stripped = false;
|
|
125
|
+
if (protocol === "anthropic" && Array.isArray(parsed.messages)) {
|
|
126
|
+
for (const msg of parsed.messages) {
|
|
127
|
+
if (!msg || typeof msg !== "object" || !Array.isArray(msg.content))
|
|
128
|
+
continue;
|
|
129
|
+
const filtered = msg.content.filter((block) => {
|
|
130
|
+
if (block && typeof block === "object" && (block.type === "thinking" || block.type === "redacted_thinking")) {
|
|
131
|
+
stripped = true;
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
});
|
|
136
|
+
if (filtered.length !== msg.content.length) {
|
|
137
|
+
msg.content = filtered.length ? filtered : [{ type: "text", text: " " }];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
else if (protocol === "gemini" && Array.isArray(parsed.contents)) {
|
|
142
|
+
for (const content of parsed.contents) {
|
|
143
|
+
if (!content || typeof content !== "object" || !Array.isArray(content.parts))
|
|
144
|
+
continue;
|
|
145
|
+
for (const part of content.parts) {
|
|
146
|
+
if (!part || typeof part !== "object")
|
|
147
|
+
continue;
|
|
148
|
+
if ("thoughtSignature" in part) {
|
|
149
|
+
delete part.thoughtSignature;
|
|
150
|
+
stripped = true;
|
|
151
|
+
}
|
|
152
|
+
if ("thought_signature" in part) {
|
|
153
|
+
delete part.thought_signature;
|
|
154
|
+
stripped = true;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
else if (protocol === "openai" && Array.isArray(parsed.input)) {
|
|
160
|
+
const filtered = parsed.input.filter((item) => {
|
|
161
|
+
if (item && typeof item === "object" && item.type === "reasoning" && typeof item.encrypted_content === "string") {
|
|
162
|
+
stripped = true;
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
return true;
|
|
166
|
+
});
|
|
167
|
+
if (filtered.length !== parsed.input.length)
|
|
168
|
+
parsed.input = filtered;
|
|
169
|
+
}
|
|
170
|
+
if (!stripped)
|
|
171
|
+
return { body, stripped: false };
|
|
172
|
+
return { body: Buffer.from(JSON.stringify(parsed), "utf8"), stripped: true };
|
|
173
|
+
}
|
|
174
|
+
const MAX_STICKY_ENTRIES = 4096;
|
|
175
|
+
function keyHashOf(key) {
|
|
176
|
+
return createHash("sha256").update(key).digest("hex").slice(0, 16);
|
|
177
|
+
}
|
|
178
|
+
/** 粘性 Key 池管理器:常规平滑轮转 + Prompt Cache 粘性优先 + 429 冷却退避 + 可选哈希持久化 */
|
|
179
|
+
export class StickyKeyPool {
|
|
180
|
+
sticky = new Map();
|
|
181
|
+
cooldown = new Map();
|
|
182
|
+
rrCursor = new Map();
|
|
183
|
+
now;
|
|
184
|
+
affinityFile;
|
|
185
|
+
constructor(now = () => Date.now(), affinityFile) {
|
|
186
|
+
this.now = now;
|
|
187
|
+
this.affinityFile = affinityFile;
|
|
188
|
+
this.load();
|
|
189
|
+
}
|
|
190
|
+
load() {
|
|
191
|
+
if (!this.affinityFile || !existsSync(this.affinityFile))
|
|
192
|
+
return;
|
|
193
|
+
try {
|
|
194
|
+
const raw = JSON.parse(readFileSync(this.affinityFile, "utf8"));
|
|
195
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
196
|
+
return;
|
|
197
|
+
const t = this.now();
|
|
198
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
199
|
+
if (v && typeof v.keyHash === "string" && typeof v.expiresAt === "number" && v.expiresAt > t) {
|
|
200
|
+
this.sticky.set(k, { keyHash: v.keyHash, expiresAt: v.expiresAt });
|
|
201
|
+
if (this.sticky.size >= MAX_STICKY_ENTRIES)
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
/* 损坏或不可读的粘性缓存忽略即可 */
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
persist() {
|
|
211
|
+
if (!this.affinityFile)
|
|
212
|
+
return;
|
|
213
|
+
const t = this.now();
|
|
214
|
+
const out = {};
|
|
215
|
+
for (const [k, v] of this.sticky.entries()) {
|
|
216
|
+
if (v.expiresAt > t)
|
|
217
|
+
out[k] = v;
|
|
218
|
+
}
|
|
219
|
+
const tmp = `${this.affinityFile}.${randomUUID()}.tmp`;
|
|
220
|
+
try {
|
|
221
|
+
mkdirSync(dirname(this.affinityFile), { recursive: true });
|
|
222
|
+
writeFileSync(tmp, `${JSON.stringify(out)}\n`, { mode: 0o600, flag: "wx" });
|
|
223
|
+
renameSync(tmp, this.affinityFile);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
/* 持久化失败不影响内存路由 */
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
try {
|
|
230
|
+
rmSync(tmp, { force: true });
|
|
231
|
+
}
|
|
232
|
+
catch { }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
cooldownKey(poolId, key) {
|
|
236
|
+
return `${poolId}\0${key}`;
|
|
237
|
+
}
|
|
238
|
+
pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
|
|
239
|
+
if (!keys.length)
|
|
240
|
+
return [];
|
|
241
|
+
const t = this.now();
|
|
242
|
+
const healthy = [];
|
|
243
|
+
const resting = [];
|
|
244
|
+
for (const key of keys) {
|
|
245
|
+
const until = this.cooldown.get(this.cooldownKey(poolId, key)) ?? 0;
|
|
246
|
+
if (until <= t) {
|
|
247
|
+
if (until > 0)
|
|
248
|
+
this.cooldown.delete(this.cooldownKey(poolId, key));
|
|
249
|
+
healthy.push(key);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
resting.push({ key, until });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// 若池内全部 Key 都在冷却,按最早解禁时间兜底放行,避免假死
|
|
256
|
+
const baseList = healthy.length
|
|
257
|
+
? healthy
|
|
258
|
+
: resting.sort((a, b) => a.until - b.until).map((r) => r.key);
|
|
259
|
+
const ordered = [];
|
|
260
|
+
if (stickyEnabled && sessionKey) {
|
|
261
|
+
const stickKey = `${poolId}\0${sessionKey}`;
|
|
262
|
+
const hit = this.sticky.get(stickKey);
|
|
263
|
+
if (hit && hit.expiresAt > t) {
|
|
264
|
+
const matched = baseList.find((k) => keyHashOf(k) === hit.keyHash);
|
|
265
|
+
if (matched)
|
|
266
|
+
ordered.push(matched);
|
|
267
|
+
}
|
|
268
|
+
else if (hit && hit.expiresAt <= t) {
|
|
269
|
+
this.sticky.delete(stickKey);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const cursor = this.rrCursor.get(poolId) ?? 0;
|
|
273
|
+
const rotated = baseList.map((_, idx) => baseList[(cursor + idx) % baseList.length]);
|
|
274
|
+
this.rrCursor.set(poolId, (cursor + 1) % Math.max(1, baseList.length));
|
|
275
|
+
for (const key of rotated) {
|
|
276
|
+
if (!ordered.includes(key))
|
|
277
|
+
ordered.push(key);
|
|
278
|
+
}
|
|
279
|
+
return ordered;
|
|
280
|
+
}
|
|
281
|
+
markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
|
|
282
|
+
this.cooldown.delete(this.cooldownKey(poolId, key));
|
|
283
|
+
if (stickyEnabled && sessionKey && ttlSeconds > 0) {
|
|
284
|
+
const stickKey = `${poolId}\0${sessionKey}`;
|
|
285
|
+
if (this.sticky.size >= MAX_STICKY_ENTRIES && !this.sticky.has(stickKey)) {
|
|
286
|
+
const oldest = this.sticky.keys().next().value;
|
|
287
|
+
if (oldest !== undefined)
|
|
288
|
+
this.sticky.delete(oldest);
|
|
289
|
+
}
|
|
290
|
+
this.sticky.set(stickKey, { keyHash: keyHashOf(key), expiresAt: this.now() + ttlSeconds * 1000 });
|
|
291
|
+
this.persist();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
markFailed(poolId, sessionKey, key, cooldownMs) {
|
|
295
|
+
this.cooldown.set(this.cooldownKey(poolId, key), this.now() + cooldownMs);
|
|
296
|
+
if (sessionKey) {
|
|
297
|
+
const stickKey = `${poolId}\0${sessionKey}`;
|
|
298
|
+
if (this.sticky.get(stickKey)?.keyHash === keyHashOf(key)) {
|
|
299
|
+
this.sticky.delete(stickKey);
|
|
300
|
+
this.persist();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
status() {
|
|
305
|
+
const t = this.now();
|
|
306
|
+
let activeStickyCount = 0;
|
|
307
|
+
for (const v of this.sticky.values())
|
|
308
|
+
if (v.expiresAt > t)
|
|
309
|
+
activeStickyCount++;
|
|
310
|
+
const cooledKeys = [];
|
|
311
|
+
for (const [ck, until] of this.cooldown.entries()) {
|
|
312
|
+
if (until <= t)
|
|
313
|
+
continue;
|
|
314
|
+
const sep = ck.indexOf("\0");
|
|
315
|
+
const poolId = sep >= 0 ? ck.slice(0, sep) : ck;
|
|
316
|
+
const rawKey = sep >= 0 ? ck.slice(sep + 1) : "";
|
|
317
|
+
cooledKeys.push({ poolId, keyHash: keyHashOf(rawKey), remainingSec: Math.ceil((until - t) / 1000) });
|
|
318
|
+
}
|
|
319
|
+
return { activeStickyCount, cooledKeys };
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function medianOf(nums) {
|
|
323
|
+
if (!nums.length)
|
|
324
|
+
return null;
|
|
325
|
+
const sorted = [...nums].sort((a, b) => a - b);
|
|
326
|
+
return sorted[Math.floor(sorted.length / 2)];
|
|
327
|
+
}
|
|
328
|
+
function isCompactPrompt(body) {
|
|
329
|
+
const chunks = [];
|
|
330
|
+
if (typeof body.system === "string")
|
|
331
|
+
chunks.push(body.system.slice(0, 600));
|
|
332
|
+
else if (Array.isArray(body.system)) {
|
|
333
|
+
for (const b of body.system)
|
|
334
|
+
if (typeof b?.text === "string")
|
|
335
|
+
chunks.push(b.text.slice(0, 400));
|
|
336
|
+
}
|
|
337
|
+
const lastUser = Array.isArray(body.messages) ? [...body.messages].reverse().find((m) => m?.role === "user") : undefined;
|
|
338
|
+
if (typeof lastUser?.content === "string")
|
|
339
|
+
chunks.push(lastUser.content.slice(0, 600));
|
|
340
|
+
else if (Array.isArray(lastUser?.content)) {
|
|
341
|
+
for (const b of lastUser.content)
|
|
342
|
+
if (typeof b?.text === "string")
|
|
343
|
+
chunks.push(b.text.slice(0, 400));
|
|
344
|
+
}
|
|
345
|
+
const text = chunks.join("\n");
|
|
346
|
+
return /(?:^|\s)\/compact\b|summarize the conversation(?: above| so far)|write a concise summary of the conversation|压缩上下文/i.test(text);
|
|
347
|
+
}
|
|
348
|
+
/** 旁路解析非流式 JSON 或 SSE 流中各厂商的 Token 用量与模型 ID */
|
|
349
|
+
export class UsageSniffer {
|
|
350
|
+
protocol;
|
|
351
|
+
sse;
|
|
352
|
+
lineBuf = "";
|
|
353
|
+
dataLines = [];
|
|
354
|
+
model;
|
|
355
|
+
inputTokens = 0;
|
|
356
|
+
outputTokens = 0;
|
|
357
|
+
cacheReadTokens = 0;
|
|
358
|
+
cacheWriteTokens = 0;
|
|
359
|
+
seenMessageStart = false;
|
|
360
|
+
constructor(protocol, contentType) {
|
|
361
|
+
this.protocol = protocol;
|
|
362
|
+
this.sse = (contentType ?? "").toLowerCase().includes("text/event-stream");
|
|
363
|
+
}
|
|
364
|
+
push(chunkText) {
|
|
365
|
+
if (!this.sse) {
|
|
366
|
+
this.lineBuf += chunkText;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
this.lineBuf += chunkText;
|
|
370
|
+
for (;;) {
|
|
371
|
+
const nl = this.lineBuf.indexOf("\n");
|
|
372
|
+
if (nl < 0)
|
|
373
|
+
break;
|
|
374
|
+
const rawLine = this.lineBuf.slice(0, nl).replace(/\r$/, "");
|
|
375
|
+
this.lineBuf = this.lineBuf.slice(nl + 1);
|
|
376
|
+
this.processSseLine(rawLine);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
finish() {
|
|
380
|
+
if (!this.sse) {
|
|
381
|
+
const raw = this.lineBuf.trim();
|
|
382
|
+
this.lineBuf = "";
|
|
383
|
+
if (raw)
|
|
384
|
+
this.parsePayload(raw);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (this.lineBuf.trim()) {
|
|
388
|
+
this.processSseLine(this.lineBuf.replace(/\r$/, ""));
|
|
389
|
+
this.lineBuf = "";
|
|
390
|
+
}
|
|
391
|
+
this.flushSseEvent();
|
|
392
|
+
}
|
|
393
|
+
processSseLine(line) {
|
|
394
|
+
if (line === "") {
|
|
395
|
+
this.flushSseEvent();
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (line.startsWith("data:")) {
|
|
399
|
+
this.dataLines.push(line.slice(5).trimStart());
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
flushSseEvent() {
|
|
403
|
+
if (!this.dataLines.length)
|
|
404
|
+
return;
|
|
405
|
+
const payload = this.dataLines.join("\n").trim();
|
|
406
|
+
this.dataLines = [];
|
|
407
|
+
if (payload && payload !== "[DONE]")
|
|
408
|
+
this.parsePayload(payload);
|
|
409
|
+
}
|
|
410
|
+
parsePayload(jsonText) {
|
|
411
|
+
let obj;
|
|
412
|
+
try {
|
|
413
|
+
obj = JSON.parse(jsonText);
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (!obj || typeof obj !== "object")
|
|
419
|
+
return;
|
|
420
|
+
if (typeof obj.model === "string" && obj.model)
|
|
421
|
+
this.model = obj.model;
|
|
422
|
+
if (typeof obj.message?.model === "string" && obj.message.model)
|
|
423
|
+
this.model = obj.message.model;
|
|
424
|
+
if (typeof obj.response?.model === "string" && obj.response.model)
|
|
425
|
+
this.model = obj.response.model;
|
|
426
|
+
if (typeof obj.modelVersion === "string" && obj.modelVersion)
|
|
427
|
+
this.model = obj.modelVersion;
|
|
428
|
+
if (this.protocol === "anthropic") {
|
|
429
|
+
const u = obj.message?.usage ?? obj.usage;
|
|
430
|
+
if (!u || typeof u !== "object")
|
|
431
|
+
return;
|
|
432
|
+
if (obj.type === "message_start" || !this.sse) {
|
|
433
|
+
this.seenMessageStart = true;
|
|
434
|
+
if (typeof u.input_tokens === "number")
|
|
435
|
+
this.inputTokens = u.input_tokens;
|
|
436
|
+
if (typeof u.cache_read_input_tokens === "number")
|
|
437
|
+
this.cacheReadTokens = u.cache_read_input_tokens;
|
|
438
|
+
if (typeof u.cache_creation_input_tokens === "number")
|
|
439
|
+
this.cacheWriteTokens = u.cache_creation_input_tokens;
|
|
440
|
+
if (typeof u.output_tokens === "number")
|
|
441
|
+
this.outputTokens = Math.max(this.outputTokens, u.output_tokens);
|
|
442
|
+
}
|
|
443
|
+
else {
|
|
444
|
+
// message_delta 等增量事件报告最终累计 output_tokens
|
|
445
|
+
if (!this.seenMessageStart && typeof u.input_tokens === "number")
|
|
446
|
+
this.inputTokens = Math.max(this.inputTokens, u.input_tokens);
|
|
447
|
+
if (typeof u.cache_read_input_tokens === "number")
|
|
448
|
+
this.cacheReadTokens = Math.max(this.cacheReadTokens, u.cache_read_input_tokens);
|
|
449
|
+
if (typeof u.cache_creation_input_tokens === "number")
|
|
450
|
+
this.cacheWriteTokens = Math.max(this.cacheWriteTokens, u.cache_creation_input_tokens);
|
|
451
|
+
if (typeof u.output_tokens === "number")
|
|
452
|
+
this.outputTokens = Math.max(this.outputTokens, u.output_tokens);
|
|
453
|
+
}
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
if (this.protocol === "openai") {
|
|
457
|
+
const u = obj.response?.usage ?? obj.usage;
|
|
458
|
+
if (!u || typeof u !== "object")
|
|
459
|
+
return;
|
|
460
|
+
const input = u.input_tokens ?? u.prompt_tokens;
|
|
461
|
+
const output = u.output_tokens ?? u.completion_tokens;
|
|
462
|
+
const cached = u.input_tokens_details?.cached_tokens ?? u.prompt_tokens_details?.cached_tokens;
|
|
463
|
+
if (typeof input === "number")
|
|
464
|
+
this.inputTokens = Math.max(this.inputTokens, input);
|
|
465
|
+
if (typeof output === "number")
|
|
466
|
+
this.outputTokens = Math.max(this.outputTokens, output);
|
|
467
|
+
if (typeof cached === "number")
|
|
468
|
+
this.cacheReadTokens = Math.max(this.cacheReadTokens, cached);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (this.protocol === "gemini") {
|
|
472
|
+
const m = obj.usageMetadata ?? obj.response?.usageMetadata;
|
|
473
|
+
if (!m || typeof m !== "object")
|
|
474
|
+
return;
|
|
475
|
+
const cached = typeof m.cachedContentTokenCount === "number" ? m.cachedContentTokenCount : 0;
|
|
476
|
+
const prompt = typeof m.promptTokenCount === "number" ? m.promptTokenCount : 0;
|
|
477
|
+
const candidates = typeof m.candidatesTokenCount === "number" ? m.candidatesTokenCount : 0;
|
|
478
|
+
const thoughts = typeof m.thoughtsTokenCount === "number" ? m.thoughtsTokenCount : 0;
|
|
479
|
+
if (prompt > 0)
|
|
480
|
+
this.inputTokens = Math.max(this.inputTokens, Math.max(0, prompt - cached));
|
|
481
|
+
if (cached > 0)
|
|
482
|
+
this.cacheReadTokens = Math.max(this.cacheReadTokens, cached);
|
|
483
|
+
if (candidates + thoughts > 0)
|
|
484
|
+
this.outputTokens = Math.max(this.outputTokens, candidates + thoughts);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
toTokenUsage() {
|
|
488
|
+
return {
|
|
489
|
+
input: this.inputTokens,
|
|
490
|
+
output: this.outputTokens,
|
|
491
|
+
...(this.cacheReadTokens > 0 ? { cacheRead: this.cacheReadTokens } : {}),
|
|
492
|
+
...(this.cacheWriteTokens > 0 ? { cacheWrite: this.cacheWriteTokens } : {}),
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
function protocolErrorBody(protocol, message, code = "budget_exceeded") {
|
|
497
|
+
if (protocol === "anthropic") {
|
|
498
|
+
return JSON.stringify({ type: "error", error: { type: "rate_limit_error", message } });
|
|
499
|
+
}
|
|
500
|
+
if (protocol === "gemini") {
|
|
501
|
+
return JSON.stringify({ error: { code: 429, message, status: "RESOURCE_EXHAUSTED" } });
|
|
502
|
+
}
|
|
503
|
+
return JSON.stringify({ error: { message, type: "insufficient_quota", code } });
|
|
504
|
+
}
|
|
505
|
+
function extractClientToken(req, url) {
|
|
506
|
+
const auth = req.headers.authorization;
|
|
507
|
+
if (typeof auth === "string" && /^Bearer\s+/i.test(auth))
|
|
508
|
+
return auth.replace(/^Bearer\s+/i, "").trim();
|
|
509
|
+
const anthropicKey = req.headers["x-api-key"];
|
|
510
|
+
if (typeof anthropicKey === "string" && anthropicKey.trim())
|
|
511
|
+
return anthropicKey.trim();
|
|
512
|
+
const googKey = req.headers["x-goog-api-key"];
|
|
513
|
+
if (typeof googKey === "string" && googKey.trim())
|
|
514
|
+
return googKey.trim();
|
|
515
|
+
const queryKey = url.searchParams.get("key");
|
|
516
|
+
if (queryKey?.trim())
|
|
517
|
+
return queryKey.trim();
|
|
518
|
+
return undefined;
|
|
519
|
+
}
|
|
520
|
+
async function readRequestBody(req) {
|
|
521
|
+
const chunks = [];
|
|
522
|
+
let total = 0;
|
|
523
|
+
for await (const chunk of req) {
|
|
524
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
525
|
+
total += buf.length;
|
|
526
|
+
if (total > MAX_REQUEST_BYTES)
|
|
527
|
+
throw new Error("代理请求体超过 16MB 限制");
|
|
528
|
+
chunks.push(buf);
|
|
529
|
+
}
|
|
530
|
+
return Buffer.concat(chunks);
|
|
531
|
+
}
|
|
532
|
+
function parseProxyRoute(pathname, config) {
|
|
533
|
+
const memberMatch = pathname.match(/^\/proxy\/member\/([a-z0-9_]+)(\/.*)?$/);
|
|
534
|
+
if (memberMatch) {
|
|
535
|
+
const kind = memberMatch[1];
|
|
536
|
+
const agent = config.agents[kind];
|
|
537
|
+
if (!agent?.api)
|
|
538
|
+
return undefined;
|
|
539
|
+
const protocol = agent.api.type === "anthropic-compatible" ? "anthropic" : "openai";
|
|
540
|
+
return {
|
|
541
|
+
protocol,
|
|
542
|
+
subpath: memberMatch[2] || "/",
|
|
543
|
+
poolId: `member:${kind}`,
|
|
544
|
+
memberKind: kind,
|
|
545
|
+
memberApi: agent.api,
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
const protoMatch = pathname.match(/^\/proxy\/(anthropic|openai|gemini)(\/.*)?$/);
|
|
549
|
+
if (!protoMatch)
|
|
550
|
+
return undefined;
|
|
551
|
+
const protocol = protoMatch[1];
|
|
552
|
+
return {
|
|
553
|
+
protocol,
|
|
554
|
+
subpath: protoMatch[2] || "/",
|
|
555
|
+
poolId: `proto:${protocol}`,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
export class LocalProxy {
|
|
559
|
+
deps;
|
|
560
|
+
tokens = new Map();
|
|
561
|
+
memberTokens = new Map();
|
|
562
|
+
keyPool;
|
|
563
|
+
redactor;
|
|
564
|
+
lastRedactConfigKey = "";
|
|
565
|
+
listenUrl;
|
|
566
|
+
onUrlChange = new Set();
|
|
567
|
+
activeUsage = new Map();
|
|
568
|
+
totalRequests = 0;
|
|
569
|
+
totalRetries = 0;
|
|
570
|
+
totalBlocked = 0;
|
|
571
|
+
totalRedacted = 0;
|
|
572
|
+
recentRedactions = [];
|
|
573
|
+
modelAcc = new Map();
|
|
574
|
+
constructor(deps) {
|
|
575
|
+
this.deps = deps;
|
|
576
|
+
const now = deps.now ?? (() => Date.now());
|
|
577
|
+
this.keyPool = new StickyKeyPool(now, deps.affinityFile);
|
|
578
|
+
this.redactor = new Redactor();
|
|
579
|
+
}
|
|
580
|
+
baseUrl() {
|
|
581
|
+
return this.listenUrl;
|
|
582
|
+
}
|
|
583
|
+
setListenUrl(url) {
|
|
584
|
+
const normalized = url ? url.replace(/\/+$/, "") : undefined;
|
|
585
|
+
if (this.listenUrl === normalized)
|
|
586
|
+
return;
|
|
587
|
+
this.listenUrl = normalized;
|
|
588
|
+
for (const listener of this.onUrlChange) {
|
|
589
|
+
try {
|
|
590
|
+
listener(normalized);
|
|
591
|
+
}
|
|
592
|
+
catch { }
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
subscribeUrl(listener) {
|
|
596
|
+
this.onUrlChange.add(listener);
|
|
597
|
+
return () => this.onUrlChange.delete(listener);
|
|
598
|
+
}
|
|
599
|
+
/** 判断给定本机 CLI 成员是否应被代理接管 */
|
|
600
|
+
shouldCaptureCli(kind) {
|
|
601
|
+
const cfg = this.deps.getConfig().proxy;
|
|
602
|
+
if (!cfg?.enabled)
|
|
603
|
+
return false;
|
|
604
|
+
if (kind === "claude" || kind === "codex" || kind === "gemini") {
|
|
605
|
+
return cfg.captureCli[kind] !== false;
|
|
606
|
+
}
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
snapshot() {
|
|
610
|
+
const cfg = this.deps.getConfig().proxy;
|
|
611
|
+
const models = [...this.modelAcc.entries()]
|
|
612
|
+
.map(([model, s]) => ({
|
|
613
|
+
model,
|
|
614
|
+
requests: s.requests,
|
|
615
|
+
errors: s.errors,
|
|
616
|
+
inputTokens: s.inputTokens,
|
|
617
|
+
outputTokens: s.outputTokens,
|
|
618
|
+
cacheReadTokens: s.cacheReadTokens,
|
|
619
|
+
cacheHitRate: s.inputTokens + s.cacheReadTokens > 0 ? Math.round((s.cacheReadTokens / (s.inputTokens + s.cacheReadTokens)) * 100) : null,
|
|
620
|
+
medianTtftMs: medianOf(s.ttfts),
|
|
621
|
+
medianTps: medianOf(s.tpsList),
|
|
622
|
+
avgDurationMs: s.requests ? Math.round(s.durationTotalMs / s.requests) : 0,
|
|
623
|
+
costUsd: Number(s.costUsd.toFixed(6)),
|
|
624
|
+
}))
|
|
625
|
+
.sort((a, b) => b.requests - a.requests);
|
|
626
|
+
return {
|
|
627
|
+
enabled: Boolean(cfg?.enabled),
|
|
628
|
+
mode: cfg?.mode ?? "byok",
|
|
629
|
+
listenUrl: this.listenUrl ?? null,
|
|
630
|
+
bridgeEnabled: Boolean(cfg?.anthropicBridge?.enabled),
|
|
631
|
+
totals: {
|
|
632
|
+
requests: this.totalRequests,
|
|
633
|
+
retries: this.totalRetries,
|
|
634
|
+
blocked: this.totalBlocked,
|
|
635
|
+
redacted: this.totalRedacted,
|
|
636
|
+
},
|
|
637
|
+
pool: this.keyPool.status(),
|
|
638
|
+
models,
|
|
639
|
+
recentRedactions: [...this.recentRedactions],
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
recordRedactionAudit(entry) {
|
|
643
|
+
this.totalRedacted += entry.count;
|
|
644
|
+
this.recentRedactions.unshift(entry);
|
|
645
|
+
if (this.recentRedactions.length > 30)
|
|
646
|
+
this.recentRedactions.length = 30;
|
|
647
|
+
}
|
|
648
|
+
recordModelMetric(args) {
|
|
649
|
+
this.totalRetries += args.retries;
|
|
650
|
+
let acc = this.modelAcc.get(args.model);
|
|
651
|
+
if (!acc) {
|
|
652
|
+
acc = { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, durationTotalMs: 0, costUsd: 0, ttfts: [], tpsList: [] };
|
|
653
|
+
this.modelAcc.set(args.model, acc);
|
|
654
|
+
}
|
|
655
|
+
acc.requests++;
|
|
656
|
+
if (!args.ok)
|
|
657
|
+
acc.errors++;
|
|
658
|
+
acc.inputTokens += args.usage.input;
|
|
659
|
+
acc.outputTokens += args.usage.output;
|
|
660
|
+
acc.cacheReadTokens += args.usage.cacheRead ?? 0;
|
|
661
|
+
acc.durationTotalMs += args.durationMs;
|
|
662
|
+
acc.costUsd += args.costUsd ?? 0;
|
|
663
|
+
if (args.ttftMs !== null) {
|
|
664
|
+
acc.ttfts.push(args.ttftMs);
|
|
665
|
+
if (acc.ttfts.length > 100)
|
|
666
|
+
acc.ttfts.shift();
|
|
667
|
+
}
|
|
668
|
+
if (args.tps !== null) {
|
|
669
|
+
acc.tpsList.push(args.tps);
|
|
670
|
+
if (acc.tpsList.length > 100)
|
|
671
|
+
acc.tpsList.shift();
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
/** 判断 API 成员是否应经过代理(全局启用代理 或 自身配置了多 Key 池) */
|
|
675
|
+
shouldRouteApiMember(api) {
|
|
676
|
+
const cfg = this.deps.getConfig().proxy;
|
|
677
|
+
if (cfg?.enabled) {
|
|
678
|
+
if (cfg.mode === "relay")
|
|
679
|
+
return cfg.relay.routeMembers !== false;
|
|
680
|
+
return true;
|
|
681
|
+
}
|
|
682
|
+
return Boolean((api.apiKeys?.length ?? 0) > 1 || (api.credentials?.length ?? 0) > 1);
|
|
683
|
+
}
|
|
684
|
+
issueToken(meta) {
|
|
685
|
+
const token = `lemma-${randomUUID().replace(/-/g, "")}`;
|
|
686
|
+
this.tokens.set(token, { ...meta, token });
|
|
687
|
+
if (meta.callId && !this.activeUsage.has(meta.callId)) {
|
|
688
|
+
this.activeUsage.set(meta.callId, { costUsd: 0, events: 0 });
|
|
689
|
+
}
|
|
690
|
+
return token;
|
|
691
|
+
}
|
|
692
|
+
/** 为 API 成员复用一个稳定的本地代理占位令牌,避免反复生成泄漏 */
|
|
693
|
+
memberTokenFor(agent, protocol) {
|
|
694
|
+
const key = `${agent}:${protocol}`;
|
|
695
|
+
const existing = this.memberTokens.get(key);
|
|
696
|
+
if (existing && this.tokens.has(existing))
|
|
697
|
+
return existing;
|
|
698
|
+
const token = this.issueToken({ agent, protocol });
|
|
699
|
+
this.memberTokens.set(key, token);
|
|
700
|
+
return token;
|
|
701
|
+
}
|
|
702
|
+
revokeToken(token) {
|
|
703
|
+
if (!token)
|
|
704
|
+
return;
|
|
705
|
+
this.tokens.delete(token);
|
|
706
|
+
}
|
|
707
|
+
/** 供 dispatch 结算前查询本次 callId 是否已经由代理累加花费(避免与退出总结算重复扣减) */
|
|
708
|
+
consumeCallReport(callId) {
|
|
709
|
+
const rec = this.activeUsage.get(callId);
|
|
710
|
+
if (rec)
|
|
711
|
+
this.activeUsage.delete(callId);
|
|
712
|
+
return rec;
|
|
713
|
+
}
|
|
714
|
+
/** 构建注入到 CLI 子进程环境变量中的代理覆写项 */
|
|
715
|
+
cliEnvFor(kind, meta) {
|
|
716
|
+
const base = this.listenUrl;
|
|
717
|
+
if (!base || !this.shouldCaptureCli(kind))
|
|
718
|
+
return undefined;
|
|
719
|
+
const protocol = kind === "codex" ? "openai" : kind === "gemini" ? "gemini" : "anthropic";
|
|
720
|
+
const token = this.issueToken({ agent: kind, protocol, ...meta });
|
|
721
|
+
if (kind === "claude") {
|
|
722
|
+
return {
|
|
723
|
+
token,
|
|
724
|
+
env: {
|
|
725
|
+
ANTHROPIC_BASE_URL: `${base}/proxy/anthropic`,
|
|
726
|
+
ANTHROPIC_API_KEY: token,
|
|
727
|
+
ANTHROPIC_AUTH_TOKEN: token,
|
|
728
|
+
},
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
if (kind === "codex") {
|
|
732
|
+
return {
|
|
733
|
+
token,
|
|
734
|
+
env: {
|
|
735
|
+
OPENAI_BASE_URL: `${base}/proxy/openai/v1`,
|
|
736
|
+
OPENAI_API_KEY: token,
|
|
737
|
+
},
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
if (kind === "gemini") {
|
|
741
|
+
return {
|
|
742
|
+
token,
|
|
743
|
+
env: {
|
|
744
|
+
GOOGLE_GEMINI_BASE_URL: `${base}/proxy/gemini`,
|
|
745
|
+
GEMINI_API_KEY: token,
|
|
746
|
+
},
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
return undefined;
|
|
750
|
+
}
|
|
751
|
+
ensureRedactor(config) {
|
|
752
|
+
const r = config.proxy?.redact;
|
|
753
|
+
const key = JSON.stringify({ allowlist: r?.allowlist ?? [], customPatterns: r?.customPatterns ?? [] });
|
|
754
|
+
if (key !== this.lastRedactConfigKey) {
|
|
755
|
+
this.lastRedactConfigKey = key;
|
|
756
|
+
this.redactor = new Redactor({
|
|
757
|
+
allowlist: r?.allowlist,
|
|
758
|
+
customPatterns: r?.customPatterns,
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
return this.redactor;
|
|
762
|
+
}
|
|
763
|
+
resolveRelayToken(config) {
|
|
764
|
+
const relay = config.proxy?.relay;
|
|
765
|
+
if (!relay)
|
|
766
|
+
return undefined;
|
|
767
|
+
for (const envName of relay.tokenEnv) {
|
|
768
|
+
const v = process.env[envName];
|
|
769
|
+
if (v?.trim())
|
|
770
|
+
return v.trim();
|
|
771
|
+
}
|
|
772
|
+
return readCredential(relay.credential);
|
|
773
|
+
}
|
|
774
|
+
resolveUpstream(route, config) {
|
|
775
|
+
if (route.memberApi) {
|
|
776
|
+
return {
|
|
777
|
+
baseUrl: route.memberApi.baseUrl,
|
|
778
|
+
keys: resolveKeyPool(route.memberApi),
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
const upstream = config.proxy?.upstreams[route.protocol] ?? {};
|
|
782
|
+
if (route.protocol === "anthropic") {
|
|
783
|
+
const explicitKeys = resolveKeyPool(upstream);
|
|
784
|
+
const claude = !upstream.baseUrl || !explicitKeys.length ? claudeSettingsEnv() : {};
|
|
785
|
+
const baseUrl = upstream.baseUrl ?? claude.baseUrl ?? "https://api.anthropic.com";
|
|
786
|
+
const keys = explicitKeys.length ? explicitKeys : resolveKeyPool({ ...upstream, extraKeys: [claude.token] });
|
|
787
|
+
return { baseUrl, keys };
|
|
788
|
+
}
|
|
789
|
+
if (route.protocol === "openai") {
|
|
790
|
+
return {
|
|
791
|
+
baseUrl: upstream.baseUrl ?? "https://api.openai.com",
|
|
792
|
+
keys: resolveKeyPool(upstream),
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
return {
|
|
796
|
+
baseUrl: upstream.baseUrl ?? "https://generativelanguage.googleapis.com",
|
|
797
|
+
keys: resolveKeyPool(upstream),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
priceFor(meta, modelId, config) {
|
|
801
|
+
const agent = config.agents[meta.agent];
|
|
802
|
+
if (!agent)
|
|
803
|
+
return undefined;
|
|
804
|
+
const target = modelId ?? meta.model ?? agent.defaultModel;
|
|
805
|
+
if (target) {
|
|
806
|
+
const matched = agent.models.find((m) => m.id === target)?.price;
|
|
807
|
+
if (matched)
|
|
808
|
+
return matched;
|
|
809
|
+
}
|
|
810
|
+
return agent.models[0]?.price;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* 处理 `/proxy/*` 请求;若路径不是 `/proxy/*` 返回 `false` 交由外层路由继续处理。
|
|
814
|
+
*/
|
|
815
|
+
async handle(req, res) {
|
|
816
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "127.0.0.1"}`);
|
|
817
|
+
if (!url.pathname.startsWith("/proxy/"))
|
|
818
|
+
return false;
|
|
819
|
+
const config = this.deps.getConfig();
|
|
820
|
+
const route = parseProxyRoute(url.pathname, config);
|
|
821
|
+
if (!route) {
|
|
822
|
+
res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
|
|
823
|
+
res.end(JSON.stringify({ error: "未知代理路由" }));
|
|
824
|
+
return true;
|
|
825
|
+
}
|
|
826
|
+
const clientToken = extractClientToken(req, url);
|
|
827
|
+
const meta = clientToken ? this.tokens.get(clientToken) : undefined;
|
|
828
|
+
if (!meta) {
|
|
829
|
+
res.writeHead(401, { "content-type": "application/json; charset=utf-8" });
|
|
830
|
+
res.end(protocolErrorBody(route.protocol, "无效的本地代理令牌", "invalid_proxy_token"));
|
|
831
|
+
return true;
|
|
832
|
+
}
|
|
833
|
+
if (this.deps.checkBudget) {
|
|
834
|
+
const check = await this.deps.checkBudget(meta);
|
|
835
|
+
if (!check.allowed) {
|
|
836
|
+
res.writeHead(429, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
837
|
+
res.end(protocolErrorBody(route.protocol, check.message ?? "当前运行已达到预算上限,代理已熔断。", "budget_exceeded"));
|
|
838
|
+
return true;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
const proxyCfg = config.proxy;
|
|
842
|
+
const now = this.deps.now ?? (() => Date.now());
|
|
843
|
+
this.totalRequests++;
|
|
844
|
+
const rawBody = await readRequestBody(req);
|
|
845
|
+
let outboundBody = rawBody;
|
|
846
|
+
let parsedBody;
|
|
847
|
+
let redactedCount = 0;
|
|
848
|
+
let redactedKinds = [];
|
|
849
|
+
const requestVault = new Map();
|
|
850
|
+
const reqContentType = String(req.headers["content-type"] ?? "");
|
|
851
|
+
let requestedModel = meta.model;
|
|
852
|
+
if (rawBody.length > 0 && reqContentType.toLowerCase().includes("application/json")) {
|
|
853
|
+
try {
|
|
854
|
+
parsedBody = JSON.parse(rawBody.toString("utf8"));
|
|
855
|
+
if (typeof parsedBody.model === "string" && parsedBody.model)
|
|
856
|
+
requestedModel = parsedBody.model;
|
|
857
|
+
if (proxyCfg?.redact.enabled) {
|
|
858
|
+
const action = proxyCfg.redact.action ?? "mask";
|
|
859
|
+
const redacted = this.ensureRedactor(config).redactJson(parsedBody, requestVault);
|
|
860
|
+
redactedCount = redacted.count;
|
|
861
|
+
redactedKinds = redacted.kinds;
|
|
862
|
+
if (redactedCount > 0) {
|
|
863
|
+
this.recordRedactionAudit({
|
|
864
|
+
at: now(),
|
|
865
|
+
agent: meta.agent,
|
|
866
|
+
protocol: route.protocol,
|
|
867
|
+
action,
|
|
868
|
+
count: redactedCount,
|
|
869
|
+
kinds: redactedKinds,
|
|
870
|
+
});
|
|
871
|
+
if (action === "block") {
|
|
872
|
+
this.totalBlocked++;
|
|
873
|
+
res.writeHead(403, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
874
|
+
res.end(protocolErrorBody(route.protocol, `请求包含敏感凭据(${redactedKinds.join(", ")}),已按隐私策略拦截。`, "privacy_policy_blocked"));
|
|
875
|
+
return true;
|
|
876
|
+
}
|
|
877
|
+
if (action === "mask") {
|
|
878
|
+
parsedBody = redacted.value;
|
|
879
|
+
outboundBody = Buffer.from(JSON.stringify(parsedBody), "utf8");
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
catch {
|
|
885
|
+
/* 非法或非 JSON 原样透传 */
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
// Gemini CLI 可能把 ?key=<localToken> 放在 query 上,转发上游前剥离本地占位 key
|
|
889
|
+
const searchParams = new URLSearchParams(url.search);
|
|
890
|
+
if (searchParams.get("key") === clientToken)
|
|
891
|
+
searchParams.delete("key");
|
|
892
|
+
const cleanSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
|
|
893
|
+
const useRelay = proxyCfg?.mode === "relay" && Boolean(proxyCfg.relay.url) && (!route.memberApi || proxyCfg.relay.routeMembers !== false);
|
|
894
|
+
const useAnthropicBridge = !useRelay &&
|
|
895
|
+
route.protocol === "anthropic" &&
|
|
896
|
+
route.subpath === "/v1/messages" &&
|
|
897
|
+
Boolean(proxyCfg?.anthropicBridge?.enabled) &&
|
|
898
|
+
parsedBody !== undefined;
|
|
899
|
+
// 应用 compactModel 降级与 modelMap 别名重写
|
|
900
|
+
let routedModel = requestedModel;
|
|
901
|
+
if (parsedBody) {
|
|
902
|
+
if (proxyCfg?.compactModel && isCompactPrompt(parsedBody)) {
|
|
903
|
+
routedModel = proxyCfg.compactModel;
|
|
904
|
+
}
|
|
905
|
+
const bridgeMap = useAnthropicBridge ? proxyCfg?.anthropicBridge?.modelMap : undefined;
|
|
906
|
+
const mapped = (routedModel ? bridgeMap?.[routedModel] : undefined) ?? (routedModel ? proxyCfg?.modelMap?.[routedModel] : undefined);
|
|
907
|
+
if (mapped)
|
|
908
|
+
routedModel = mapped;
|
|
909
|
+
if (useAnthropicBridge) {
|
|
910
|
+
const translated = anthropicToOpenAiRequest(parsedBody, routedModel ?? "gpt-4.1");
|
|
911
|
+
outboundBody = Buffer.from(JSON.stringify(translated), "utf8");
|
|
912
|
+
}
|
|
913
|
+
else if (routedModel && routedModel !== parsedBody.model) {
|
|
914
|
+
parsedBody = { ...parsedBody, model: routedModel };
|
|
915
|
+
outboundBody = Buffer.from(JSON.stringify(parsedBody), "utf8");
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
const stickyCfg = proxyCfg?.sticky ?? { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 };
|
|
919
|
+
const sessionKey = meta.sessionId ||
|
|
920
|
+
meta.taskId ||
|
|
921
|
+
(typeof req.headers["x-lemma-session-id"] === "string" ? req.headers["x-lemma-session-id"] : undefined) ||
|
|
922
|
+
(typeof req.headers["x-codex-window-id"] === "string" ? req.headers["x-codex-window-id"] : undefined) ||
|
|
923
|
+
meta.callId ||
|
|
924
|
+
meta.agent;
|
|
925
|
+
const poolId = useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
|
|
926
|
+
let targetUrl;
|
|
927
|
+
let candidates;
|
|
928
|
+
if (useRelay) {
|
|
929
|
+
const relayUrl = proxyCfg.relay.url;
|
|
930
|
+
const relayPath = route.memberKind ? `/member/${route.memberKind}${route.subpath}` : `/${route.protocol}${route.subpath}`;
|
|
931
|
+
targetUrl = joinUpstreamUrl(relayUrl, relayPath, cleanSearch);
|
|
932
|
+
const relayToken = this.resolveRelayToken(config);
|
|
933
|
+
if (!relayToken) {
|
|
934
|
+
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
935
|
+
res.end(protocolErrorBody(route.protocol, "托管中转模式缺少 relay token,请检查环境变量或本机凭据。", "missing_relay_token"));
|
|
936
|
+
return true;
|
|
937
|
+
}
|
|
938
|
+
candidates = [relayToken];
|
|
939
|
+
}
|
|
940
|
+
else if (useAnthropicBridge) {
|
|
941
|
+
const bridge = proxyCfg.anthropicBridge;
|
|
942
|
+
const bridgeBase = bridge.baseUrl ?? proxyCfg?.upstreams.openai.baseUrl ?? "https://api.openai.com";
|
|
943
|
+
const bridgeKeys = resolveKeyPool(bridge);
|
|
944
|
+
const keys = bridgeKeys.length ? bridgeKeys : resolveKeyPool(proxyCfg?.upstreams.openai ?? {});
|
|
945
|
+
targetUrl = joinUpstreamUrl(bridgeBase, "/v1/chat/completions", cleanSearch);
|
|
946
|
+
candidates = this.keyPool.pickCandidates(poolId, keys, sessionKey, stickyCfg.enabled);
|
|
947
|
+
if (!candidates.length) {
|
|
948
|
+
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
949
|
+
res.end(protocolErrorBody(route.protocol, "Anthropic 协议桥接未配置可用 OpenAI 兼容密钥。", "missing_api_key"));
|
|
950
|
+
return true;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
else {
|
|
954
|
+
const upstream = this.resolveUpstream(route, config);
|
|
955
|
+
targetUrl = joinUpstreamUrl(upstream.baseUrl, route.subpath, cleanSearch);
|
|
956
|
+
candidates = this.keyPool.pickCandidates(poolId, upstream.keys, sessionKey, stickyCfg.enabled);
|
|
957
|
+
if (!candidates.length) {
|
|
958
|
+
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
959
|
+
res.end(protocolErrorBody(route.protocol, `上游 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
|
|
960
|
+
return true;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const fetchFn = this.deps.fetchImpl ?? fetch;
|
|
964
|
+
const controller = new AbortController();
|
|
965
|
+
const onClientAbort = () => controller.abort();
|
|
966
|
+
req.once("aborted", onClientAbort);
|
|
967
|
+
res.once("close", onClientAbort);
|
|
968
|
+
const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 3);
|
|
969
|
+
let finalResponse;
|
|
970
|
+
let retries = 0;
|
|
971
|
+
let strippedSignatures = false;
|
|
972
|
+
const upstreamAuthProtocol = useAnthropicBridge ? "openai" : route.protocol;
|
|
973
|
+
const reqStartedAt = Date.now();
|
|
974
|
+
const buildUpstreamHeaders = (apiKey) => {
|
|
975
|
+
const headers = new Headers();
|
|
976
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
977
|
+
const lower = k.toLowerCase();
|
|
978
|
+
if (HOP_BY_HOP_HEADERS.has(lower))
|
|
979
|
+
continue;
|
|
980
|
+
if (lower === "authorization" || lower === "x-api-key" || lower === "x-goog-api-key")
|
|
981
|
+
continue;
|
|
982
|
+
if (useAnthropicBridge && (lower === "anthropic-version" || lower === "anthropic-beta"))
|
|
983
|
+
continue;
|
|
984
|
+
if (Array.isArray(v))
|
|
985
|
+
headers.set(k, v.join(", "));
|
|
986
|
+
else if (typeof v === "string")
|
|
987
|
+
headers.set(k, v);
|
|
988
|
+
}
|
|
989
|
+
if (useRelay) {
|
|
990
|
+
headers.set("authorization", `Bearer ${apiKey}`);
|
|
991
|
+
if (meta.taskId)
|
|
992
|
+
headers.set("x-lemma-task-id", meta.taskId);
|
|
993
|
+
if (meta.sessionId)
|
|
994
|
+
headers.set("x-lemma-session-id", meta.sessionId);
|
|
995
|
+
headers.set("x-lemma-member", meta.agent);
|
|
996
|
+
}
|
|
997
|
+
else if (upstreamAuthProtocol === "anthropic") {
|
|
998
|
+
headers.set("x-api-key", apiKey);
|
|
999
|
+
}
|
|
1000
|
+
else if (upstreamAuthProtocol === "gemini") {
|
|
1001
|
+
headers.set("x-goog-api-key", apiKey);
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
headers.set("authorization", `Bearer ${apiKey}`);
|
|
1005
|
+
}
|
|
1006
|
+
return headers;
|
|
1007
|
+
};
|
|
1008
|
+
try {
|
|
1009
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1010
|
+
const apiKey = candidates[attempt];
|
|
1011
|
+
for (;;) {
|
|
1012
|
+
const upstreamRes = await fetchFn(targetUrl, {
|
|
1013
|
+
method: req.method ?? "POST",
|
|
1014
|
+
headers: buildUpstreamHeaders(apiKey),
|
|
1015
|
+
body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(outboundBody),
|
|
1016
|
+
signal: controller.signal,
|
|
1017
|
+
});
|
|
1018
|
+
if (upstreamRes.ok) {
|
|
1019
|
+
if (!useRelay) {
|
|
1020
|
+
this.keyPool.markSuccess(poolId, sessionKey, apiKey, stickyCfg.ttlSeconds, stickyCfg.enabled);
|
|
1021
|
+
}
|
|
1022
|
+
finalResponse = upstreamRes;
|
|
1023
|
+
break;
|
|
1024
|
+
}
|
|
1025
|
+
const errText = await upstreamRes.text();
|
|
1026
|
+
// 若因跨账号/跨中转思考块签名失效返回 400:剥离兼容签名后用同一个健康 Key 重发一次,不误拉黑 Key
|
|
1027
|
+
if (!useAnthropicBridge && !strippedSignatures && isSignatureRefused(upstreamRes.status, errText)) {
|
|
1028
|
+
const stripped = stripIncompatibleSignatures(route.protocol, outboundBody);
|
|
1029
|
+
if (stripped.stripped) {
|
|
1030
|
+
outboundBody = stripped.body;
|
|
1031
|
+
strippedSignatures = true;
|
|
1032
|
+
retries++;
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
if (!useRelay && attempt + 1 < maxAttempts && shouldFailoverStatus(upstreamRes.status, errText)) {
|
|
1037
|
+
const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
|
|
1038
|
+
this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
|
|
1039
|
+
retries++;
|
|
1040
|
+
break;
|
|
1041
|
+
}
|
|
1042
|
+
if (!useRelay && shouldFailoverStatus(upstreamRes.status, errText)) {
|
|
1043
|
+
const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
|
|
1044
|
+
this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
|
|
1045
|
+
}
|
|
1046
|
+
finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
|
|
1047
|
+
break;
|
|
1048
|
+
}
|
|
1049
|
+
if (finalResponse)
|
|
1050
|
+
break;
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
catch (error) {
|
|
1054
|
+
if (!controller.signal.aborted && !res.headersSent) {
|
|
1055
|
+
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
1056
|
+
res.end(protocolErrorBody(route.protocol, `上游请求失败:${error instanceof Error ? error.message : String(error)}`, "upstream_error"));
|
|
1057
|
+
}
|
|
1058
|
+
return true;
|
|
1059
|
+
}
|
|
1060
|
+
finally {
|
|
1061
|
+
req.off("aborted", onClientAbort);
|
|
1062
|
+
res.off("close", onClientAbort);
|
|
1063
|
+
}
|
|
1064
|
+
if (!finalResponse) {
|
|
1065
|
+
if (!res.headersSent) {
|
|
1066
|
+
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
1067
|
+
res.end(protocolErrorBody(route.protocol, "未收到上游响应。", "upstream_error"));
|
|
1068
|
+
}
|
|
1069
|
+
return true;
|
|
1070
|
+
}
|
|
1071
|
+
const outHeaders = {};
|
|
1072
|
+
finalResponse.headers.forEach((v, k) => {
|
|
1073
|
+
const lower = k.toLowerCase();
|
|
1074
|
+
if (lower === "content-length" || lower === "content-encoding" || lower === "transfer-encoding" || lower === "connection")
|
|
1075
|
+
return;
|
|
1076
|
+
outHeaders[k] = v;
|
|
1077
|
+
});
|
|
1078
|
+
const resContentType = finalResponse.headers.get("content-type");
|
|
1079
|
+
const isSse = (resContentType ?? "").toLowerCase().includes("text/event-stream");
|
|
1080
|
+
const translateBridgeOk = useAnthropicBridge && finalResponse.ok;
|
|
1081
|
+
if (translateBridgeOk) {
|
|
1082
|
+
outHeaders["content-type"] = isSse ? "text/event-stream; charset=utf-8" : "application/json; charset=utf-8";
|
|
1083
|
+
}
|
|
1084
|
+
res.writeHead(finalResponse.status, outHeaders);
|
|
1085
|
+
const sniffer = new UsageSniffer(route.protocol, translateBridgeOk && !isSse ? "application/json" : resContentType);
|
|
1086
|
+
const restore = Boolean(proxyCfg?.redact.restoreInResponse && redactedCount > 0 && proxyCfg?.redact.action === "mask");
|
|
1087
|
+
const redactor = this.ensureRedactor(config);
|
|
1088
|
+
const unredactor = restore ? new StreamUnredactor((t) => redactor.restoreText(t, requestVault)) : undefined;
|
|
1089
|
+
let firstChunkAt;
|
|
1090
|
+
if (translateBridgeOk && !isSse) {
|
|
1091
|
+
try {
|
|
1092
|
+
const rawText = await finalResponse.text();
|
|
1093
|
+
firstChunkAt = Date.now();
|
|
1094
|
+
const parsedOai = JSON.parse(rawText);
|
|
1095
|
+
const anthropicJson = openAiToAnthropicJsonResponse(parsedOai, requestedModel ?? routedModel ?? "unknown");
|
|
1096
|
+
const encoded = JSON.stringify(anthropicJson);
|
|
1097
|
+
sniffer.push(encoded);
|
|
1098
|
+
const emitted = restore ? redactor.restoreText(encoded, requestVault) : encoded;
|
|
1099
|
+
if (!res.destroyed)
|
|
1100
|
+
res.write(emitted);
|
|
1101
|
+
}
|
|
1102
|
+
catch {
|
|
1103
|
+
/* 上游返回非法 JSON 时跳过桥接写空响应 */
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
else {
|
|
1107
|
+
const sseTranslator = translateBridgeOk && isSse ? new OpenAiToAnthropicSseTranslator(requestedModel ?? routedModel ?? "unknown") : undefined;
|
|
1108
|
+
if (finalResponse.body) {
|
|
1109
|
+
const decoder = new TextDecoder();
|
|
1110
|
+
const reader = finalResponse.body.getReader();
|
|
1111
|
+
try {
|
|
1112
|
+
for (;;) {
|
|
1113
|
+
const { done, value } = await reader.read();
|
|
1114
|
+
if (done)
|
|
1115
|
+
break;
|
|
1116
|
+
const text = decoder.decode(value, { stream: true });
|
|
1117
|
+
if (text) {
|
|
1118
|
+
if (firstChunkAt === undefined)
|
|
1119
|
+
firstChunkAt = Date.now();
|
|
1120
|
+
const normalized = sseTranslator ? sseTranslator.push(text) : text;
|
|
1121
|
+
if (normalized) {
|
|
1122
|
+
sniffer.push(normalized);
|
|
1123
|
+
const emit = unredactor ? unredactor.push(normalized) : normalized;
|
|
1124
|
+
if (emit && !res.destroyed)
|
|
1125
|
+
res.write(emit);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
const tail = decoder.decode();
|
|
1130
|
+
const flushedBridge = (sseTranslator ? sseTranslator.push(tail) + sseTranslator.finish() : tail);
|
|
1131
|
+
if (flushedBridge) {
|
|
1132
|
+
if (firstChunkAt === undefined)
|
|
1133
|
+
firstChunkAt = Date.now();
|
|
1134
|
+
sniffer.push(flushedBridge);
|
|
1135
|
+
const emit = unredactor ? unredactor.push(flushedBridge) : flushedBridge;
|
|
1136
|
+
if (emit && !res.destroyed)
|
|
1137
|
+
res.write(emit);
|
|
1138
|
+
}
|
|
1139
|
+
if (unredactor) {
|
|
1140
|
+
const rem = unredactor.flush();
|
|
1141
|
+
if (rem && !res.destroyed)
|
|
1142
|
+
res.write(rem);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
catch {
|
|
1146
|
+
/* 流中断时仍尽量提交已嗅探到的部分用量 */
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
else if (sseTranslator) {
|
|
1150
|
+
const emptyDone = sseTranslator.finish();
|
|
1151
|
+
if (emptyDone) {
|
|
1152
|
+
sniffer.push(emptyDone);
|
|
1153
|
+
if (!res.destroyed)
|
|
1154
|
+
res.write(emptyDone);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
sniffer.finish();
|
|
1159
|
+
if (!res.writableEnded)
|
|
1160
|
+
res.end();
|
|
1161
|
+
const endedAt = Date.now();
|
|
1162
|
+
const durationMs = Math.max(1, endedAt - reqStartedAt);
|
|
1163
|
+
const ttftMs = firstChunkAt !== undefined ? Math.max(0, firstChunkAt - reqStartedAt) : null;
|
|
1164
|
+
const usage = sniffer.toTokenUsage();
|
|
1165
|
+
const tps = usage.output >= 20 ? Number((usage.output / (Math.max(1, endedAt - (firstChunkAt ?? reqStartedAt)) / 1000)).toFixed(1)) : null;
|
|
1166
|
+
const usedModel = useAnthropicBridge ? (routedModel ?? requestedModel) : (sniffer.model ?? routedModel ?? requestedModel);
|
|
1167
|
+
const hasTokens = usage.input > 0 || usage.output > 0 || (usage.cacheRead ?? 0) > 0;
|
|
1168
|
+
const costUsd = hasTokens ? calculateUsageCost(this.priceFor(meta, usedModel, config), usage) : undefined;
|
|
1169
|
+
this.recordModelMetric({
|
|
1170
|
+
model: usedModel ?? route.poolId,
|
|
1171
|
+
ok: finalResponse.ok,
|
|
1172
|
+
durationMs,
|
|
1173
|
+
ttftMs,
|
|
1174
|
+
tps,
|
|
1175
|
+
usage,
|
|
1176
|
+
costUsd,
|
|
1177
|
+
retries,
|
|
1178
|
+
});
|
|
1179
|
+
if (meta.callId && costUsd !== undefined && costUsd > 0) {
|
|
1180
|
+
const prev = this.activeUsage.get(meta.callId) ?? { costUsd: 0, events: 0 };
|
|
1181
|
+
prev.costUsd += costUsd;
|
|
1182
|
+
prev.events++;
|
|
1183
|
+
this.activeUsage.set(meta.callId, prev);
|
|
1184
|
+
}
|
|
1185
|
+
if (this.deps.onUsage && (hasTokens || costUsd !== undefined)) {
|
|
1186
|
+
await Promise.resolve(this.deps.onUsage({
|
|
1187
|
+
agent: meta.agent,
|
|
1188
|
+
protocol: route.protocol,
|
|
1189
|
+
taskId: meta.taskId,
|
|
1190
|
+
sessionId: meta.sessionId,
|
|
1191
|
+
callId: meta.callId,
|
|
1192
|
+
model: usedModel,
|
|
1193
|
+
usage,
|
|
1194
|
+
costUsd,
|
|
1195
|
+
status: finalResponse.status,
|
|
1196
|
+
redactedCount,
|
|
1197
|
+
retries,
|
|
1198
|
+
})).catch(() => { });
|
|
1199
|
+
}
|
|
1200
|
+
return true;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
/** 仅启动代理路由的轻量本地 HTTP 服务(用于 `--no-web`、单轮或离线测试场景) */
|
|
1204
|
+
export async function startProxyServer(proxy, preferredPort = 8787) {
|
|
1205
|
+
let port = preferredPort;
|
|
1206
|
+
const server = createServer((req, res) => {
|
|
1207
|
+
const host = String(req.headers.host ?? "");
|
|
1208
|
+
if (host && !host.startsWith(`127.0.0.1:${port}`) && !host.startsWith(`localhost:${port}`)) {
|
|
1209
|
+
res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
|
|
1210
|
+
res.end(JSON.stringify({ error: "bad host" }));
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
void proxy.handle(req, res).then((handled) => {
|
|
1214
|
+
if (!handled && !res.headersSent) {
|
|
1215
|
+
res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
|
|
1216
|
+
res.end(JSON.stringify({ error: "not found" }));
|
|
1217
|
+
}
|
|
1218
|
+
}).catch((err) => {
|
|
1219
|
+
if (!res.headersSent && !res.destroyed) {
|
|
1220
|
+
res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
|
|
1221
|
+
res.end(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }));
|
|
1222
|
+
}
|
|
1223
|
+
});
|
|
1224
|
+
});
|
|
1225
|
+
for (let attempt = 0;; attempt++) {
|
|
1226
|
+
try {
|
|
1227
|
+
await new Promise((resolve, reject) => {
|
|
1228
|
+
server.once("error", reject);
|
|
1229
|
+
server.listen(port, "127.0.0.1", () => { server.off("error", reject); resolve(); });
|
|
1230
|
+
});
|
|
1231
|
+
port = server.address().port;
|
|
1232
|
+
break;
|
|
1233
|
+
}
|
|
1234
|
+
catch (error) {
|
|
1235
|
+
if (error?.code !== "EADDRINUSE" || attempt >= 9 || port === 0)
|
|
1236
|
+
throw error;
|
|
1237
|
+
port++;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
const url = `http://127.0.0.1:${port}`;
|
|
1241
|
+
proxy.setListenUrl(url);
|
|
1242
|
+
return {
|
|
1243
|
+
url,
|
|
1244
|
+
async close() {
|
|
1245
|
+
proxy.setListenUrl(undefined);
|
|
1246
|
+
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
1247
|
+
server.closeAllConnections();
|
|
1248
|
+
await stopped;
|
|
1249
|
+
},
|
|
1250
|
+
};
|
|
1251
|
+
}
|