lemma-agent 1.1.0 → 1.1.2

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 CHANGED
@@ -1,7 +1,10 @@
1
1
  import { createServer } from "node:http";
2
- import { randomUUID } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname } from "node:path";
3
5
  import { claudeSettingsEnv } from "./config.js";
4
6
  import { readCredential, readCredentials } from "./credentials.js";
7
+ import { anthropicToOpenAiRequest, OpenAiToAnthropicSseTranslator, openAiToAnthropicJsonResponse } from "./bridge.js";
5
8
  import { Redactor, StreamUnredactor } from "./redact.js";
6
9
  function calculateUsageCost(price, usage) {
7
10
  if (!price)
@@ -96,73 +99,264 @@ export function shouldFailoverStatus(status, bodyText) {
96
99
  }
97
100
  return false;
98
101
  }
99
- /** 粘性 Key 池管理器:常规平滑轮转 + Prompt Cache 粘性优先 + 429 冷却退避 */
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 / 多上游路由组管理器:支持 order 主备与 rotate 轮转 + Prompt Cache 粘性 + 429 冷却 + 哈希持久化 */
100
179
  export class StickyKeyPool {
101
180
  sticky = new Map();
102
181
  cooldown = new Map();
103
182
  rrCursor = new Map();
104
183
  now;
105
- constructor(now = () => Date.now()) {
184
+ affinityFile;
185
+ constructor(now = () => Date.now(), affinityFile) {
106
186
  this.now = now;
187
+ this.affinityFile = affinityFile;
188
+ this.load();
107
189
  }
108
- cooldownKey(poolId, key) {
109
- return `${poolId}\0${key}`;
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
+ }
110
209
  }
111
- pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
112
- if (!keys.length)
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, cooldownId) {
236
+ return `${poolId}\0${cooldownId}`;
237
+ }
238
+ pickFromCandidates(poolId, candidates, sessionKey, stickyEnabled, strategy = "rotate") {
239
+ if (!candidates.length)
113
240
  return [];
114
241
  const t = this.now();
115
242
  const healthy = [];
116
243
  const resting = [];
117
- for (const key of keys) {
118
- const until = this.cooldown.get(this.cooldownKey(poolId, key)) ?? 0;
244
+ for (const item of candidates) {
245
+ const until = this.cooldown.get(this.cooldownKey(poolId, item.cooldownId)) ?? 0;
119
246
  if (until <= t) {
120
247
  if (until > 0)
121
- this.cooldown.delete(this.cooldownKey(poolId, key));
122
- healthy.push(key);
248
+ this.cooldown.delete(this.cooldownKey(poolId, item.cooldownId));
249
+ healthy.push(item);
123
250
  }
124
251
  else {
125
- resting.push({ key, until });
252
+ resting.push({ item, until });
126
253
  }
127
254
  }
128
- // 若池内全部 Key 都在冷却,按最早解禁时间兜底放行,避免假死
255
+ // 若池内全部候选都在冷却,按最早解禁时间兜底放行,避免假死
129
256
  const baseList = healthy.length
130
257
  ? healthy
131
- : resting.sort((a, b) => a.until - b.until).map((r) => r.key);
258
+ : resting.sort((a, b) => a.until - b.until).map((r) => r.item);
132
259
  const ordered = [];
133
260
  if (stickyEnabled && sessionKey) {
134
261
  const stickKey = `${poolId}\0${sessionKey}`;
135
262
  const hit = this.sticky.get(stickKey);
136
- if (hit && hit.expiresAt > t && baseList.includes(hit.key)) {
137
- ordered.push(hit.key);
263
+ if (hit && hit.expiresAt > t) {
264
+ const matched = baseList.find((c) => c.cooldownId === hit.keyHash);
265
+ if (matched)
266
+ ordered.push(matched);
138
267
  }
139
268
  else if (hit && hit.expiresAt <= t) {
140
269
  this.sticky.delete(stickKey);
141
270
  }
142
271
  }
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);
272
+ let remainder = baseList;
273
+ if (strategy === "rotate") {
274
+ const cursor = this.rrCursor.get(poolId) ?? 0;
275
+ remainder = baseList.map((_, idx) => baseList[(cursor + idx) % baseList.length]);
276
+ this.rrCursor.set(poolId, (cursor + 1) % Math.max(1, baseList.length));
277
+ }
278
+ for (const item of remainder) {
279
+ if (!ordered.includes(item))
280
+ ordered.push(item);
149
281
  }
150
282
  return ordered;
151
283
  }
152
- markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
153
- this.cooldown.delete(this.cooldownKey(poolId, key));
284
+ pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
285
+ const wrapped = keys.map((k) => ({ cooldownId: keyHashOf(k), raw: k }));
286
+ return this.pickFromCandidates(poolId, wrapped, sessionKey, stickyEnabled, "rotate").map((w) => w.raw);
287
+ }
288
+ markSuccessById(poolId, sessionKey, cooldownId, ttlSeconds, stickyEnabled) {
289
+ this.cooldown.delete(this.cooldownKey(poolId, cooldownId));
154
290
  if (stickyEnabled && sessionKey && ttlSeconds > 0) {
155
- this.sticky.set(`${poolId}\0${sessionKey}`, { key, expiresAt: this.now() + ttlSeconds * 1000 });
291
+ const stickKey = `${poolId}\0${sessionKey}`;
292
+ if (this.sticky.size >= MAX_STICKY_ENTRIES && !this.sticky.has(stickKey)) {
293
+ const oldest = this.sticky.keys().next().value;
294
+ if (oldest !== undefined)
295
+ this.sticky.delete(oldest);
296
+ }
297
+ this.sticky.set(stickKey, { keyHash: cooldownId, expiresAt: this.now() + ttlSeconds * 1000 });
298
+ this.persist();
156
299
  }
157
300
  }
158
- markFailed(poolId, sessionKey, key, cooldownMs) {
159
- this.cooldown.set(this.cooldownKey(poolId, key), this.now() + cooldownMs);
301
+ markFailedById(poolId, sessionKey, cooldownId, cooldownMs) {
302
+ this.cooldown.set(this.cooldownKey(poolId, cooldownId), this.now() + cooldownMs);
160
303
  if (sessionKey) {
161
304
  const stickKey = `${poolId}\0${sessionKey}`;
162
- if (this.sticky.get(stickKey)?.key === key)
305
+ if (this.sticky.get(stickKey)?.keyHash === cooldownId) {
163
306
  this.sticky.delete(stickKey);
307
+ this.persist();
308
+ }
164
309
  }
165
310
  }
311
+ markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
312
+ this.markSuccessById(poolId, sessionKey, keyHashOf(key), ttlSeconds, stickyEnabled);
313
+ }
314
+ markFailed(poolId, sessionKey, key, cooldownMs) {
315
+ this.markFailedById(poolId, sessionKey, keyHashOf(key), cooldownMs);
316
+ }
317
+ status() {
318
+ const t = this.now();
319
+ let activeStickyCount = 0;
320
+ for (const v of this.sticky.values())
321
+ if (v.expiresAt > t)
322
+ activeStickyCount++;
323
+ const cooledKeys = [];
324
+ for (const [ck, until] of this.cooldown.entries()) {
325
+ if (until <= t)
326
+ continue;
327
+ const sep = ck.indexOf("\0");
328
+ const poolId = sep >= 0 ? ck.slice(0, sep) : ck;
329
+ const cooldownId = sep >= 0 ? ck.slice(sep + 1) : "";
330
+ cooledKeys.push({ poolId, keyHash: cooldownId, remainingSec: Math.ceil((until - t) / 1000) });
331
+ }
332
+ return { activeStickyCount, cooledKeys };
333
+ }
334
+ }
335
+ function medianOf(nums) {
336
+ if (!nums.length)
337
+ return null;
338
+ const sorted = [...nums].sort((a, b) => a - b);
339
+ return sorted[Math.floor(sorted.length / 2)];
340
+ }
341
+ function isCompactPrompt(body) {
342
+ const chunks = [];
343
+ if (typeof body.system === "string")
344
+ chunks.push(body.system.slice(0, 600));
345
+ else if (Array.isArray(body.system)) {
346
+ for (const b of body.system)
347
+ if (typeof b?.text === "string")
348
+ chunks.push(b.text.slice(0, 400));
349
+ }
350
+ const lastUser = Array.isArray(body.messages) ? [...body.messages].reverse().find((m) => m?.role === "user") : undefined;
351
+ if (typeof lastUser?.content === "string")
352
+ chunks.push(lastUser.content.slice(0, 600));
353
+ else if (Array.isArray(lastUser?.content)) {
354
+ for (const b of lastUser.content)
355
+ if (typeof b?.text === "string")
356
+ chunks.push(b.text.slice(0, 400));
357
+ }
358
+ const text = chunks.join("\n");
359
+ return /(?:^|\s)\/compact\b|summarize the conversation(?: above| so far)|write a concise summary of the conversation|压缩上下文/i.test(text);
166
360
  }
167
361
  /** 旁路解析非流式 JSON 或 SSE 流中各厂商的 Token 用量与模型 ID */
168
362
  export class UsageSniffer {
@@ -384,10 +578,16 @@ export class LocalProxy {
384
578
  listenUrl;
385
579
  onUrlChange = new Set();
386
580
  activeUsage = new Map();
581
+ totalRequests = 0;
582
+ totalRetries = 0;
583
+ totalBlocked = 0;
584
+ totalRedacted = 0;
585
+ recentRedactions = [];
586
+ modelAcc = new Map();
387
587
  constructor(deps) {
388
588
  this.deps = deps;
389
589
  const now = deps.now ?? (() => Date.now());
390
- this.keyPool = new StickyKeyPool(now);
590
+ this.keyPool = new StickyKeyPool(now, deps.affinityFile);
391
591
  this.redactor = new Redactor();
392
592
  }
393
593
  baseUrl() {
@@ -419,11 +619,79 @@ export class LocalProxy {
419
619
  }
420
620
  return true;
421
621
  }
622
+ snapshot() {
623
+ const cfg = this.deps.getConfig().proxy;
624
+ const models = [...this.modelAcc.entries()]
625
+ .map(([model, s]) => ({
626
+ model,
627
+ requests: s.requests,
628
+ errors: s.errors,
629
+ inputTokens: s.inputTokens,
630
+ outputTokens: s.outputTokens,
631
+ cacheReadTokens: s.cacheReadTokens,
632
+ cacheHitRate: s.inputTokens + s.cacheReadTokens > 0 ? Math.round((s.cacheReadTokens / (s.inputTokens + s.cacheReadTokens)) * 100) : null,
633
+ medianTtftMs: medianOf(s.ttfts),
634
+ medianTps: medianOf(s.tpsList),
635
+ avgDurationMs: s.requests ? Math.round(s.durationTotalMs / s.requests) : 0,
636
+ costUsd: Number(s.costUsd.toFixed(6)),
637
+ }))
638
+ .sort((a, b) => b.requests - a.requests);
639
+ return {
640
+ enabled: Boolean(cfg?.enabled),
641
+ mode: cfg?.mode ?? "byok",
642
+ listenUrl: this.listenUrl ?? null,
643
+ bridgeEnabled: Boolean(cfg?.anthropicBridge?.enabled),
644
+ totals: {
645
+ requests: this.totalRequests,
646
+ retries: this.totalRetries,
647
+ blocked: this.totalBlocked,
648
+ redacted: this.totalRedacted,
649
+ },
650
+ pool: this.keyPool.status(),
651
+ models,
652
+ recentRedactions: [...this.recentRedactions],
653
+ };
654
+ }
655
+ recordRedactionAudit(entry) {
656
+ this.totalRedacted += entry.count;
657
+ this.recentRedactions.unshift(entry);
658
+ if (this.recentRedactions.length > 30)
659
+ this.recentRedactions.length = 30;
660
+ }
661
+ recordModelMetric(args) {
662
+ this.totalRetries += args.retries;
663
+ let acc = this.modelAcc.get(args.model);
664
+ if (!acc) {
665
+ acc = { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, durationTotalMs: 0, costUsd: 0, ttfts: [], tpsList: [] };
666
+ this.modelAcc.set(args.model, acc);
667
+ }
668
+ acc.requests++;
669
+ if (!args.ok)
670
+ acc.errors++;
671
+ acc.inputTokens += args.usage.input;
672
+ acc.outputTokens += args.usage.output;
673
+ acc.cacheReadTokens += args.usage.cacheRead ?? 0;
674
+ acc.durationTotalMs += args.durationMs;
675
+ acc.costUsd += args.costUsd ?? 0;
676
+ if (args.ttftMs !== null) {
677
+ acc.ttfts.push(args.ttftMs);
678
+ if (acc.ttfts.length > 100)
679
+ acc.ttfts.shift();
680
+ }
681
+ if (args.tps !== null) {
682
+ acc.tpsList.push(args.tps);
683
+ if (acc.tpsList.length > 100)
684
+ acc.tpsList.shift();
685
+ }
686
+ }
422
687
  /** 判断 API 成员是否应经过代理(全局启用代理 或 自身配置了多 Key 池) */
423
688
  shouldRouteApiMember(api) {
424
689
  const cfg = this.deps.getConfig().proxy;
425
- if (cfg?.enabled)
690
+ if (cfg?.enabled) {
691
+ if (cfg.mode === "relay")
692
+ return cfg.relay.routeMembers !== false;
426
693
  return true;
694
+ }
427
695
  return Boolean((api.apiKeys?.length ?? 0) > 1 || (api.credentials?.length ?? 0) > 1);
428
696
  }
429
697
  issueToken(meta) {
@@ -584,22 +852,46 @@ export class LocalProxy {
584
852
  }
585
853
  }
586
854
  const proxyCfg = config.proxy;
855
+ const now = this.deps.now ?? (() => Date.now());
856
+ this.totalRequests++;
587
857
  const rawBody = await readRequestBody(req);
588
858
  let outboundBody = rawBody;
859
+ let parsedBody;
589
860
  let redactedCount = 0;
861
+ let redactedKinds = [];
590
862
  const requestVault = new Map();
591
863
  const reqContentType = String(req.headers["content-type"] ?? "");
592
864
  let requestedModel = meta.model;
593
865
  if (rawBody.length > 0 && reqContentType.toLowerCase().includes("application/json")) {
594
866
  try {
595
- const parsed = JSON.parse(rawBody.toString("utf8"));
596
- if (typeof parsed.model === "string" && parsed.model)
597
- requestedModel = parsed.model;
867
+ parsedBody = JSON.parse(rawBody.toString("utf8"));
868
+ if (typeof parsedBody.model === "string" && parsedBody.model)
869
+ requestedModel = parsedBody.model;
598
870
  if (proxyCfg?.redact.enabled) {
599
- const redacted = this.ensureRedactor(config).redactJson(parsed, requestVault);
871
+ const action = proxyCfg.redact.action ?? "mask";
872
+ const redacted = this.ensureRedactor(config).redactJson(parsedBody, requestVault);
600
873
  redactedCount = redacted.count;
601
- if (redactedCount > 0)
602
- outboundBody = Buffer.from(JSON.stringify(redacted.value), "utf8");
874
+ redactedKinds = redacted.kinds;
875
+ if (redactedCount > 0) {
876
+ this.recordRedactionAudit({
877
+ at: now(),
878
+ agent: meta.agent,
879
+ protocol: route.protocol,
880
+ action,
881
+ count: redactedCount,
882
+ kinds: redactedKinds,
883
+ });
884
+ if (action === "block") {
885
+ this.totalBlocked++;
886
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
887
+ res.end(protocolErrorBody(route.protocol, `请求包含敏感凭据(${redactedKinds.join(", ")}),已按隐私策略拦截。`, "privacy_policy_blocked"));
888
+ return true;
889
+ }
890
+ if (action === "mask") {
891
+ parsedBody = redacted.value;
892
+ outboundBody = Buffer.from(JSON.stringify(parsedBody), "utf8");
893
+ }
894
+ }
603
895
  }
604
896
  }
605
897
  catch {
@@ -611,7 +903,25 @@ export class LocalProxy {
611
903
  if (searchParams.get("key") === clientToken)
612
904
  searchParams.delete("key");
613
905
  const cleanSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
614
- const useRelay = proxyCfg?.mode === "relay" && Boolean(proxyCfg.relay.url) && !route.memberApi;
906
+ const useRelay = proxyCfg?.mode === "relay" && Boolean(proxyCfg.relay.url) && (!route.memberApi || proxyCfg.relay.routeMembers !== false);
907
+ const groupCfg = !useRelay && !route.memberApi ? proxyCfg?.groups?.[route.protocol] : undefined;
908
+ const useAnthropicBridge = !useRelay &&
909
+ !groupCfg?.targets.length &&
910
+ route.protocol === "anthropic" &&
911
+ route.subpath === "/v1/messages" &&
912
+ Boolean(proxyCfg?.anthropicBridge?.enabled) &&
913
+ parsedBody !== undefined;
914
+ // 应用 compactModel 降级与 modelMap 别名重写
915
+ let routedModel = requestedModel;
916
+ if (parsedBody) {
917
+ if (proxyCfg?.compactModel && isCompactPrompt(parsedBody)) {
918
+ routedModel = proxyCfg.compactModel;
919
+ }
920
+ const bridgeMap = useAnthropicBridge ? proxyCfg?.anthropicBridge?.modelMap : undefined;
921
+ const mapped = (routedModel ? bridgeMap?.[routedModel] : undefined) ?? (routedModel ? proxyCfg?.modelMap?.[routedModel] : undefined);
922
+ if (mapped)
923
+ routedModel = mapped;
924
+ }
615
925
  const stickyCfg = proxyCfg?.sticky ?? { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 };
616
926
  const sessionKey = meta.sessionId ||
617
927
  meta.taskId ||
@@ -619,97 +929,206 @@ export class LocalProxy {
619
929
  (typeof req.headers["x-codex-window-id"] === "string" ? req.headers["x-codex-window-id"] : undefined) ||
620
930
  meta.callId ||
621
931
  meta.agent;
622
- let targetUrl;
932
+ const poolId = groupCfg?.targets.length ? `group:${route.protocol}` : useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
623
933
  let candidates;
624
934
  if (useRelay) {
625
935
  const relayUrl = proxyCfg.relay.url;
626
- targetUrl = joinUpstreamUrl(relayUrl, `/${route.protocol}${route.subpath}`, cleanSearch);
936
+ const relayPath = route.memberKind ? `/member/${route.memberKind}${route.subpath}` : `/${route.protocol}${route.subpath}`;
627
937
  const relayToken = this.resolveRelayToken(config);
628
938
  if (!relayToken) {
629
939
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
630
940
  res.end(protocolErrorBody(route.protocol, "托管中转模式缺少 relay token,请检查环境变量或本机凭据。", "missing_relay_token"));
631
941
  return true;
632
942
  }
633
- candidates = [relayToken];
943
+ candidates = [
944
+ {
945
+ cooldownId: "relay",
946
+ key: relayToken,
947
+ baseUrl: joinUpstreamUrl(relayUrl, relayPath, cleanSearch),
948
+ protocol: route.protocol,
949
+ label: "relay",
950
+ },
951
+ ];
952
+ }
953
+ else if (groupCfg?.targets.length) {
954
+ const expanded = [];
955
+ for (const t of groupCfg.targets) {
956
+ const proto = t.protocol ?? route.protocol;
957
+ const keys = resolveKeyPool(t);
958
+ for (const k of keys) {
959
+ expanded.push({
960
+ cooldownId: keyHashOf(`${proto}\0${t.baseUrl}\0${k}\0${t.model ?? ""}`),
961
+ key: k,
962
+ baseUrl: t.baseUrl,
963
+ protocol: proto,
964
+ model: t.model,
965
+ label: t.name ?? t.baseUrl,
966
+ });
967
+ }
968
+ }
969
+ candidates = this.keyPool.pickFromCandidates(poolId, expanded, sessionKey, stickyCfg.enabled, groupCfg.strategy);
970
+ if (!candidates.length) {
971
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
972
+ res.end(protocolErrorBody(route.protocol, `路由组 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
973
+ return true;
974
+ }
975
+ }
976
+ else if (useAnthropicBridge) {
977
+ const bridge = proxyCfg.anthropicBridge;
978
+ const bridgeBase = bridge.baseUrl ?? proxyCfg?.upstreams.openai.baseUrl ?? "https://api.openai.com";
979
+ const bridgeKeys = resolveKeyPool(bridge);
980
+ const keys = bridgeKeys.length ? bridgeKeys : resolveKeyPool(proxyCfg?.upstreams.openai ?? {});
981
+ const expanded = keys.map((k) => ({
982
+ cooldownId: keyHashOf(`openai\0${bridgeBase}\0${k}`),
983
+ key: k,
984
+ baseUrl: bridgeBase,
985
+ protocol: "openai",
986
+ label: "anthropic-bridge",
987
+ }));
988
+ candidates = this.keyPool.pickFromCandidates(poolId, expanded, sessionKey, stickyCfg.enabled, "rotate");
989
+ if (!candidates.length) {
990
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
991
+ res.end(protocolErrorBody(route.protocol, "Anthropic 协议桥接未配置可用 OpenAI 兼容密钥。", "missing_api_key"));
992
+ return true;
993
+ }
634
994
  }
635
995
  else {
636
996
  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);
997
+ const expanded = upstream.keys.map((k) => ({
998
+ cooldownId: keyHashOf(k),
999
+ key: k,
1000
+ baseUrl: upstream.baseUrl,
1001
+ protocol: route.protocol,
1002
+ label: route.poolId,
1003
+ }));
1004
+ candidates = this.keyPool.pickFromCandidates(poolId, expanded, sessionKey, stickyCfg.enabled, "rotate");
639
1005
  if (!candidates.length) {
640
1006
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
641
- res.end(protocolErrorBody(route.protocol, `上游 ${route.poolId} 未配置可用 API Key。`, "missing_api_key"));
1007
+ res.end(protocolErrorBody(route.protocol, `上游 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
642
1008
  return true;
643
1009
  }
644
1010
  }
645
1011
  const fetchFn = this.deps.fetchImpl ?? fetch;
646
- const now = this.deps.now ?? (() => Date.now());
647
1012
  const controller = new AbortController();
648
1013
  const onClientAbort = () => controller.abort();
649
1014
  req.once("aborted", onClientAbort);
650
1015
  res.once("close", onClientAbort);
651
- const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 3);
1016
+ const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 6);
652
1017
  let finalResponse;
1018
+ let winningCandidate;
1019
+ let usedBridge = false;
653
1020
  let retries = 0;
1021
+ let strippedSignatures = false;
1022
+ const reqStartedAt = Date.now();
1023
+ const buildUpstreamHeaders = (cand, isBridged) => {
1024
+ const headers = new Headers();
1025
+ for (const [k, v] of Object.entries(req.headers)) {
1026
+ const lower = k.toLowerCase();
1027
+ if (HOP_BY_HOP_HEADERS.has(lower))
1028
+ continue;
1029
+ if (lower === "authorization" || lower === "x-api-key" || lower === "x-goog-api-key")
1030
+ continue;
1031
+ if (isBridged && (lower === "anthropic-version" || lower === "anthropic-beta"))
1032
+ continue;
1033
+ if (Array.isArray(v))
1034
+ headers.set(k, v.join(", "));
1035
+ else if (typeof v === "string")
1036
+ headers.set(k, v);
1037
+ }
1038
+ if (useRelay) {
1039
+ headers.set("authorization", `Bearer ${cand.key}`);
1040
+ if (meta.taskId)
1041
+ headers.set("x-lemma-task-id", meta.taskId);
1042
+ if (meta.sessionId)
1043
+ headers.set("x-lemma-session-id", meta.sessionId);
1044
+ headers.set("x-lemma-member", meta.agent);
1045
+ }
1046
+ else if (cand.protocol === "anthropic") {
1047
+ headers.set("x-api-key", cand.key);
1048
+ }
1049
+ else if (cand.protocol === "gemini") {
1050
+ headers.set("x-goog-api-key", cand.key);
1051
+ }
1052
+ else {
1053
+ headers.set("authorization", `Bearer ${cand.key}`);
1054
+ }
1055
+ return headers;
1056
+ };
1057
+ const prepareCandidateRequest = (cand) => {
1058
+ if (useRelay)
1059
+ return { url: cand.baseUrl, body: outboundBody, isBridged: false };
1060
+ const isBridged = route.protocol === "anthropic" && route.subpath === "/v1/messages" && cand.protocol === "openai" && parsedBody !== undefined;
1061
+ const effectiveModel = cand.model ?? routedModel;
1062
+ if (isBridged) {
1063
+ const translated = anthropicToOpenAiRequest(parsedBody, effectiveModel ?? "gpt-4.1");
1064
+ return {
1065
+ url: joinUpstreamUrl(cand.baseUrl, "/v1/chat/completions", cleanSearch),
1066
+ body: Buffer.from(JSON.stringify(translated), "utf8"),
1067
+ isBridged: true,
1068
+ };
1069
+ }
1070
+ let bodyBuf = outboundBody;
1071
+ if (parsedBody && effectiveModel && effectiveModel !== parsedBody.model) {
1072
+ bodyBuf = Buffer.from(JSON.stringify({ ...parsedBody, model: effectiveModel }), "utf8");
1073
+ }
1074
+ return {
1075
+ url: joinUpstreamUrl(cand.baseUrl, route.subpath, cleanSearch),
1076
+ body: bodyBuf,
1077
+ isBridged: false,
1078
+ };
1079
+ };
654
1080
  try {
655
1081
  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) {
1082
+ const cand = candidates[attempt];
1083
+ for (;;) {
1084
+ const prep = prepareCandidateRequest(cand);
1085
+ const upstreamRes = await fetchFn(prep.url, {
1086
+ method: req.method ?? "POST",
1087
+ headers: buildUpstreamHeaders(cand, prep.isBridged),
1088
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(prep.body),
1089
+ signal: controller.signal,
1090
+ });
1091
+ if (upstreamRes.ok) {
1092
+ if (!useRelay) {
1093
+ this.keyPool.markSuccessById(poolId, sessionKey, cand.cooldownId, stickyCfg.ttlSeconds, stickyCfg.enabled);
1094
+ }
1095
+ finalResponse = upstreamRes;
1096
+ winningCandidate = cand;
1097
+ usedBridge = prep.isBridged;
1098
+ break;
1099
+ }
694
1100
  const errText = await upstreamRes.text();
695
- if (shouldFailoverStatus(upstreamRes.status, errText)) {
1101
+ // 若因跨账号/跨中转思考块签名失效返回 400:剥离兼容签名后用同一个健康 Key 重发一次,不误拉黑 Key
1102
+ if (!prep.isBridged && !strippedSignatures && isSignatureRefused(upstreamRes.status, errText)) {
1103
+ const stripped = stripIncompatibleSignatures(route.protocol, prep.body);
1104
+ if (stripped.stripped) {
1105
+ outboundBody = stripped.body;
1106
+ try {
1107
+ parsedBody = JSON.parse(stripped.body.toString("utf8"));
1108
+ }
1109
+ catch { }
1110
+ strippedSignatures = true;
1111
+ retries++;
1112
+ continue;
1113
+ }
1114
+ }
1115
+ if (!useRelay && attempt + 1 < maxAttempts && shouldFailoverStatus(upstreamRes.status, errText)) {
696
1116
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
697
- this.keyPool.markFailed(route.poolId, sessionKey, apiKey, cooldownMs);
1117
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs);
698
1118
  retries++;
699
- continue;
1119
+ break;
1120
+ }
1121
+ if (!useRelay && shouldFailoverStatus(upstreamRes.status, errText)) {
1122
+ const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1123
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs);
700
1124
  }
701
1125
  finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
1126
+ winningCandidate = cand;
1127
+ usedBridge = prep.isBridged;
702
1128
  break;
703
1129
  }
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;
1130
+ if (finalResponse)
1131
+ break;
713
1132
  }
714
1133
  }
715
1134
  catch (error) {
@@ -737,52 +1156,108 @@ export class LocalProxy {
737
1156
  return;
738
1157
  outHeaders[k] = v;
739
1158
  });
740
- res.writeHead(finalResponse.status, outHeaders);
741
1159
  const resContentType = finalResponse.headers.get("content-type");
742
- const sniffer = new UsageSniffer(route.protocol, resContentType);
743
- const restore = Boolean(proxyCfg?.redact.restoreInResponse && redactedCount > 0);
1160
+ const isSse = (resContentType ?? "").toLowerCase().includes("text/event-stream");
1161
+ const translateBridgeOk = usedBridge && finalResponse.ok;
1162
+ if (translateBridgeOk) {
1163
+ outHeaders["content-type"] = isSse ? "text/event-stream; charset=utf-8" : "application/json; charset=utf-8";
1164
+ }
1165
+ res.writeHead(finalResponse.status, outHeaders);
1166
+ const sniffer = new UsageSniffer(route.protocol, translateBridgeOk && !isSse ? "application/json" : resContentType);
1167
+ const restore = Boolean(proxyCfg?.redact.restoreInResponse && redactedCount > 0 && proxyCfg?.redact.action === "mask");
744
1168
  const redactor = this.ensureRedactor(config);
745
1169
  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();
1170
+ const effectiveTargetModel = winningCandidate?.model ?? routedModel;
1171
+ let firstChunkAt;
1172
+ if (translateBridgeOk && !isSse) {
749
1173
  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;
1174
+ const rawText = await finalResponse.text();
1175
+ firstChunkAt = Date.now();
1176
+ const parsedOai = JSON.parse(rawText);
1177
+ const anthropicJson = openAiToAnthropicJsonResponse(parsedOai, requestedModel ?? effectiveTargetModel ?? "unknown");
1178
+ const encoded = JSON.stringify(anthropicJson);
1179
+ sniffer.push(encoded);
1180
+ const emitted = restore ? redactor.restoreText(encoded, requestVault) : encoded;
1181
+ if (!res.destroyed)
1182
+ res.write(emitted);
1183
+ }
1184
+ catch {
1185
+ /* 上游返回非法 JSON 时跳过桥接写空响应 */
1186
+ }
1187
+ }
1188
+ else {
1189
+ const sseTranslator = translateBridgeOk && isSse ? new OpenAiToAnthropicSseTranslator(requestedModel ?? effectiveTargetModel ?? "unknown") : undefined;
1190
+ if (finalResponse.body) {
1191
+ const decoder = new TextDecoder();
1192
+ const reader = finalResponse.body.getReader();
1193
+ try {
1194
+ for (;;) {
1195
+ const { done, value } = await reader.read();
1196
+ if (done)
1197
+ break;
1198
+ const text = decoder.decode(value, { stream: true });
1199
+ if (text) {
1200
+ if (firstChunkAt === undefined)
1201
+ firstChunkAt = Date.now();
1202
+ const normalized = sseTranslator ? sseTranslator.push(text) : text;
1203
+ if (normalized) {
1204
+ sniffer.push(normalized);
1205
+ const emit = unredactor ? unredactor.push(normalized) : normalized;
1206
+ if (emit && !res.destroyed)
1207
+ res.write(emit);
1208
+ }
1209
+ }
1210
+ }
1211
+ const tail = decoder.decode();
1212
+ const flushedBridge = (sseTranslator ? sseTranslator.push(tail) + sseTranslator.finish() : tail);
1213
+ if (flushedBridge) {
1214
+ if (firstChunkAt === undefined)
1215
+ firstChunkAt = Date.now();
1216
+ sniffer.push(flushedBridge);
1217
+ const emit = unredactor ? unredactor.push(flushedBridge) : flushedBridge;
758
1218
  if (emit && !res.destroyed)
759
1219
  res.write(emit);
760
1220
  }
1221
+ if (unredactor) {
1222
+ const rem = unredactor.flush();
1223
+ if (rem && !res.destroyed)
1224
+ res.write(rem);
1225
+ }
761
1226
  }
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);
1227
+ catch {
1228
+ /* 流中断时仍尽量提交已嗅探到的部分用量 */
773
1229
  }
774
1230
  }
775
- catch {
776
- /* 流中断时仍尽量提交已嗅探到的部分用量 */
1231
+ else if (sseTranslator) {
1232
+ const emptyDone = sseTranslator.finish();
1233
+ if (emptyDone) {
1234
+ sniffer.push(emptyDone);
1235
+ if (!res.destroyed)
1236
+ res.write(emptyDone);
1237
+ }
777
1238
  }
778
1239
  }
779
1240
  sniffer.finish();
780
1241
  if (!res.writableEnded)
781
1242
  res.end();
1243
+ const endedAt = Date.now();
1244
+ const durationMs = Math.max(1, endedAt - reqStartedAt);
1245
+ const ttftMs = firstChunkAt !== undefined ? Math.max(0, firstChunkAt - reqStartedAt) : null;
782
1246
  const usage = sniffer.toTokenUsage();
783
- const usedModel = sniffer.model ?? requestedModel;
1247
+ const tps = usage.output >= 20 ? Number((usage.output / (Math.max(1, endedAt - (firstChunkAt ?? reqStartedAt)) / 1000)).toFixed(1)) : null;
1248
+ const usedModel = usedBridge ? effectiveTargetModel : (sniffer.model ?? effectiveTargetModel ?? requestedModel);
784
1249
  const hasTokens = usage.input > 0 || usage.output > 0 || (usage.cacheRead ?? 0) > 0;
785
1250
  const costUsd = hasTokens ? calculateUsageCost(this.priceFor(meta, usedModel, config), usage) : undefined;
1251
+ this.recordModelMetric({
1252
+ model: usedModel ?? route.poolId,
1253
+ ok: finalResponse.ok,
1254
+ durationMs,
1255
+ ttftMs,
1256
+ tps,
1257
+ usage,
1258
+ costUsd,
1259
+ retries,
1260
+ });
786
1261
  if (meta.callId && costUsd !== undefined && costUsd > 0) {
787
1262
  const prev = this.activeUsage.get(meta.callId) ?? { costUsd: 0, events: 0 };
788
1263
  prev.costUsd += costUsd;