lemma-agent 1.1.1 → 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
@@ -175,7 +175,7 @@ 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();
@@ -232,36 +232,36 @@ export class StickyKeyPool {
232
232
  catch { }
233
233
  }
234
234
  }
235
- cooldownKey(poolId, key) {
236
- return `${poolId}\0${key}`;
235
+ cooldownKey(poolId, cooldownId) {
236
+ return `${poolId}\0${cooldownId}`;
237
237
  }
238
- pickCandidates(poolId, keys, sessionKey, stickyEnabled) {
239
- if (!keys.length)
238
+ pickFromCandidates(poolId, candidates, sessionKey, stickyEnabled, strategy = "rotate") {
239
+ if (!candidates.length)
240
240
  return [];
241
241
  const t = this.now();
242
242
  const healthy = [];
243
243
  const resting = [];
244
- for (const key of keys) {
245
- 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;
246
246
  if (until <= t) {
247
247
  if (until > 0)
248
- this.cooldown.delete(this.cooldownKey(poolId, key));
249
- healthy.push(key);
248
+ this.cooldown.delete(this.cooldownKey(poolId, item.cooldownId));
249
+ healthy.push(item);
250
250
  }
251
251
  else {
252
- resting.push({ key, until });
252
+ resting.push({ item, until });
253
253
  }
254
254
  }
255
- // 若池内全部 Key 都在冷却,按最早解禁时间兜底放行,避免假死
255
+ // 若池内全部候选都在冷却,按最早解禁时间兜底放行,避免假死
256
256
  const baseList = healthy.length
257
257
  ? healthy
258
- : 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);
259
259
  const ordered = [];
260
260
  if (stickyEnabled && sessionKey) {
261
261
  const stickKey = `${poolId}\0${sessionKey}`;
262
262
  const hit = this.sticky.get(stickKey);
263
263
  if (hit && hit.expiresAt > t) {
264
- const matched = baseList.find((k) => keyHashOf(k) === hit.keyHash);
264
+ const matched = baseList.find((c) => c.cooldownId === hit.keyHash);
265
265
  if (matched)
266
266
  ordered.push(matched);
267
267
  }
@@ -269,17 +269,24 @@ export class StickyKeyPool {
269
269
  this.sticky.delete(stickKey);
270
270
  }
271
271
  }
272
- const cursor = this.rrCursor.get(poolId) ?? 0;
273
- const rotated = baseList.map((_, idx) => baseList[(cursor + idx) % baseList.length]);
274
- this.rrCursor.set(poolId, (cursor + 1) % Math.max(1, baseList.length));
275
- for (const key of rotated) {
276
- if (!ordered.includes(key))
277
- ordered.push(key);
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);
278
281
  }
279
282
  return ordered;
280
283
  }
281
- markSuccess(poolId, sessionKey, key, ttlSeconds, stickyEnabled) {
282
- 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));
283
290
  if (stickyEnabled && sessionKey && ttlSeconds > 0) {
284
291
  const stickKey = `${poolId}\0${sessionKey}`;
285
292
  if (this.sticky.size >= MAX_STICKY_ENTRIES && !this.sticky.has(stickKey)) {
@@ -287,20 +294,26 @@ export class StickyKeyPool {
287
294
  if (oldest !== undefined)
288
295
  this.sticky.delete(oldest);
289
296
  }
290
- this.sticky.set(stickKey, { keyHash: keyHashOf(key), expiresAt: this.now() + ttlSeconds * 1000 });
297
+ this.sticky.set(stickKey, { keyHash: cooldownId, expiresAt: this.now() + ttlSeconds * 1000 });
291
298
  this.persist();
292
299
  }
293
300
  }
294
- markFailed(poolId, sessionKey, key, cooldownMs) {
295
- 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);
296
303
  if (sessionKey) {
297
304
  const stickKey = `${poolId}\0${sessionKey}`;
298
- if (this.sticky.get(stickKey)?.keyHash === keyHashOf(key)) {
305
+ if (this.sticky.get(stickKey)?.keyHash === cooldownId) {
299
306
  this.sticky.delete(stickKey);
300
307
  this.persist();
301
308
  }
302
309
  }
303
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
+ }
304
317
  status() {
305
318
  const t = this.now();
306
319
  let activeStickyCount = 0;
@@ -313,8 +326,8 @@ export class StickyKeyPool {
313
326
  continue;
314
327
  const sep = ck.indexOf("\0");
315
328
  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) });
329
+ const cooldownId = sep >= 0 ? ck.slice(sep + 1) : "";
330
+ cooledKeys.push({ poolId, keyHash: cooldownId, remainingSec: Math.ceil((until - t) / 1000) });
318
331
  }
319
332
  return { activeStickyCount, cooledKeys };
320
333
  }
@@ -891,7 +904,9 @@ export class LocalProxy {
891
904
  searchParams.delete("key");
892
905
  const cleanSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
893
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;
894
908
  const useAnthropicBridge = !useRelay &&
909
+ !groupCfg?.targets.length &&
895
910
  route.protocol === "anthropic" &&
896
911
  route.subpath === "/v1/messages" &&
897
912
  Boolean(proxyCfg?.anthropicBridge?.enabled) &&
@@ -906,14 +921,6 @@ export class LocalProxy {
906
921
  const mapped = (routedModel ? bridgeMap?.[routedModel] : undefined) ?? (routedModel ? proxyCfg?.modelMap?.[routedModel] : undefined);
907
922
  if (mapped)
908
923
  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
924
  }
918
925
  const stickyCfg = proxyCfg?.sticky ?? { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 };
919
926
  const sessionKey = meta.sessionId ||
@@ -922,28 +929,63 @@ export class LocalProxy {
922
929
  (typeof req.headers["x-codex-window-id"] === "string" ? req.headers["x-codex-window-id"] : undefined) ||
923
930
  meta.callId ||
924
931
  meta.agent;
925
- const poolId = useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
926
- let targetUrl;
932
+ const poolId = groupCfg?.targets.length ? `group:${route.protocol}` : useAnthropicBridge ? "bridge:anthropic-openai" : route.poolId;
927
933
  let candidates;
928
934
  if (useRelay) {
929
935
  const relayUrl = proxyCfg.relay.url;
930
936
  const relayPath = route.memberKind ? `/member/${route.memberKind}${route.subpath}` : `/${route.protocol}${route.subpath}`;
931
- targetUrl = joinUpstreamUrl(relayUrl, relayPath, cleanSearch);
932
937
  const relayToken = this.resolveRelayToken(config);
933
938
  if (!relayToken) {
934
939
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
935
940
  res.end(protocolErrorBody(route.protocol, "托管中转模式缺少 relay token,请检查环境变量或本机凭据。", "missing_relay_token"));
936
941
  return true;
937
942
  }
938
- 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
+ }
939
975
  }
940
976
  else if (useAnthropicBridge) {
941
977
  const bridge = proxyCfg.anthropicBridge;
942
978
  const bridgeBase = bridge.baseUrl ?? proxyCfg?.upstreams.openai.baseUrl ?? "https://api.openai.com";
943
979
  const bridgeKeys = resolveKeyPool(bridge);
944
980
  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);
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");
947
989
  if (!candidates.length) {
948
990
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
949
991
  res.end(protocolErrorBody(route.protocol, "Anthropic 协议桥接未配置可用 OpenAI 兼容密钥。", "missing_api_key"));
@@ -952,8 +994,14 @@ export class LocalProxy {
952
994
  }
953
995
  else {
954
996
  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);
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");
957
1005
  if (!candidates.length) {
958
1006
  res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
959
1007
  res.end(protocolErrorBody(route.protocol, `上游 ${poolId} 未配置可用 API Key。`, "missing_api_key"));
@@ -965,13 +1013,14 @@ export class LocalProxy {
965
1013
  const onClientAbort = () => controller.abort();
966
1014
  req.once("aborted", onClientAbort);
967
1015
  res.once("close", onClientAbort);
968
- const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 3);
1016
+ const maxAttempts = useRelay ? 1 : Math.min(candidates.length, 6);
969
1017
  let finalResponse;
1018
+ let winningCandidate;
1019
+ let usedBridge = false;
970
1020
  let retries = 0;
971
1021
  let strippedSignatures = false;
972
- const upstreamAuthProtocol = useAnthropicBridge ? "openai" : route.protocol;
973
1022
  const reqStartedAt = Date.now();
974
- const buildUpstreamHeaders = (apiKey) => {
1023
+ const buildUpstreamHeaders = (cand, isBridged) => {
975
1024
  const headers = new Headers();
976
1025
  for (const [k, v] of Object.entries(req.headers)) {
977
1026
  const lower = k.toLowerCase();
@@ -979,7 +1028,7 @@ export class LocalProxy {
979
1028
  continue;
980
1029
  if (lower === "authorization" || lower === "x-api-key" || lower === "x-goog-api-key")
981
1030
  continue;
982
- if (useAnthropicBridge && (lower === "anthropic-version" || lower === "anthropic-beta"))
1031
+ if (isBridged && (lower === "anthropic-version" || lower === "anthropic-beta"))
983
1032
  continue;
984
1033
  if (Array.isArray(v))
985
1034
  headers.set(k, v.join(", "));
@@ -987,47 +1036,77 @@ export class LocalProxy {
987
1036
  headers.set(k, v);
988
1037
  }
989
1038
  if (useRelay) {
990
- headers.set("authorization", `Bearer ${apiKey}`);
1039
+ headers.set("authorization", `Bearer ${cand.key}`);
991
1040
  if (meta.taskId)
992
1041
  headers.set("x-lemma-task-id", meta.taskId);
993
1042
  if (meta.sessionId)
994
1043
  headers.set("x-lemma-session-id", meta.sessionId);
995
1044
  headers.set("x-lemma-member", meta.agent);
996
1045
  }
997
- else if (upstreamAuthProtocol === "anthropic") {
998
- headers.set("x-api-key", apiKey);
1046
+ else if (cand.protocol === "anthropic") {
1047
+ headers.set("x-api-key", cand.key);
999
1048
  }
1000
- else if (upstreamAuthProtocol === "gemini") {
1001
- headers.set("x-goog-api-key", apiKey);
1049
+ else if (cand.protocol === "gemini") {
1050
+ headers.set("x-goog-api-key", cand.key);
1002
1051
  }
1003
1052
  else {
1004
- headers.set("authorization", `Bearer ${apiKey}`);
1053
+ headers.set("authorization", `Bearer ${cand.key}`);
1005
1054
  }
1006
1055
  return headers;
1007
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
+ };
1008
1080
  try {
1009
1081
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1010
- const apiKey = candidates[attempt];
1082
+ const cand = candidates[attempt];
1011
1083
  for (;;) {
1012
- const upstreamRes = await fetchFn(targetUrl, {
1084
+ const prep = prepareCandidateRequest(cand);
1085
+ const upstreamRes = await fetchFn(prep.url, {
1013
1086
  method: req.method ?? "POST",
1014
- headers: buildUpstreamHeaders(apiKey),
1015
- body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(outboundBody),
1087
+ headers: buildUpstreamHeaders(cand, prep.isBridged),
1088
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : new Uint8Array(prep.body),
1016
1089
  signal: controller.signal,
1017
1090
  });
1018
1091
  if (upstreamRes.ok) {
1019
1092
  if (!useRelay) {
1020
- this.keyPool.markSuccess(poolId, sessionKey, apiKey, stickyCfg.ttlSeconds, stickyCfg.enabled);
1093
+ this.keyPool.markSuccessById(poolId, sessionKey, cand.cooldownId, stickyCfg.ttlSeconds, stickyCfg.enabled);
1021
1094
  }
1022
1095
  finalResponse = upstreamRes;
1096
+ winningCandidate = cand;
1097
+ usedBridge = prep.isBridged;
1023
1098
  break;
1024
1099
  }
1025
1100
  const errText = await upstreamRes.text();
1026
1101
  // 若因跨账号/跨中转思考块签名失效返回 400:剥离兼容签名后用同一个健康 Key 重发一次,不误拉黑 Key
1027
- if (!useAnthropicBridge && !strippedSignatures && isSignatureRefused(upstreamRes.status, errText)) {
1028
- const stripped = stripIncompatibleSignatures(route.protocol, outboundBody);
1102
+ if (!prep.isBridged && !strippedSignatures && isSignatureRefused(upstreamRes.status, errText)) {
1103
+ const stripped = stripIncompatibleSignatures(route.protocol, prep.body);
1029
1104
  if (stripped.stripped) {
1030
1105
  outboundBody = stripped.body;
1106
+ try {
1107
+ parsedBody = JSON.parse(stripped.body.toString("utf8"));
1108
+ }
1109
+ catch { }
1031
1110
  strippedSignatures = true;
1032
1111
  retries++;
1033
1112
  continue;
@@ -1035,15 +1114,17 @@ export class LocalProxy {
1035
1114
  }
1036
1115
  if (!useRelay && attempt + 1 < maxAttempts && shouldFailoverStatus(upstreamRes.status, errText)) {
1037
1116
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1038
- this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
1117
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs);
1039
1118
  retries++;
1040
1119
  break;
1041
1120
  }
1042
1121
  if (!useRelay && shouldFailoverStatus(upstreamRes.status, errText)) {
1043
1122
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1044
- this.keyPool.markFailed(poolId, sessionKey, apiKey, cooldownMs);
1123
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs);
1045
1124
  }
1046
1125
  finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
1126
+ winningCandidate = cand;
1127
+ usedBridge = prep.isBridged;
1047
1128
  break;
1048
1129
  }
1049
1130
  if (finalResponse)
@@ -1077,7 +1158,7 @@ export class LocalProxy {
1077
1158
  });
1078
1159
  const resContentType = finalResponse.headers.get("content-type");
1079
1160
  const isSse = (resContentType ?? "").toLowerCase().includes("text/event-stream");
1080
- const translateBridgeOk = useAnthropicBridge && finalResponse.ok;
1161
+ const translateBridgeOk = usedBridge && finalResponse.ok;
1081
1162
  if (translateBridgeOk) {
1082
1163
  outHeaders["content-type"] = isSse ? "text/event-stream; charset=utf-8" : "application/json; charset=utf-8";
1083
1164
  }
@@ -1086,13 +1167,14 @@ export class LocalProxy {
1086
1167
  const restore = Boolean(proxyCfg?.redact.restoreInResponse && redactedCount > 0 && proxyCfg?.redact.action === "mask");
1087
1168
  const redactor = this.ensureRedactor(config);
1088
1169
  const unredactor = restore ? new StreamUnredactor((t) => redactor.restoreText(t, requestVault)) : undefined;
1170
+ const effectiveTargetModel = winningCandidate?.model ?? routedModel;
1089
1171
  let firstChunkAt;
1090
1172
  if (translateBridgeOk && !isSse) {
1091
1173
  try {
1092
1174
  const rawText = await finalResponse.text();
1093
1175
  firstChunkAt = Date.now();
1094
1176
  const parsedOai = JSON.parse(rawText);
1095
- const anthropicJson = openAiToAnthropicJsonResponse(parsedOai, requestedModel ?? routedModel ?? "unknown");
1177
+ const anthropicJson = openAiToAnthropicJsonResponse(parsedOai, requestedModel ?? effectiveTargetModel ?? "unknown");
1096
1178
  const encoded = JSON.stringify(anthropicJson);
1097
1179
  sniffer.push(encoded);
1098
1180
  const emitted = restore ? redactor.restoreText(encoded, requestVault) : encoded;
@@ -1104,7 +1186,7 @@ export class LocalProxy {
1104
1186
  }
1105
1187
  }
1106
1188
  else {
1107
- const sseTranslator = translateBridgeOk && isSse ? new OpenAiToAnthropicSseTranslator(requestedModel ?? routedModel ?? "unknown") : undefined;
1189
+ const sseTranslator = translateBridgeOk && isSse ? new OpenAiToAnthropicSseTranslator(requestedModel ?? effectiveTargetModel ?? "unknown") : undefined;
1108
1190
  if (finalResponse.body) {
1109
1191
  const decoder = new TextDecoder();
1110
1192
  const reader = finalResponse.body.getReader();
@@ -1163,7 +1245,7 @@ export class LocalProxy {
1163
1245
  const ttftMs = firstChunkAt !== undefined ? Math.max(0, firstChunkAt - reqStartedAt) : null;
1164
1246
  const usage = sniffer.toTokenUsage();
1165
1247
  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);
1248
+ const usedModel = usedBridge ? effectiveTargetModel : (sniffer.model ?? effectiveTargetModel ?? requestedModel);
1167
1249
  const hasTokens = usage.input > 0 || usage.output > 0 || (usage.cacheRead ?? 0) > 0;
1168
1250
  const costUsd = hasTokens ? calculateUsageCost(this.priceFor(meta, usedModel, config), usage) : undefined;
1169
1251
  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 };
@@ -679,31 +684,28 @@ export class AgentTerminal {
679
684
  question(options) {
680
685
  if (this.stopped)
681
686
  return Promise.reject(new Error("终端已关闭。"));
682
- this.closePicker();
683
687
  return new Promise((resolve, reject) => {
684
688
  const input = new SettingsInput({ placeholder: options.value ? `留空保留:${plain(options.value, 180)}` : "请输入" });
685
689
  input.secret = options.secret === true;
686
690
  const panel = new Container();
687
- panel.addChild(new Text(c.cyan(plain(options.title, 300)), 1, 1));
691
+ panel.addChild(new Text(c.cyan(plain(options.title, 300)), 1, 0));
692
+ for (const line of options.lines ?? [])
693
+ panel.addChild(new Text(plain(line, 260), 1, 0));
688
694
  panel.addChild(input);
689
- panel.addChild(new Text(c.dim("Enter 确认 · Esc / Ctrl+C 取消(不会发送给模型)"), 1, 1));
695
+ panel.addChild(new Text(c.dim("Enter 确认 · Esc / Ctrl+C 取消(不会发送给模型)"), 1, 0));
690
696
  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();
697
+ input.onSubmit = (value) => { settled = true; input.setValue(""); this.closeDock(); resolve(value); };
698
+ input.onEscape = () => this.closeDock();
699
+ this.showDock(panel, input, () => { input.setValue(""); if (!settled)
700
+ reject(new Error("配置已取消,未保存。")); });
698
701
  });
699
702
  }
700
- pickSelectOverlay(options) {
703
+ select(options) {
701
704
  if (this.stopped || !options.items.length)
702
705
  return Promise.resolve(undefined);
703
- this.closePicker();
704
706
  return new Promise((resolve) => {
705
707
  const panel = new Container();
706
- panel.addChild(new Text(c.cyan(plain(options.title, 200)), 1, 1));
708
+ panel.addChild(new Text(c.cyan(plain(options.title, 200)), 1, 0));
707
709
  for (const line of options.lines ?? [])
708
710
  panel.addChild(new Text(plain(line, 260), 1, 0));
709
711
  const list = new SelectList(options.items, Math.min(8, options.items.length), selectTheme, { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 38 });
@@ -716,17 +718,14 @@ export class AgentTerminal {
716
718
  };
717
719
  list.onSelect = (item) => {
718
720
  settled = true;
719
- this.closePicker();
721
+ this.closeDock();
720
722
  resolve(item.value);
721
723
  };
722
- list.onCancel = () => this.closePicker();
724
+ list.onCancel = () => this.closeDock();
723
725
  list.onSelectionChange = () => this.tui.requestRender();
724
726
  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();
727
+ panel.addChild(new Text(c.dim(options.hint ?? "↑↓ 选择 · Enter 确认 · Esc / Ctrl+C 取消"), 1, 0));
728
+ this.showDock(panel, list, () => finish(undefined));
730
729
  });
731
730
  }
732
731
  async confirmApply(req) {
@@ -748,7 +747,7 @@ export class AgentTerminal {
748
747
  : []),
749
748
  { value: "reject", label: "暂不合并", description: "保留在待合并队列,稍后用 /apply 或网页处理" },
750
749
  ];
751
- const picked = await this.pickSelectOverlay({
750
+ const picked = await this.select({
752
751
  title: "⚑ 请求确认合并改动到工作区",
753
752
  lines,
754
753
  items: choices,
@@ -774,20 +773,42 @@ export class AgentTerminal {
774
773
  description: `${item.filesCount} 文件 +${item.add} −${item.del} · ${plain(item.task, 55)}`,
775
774
  })),
776
775
  ];
777
- return this.pickSelectOverlay({
776
+ return this.select({
778
777
  title: mode === "/apply" ? "选择要合并的改动 (/apply)" : "选择要丢弃的改动 (/drop)",
779
778
  items: choices,
780
779
  });
781
780
  }
782
- closePicker() {
783
- if (!this.picker)
781
+ showDock(panel, focus, dispose) {
782
+ this.closePicker();
783
+ this.dockActive = true;
784
+ this.promptDock.clear();
785
+ this.promptDock.addChild(new Line((width) => c.cyan("─".repeat(Math.max(1, width)))));
786
+ this.promptDock.addChild(panel);
787
+ this.disposeDock = dispose;
788
+ this.tui.setFocus(focus);
789
+ this.tui.requestRender();
790
+ }
791
+ closeDock() {
792
+ if (!this.dockActive)
784
793
  return;
785
- const picker = this.picker, dispose = this.disposePicker;
786
- this.picker = undefined;
787
- this.disposePicker = undefined;
788
- picker.hide();
794
+ const dispose = this.disposeDock;
795
+ this.dockActive = false;
796
+ this.disposeDock = undefined;
797
+ this.promptDock.clear();
789
798
  dispose?.();
790
799
  this.tui.setFocus(this.editor);
800
+ this.tui.requestRender();
801
+ }
802
+ closePicker() {
803
+ if (this.picker) {
804
+ const picker = this.picker, dispose = this.disposePicker;
805
+ this.picker = undefined;
806
+ this.disposePicker = undefined;
807
+ picker.hide();
808
+ dispose?.();
809
+ this.tui.setFocus(this.editor);
810
+ }
811
+ this.closeDock();
791
812
  }
792
813
  stop() {
793
814
  if (this.stopped)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemma-agent",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Lemma: durable local multi-agent coding orchestration with isolated worktrees, blind review, and verified integration",
5
5
  "bin": {
6
6
  "lemma": "bin/lemma.mjs"