lemma-agent 1.1.1 → 1.1.3

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
@@ -175,11 +175,12 @@ const MAX_STICKY_ENTRIES = 4096;
175
175
  function keyHashOf(key) {
176
176
  return createHash("sha256").update(key).digest("hex").slice(0, 16);
177
177
  }
178
- /** 粘性 Key 池管理器:常规平滑轮转 + Prompt Cache 粘性优先 + 429 冷却退避 + 可选哈希持久化 */
178
+ /** 粘性 Key / 多上游路由组管理器:支持 order 主备与 rotate 轮转 + Prompt Cache 粘性 + 429 冷却 + 哈希持久化 */
179
179
  export class StickyKeyPool {
180
180
  sticky = new Map();
181
181
  cooldown = new Map();
182
182
  rrCursor = new Map();
183
+ channelStats = new Map();
183
184
  now;
184
185
  affinityFile;
185
186
  constructor(now = () => Date.now(), affinityFile) {
@@ -232,36 +233,36 @@ export class StickyKeyPool {
232
233
  catch { }
233
234
  }
234
235
  }
235
- cooldownKey(poolId, key) {
236
- return `${poolId}\0${key}`;
236
+ cooldownKey(poolId, cooldownId) {
237
+ return `${poolId}\0${cooldownId}`;
237
238
  }
238
- pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
239
- if (!keys.length)
239
+ pickFromCandidates(poolId, candidates, sessionKey, stickyEnabled, strategy = "rotate") {
240
+ if (!candidates.length)
240
241
  return [];
241
242
  const t = this.now();
242
243
  const healthy = [];
243
244
  const resting = [];
244
- for (const key of keys) {
245
- const until = this.cooldown.get(this.cooldownKey(poolId, key)) ?? 0;
245
+ for (const item of candidates) {
246
+ const until = this.cooldown.get(this.cooldownKey(poolId, item.cooldownId)) ?? 0;
246
247
  if (until <= t) {
247
248
  if (until > 0)
248
- this.cooldown.delete(this.cooldownKey(poolId, key));
249
- healthy.push(key);
249
+ this.cooldown.delete(this.cooldownKey(poolId, item.cooldownId));
250
+ healthy.push(item);
250
251
  }
251
252
  else {
252
- resting.push({ key, until });
253
+ resting.push({ item, until });
253
254
  }
254
255
  }
255
- // 若池内全部 Key 都在冷却,按最早解禁时间兜底放行,避免假死
256
+ // 若池内全部候选都在冷却,按最早解禁时间兜底放行,避免假死
256
257
  const baseList = healthy.length
257
258
  ? healthy
258
- : resting.sort((a, b) => a.until - b.until).map((r) => r.key);
259
+ : resting.sort((a, b) => a.until - b.until).map((r) => r.item);
259
260
  const ordered = [];
260
261
  if (stickyEnabled && sessionKey) {
261
262
  const stickKey = `${poolId}\0${sessionKey}`;
262
263
  const hit = this.sticky.get(stickKey);
263
264
  if (hit && hit.expiresAt > t) {
264
- const matched = baseList.find((k) => keyHashOf(k) === hit.keyHash);
265
+ const matched = baseList.find((c) => c.cooldownId === hit.keyHash);
265
266
  if (matched)
266
267
  ordered.push(matched);
267
268
  }
@@ -269,17 +270,51 @@ export class StickyKeyPool {
269
270
  this.sticky.delete(stickKey);
270
271
  }
271
272
  }
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);
273
+ let remainder = baseList;
274
+ if (strategy === "rotate") {
275
+ const cursor = this.rrCursor.get(poolId) ?? 0;
276
+ remainder = baseList.map((_, idx) => baseList[(cursor + idx) % baseList.length]);
277
+ this.rrCursor.set(poolId, (cursor + 1) % Math.max(1, baseList.length));
278
+ }
279
+ for (const item of remainder) {
280
+ if (!ordered.includes(item))
281
+ ordered.push(item);
278
282
  }
279
283
  return ordered;
280
284
  }
281
- markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
282
- this.cooldown.delete(this.cooldownKey(poolId, key));
285
+ pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
286
+ const wrapped = keys.map((k) => ({ cooldownId: keyHashOf(k), raw: k }));
287
+ return this.pickFromCandidates(poolId, wrapped, sessionKey, stickyEnabled, "rotate").map((w) => w.raw);
288
+ }
289
+ ensureChannelStat(poolId, cooldownId, meta) {
290
+ const ck = this.cooldownKey(poolId, cooldownId);
291
+ let stat = this.channelStats.get(ck);
292
+ if (!stat) {
293
+ stat = {
294
+ poolId,
295
+ keyHash: cooldownId,
296
+ label: meta?.label || poolId,
297
+ protocol: meta?.protocol || (poolId.startsWith("proto:") ? poolId.slice(6) : "unknown"),
298
+ successes: 0,
299
+ failures: 0,
300
+ failovers: 0,
301
+ };
302
+ this.channelStats.set(ck, stat);
303
+ }
304
+ else {
305
+ if (meta?.label)
306
+ stat.label = meta.label;
307
+ if (meta?.protocol)
308
+ stat.protocol = meta.protocol;
309
+ }
310
+ return stat;
311
+ }
312
+ markSuccessById(poolId, sessionKey, cooldownId, ttlSeconds, stickyEnabled, meta) {
313
+ this.cooldown.delete(this.cooldownKey(poolId, cooldownId));
314
+ const stat = this.ensureChannelStat(poolId, cooldownId, meta);
315
+ stat.successes++;
316
+ if (meta?.failover)
317
+ stat.failovers++;
283
318
  if (stickyEnabled && sessionKey && ttlSeconds > 0) {
284
319
  const stickKey = `${poolId}\0${sessionKey}`;
285
320
  if (this.sticky.size >= MAX_STICKY_ENTRIES && !this.sticky.has(stickKey)) {
@@ -287,20 +322,28 @@ export class StickyKeyPool {
287
322
  if (oldest !== undefined)
288
323
  this.sticky.delete(oldest);
289
324
  }
290
- this.sticky.set(stickKey, { keyHash: keyHashOf(key), expiresAt: this.now() + ttlSeconds * 1000 });
325
+ this.sticky.set(stickKey, { keyHash: cooldownId, expiresAt: this.now() + ttlSeconds * 1000 });
291
326
  this.persist();
292
327
  }
293
328
  }
294
- markFailed(poolId, sessionKey, key, cooldownMs) {
295
- this.cooldown.set(this.cooldownKey(poolId, key), this.now() + cooldownMs);
329
+ markFailedById(poolId, sessionKey, cooldownId, cooldownMs, meta) {
330
+ this.cooldown.set(this.cooldownKey(poolId, cooldownId), this.now() + cooldownMs);
331
+ const stat = this.ensureChannelStat(poolId, cooldownId, meta);
332
+ stat.failures++;
296
333
  if (sessionKey) {
297
334
  const stickKey = `${poolId}\0${sessionKey}`;
298
- if (this.sticky.get(stickKey)?.keyHash === keyHashOf(key)) {
335
+ if (this.sticky.get(stickKey)?.keyHash === cooldownId) {
299
336
  this.sticky.delete(stickKey);
300
337
  this.persist();
301
338
  }
302
339
  }
303
340
  }
341
+ markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
342
+ this.markSuccessById(poolId, sessionKey, keyHashOf(key), ttlSeconds, stickyEnabled);
343
+ }
344
+ markFailed(poolId, sessionKey, key, cooldownMs) {
345
+ this.markFailedById(poolId, sessionKey, keyHashOf(key), cooldownMs);
346
+ }
304
347
  status() {
305
348
  const t = this.now();
306
349
  let activeStickyCount = 0;
@@ -313,10 +356,25 @@ export class StickyKeyPool {
313
356
  continue;
314
357
  const sep = ck.indexOf("\0");
315
358
  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) });
359
+ const cooldownId = sep >= 0 ? ck.slice(sep + 1) : "";
360
+ const stat = this.channelStats.get(ck);
361
+ cooledKeys.push({ poolId, ...(stat?.label ? { label: stat.label } : {}), keyHash: cooldownId, remainingSec: Math.ceil((until - t) / 1000) });
318
362
  }
319
- return { activeStickyCount, cooledKeys };
363
+ const channels = [...this.channelStats.entries()].map(([ck, stat]) => {
364
+ const until = this.cooldown.get(ck) ?? 0;
365
+ const remainingSec = until > t ? Math.ceil((until - t) / 1000) : 0;
366
+ return {
367
+ poolId: stat.poolId,
368
+ label: stat.label,
369
+ protocol: stat.protocol,
370
+ healthy: remainingSec === 0,
371
+ remainingSec,
372
+ successes: stat.successes,
373
+ failures: stat.failures,
374
+ failovers: stat.failovers,
375
+ };
376
+ });
377
+ return { activeStickyCount, cooledKeys, channels };
320
378
  }
321
379
  }
322
380
  function medianOf(nums) {
@@ -891,7 +949,9 @@ export class LocalProxy {
891
949
  searchParams.delete("key");
892
950
  const cleanSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
893
951
  const useRelay = proxyCfg?.mode === "relay" && Boolean(proxyCfg.relay.url) && (!route.memberApi || proxyCfg.relay.routeMembers !== false);
952
+ const groupCfg = !useRelay && !route.memberApi ? proxyCfg?.groups?.[route.protocol] : undefined;
894
953
  const useAnthropicBridge = !useRelay &&
954
+ !groupCfg?.targets.length &&
895
955
  route.protocol === "anthropic" &&
896
956
  route.subpath === "/v1/messages" &&
897
957
  Boolean(proxyCfg?.anthropicBridge?.enabled) &&
@@ -906,14 +966,6 @@ export class LocalProxy {
906
966
  const mapped = (routedModel ? bridgeMap?.[routedModel] : undefined) ?? (routedModel ? proxyCfg?.modelMap?.[routedModel] : undefined);
907
967
  if (mapped)
908
968
  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
969
  }
918
970
  const stickyCfg = proxyCfg?.sticky ?? { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 };
919
971
  const sessionKey = meta.sessionId ||
@@ -922,28 +974,63 @@ export class LocalProxy {
922
974
  (typeof req.headers["x-codex-window-id"] === "string" ? req.headers["x-codex-window-id"] : undefined) ||
923
975
  meta.callId ||
924
976
  meta.agent;
925
- const poolId = useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
926
- let targetUrl;
977
+ const poolId = groupCfg?.targets.length ? `group:${route.protocol}` : useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
927
978
  let candidates;
928
979
  if (useRelay) {
929
980
  const relayUrl = proxyCfg.relay.url;
930
981
  const relayPath = route.memberKind ? `/member/${route.memberKind}${route.subpath}` : `/${route.protocol}${route.subpath}`;
931
- targetUrl = joinUpstreamUrl(relayUrl, relayPath, cleanSearch);
932
982
  const relayToken = this.resolveRelayToken(config);
933
983
  if (!relayToken) {
934
984
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
935
985
  res.end(protocolErrorBody(route.protocol, "托管中转模式缺少 relay token,请检查环境变量或本机凭据。", "missing_relay_token"));
936
986
  return true;
937
987
  }
938
- candidates = [relayToken];
988
+ candidates = [
989
+ {
990
+ cooldownId: "relay",
991
+ key: relayToken,
992
+ baseUrl: joinUpstreamUrl(relayUrl, relayPath, cleanSearch),
993
+ protocol: route.protocol,
994
+ label: "relay",
995
+ },
996
+ ];
997
+ }
998
+ else if (groupCfg?.targets.length) {
999
+ const expanded = [];
1000
+ for (const t of groupCfg.targets) {
1001
+ const proto = t.protocol ?? route.protocol;
1002
+ const keys = resolveKeyPool(t);
1003
+ for (const k of keys) {
1004
+ expanded.push({
1005
+ cooldownId: keyHashOf(`${proto}\0${t.baseUrl}\0${k}\0${t.model ?? ""}`),
1006
+ key: k,
1007
+ baseUrl: t.baseUrl,
1008
+ protocol: proto,
1009
+ model: t.model,
1010
+ label: t.name ?? t.baseUrl,
1011
+ });
1012
+ }
1013
+ }
1014
+ candidates = this.keyPool.pickFromCandidates(poolId, expanded, sessionKey, stickyCfg.enabled, groupCfg.strategy);
1015
+ if (!candidates.length) {
1016
+ res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
1017
+ res.end(protocolErrorBody(route.protocol, `路由组 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
1018
+ return true;
1019
+ }
939
1020
  }
940
1021
  else if (useAnthropicBridge) {
941
1022
  const bridge = proxyCfg.anthropicBridge;
942
1023
  const bridgeBase = bridge.baseUrl ?? proxyCfg?.upstreams.openai.baseUrl ?? "https://api.openai.com";
943
1024
  const bridgeKeys = resolveKeyPool(bridge);
944
1025
  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);
1026
+ const expanded = keys.map((k) => ({
1027
+ cooldownId: keyHashOf(`openai\0${bridgeBase}\0${k}`),
1028
+ key: k,
1029
+ baseUrl: bridgeBase,
1030
+ protocol: "openai",
1031
+ label: "anthropic-bridge",
1032
+ }));
1033
+ candidates = this.keyPool.pickFromCandidates(poolId, expanded, sessionKey, stickyCfg.enabled, "rotate");
947
1034
  if (!candidates.length) {
948
1035
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
949
1036
  res.end(protocolErrorBody(route.protocol, "Anthropic 协议桥接未配置可用 OpenAI 兼容密钥。", "missing_api_key"));
@@ -952,8 +1039,14 @@ export class LocalProxy {
952
1039
  }
953
1040
  else {
954
1041
  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);
1042
+ const expanded = upstream.keys.map((k) => ({
1043
+ cooldownId: keyHashOf(k),
1044
+ key: k,
1045
+ baseUrl: upstream.baseUrl,
1046
+ protocol: route.protocol,
1047
+ label: route.poolId,
1048
+ }));
1049
+ candidates = this.keyPool.pickFromCandidates(poolId, expanded, sessionKey, stickyCfg.enabled, "rotate");
957
1050
  if (!candidates.length) {
958
1051
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
959
1052
  res.end(protocolErrorBody(route.protocol, `上游 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
@@ -965,13 +1058,14 @@ export class LocalProxy {
965
1058
  const onClientAbort = () => controller.abort();
966
1059
  req.once("aborted", onClientAbort);
967
1060
  res.once("close", onClientAbort);
968
- const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 3);
1061
+ const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 6);
969
1062
  let finalResponse;
1063
+ let winningCandidate;
1064
+ let usedBridge = false;
970
1065
  let retries = 0;
971
1066
  let strippedSignatures = false;
972
- const upstreamAuthProtocol = useAnthropicBridge ? "openai" : route.protocol;
973
1067
  const reqStartedAt = Date.now();
974
- const buildUpstreamHeaders = (apiKey) => {
1068
+ const buildUpstreamHeaders = (cand, isBridged) => {
975
1069
  const headers = new Headers();
976
1070
  for (const [k, v] of Object.entries(req.headers)) {
977
1071
  const lower = k.toLowerCase();
@@ -979,7 +1073,7 @@ export class LocalProxy {
979
1073
  continue;
980
1074
  if (lower === "authorization" || lower === "x-api-key" || lower === "x-goog-api-key")
981
1075
  continue;
982
- if (useAnthropicBridge && (lower === "anthropic-version" || lower === "anthropic-beta"))
1076
+ if (isBridged && (lower === "anthropic-version" || lower === "anthropic-beta"))
983
1077
  continue;
984
1078
  if (Array.isArray(v))
985
1079
  headers.set(k, v.join(", "));
@@ -987,47 +1081,81 @@ export class LocalProxy {
987
1081
  headers.set(k, v);
988
1082
  }
989
1083
  if (useRelay) {
990
- headers.set("authorization", `Bearer ${apiKey}`);
1084
+ headers.set("authorization", `Bearer ${cand.key}`);
991
1085
  if (meta.taskId)
992
1086
  headers.set("x-lemma-task-id", meta.taskId);
993
1087
  if (meta.sessionId)
994
1088
  headers.set("x-lemma-session-id", meta.sessionId);
995
1089
  headers.set("x-lemma-member", meta.agent);
996
1090
  }
997
- else if (upstreamAuthProtocol === "anthropic") {
998
- headers.set("x-api-key", apiKey);
1091
+ else if (cand.protocol === "anthropic") {
1092
+ headers.set("x-api-key", cand.key);
999
1093
  }
1000
- else if (upstreamAuthProtocol === "gemini") {
1001
- headers.set("x-goog-api-key", apiKey);
1094
+ else if (cand.protocol === "gemini") {
1095
+ headers.set("x-goog-api-key", cand.key);
1002
1096
  }
1003
1097
  else {
1004
- headers.set("authorization", `Bearer ${apiKey}`);
1098
+ headers.set("authorization", `Bearer ${cand.key}`);
1005
1099
  }
1006
1100
  return headers;
1007
1101
  };
1102
+ const prepareCandidateRequest = (cand) => {
1103
+ if (useRelay)
1104
+ return { url: cand.baseUrl, body: outboundBody, isBridged: false };
1105
+ const isBridged = route.protocol === "anthropic" && route.subpath === "/v1/messages" && cand.protocol === "openai" && parsedBody !== undefined;
1106
+ const effectiveModel = cand.model ?? routedModel;
1107
+ if (isBridged) {
1108
+ const translated = anthropicToOpenAiRequest(parsedBody, effectiveModel ?? "gpt-4.1");
1109
+ return {
1110
+ url: joinUpstreamUrl(cand.baseUrl, "/v1/chat/completions", cleanSearch),
1111
+ body: Buffer.from(JSON.stringify(translated), "utf8"),
1112
+ isBridged: true,
1113
+ };
1114
+ }
1115
+ let bodyBuf = outboundBody;
1116
+ if (parsedBody && effectiveModel && effectiveModel !== parsedBody.model) {
1117
+ bodyBuf = Buffer.from(JSON.stringify({ ...parsedBody, model: effectiveModel }), "utf8");
1118
+ }
1119
+ return {
1120
+ url: joinUpstreamUrl(cand.baseUrl, route.subpath, cleanSearch),
1121
+ body: bodyBuf,
1122
+ isBridged: false,
1123
+ };
1124
+ };
1008
1125
  try {
1009
1126
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1010
- const apiKey = candidates[attempt];
1127
+ const cand = candidates[attempt];
1011
1128
  for (;;) {
1012
- const upstreamRes = await fetchFn(targetUrl, {
1129
+ const prep = prepareCandidateRequest(cand);
1130
+ const upstreamRes = await fetchFn(prep.url, {
1013
1131
  method: req.method ?? "POST",
1014
- headers: buildUpstreamHeaders(apiKey),
1015
- body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(outboundBody),
1132
+ headers: buildUpstreamHeaders(cand, prep.isBridged),
1133
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(prep.body),
1016
1134
  signal: controller.signal,
1017
1135
  });
1018
1136
  if (upstreamRes.ok) {
1019
1137
  if (!useRelay) {
1020
- this.keyPool.markSuccess(poolId, sessionKey, apiKey, stickyCfg.ttlSeconds, stickyCfg.enabled);
1138
+ this.keyPool.markSuccessById(poolId, sessionKey, cand.cooldownId, stickyCfg.ttlSeconds, stickyCfg.enabled, {
1139
+ label: cand.label,
1140
+ protocol: cand.protocol,
1141
+ failover: attempt > 0,
1142
+ });
1021
1143
  }
1022
1144
  finalResponse = upstreamRes;
1145
+ winningCandidate = cand;
1146
+ usedBridge = prep.isBridged;
1023
1147
  break;
1024
1148
  }
1025
1149
  const errText = await upstreamRes.text();
1026
1150
  // 若因跨账号/跨中转思考块签名失效返回 400:剥离兼容签名后用同一个健康 Key 重发一次,不误拉黑 Key
1027
- if (!useAnthropicBridge && !strippedSignatures && isSignatureRefused(upstreamRes.status, errText)) {
1028
- const stripped = stripIncompatibleSignatures(route.protocol, outboundBody);
1151
+ if (!prep.isBridged && !strippedSignatures && isSignatureRefused(upstreamRes.status, errText)) {
1152
+ const stripped = stripIncompatibleSignatures(route.protocol, prep.body);
1029
1153
  if (stripped.stripped) {
1030
1154
  outboundBody = stripped.body;
1155
+ try {
1156
+ parsedBody = JSON.parse(stripped.body.toString("utf8"));
1157
+ }
1158
+ catch { }
1031
1159
  strippedSignatures = true;
1032
1160
  retries++;
1033
1161
  continue;
@@ -1035,15 +1163,23 @@ export class LocalProxy {
1035
1163
  }
1036
1164
  if (!useRelay && attempt + 1 < maxAttempts && shouldFailoverStatus(upstreamRes.status, errText)) {
1037
1165
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1038
- this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
1166
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs, {
1167
+ label: cand.label,
1168
+ protocol: cand.protocol,
1169
+ });
1039
1170
  retries++;
1040
1171
  break;
1041
1172
  }
1042
1173
  if (!useRelay && shouldFailoverStatus(upstreamRes.status, errText)) {
1043
1174
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1044
- this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
1175
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs, {
1176
+ label: cand.label,
1177
+ protocol: cand.protocol,
1178
+ });
1045
1179
  }
1046
1180
  finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
1181
+ winningCandidate = cand;
1182
+ usedBridge = prep.isBridged;
1047
1183
  break;
1048
1184
  }
1049
1185
  if (finalResponse)
@@ -1077,7 +1213,7 @@ export class LocalProxy {
1077
1213
  });
1078
1214
  const resContentType = finalResponse.headers.get("content-type");
1079
1215
  const isSse = (resContentType ?? "").toLowerCase().includes("text/event-stream");
1080
- const translateBridgeOk = useAnthropicBridge && finalResponse.ok;
1216
+ const translateBridgeOk = usedBridge && finalResponse.ok;
1081
1217
  if (translateBridgeOk) {
1082
1218
  outHeaders["content-type"] = isSse ? "text/event-stream; charset=utf-8" : "application/json; charset=utf-8";
1083
1219
  }
@@ -1086,13 +1222,14 @@ export class LocalProxy {
1086
1222
  const restore = Boolean(proxyCfg?.redact.restoreInResponse && redactedCount > 0 && proxyCfg?.redact.action === "mask");
1087
1223
  const redactor = this.ensureRedactor(config);
1088
1224
  const unredactor = restore ? new StreamUnredactor((t) => redactor.restoreText(t, requestVault)) : undefined;
1225
+ const effectiveTargetModel = winningCandidate?.model ?? routedModel;
1089
1226
  let firstChunkAt;
1090
1227
  if (translateBridgeOk && !isSse) {
1091
1228
  try {
1092
1229
  const rawText = await finalResponse.text();
1093
1230
  firstChunkAt = Date.now();
1094
1231
  const parsedOai = JSON.parse(rawText);
1095
- const anthropicJson = openAiToAnthropicJsonResponse(parsedOai, requestedModel ?? routedModel ?? "unknown");
1232
+ const anthropicJson = openAiToAnthropicJsonResponse(parsedOai, requestedModel ?? effectiveTargetModel ?? "unknown");
1096
1233
  const encoded = JSON.stringify(anthropicJson);
1097
1234
  sniffer.push(encoded);
1098
1235
  const emitted = restore ? redactor.restoreText(encoded, requestVault) : encoded;
@@ -1104,7 +1241,7 @@ export class LocalProxy {
1104
1241
  }
1105
1242
  }
1106
1243
  else {
1107
- const sseTranslator = translateBridgeOk && isSse ? new OpenAiToAnthropicSseTranslator(requestedModel ?? routedModel ?? "unknown") : undefined;
1244
+ const sseTranslator = translateBridgeOk && isSse ? new OpenAiToAnthropicSseTranslator(requestedModel ?? effectiveTargetModel ?? "unknown") : undefined;
1108
1245
  if (finalResponse.body) {
1109
1246
  const decoder = new TextDecoder();
1110
1247
  const reader = finalResponse.body.getReader();
@@ -1163,7 +1300,7 @@ export class LocalProxy {
1163
1300
  const ttftMs = firstChunkAt !== undefined ? Math.max(0, firstChunkAt - reqStartedAt) : null;
1164
1301
  const usage = sniffer.toTokenUsage();
1165
1302
  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);
1303
+ const usedModel = usedBridge ? effectiveTargetModel : (sniffer.model ?? effectiveTargetModel ?? requestedModel);
1167
1304
  const hasTokens = usage.input > 0 || usage.output > 0 || (usage.cacheRead ?? 0) > 0;
1168
1305
  const costUsd = hasTokens ? calculateUsageCost(this.priceFor(meta, usedModel, config), usage) : undefined;
1169
1306
  this.recordModelMetric({
package/dist/terminal.js CHANGED
@@ -8,6 +8,7 @@ import { conversationWelcome, terminalLabel, terminalRow } from "./terminal-layo
8
8
  export const TERMINAL_COMMANDS = [
9
9
  ["agents", "成员和模型"],
10
10
  ["agent", "add / edit / show / enable / disable / model / key 成员配置"],
11
+ ["onboarding", "引导初始化模型凭据与本地网关"],
11
12
  ["setup", "引导配置总控模型、接口与凭据"],
12
13
  ["tool", "list / add / edit / key / remove / test 成员业务工具"],
13
14
  ["limits", "查看并发和预算;edit 引导修改限制"],
@@ -207,6 +208,9 @@ export class AgentTerminal {
207
208
  thinkingHidden = false;
208
209
  picker;
209
210
  disposePicker;
211
+ promptDock = new Container();
212
+ dockActive = false;
213
+ disposeDock;
210
214
  size = 0;
211
215
  stopped = false;
212
216
  started = false;
@@ -268,7 +272,8 @@ export class AgentTerminal {
268
272
  visible: ({ height }) => this.tasksVisible && height >= 14,
269
273
  },
270
274
  { component: new Line((width) => this.statusLine(width)), shrink: 0 },
271
- { component: this.editor, maxSize: 9, minSize: 3 },
275
+ { component: this.editor, maxSize: 9, minSize: 3, visible: () => !this.dockActive },
276
+ { component: this.promptDock, maxSize: 18, shrink: 1, visible: () => this.dockActive },
272
277
  {
273
278
  component: new Line((width) => this.helpLine(width)),
274
279
  shrink: 0,
@@ -278,7 +283,7 @@ export class AgentTerminal {
278
283
  this.bind(options);
279
284
  this.tui.setFocus(this.editor);
280
285
  this.tui.addInputListener((data) => {
281
- if (this.picker) {
286
+ if (this.picker || this.dockActive) {
282
287
  if (matchesKey(data, "ctrl+c") || matchesKey(data, "ctrl+k")) {
283
288
  this.closePicker();
284
289
  return { consume: true };
@@ -420,7 +425,14 @@ export class AgentTerminal {
420
425
  const tools = (this.view?.tools ?? this.view?.live.tools ?? []).filter((tool) => !["done", "error", "aborted", "interrupted"].includes(tool.status)), queued = tools.filter((tool) => ["waiting", "sleeping", "pending"].includes(tool.status)).length;
421
426
  const inbox = this.view?.live.inbox.length ?? 0;
422
427
  const activity = `${tools.length ? ` · 工具 ${tools.length}${queued ? `(等待 ${queued})` : ""}` : ""}${inbox ? ` · 待处理消息 ${inbox}` : ""}${s.jobs.length ? ` · 后台 ${s.jobs.map((job) => terminalLabel(job)).join(" / ")}` : ""}`;
423
- return terminalRow(` ${state}${activity}`, `成员 ${budget} · 待合并 ${s.pending}`, width);
428
+ const proxyHint = s.proxy?.enabled
429
+ ? s.proxy.cooled > 0
430
+ ? ` · ${c.yellow(`冷却 ${s.proxy.cooled}`)}`
431
+ : s.proxy.retries > 0
432
+ ? ` · 切流 ${s.proxy.retries}`
433
+ : ""
434
+ : "";
435
+ return terminalRow(` ${state}${activity}`, `成员 ${budget} · 待合并 ${s.pending}${proxyHint}`, width);
424
436
  }
425
437
  start() {
426
438
  if (this.started || this.stopped)
@@ -679,31 +691,28 @@ export class AgentTerminal {
679
691
  question(options) {
680
692
  if (this.stopped)
681
693
  return Promise.reject(new Error("终端已关闭。"));
682
- this.closePicker();
683
694
  return new Promise((resolve, reject) => {
684
695
  const input = new SettingsInput({ placeholder: options.value ? `留空保留:${plain(options.value, 180)}` : "请输入" });
685
696
  input.secret = options.secret === true;
686
697
  const panel = new Container();
687
- panel.addChild(new Text(c.cyan(plain(options.title, 300)), 1, 1));
698
+ panel.addChild(new Text(c.cyan(plain(options.title, 300)), 1, 0));
699
+ for (const line of options.lines ?? [])
700
+ panel.addChild(new Text(plain(line, 260), 1, 0));
688
701
  panel.addChild(input);
689
- panel.addChild(new Text(c.dim("Enter 确认 · Esc / Ctrl+C 取消(不会发送给模型)"), 1, 1));
702
+ panel.addChild(new Text(c.dim("Enter 确认 · Esc / Ctrl+C 取消(不会发送给模型)"), 1, 0));
690
703
  let settled = false;
691
- input.onSubmit = (value) => { settled = true; input.setValue(""); this.closePicker(); resolve(value); };
692
- input.onEscape = () => this.closePicker();
693
- this.picker = this.tui.showOverlay(panel, { width: "88%", maxHeight: "85%", anchor: "center", margin: 1 });
694
- this.disposePicker = () => { input.setValue(""); if (!settled)
695
- reject(new Error("配置已取消,未保存。")); };
696
- this.tui.setFocus(input);
697
- this.tui.requestRender();
704
+ input.onSubmit = (value) => { settled = true; input.setValue(""); this.closeDock(); resolve(value); };
705
+ input.onEscape = () => this.closeDock();
706
+ this.showDock(panel, input, () => { input.setValue(""); if (!settled)
707
+ reject(new Error("配置已取消,未保存。")); });
698
708
  });
699
709
  }
700
- pickSelectOverlay(options) {
710
+ select(options) {
701
711
  if (this.stopped || !options.items.length)
702
712
  return Promise.resolve(undefined);
703
- this.closePicker();
704
713
  return new Promise((resolve) => {
705
714
  const panel = new Container();
706
- panel.addChild(new Text(c.cyan(plain(options.title, 200)), 1, 1));
715
+ panel.addChild(new Text(c.cyan(plain(options.title, 200)), 1, 0));
707
716
  for (const line of options.lines ?? [])
708
717
  panel.addChild(new Text(plain(line, 260), 1, 0));
709
718
  const list = new SelectList(options.items, Math.min(8, options.items.length), selectTheme, { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 38 });
@@ -716,17 +725,14 @@ export class AgentTerminal {
716
725
  };
717
726
  list.onSelect = (item) => {
718
727
  settled = true;
719
- this.closePicker();
728
+ this.closeDock();
720
729
  resolve(item.value);
721
730
  };
722
- list.onCancel = () => this.closePicker();
731
+ list.onCancel = () => this.closeDock();
723
732
  list.onSelectionChange = () => this.tui.requestRender();
724
733
  panel.addChild(list);
725
- panel.addChild(new Text(c.dim(options.hint ?? "↑↓ 选择 · Enter 确认 · Esc / Ctrl+C 取消"), 1, 1));
726
- this.picker = this.tui.showOverlay(panel, { width: "90%", maxHeight: "88%", anchor: "center", margin: 1 });
727
- this.disposePicker = () => finish(undefined);
728
- this.tui.setFocus(list);
729
- this.tui.requestRender();
734
+ panel.addChild(new Text(c.dim(options.hint ?? "↑↓ 选择 · Enter 确认 · Esc / Ctrl+C 取消"), 1, 0));
735
+ this.showDock(panel, list, () => finish(undefined));
730
736
  });
731
737
  }
732
738
  async confirmApply(req) {
@@ -748,7 +754,7 @@ export class AgentTerminal {
748
754
  : []),
749
755
  { value: "reject", label: "暂不合并", description: "保留在待合并队列,稍后用 /apply 或网页处理" },
750
756
  ];
751
- const picked = await this.pickSelectOverlay({
757
+ const picked = await this.select({
752
758
  title: "⚑ 请求确认合并改动到工作区",
753
759
  lines,
754
760
  items: choices,
@@ -774,20 +780,42 @@ export class AgentTerminal {
774
780
  description: `${item.filesCount} 文件 +${item.add} −${item.del} · ${plain(item.task, 55)}`,
775
781
  })),
776
782
  ];
777
- return this.pickSelectOverlay({
783
+ return this.select({
778
784
  title: mode === "/apply" ? "选择要合并的改动 (/apply)" : "选择要丢弃的改动 (/drop)",
779
785
  items: choices,
780
786
  });
781
787
  }
782
- closePicker() {
783
- if (!this.picker)
788
+ showDock(panel, focus, dispose) {
789
+ this.closePicker();
790
+ this.dockActive = true;
791
+ this.promptDock.clear();
792
+ this.promptDock.addChild(new Line((width) => c.cyan("─".repeat(Math.max(1, width)))));
793
+ this.promptDock.addChild(panel);
794
+ this.disposeDock = dispose;
795
+ this.tui.setFocus(focus);
796
+ this.tui.requestRender();
797
+ }
798
+ closeDock() {
799
+ if (!this.dockActive)
784
800
  return;
785
- const picker = this.picker, dispose = this.disposePicker;
786
- this.picker = undefined;
787
- this.disposePicker = undefined;
788
- picker.hide();
801
+ const dispose = this.disposeDock;
802
+ this.dockActive = false;
803
+ this.disposeDock = undefined;
804
+ this.promptDock.clear();
789
805
  dispose?.();
790
806
  this.tui.setFocus(this.editor);
807
+ this.tui.requestRender();
808
+ }
809
+ closePicker() {
810
+ if (this.picker) {
811
+ const picker = this.picker, dispose = this.disposePicker;
812
+ this.picker = undefined;
813
+ this.disposePicker = undefined;
814
+ picker.hide();
815
+ dispose?.();
816
+ this.tui.setFocus(this.editor);
817
+ }
818
+ this.closeDock();
791
819
  }
792
820
  stop() {
793
821
  if (this.stopped)