lemma-agent 1.1.0 → 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/dist/account-discovery.js +159 -0
- package/dist/admin.js +5 -0
- package/dist/app.js +1 -0
- package/dist/bridge.js +341 -0
- package/dist/config.js +43 -3
- package/dist/proxy.js +490 -97
- package/dist/redact.js +9 -3
- package/package.json +1 -1
- package/web/js/views.js +40 -0
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,14 +99,138 @@ export function shouldFailoverStatus(status, bodyText) {
|
|
|
96
99
|
}
|
|
97
100
|
return false;
|
|
98
101
|
}
|
|
99
|
-
/**
|
|
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 冷却退避 + 可选哈希持久化 */
|
|
100
179
|
export class StickyKeyPool {
|
|
101
180
|
sticky = new Map();
|
|
102
181
|
cooldown = new Map();
|
|
103
182
|
rrCursor = new Map();
|
|
104
183
|
now;
|
|
105
|
-
|
|
184
|
+
affinityFile;
|
|
185
|
+
constructor(now = () => Date.now(), affinityFile) {
|
|
106
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
|
+
}
|
|
107
234
|
}
|
|
108
235
|
cooldownKey(poolId, key) {
|
|
109
236
|
return `${poolId}\0${key}`;
|
|
@@ -133,8 +260,10 @@ export class StickyKeyPool {
|
|
|
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
|
|
137
|
-
|
|
263
|
+
if (hit && hit.expiresAt > t) {
|
|
264
|
+
const matched = baseList.find((k) => keyHashOf(k) === 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);
|
|
@@ -152,17 +281,69 @@ export class StickyKeyPool {
|
|
|
152
281
|
markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
|
|
153
282
|
this.cooldown.delete(this.cooldownKey(poolId, key));
|
|
154
283
|
if (stickyEnabled && sessionKey && ttlSeconds > 0) {
|
|
155
|
-
|
|
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();
|
|
156
292
|
}
|
|
157
293
|
}
|
|
158
294
|
markFailed(poolId, sessionKey, key, cooldownMs) {
|
|
159
295
|
this.cooldown.set(this.cooldownKey(poolId, key), this.now() + cooldownMs);
|
|
160
296
|
if (sessionKey) {
|
|
161
297
|
const stickKey = `${poolId}\0${sessionKey}`;
|
|
162
|
-
if (this.sticky.get(stickKey)?.
|
|
298
|
+
if (this.sticky.get(stickKey)?.keyHash === keyHashOf(key)) {
|
|
163
299
|
this.sticky.delete(stickKey);
|
|
300
|
+
this.persist();
|
|
301
|
+
}
|
|
164
302
|
}
|
|
165
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);
|
|
166
347
|
}
|
|
167
348
|
/** 旁路解析非流式 JSON 或 SSE 流中各厂商的 Token 用量与模型 ID */
|
|
168
349
|
export class UsageSniffer {
|
|
@@ -384,10 +565,16 @@ export class LocalProxy {
|
|
|
384
565
|
listenUrl;
|
|
385
566
|
onUrlChange = new Set();
|
|
386
567
|
activeUsage = new Map();
|
|
568
|
+
totalRequests = 0;
|
|
569
|
+
totalRetries = 0;
|
|
570
|
+
totalBlocked = 0;
|
|
571
|
+
totalRedacted = 0;
|
|
572
|
+
recentRedactions = [];
|
|
573
|
+
modelAcc = new Map();
|
|
387
574
|
constructor(deps) {
|
|
388
575
|
this.deps = deps;
|
|
389
576
|
const now = deps.now ?? (() => Date.now());
|
|
390
|
-
this.keyPool = new StickyKeyPool(now);
|
|
577
|
+
this.keyPool = new StickyKeyPool(now, deps.affinityFile);
|
|
391
578
|
this.redactor = new Redactor();
|
|
392
579
|
}
|
|
393
580
|
baseUrl() {
|
|
@@ -419,11 +606,79 @@ export class LocalProxy {
|
|
|
419
606
|
}
|
|
420
607
|
return true;
|
|
421
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
|
+
}
|
|
422
674
|
/** 判断 API 成员是否应经过代理(全局启用代理 或 自身配置了多 Key 池) */
|
|
423
675
|
shouldRouteApiMember(api) {
|
|
424
676
|
const cfg = this.deps.getConfig().proxy;
|
|
425
|
-
if (cfg?.enabled)
|
|
677
|
+
if (cfg?.enabled) {
|
|
678
|
+
if (cfg.mode === "relay")
|
|
679
|
+
return cfg.relay.routeMembers !== false;
|
|
426
680
|
return true;
|
|
681
|
+
}
|
|
427
682
|
return Boolean((api.apiKeys?.length ?? 0) > 1 || (api.credentials?.length ?? 0) > 1);
|
|
428
683
|
}
|
|
429
684
|
issueToken(meta) {
|
|
@@ -584,22 +839,46 @@ export class LocalProxy {
|
|
|
584
839
|
}
|
|
585
840
|
}
|
|
586
841
|
const proxyCfg = config.proxy;
|
|
842
|
+
const now = this.deps.now ?? (() => Date.now());
|
|
843
|
+
this.totalRequests++;
|
|
587
844
|
const rawBody = await readRequestBody(req);
|
|
588
845
|
let outboundBody = rawBody;
|
|
846
|
+
let parsedBody;
|
|
589
847
|
let redactedCount = 0;
|
|
848
|
+
let redactedKinds = [];
|
|
590
849
|
const requestVault = new Map();
|
|
591
850
|
const reqContentType = String(req.headers["content-type"] ?? "");
|
|
592
851
|
let requestedModel = meta.model;
|
|
593
852
|
if (rawBody.length > 0 && reqContentType.toLowerCase().includes("application/json")) {
|
|
594
853
|
try {
|
|
595
|
-
|
|
596
|
-
if (typeof
|
|
597
|
-
requestedModel =
|
|
854
|
+
parsedBody = JSON.parse(rawBody.toString("utf8"));
|
|
855
|
+
if (typeof parsedBody.model === "string" && parsedBody.model)
|
|
856
|
+
requestedModel = parsedBody.model;
|
|
598
857
|
if (proxyCfg?.redact.enabled) {
|
|
599
|
-
const
|
|
858
|
+
const action = proxyCfg.redact.action ?? "mask";
|
|
859
|
+
const redacted = this.ensureRedactor(config).redactJson(parsedBody, requestVault);
|
|
600
860
|
redactedCount = redacted.count;
|
|
601
|
-
|
|
602
|
-
|
|
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
|
+
}
|
|
603
882
|
}
|
|
604
883
|
}
|
|
605
884
|
catch {
|
|
@@ -611,7 +890,31 @@ export class LocalProxy {
|
|
|
611
890
|
if (searchParams.get("key") === clientToken)
|
|
612
891
|
searchParams.delete("key");
|
|
613
892
|
const cleanSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
|
|
614
|
-
const useRelay = proxyCfg?.mode === "relay" && Boolean(proxyCfg.relay.url) && !route.memberApi;
|
|
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
|
+
}
|
|
615
918
|
const stickyCfg = proxyCfg?.sticky ?? { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 };
|
|
616
919
|
const sessionKey = meta.sessionId ||
|
|
617
920
|
meta.taskId ||
|
|
@@ -619,11 +922,13 @@ export class LocalProxy {
|
|
|
619
922
|
(typeof req.headers["x-codex-window-id"] === "string" ? req.headers["x-codex-window-id"] : undefined) ||
|
|
620
923
|
meta.callId ||
|
|
621
924
|
meta.agent;
|
|
925
|
+
const poolId = useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
|
|
622
926
|
let targetUrl;
|
|
623
927
|
let candidates;
|
|
624
928
|
if (useRelay) {
|
|
625
929
|
const relayUrl = proxyCfg.relay.url;
|
|
626
|
-
|
|
930
|
+
const relayPath = route.memberKind ? `/member/${route.memberKind}${route.subpath}` : `/${route.protocol}${route.subpath}`;
|
|
931
|
+
targetUrl = joinUpstreamUrl(relayUrl, relayPath, cleanSearch);
|
|
627
932
|
const relayToken = this.resolveRelayToken(config);
|
|
628
933
|
if (!relayToken) {
|
|
629
934
|
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
@@ -632,18 +937,30 @@ export class LocalProxy {
|
|
|
632
937
|
}
|
|
633
938
|
candidates = [relayToken];
|
|
634
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
|
+
}
|
|
635
953
|
else {
|
|
636
954
|
const upstream = this.resolveUpstream(route, config);
|
|
637
955
|
targetUrl = joinUpstreamUrl(upstream.baseUrl, route.subpath, cleanSearch);
|
|
638
|
-
candidates = this.keyPool.pickCandidates(
|
|
956
|
+
candidates = this.keyPool.pickCandidates(poolId, upstream.keys, sessionKey, stickyCfg.enabled);
|
|
639
957
|
if (!candidates.length) {
|
|
640
958
|
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
641
|
-
res.end(protocolErrorBody(route.protocol, `上游 ${
|
|
959
|
+
res.end(protocolErrorBody(route.protocol, `上游 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
|
|
642
960
|
return true;
|
|
643
961
|
}
|
|
644
962
|
}
|
|
645
963
|
const fetchFn = this.deps.fetchImpl ?? fetch;
|
|
646
|
-
const now = this.deps.now ?? (() => Date.now());
|
|
647
964
|
const controller = new AbortController();
|
|
648
965
|
const onClientAbort = () => controller.abort();
|
|
649
966
|
req.once("aborted", onClientAbort);
|
|
@@ -651,65 +968,86 @@ export class LocalProxy {
|
|
|
651
968
|
const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 3);
|
|
652
969
|
let finalResponse;
|
|
653
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
|
+
};
|
|
654
1008
|
try {
|
|
655
1009
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
656
1010
|
const apiKey = candidates[attempt];
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
if (
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
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) {
|
|
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
|
+
}
|
|
694
1025
|
const errText = await upstreamRes.text();
|
|
695
|
-
|
|
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)) {
|
|
696
1037
|
const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
|
|
697
|
-
this.keyPool.markFailed(
|
|
1038
|
+
this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
|
|
698
1039
|
retries++;
|
|
699
|
-
|
|
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);
|
|
700
1045
|
}
|
|
701
1046
|
finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
|
|
702
1047
|
break;
|
|
703
1048
|
}
|
|
704
|
-
if (
|
|
705
|
-
|
|
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;
|
|
1049
|
+
if (finalResponse)
|
|
1050
|
+
break;
|
|
713
1051
|
}
|
|
714
1052
|
}
|
|
715
1053
|
catch (error) {
|
|
@@ -737,52 +1075,107 @@ export class LocalProxy {
|
|
|
737
1075
|
return;
|
|
738
1076
|
outHeaders[k] = v;
|
|
739
1077
|
});
|
|
740
|
-
res.writeHead(finalResponse.status, outHeaders);
|
|
741
1078
|
const resContentType = finalResponse.headers.get("content-type");
|
|
742
|
-
const
|
|
743
|
-
const
|
|
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");
|
|
744
1087
|
const redactor = this.ensureRedactor(config);
|
|
745
1088
|
const unredactor = restore ? new StreamUnredactor((t) => redactor.restoreText(t, requestVault)) : undefined;
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
const reader = finalResponse.body.getReader();
|
|
1089
|
+
let firstChunkAt;
|
|
1090
|
+
if (translateBridgeOk && !isSse) {
|
|
749
1091
|
try {
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
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;
|
|
758
1136
|
if (emit && !res.destroyed)
|
|
759
1137
|
res.write(emit);
|
|
760
1138
|
}
|
|
1139
|
+
if (unredactor) {
|
|
1140
|
+
const rem = unredactor.flush();
|
|
1141
|
+
if (rem && !res.destroyed)
|
|
1142
|
+
res.write(rem);
|
|
1143
|
+
}
|
|
761
1144
|
}
|
|
762
|
-
|
|
763
|
-
|
|
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);
|
|
1145
|
+
catch {
|
|
1146
|
+
/* 流中断时仍尽量提交已嗅探到的部分用量 */
|
|
773
1147
|
}
|
|
774
1148
|
}
|
|
775
|
-
|
|
776
|
-
|
|
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
|
+
}
|
|
777
1156
|
}
|
|
778
1157
|
}
|
|
779
1158
|
sniffer.finish();
|
|
780
1159
|
if (!res.writableEnded)
|
|
781
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;
|
|
782
1164
|
const usage = sniffer.toTokenUsage();
|
|
783
|
-
const
|
|
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);
|
|
784
1167
|
const hasTokens = usage.input > 0 || usage.output > 0 || (usage.cacheRead ?? 0) > 0;
|
|
785
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
|
+
});
|
|
786
1179
|
if (meta.callId && costUsd !== undefined && costUsd > 0) {
|
|
787
1180
|
const prev = this.activeUsage.get(meta.callId) ?? { costUsd: 0, events: 0 };
|
|
788
1181
|
prev.costUsd += costUsd;
|