lemma-agent 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account-discovery.js +159 -0
- package/dist/admin.js +33 -0
- package/dist/app.js +1 -0
- package/dist/bridge.js +341 -0
- package/dist/config.js +87 -3
- package/dist/main.js +44 -2
- package/dist/onboarding.js +428 -0
- package/dist/proxy.js +598 -123
- package/dist/redact.js +9 -3
- package/dist/terminal.js +51 -30
- package/package.json +1 -1
- package/web/js/editors.js +96 -0
- package/web/js/views.js +51 -2
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { claudeSettingsEnv } from "./config.js";
|
|
5
|
+
import { readCredential } from "./credentials.js";
|
|
6
|
+
import { resolveKeyPool } from "./proxy.js";
|
|
7
|
+
function readJsonSafe(file) {
|
|
8
|
+
if (!existsSync(file))
|
|
9
|
+
return undefined;
|
|
10
|
+
try {
|
|
11
|
+
const raw = JSON.parse(readFileSync(file, "utf8"));
|
|
12
|
+
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : undefined;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function readEnvFileVar(file, key) {
|
|
19
|
+
if (!existsSync(file))
|
|
20
|
+
return undefined;
|
|
21
|
+
try {
|
|
22
|
+
const lines = readFileSync(file, "utf8").split(/\r?\n/);
|
|
23
|
+
for (const line of lines) {
|
|
24
|
+
const trimmed = line.trim();
|
|
25
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
26
|
+
continue;
|
|
27
|
+
const eq = trimmed.indexOf("=");
|
|
28
|
+
if (eq <= 0)
|
|
29
|
+
continue;
|
|
30
|
+
const k = trimmed.slice(0, eq).trim();
|
|
31
|
+
if (k === key)
|
|
32
|
+
return trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, "") || undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
function readTomlTopString(file, key) {
|
|
39
|
+
if (!existsSync(file))
|
|
40
|
+
return undefined;
|
|
41
|
+
try {
|
|
42
|
+
const lines = readFileSync(file, "utf8").split(/\r?\n/);
|
|
43
|
+
for (const line of lines) {
|
|
44
|
+
const trimmed = line.trim();
|
|
45
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
46
|
+
continue;
|
|
47
|
+
if (trimmed.startsWith("["))
|
|
48
|
+
break; // 只读顶层键
|
|
49
|
+
const m = trimmed.match(new RegExp(`^${key}\\s*=\\s*["']([^"']+)["']`));
|
|
50
|
+
if (m)
|
|
51
|
+
return m[1];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch { }
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 发现本机已有订阅账号、CLI 本地配置、环境变量与配置池(只读检测,绝不返回任何明文凭据)。
|
|
59
|
+
* 设置 `LEMMA_NO_ACCOUNTS=1` 时跳过本机 CLI 凭据文件扫描。
|
|
60
|
+
*/
|
|
61
|
+
export function discoverLocalAccounts(config, homeDir = homedir()) {
|
|
62
|
+
if (process.env.LEMMA_NO_ACCOUNTS === "1")
|
|
63
|
+
return [];
|
|
64
|
+
const out = [];
|
|
65
|
+
const up = config.proxy?.upstreams;
|
|
66
|
+
// 1. Claude Code(订阅 OAuth / settings.json / 网关 key 池)
|
|
67
|
+
{
|
|
68
|
+
const pool = resolveKeyPool(up?.anthropic ?? { apiKeyEnv: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] });
|
|
69
|
+
const claudeCfg = claudeSettingsEnv();
|
|
70
|
+
const creds = readJsonSafe(join(homeDir, ".claude", ".credentials.json"));
|
|
71
|
+
const claudeJson = readJsonSafe(join(homeDir, ".claude.json"));
|
|
72
|
+
const hasOauth = Boolean(creds?.claudeAiOauth?.accessToken || claudeJson?.oauthAccount);
|
|
73
|
+
const keyCount = pool.length + (claudeCfg.token && !pool.includes(claudeCfg.token) ? 1 : 0);
|
|
74
|
+
if (keyCount > 1) {
|
|
75
|
+
out.push({ provider: "claude", kind: "cli", detected: true, authMode: "key-pool", source: "proxy.upstreams.anthropic 多 Key 池", keyCount, baseUrl: up?.anthropic.baseUrl ?? claudeCfg.baseUrl });
|
|
76
|
+
}
|
|
77
|
+
else if (keyCount === 1) {
|
|
78
|
+
out.push({ provider: "claude", kind: "cli", detected: true, authMode: "api-key", source: claudeCfg.token && !pool.length ? "~/.claude/settings.json" : "环境变量 / 配置池", keyCount: 1, baseUrl: up?.anthropic.baseUrl ?? claudeCfg.baseUrl });
|
|
79
|
+
}
|
|
80
|
+
else if (hasOauth) {
|
|
81
|
+
out.push({ provider: "claude", kind: "cli", detected: true, authMode: "oauth", source: "~/.claude OAuth 登录态", keyCount: 0 });
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
out.push({ provider: "claude", kind: "cli", detected: false, authMode: "none", source: "未检测到凭据", keyCount: 0 });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// 2. Codex / OpenAI(auth.json / config.toml / 网关 key 池)
|
|
88
|
+
{
|
|
89
|
+
const pool = resolveKeyPool(up?.openai ?? { apiKeyEnv: ["OPENAI_API_KEY"] });
|
|
90
|
+
const codexAuth = readJsonSafe(join(homeDir, ".codex", "auth.json"));
|
|
91
|
+
const codexBase = readTomlTopString(join(homeDir, ".codex", "config.toml"), "openai_base_url");
|
|
92
|
+
const hasAuthKey = typeof codexAuth?.OPENAI_API_KEY === "string" && !!codexAuth.OPENAI_API_KEY.trim();
|
|
93
|
+
const hasOauth = Boolean(codexAuth?.tokens?.access_token || codexAuth?.access_token);
|
|
94
|
+
const keyCount = pool.length || (hasAuthKey ? 1 : 0);
|
|
95
|
+
if (keyCount > 1) {
|
|
96
|
+
out.push({ provider: "codex", kind: "cli", detected: true, authMode: "key-pool", source: "proxy.upstreams.openai 多 Key 池", keyCount, baseUrl: up?.openai.baseUrl ?? codexBase });
|
|
97
|
+
}
|
|
98
|
+
else if (keyCount === 1) {
|
|
99
|
+
out.push({ provider: "codex", kind: "cli", detected: true, authMode: "api-key", source: pool.length ? "环境变量 / 配置池" : "~/.codex/auth.json", keyCount: 1, baseUrl: up?.openai.baseUrl ?? codexBase });
|
|
100
|
+
}
|
|
101
|
+
else if (hasOauth) {
|
|
102
|
+
out.push({ provider: "codex", kind: "cli", detected: true, authMode: "oauth", source: "~/.codex OAuth 登录态", keyCount: 0, baseUrl: codexBase });
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
out.push({ provider: "codex", kind: "cli", detected: false, authMode: "none", source: "未检测到凭据", keyCount: 0 });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// 3. Gemini CLI(~/.gemini/.env / oauth_creds.json / 网关 key 池)
|
|
109
|
+
{
|
|
110
|
+
const pool = resolveKeyPool(up?.gemini ?? { apiKeyEnv: ["GEMINI_API_KEY"] });
|
|
111
|
+
const gemEnvPath = join(homeDir, ".gemini", ".env");
|
|
112
|
+
const gemKey = readEnvFileVar(gemEnvPath, "GEMINI_API_KEY");
|
|
113
|
+
const gemBase = readEnvFileVar(gemEnvPath, "GOOGLE_GEMINI_BASE_URL");
|
|
114
|
+
const gemOauth = readJsonSafe(join(homeDir, ".gemini", "oauth_creds.json"));
|
|
115
|
+
const hasOauth = Boolean(gemOauth?.access_token || gemOauth?.refresh_token);
|
|
116
|
+
const keyCount = pool.length || (gemKey ? 1 : 0);
|
|
117
|
+
if (keyCount > 1) {
|
|
118
|
+
out.push({ provider: "gemini", kind: "cli", detected: true, authMode: "key-pool", source: "proxy.upstreams.gemini 多 Key 池", keyCount, baseUrl: up?.gemini.baseUrl ?? gemBase });
|
|
119
|
+
}
|
|
120
|
+
else if (keyCount === 1) {
|
|
121
|
+
out.push({ provider: "gemini", kind: "cli", detected: true, authMode: "api-key", source: pool.length ? "环境变量 / 配置池" : "~/.gemini/.env", keyCount: 1, baseUrl: up?.gemini.baseUrl ?? gemBase });
|
|
122
|
+
}
|
|
123
|
+
else if (hasOauth) {
|
|
124
|
+
out.push({ provider: "gemini", kind: "cli", detected: true, authMode: "oauth", source: "~/.gemini OAuth 登录态", keyCount: 0, baseUrl: gemBase });
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
out.push({ provider: "gemini", kind: "cli", detected: false, authMode: "none", source: "未检测到凭据", keyCount: 0 });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// 4. API 成员(DeepSeek 等)
|
|
131
|
+
for (const [kind, agent] of Object.entries(config.agents)) {
|
|
132
|
+
if (!agent.enabled || !agent.api)
|
|
133
|
+
continue;
|
|
134
|
+
const keys = resolveKeyPool(agent.api);
|
|
135
|
+
out.push({
|
|
136
|
+
provider: kind,
|
|
137
|
+
kind: "api",
|
|
138
|
+
detected: keys.length > 0,
|
|
139
|
+
authMode: keys.length > 1 ? "key-pool" : keys.length === 1 ? "api-key" : "none",
|
|
140
|
+
source: keys.length > 1 ? `多 Key 池 (${keys.length})` : keys.length === 1 ? "配置环境变量 / 本机凭据" : "未配置密钥",
|
|
141
|
+
keyCount: keys.length,
|
|
142
|
+
baseUrl: agent.api.baseUrl,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
// 5. Hosted Relay 云端中转
|
|
146
|
+
if (config.proxy?.relay.url) {
|
|
147
|
+
const relayTok = config.proxy.relay.tokenEnv.some((e) => Boolean(process.env[e]?.trim())) || Boolean(readCredential(config.proxy.relay.credential));
|
|
148
|
+
out.push({
|
|
149
|
+
provider: "relay",
|
|
150
|
+
kind: "relay",
|
|
151
|
+
detected: relayTok,
|
|
152
|
+
authMode: relayTok ? "api-key" : "none",
|
|
153
|
+
source: relayTok ? "云端中转令牌已就绪" : "缺少 relay 令牌",
|
|
154
|
+
keyCount: relayTok ? 1 : 0,
|
|
155
|
+
baseUrl: config.proxy.relay.url,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
package/dist/admin.js
CHANGED
|
@@ -26,6 +26,9 @@ import { Learning } from "./learning.js";
|
|
|
26
26
|
import { Integrations, integrationSummary } from "./integrations.js";
|
|
27
27
|
import { readyTasks } from "./task-readiness.js";
|
|
28
28
|
import { Workflow } from "./task-workflow.js";
|
|
29
|
+
import { discoverLocalAccounts } from "./account-discovery.js";
|
|
30
|
+
import { applyOnboardingPlan, ONBOARDING_PRESETS } from "./onboarding.js";
|
|
31
|
+
import { orchestratorKeyWarning } from "./models.js";
|
|
29
32
|
import { parseToolResult, toViewItem, toViewLive } from "./view.js";
|
|
30
33
|
const WEB_DIR = fileURLToPath(new URL("../web/", import.meta.url));
|
|
31
34
|
const HOST = "127.0.0.1";
|
|
@@ -780,6 +783,12 @@ async function createAdminBinding(options, startedAt) {
|
|
|
780
783
|
budget: { ...config.budget, ...(await harness.snapshot(RunBudget, context)) },
|
|
781
784
|
resources: resourceSnapshot(await harness.snapshot(Resources, context)),
|
|
782
785
|
costLedger: Object.values((await harness.snapshot(CostLedger, context))?.entries ?? {}),
|
|
786
|
+
proxyStatus: {
|
|
787
|
+
...app.proxy.snapshot(),
|
|
788
|
+
discoveredAccounts: discoverLocalAccounts(config),
|
|
789
|
+
},
|
|
790
|
+
needsOnboarding: Boolean(orchestratorKeyWarning(config.orchestrator)),
|
|
791
|
+
onboardingPresets: ONBOARDING_PRESETS,
|
|
783
792
|
uxTelemetry: computeUxMetrics(((await harness.snapshot(UxTelemetry, context))?.events ?? [])),
|
|
784
793
|
modelStats: modelStats(),
|
|
785
794
|
project: {
|
|
@@ -1319,6 +1328,30 @@ async function createAdminBinding(options, startedAt) {
|
|
|
1319
1328
|
}));
|
|
1320
1329
|
return sendJson(res, 200, out);
|
|
1321
1330
|
}
|
|
1331
|
+
if (url.pathname === "/api/onboarding" && req.method === "POST") {
|
|
1332
|
+
const out = await mutateSettings(req, true, (body, draft, current) => {
|
|
1333
|
+
const mode = body.mode;
|
|
1334
|
+
if (mode !== "native" && mode !== "byok" && mode !== "relay")
|
|
1335
|
+
throw new Error("mode 需要为 native、byok 或 relay");
|
|
1336
|
+
const { next, summary } = applyOnboardingPlan(draft, current, {
|
|
1337
|
+
mode,
|
|
1338
|
+
preset: typeof body.preset === "string" ? body.preset : undefined,
|
|
1339
|
+
type: body.type === "anthropic-compatible" || body.type === "openai-compatible" ? body.type : undefined,
|
|
1340
|
+
baseUrl: typeof body.baseUrl === "string" ? body.baseUrl : undefined,
|
|
1341
|
+
modelId: typeof body.modelId === "string" ? body.modelId : undefined,
|
|
1342
|
+
secret: typeof body.secret === "string" ? body.secret : undefined,
|
|
1343
|
+
relayUrl: typeof body.relayUrl === "string" ? body.relayUrl : undefined,
|
|
1344
|
+
strategy: body.strategy === "order" || body.strategy === "rotate" ? body.strategy : undefined,
|
|
1345
|
+
enableBridge: typeof body.enableBridge === "boolean" ? body.enableBridge : undefined,
|
|
1346
|
+
enableProxy: typeof body.enableProxy === "boolean" ? body.enableProxy : undefined,
|
|
1347
|
+
redactAction: body.redactAction === "mask" || body.redactAction === "warn" || body.redactAction === "block" ? body.redactAction : undefined,
|
|
1348
|
+
compactModel: typeof body.compactModel === "string" ? body.compactModel : undefined,
|
|
1349
|
+
perRunUsd: body.perRunUsd === null || body.perRunUsd === "" ? null : body.perRunUsd === undefined ? undefined : Number(body.perRunUsd),
|
|
1350
|
+
});
|
|
1351
|
+
return { next, notify: `后台网页:${summary}`, result: { summary } };
|
|
1352
|
+
});
|
|
1353
|
+
return sendJson(res, 200, out);
|
|
1354
|
+
}
|
|
1322
1355
|
if (url.pathname === "/api/autonomy" && req.method === "POST") {
|
|
1323
1356
|
const out = await mutateSettings(req, false, (body, draft, current) => {
|
|
1324
1357
|
const checks = body.checks === undefined ? undefined : Array.isArray(body.checks) ? body.checks.map((item) => {
|
package/dist/app.js
CHANGED
|
@@ -66,6 +66,7 @@ export async function openApp(config, orchestrator, context, options = {}) {
|
|
|
66
66
|
let harnessRef;
|
|
67
67
|
const proxy = new LocalProxy({
|
|
68
68
|
getConfig: () => config,
|
|
69
|
+
affinityFile: options.memory || options.readOnly ? undefined : `${config.storage}.affinity.json`,
|
|
69
70
|
async checkBudget() {
|
|
70
71
|
const perRunUsd = config.budget.perRunUsd;
|
|
71
72
|
if (perRunUsd === null || !harnessRef)
|
package/dist/bridge.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
function textOfAnthropicContent(content) {
|
|
3
|
+
if (typeof content === "string")
|
|
4
|
+
return content;
|
|
5
|
+
if (!Array.isArray(content))
|
|
6
|
+
return "";
|
|
7
|
+
return content
|
|
8
|
+
.map((b) => (b && typeof b === "object" && b.type === "text" && typeof b.text === "string" ? b.text : ""))
|
|
9
|
+
.filter(Boolean)
|
|
10
|
+
.join("\n");
|
|
11
|
+
}
|
|
12
|
+
function mapStopReasonFromOpenAi(reason) {
|
|
13
|
+
if (reason === "tool_calls")
|
|
14
|
+
return "tool_use";
|
|
15
|
+
if (reason === "length")
|
|
16
|
+
return "max_tokens";
|
|
17
|
+
if (reason === "stop")
|
|
18
|
+
return "end_turn";
|
|
19
|
+
return "end_turn";
|
|
20
|
+
}
|
|
21
|
+
/** 将 Anthropic `/v1/messages` 请求体转换为 OpenAI `/v1/chat/completions` 请求体(含工具定义与 tool_result 转换) */
|
|
22
|
+
export function anthropicToOpenAiRequest(body, targetModel) {
|
|
23
|
+
const messages = [];
|
|
24
|
+
const sys = textOfAnthropicContent(body.system);
|
|
25
|
+
if (sys)
|
|
26
|
+
messages.push({ role: "system", content: sys });
|
|
27
|
+
if (Array.isArray(body.messages)) {
|
|
28
|
+
for (const msg of body.messages) {
|
|
29
|
+
if (!msg || typeof msg !== "object")
|
|
30
|
+
continue;
|
|
31
|
+
const role = msg.role === "assistant" ? "assistant" : "user";
|
|
32
|
+
if (typeof msg.content === "string") {
|
|
33
|
+
messages.push({ role, content: msg.content });
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!Array.isArray(msg.content))
|
|
37
|
+
continue;
|
|
38
|
+
if (role === "user") {
|
|
39
|
+
const textParts = [];
|
|
40
|
+
for (const block of msg.content) {
|
|
41
|
+
if (!block || typeof block !== "object")
|
|
42
|
+
continue;
|
|
43
|
+
if (block.type === "tool_result") {
|
|
44
|
+
const toolText = typeof block.content === "string" ? block.content : textOfAnthropicContent(block.content) || JSON.stringify(block.content ?? "");
|
|
45
|
+
messages.push({ role: "tool", tool_call_id: block.tool_use_id ?? "", content: toolText });
|
|
46
|
+
}
|
|
47
|
+
else if (block.type === "text" && typeof block.text === "string") {
|
|
48
|
+
textParts.push(block.text);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (textParts.length)
|
|
52
|
+
messages.push({ role: "user", content: textParts.join("\n") });
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
const textParts = [];
|
|
56
|
+
const toolCalls = [];
|
|
57
|
+
for (const block of msg.content) {
|
|
58
|
+
if (!block || typeof block !== "object")
|
|
59
|
+
continue;
|
|
60
|
+
if (block.type === "thinking" || block.type === "redacted_thinking")
|
|
61
|
+
continue;
|
|
62
|
+
if (block.type === "text" && typeof block.text === "string")
|
|
63
|
+
textParts.push(block.text);
|
|
64
|
+
if (block.type === "tool_use") {
|
|
65
|
+
toolCalls.push({
|
|
66
|
+
id: block.id ?? `call_${randomUUID().slice(0, 12)}`,
|
|
67
|
+
type: "function",
|
|
68
|
+
function: {
|
|
69
|
+
name: block.name ?? "tool",
|
|
70
|
+
arguments: typeof block.input === "string" ? block.input : JSON.stringify(block.input ?? {}),
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const outMsg = {
|
|
76
|
+
role: "assistant",
|
|
77
|
+
content: textParts.length ? textParts.join("\n") : null,
|
|
78
|
+
};
|
|
79
|
+
if (toolCalls.length)
|
|
80
|
+
outMsg.tool_calls = toolCalls;
|
|
81
|
+
if (outMsg.content !== null || toolCalls.length)
|
|
82
|
+
messages.push(outMsg);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const out = {
|
|
87
|
+
model: targetModel,
|
|
88
|
+
messages,
|
|
89
|
+
stream: Boolean(body.stream),
|
|
90
|
+
};
|
|
91
|
+
if (typeof body.max_tokens === "number")
|
|
92
|
+
out.max_tokens = body.max_tokens;
|
|
93
|
+
if (typeof body.temperature === "number")
|
|
94
|
+
out.temperature = body.temperature;
|
|
95
|
+
if (typeof body.top_p === "number")
|
|
96
|
+
out.top_p = body.top_p;
|
|
97
|
+
if (Array.isArray(body.stop_sequences) && body.stop_sequences.length)
|
|
98
|
+
out.stop = body.stop_sequences;
|
|
99
|
+
if (body.stream)
|
|
100
|
+
out.stream_options = { include_usage: true };
|
|
101
|
+
if (Array.isArray(body.tools) && body.tools.length) {
|
|
102
|
+
out.tools = body.tools.map((t) => ({
|
|
103
|
+
type: "function",
|
|
104
|
+
function: {
|
|
105
|
+
name: t.name,
|
|
106
|
+
...(t.description ? { description: t.description } : {}),
|
|
107
|
+
parameters: t.input_schema ?? { type: "object", properties: {} },
|
|
108
|
+
},
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
if (body.tool_choice && typeof body.tool_choice === "object") {
|
|
112
|
+
const tc = body.tool_choice;
|
|
113
|
+
if (tc.type === "any")
|
|
114
|
+
out.tool_choice = "required";
|
|
115
|
+
else if (tc.type === "auto" || tc.type === "none")
|
|
116
|
+
out.tool_choice = tc.type;
|
|
117
|
+
else if (tc.type === "tool" && tc.name)
|
|
118
|
+
out.tool_choice = { type: "function", function: { name: tc.name } };
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
/** 将非流式 OpenAI Chat Completions JSON 转换为 Anthropic Messages JSON */
|
|
123
|
+
export function openAiToAnthropicJsonResponse(oai, requestedModel) {
|
|
124
|
+
const choice = oai?.choices?.[0];
|
|
125
|
+
const msg = choice?.message ?? {};
|
|
126
|
+
const content = [];
|
|
127
|
+
if (typeof msg.content === "string" && msg.content) {
|
|
128
|
+
content.push({ type: "text", text: msg.content });
|
|
129
|
+
}
|
|
130
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
131
|
+
for (const tc of msg.tool_calls) {
|
|
132
|
+
let input = {};
|
|
133
|
+
try {
|
|
134
|
+
input = typeof tc.function?.arguments === "string" && tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
input = {};
|
|
138
|
+
}
|
|
139
|
+
content.push({
|
|
140
|
+
type: "tool_use",
|
|
141
|
+
id: tc.id ?? `toolu_${randomUUID().slice(0, 12)}`,
|
|
142
|
+
name: tc.function?.name ?? "tool",
|
|
143
|
+
input,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!content.length)
|
|
148
|
+
content.push({ type: "text", text: "" });
|
|
149
|
+
const u = oai?.usage ?? {};
|
|
150
|
+
const cached = u.prompt_tokens_details?.cached_tokens ?? 0;
|
|
151
|
+
const prompt = typeof u.prompt_tokens === "number" ? Math.max(0, u.prompt_tokens - cached) : 0;
|
|
152
|
+
return {
|
|
153
|
+
id: oai?.id ?? `msg_${randomUUID().slice(0, 16)}`,
|
|
154
|
+
type: "message",
|
|
155
|
+
role: "assistant",
|
|
156
|
+
model: requestedModel,
|
|
157
|
+
content,
|
|
158
|
+
stop_reason: mapStopReasonFromOpenAi(choice?.finish_reason),
|
|
159
|
+
stop_sequence: null,
|
|
160
|
+
usage: {
|
|
161
|
+
input_tokens: prompt,
|
|
162
|
+
output_tokens: typeof u.completion_tokens === "number" ? u.completion_tokens : 0,
|
|
163
|
+
...(cached > 0 ? { cache_read_input_tokens: cached } : {}),
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** 流式将 OpenAI Chat Completions SSE 实时翻译为 Anthropic Messages SSE 事件序列 */
|
|
168
|
+
export class OpenAiToAnthropicSseTranslator {
|
|
169
|
+
requestedModel;
|
|
170
|
+
messageId = `msg_${randomUUID().slice(0, 16)}`;
|
|
171
|
+
lineBuf = "";
|
|
172
|
+
dataLines = [];
|
|
173
|
+
started = false;
|
|
174
|
+
textBlockOpen = false;
|
|
175
|
+
nextBlockIndex = 0;
|
|
176
|
+
textBlockIndex = -1;
|
|
177
|
+
toolBlocks = new Map();
|
|
178
|
+
finishReason = "end_turn";
|
|
179
|
+
inputTokens = 0;
|
|
180
|
+
outputTokens = 0;
|
|
181
|
+
cacheReadTokens = 0;
|
|
182
|
+
finished = false;
|
|
183
|
+
constructor(requestedModel) {
|
|
184
|
+
this.requestedModel = requestedModel;
|
|
185
|
+
}
|
|
186
|
+
sse(event, data) {
|
|
187
|
+
return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
188
|
+
}
|
|
189
|
+
ensureStarted() {
|
|
190
|
+
if (this.started)
|
|
191
|
+
return "";
|
|
192
|
+
this.started = true;
|
|
193
|
+
return this.sse("message_start", {
|
|
194
|
+
type: "message_start",
|
|
195
|
+
message: {
|
|
196
|
+
id: this.messageId,
|
|
197
|
+
type: "message",
|
|
198
|
+
role: "assistant",
|
|
199
|
+
model: this.requestedModel,
|
|
200
|
+
content: [],
|
|
201
|
+
stop_reason: null,
|
|
202
|
+
stop_sequence: null,
|
|
203
|
+
usage: { input_tokens: 0, output_tokens: 0 },
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
push(chunkText) {
|
|
208
|
+
this.lineBuf += chunkText;
|
|
209
|
+
let out = "";
|
|
210
|
+
for (;;) {
|
|
211
|
+
const nl = this.lineBuf.indexOf("\n");
|
|
212
|
+
if (nl < 0)
|
|
213
|
+
break;
|
|
214
|
+
const rawLine = this.lineBuf.slice(0, nl).replace(/\r$/, "");
|
|
215
|
+
this.lineBuf = this.lineBuf.slice(nl + 1);
|
|
216
|
+
if (rawLine === "") {
|
|
217
|
+
out += this.flushEvent();
|
|
218
|
+
}
|
|
219
|
+
else if (rawLine.startsWith("data:")) {
|
|
220
|
+
this.dataLines.push(rawLine.slice(5).trimStart());
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return out;
|
|
224
|
+
}
|
|
225
|
+
finish() {
|
|
226
|
+
let out = "";
|
|
227
|
+
if (this.lineBuf.trim()) {
|
|
228
|
+
const tail = this.lineBuf.replace(/\r$/, "");
|
|
229
|
+
this.lineBuf = "";
|
|
230
|
+
if (tail.startsWith("data:"))
|
|
231
|
+
this.dataLines.push(tail.slice(5).trimStart());
|
|
232
|
+
}
|
|
233
|
+
out += this.flushEvent();
|
|
234
|
+
out += this.emitEnd();
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
flushEvent() {
|
|
238
|
+
if (!this.dataLines.length)
|
|
239
|
+
return "";
|
|
240
|
+
const payload = this.dataLines.join("\n").trim();
|
|
241
|
+
this.dataLines = [];
|
|
242
|
+
if (!payload)
|
|
243
|
+
return "";
|
|
244
|
+
if (payload === "[DONE]")
|
|
245
|
+
return this.emitEnd();
|
|
246
|
+
let obj;
|
|
247
|
+
try {
|
|
248
|
+
obj = JSON.parse(payload);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return "";
|
|
252
|
+
}
|
|
253
|
+
let out = this.ensureStarted();
|
|
254
|
+
if (obj.usage && typeof obj.usage === "object") {
|
|
255
|
+
const cached = obj.usage.prompt_tokens_details?.cached_tokens ?? 0;
|
|
256
|
+
const prompt = typeof obj.usage.prompt_tokens === "number" ? Math.max(0, obj.usage.prompt_tokens - cached) : 0;
|
|
257
|
+
this.inputTokens = Math.max(this.inputTokens, prompt);
|
|
258
|
+
if (cached > 0)
|
|
259
|
+
this.cacheReadTokens = Math.max(this.cacheReadTokens, cached);
|
|
260
|
+
if (typeof obj.usage.completion_tokens === "number")
|
|
261
|
+
this.outputTokens = Math.max(this.outputTokens, obj.usage.completion_tokens);
|
|
262
|
+
}
|
|
263
|
+
const choice = obj.choices?.[0];
|
|
264
|
+
if (!choice)
|
|
265
|
+
return out;
|
|
266
|
+
if (choice.finish_reason)
|
|
267
|
+
this.finishReason = mapStopReasonFromOpenAi(choice.finish_reason);
|
|
268
|
+
const delta = choice.delta ?? {};
|
|
269
|
+
if (typeof delta.content === "string" && delta.content.length > 0) {
|
|
270
|
+
if (!this.textBlockOpen) {
|
|
271
|
+
this.textBlockOpen = true;
|
|
272
|
+
this.textBlockIndex = this.nextBlockIndex++;
|
|
273
|
+
out += this.sse("content_block_start", {
|
|
274
|
+
type: "content_block_start",
|
|
275
|
+
index: this.textBlockIndex,
|
|
276
|
+
content_block: { type: "text", text: "" },
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
out += this.sse("content_block_delta", {
|
|
280
|
+
type: "content_block_delta",
|
|
281
|
+
index: this.textBlockIndex,
|
|
282
|
+
delta: { type: "text_delta", text: delta.content },
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
286
|
+
if (this.textBlockOpen) {
|
|
287
|
+
out += this.sse("content_block_stop", { type: "content_block_stop", index: this.textBlockIndex });
|
|
288
|
+
this.textBlockOpen = false;
|
|
289
|
+
}
|
|
290
|
+
for (const tc of delta.tool_calls) {
|
|
291
|
+
const idx = typeof tc.index === "number" ? tc.index : 0;
|
|
292
|
+
let tb = this.toolBlocks.get(idx);
|
|
293
|
+
if (!tb) {
|
|
294
|
+
tb = {
|
|
295
|
+
blockIndex: this.nextBlockIndex++,
|
|
296
|
+
id: tc.id ?? `toolu_${randomUUID().slice(0, 12)}`,
|
|
297
|
+
name: tc.function?.name ?? "tool",
|
|
298
|
+
};
|
|
299
|
+
this.toolBlocks.set(idx, tb);
|
|
300
|
+
out += this.sse("content_block_start", {
|
|
301
|
+
type: "content_block_start",
|
|
302
|
+
index: tb.blockIndex,
|
|
303
|
+
content_block: { type: "tool_use", id: tb.id, name: tb.name, input: {} },
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
if (typeof tc.function?.arguments === "string" && tc.function.arguments.length > 0) {
|
|
307
|
+
out += this.sse("content_block_delta", {
|
|
308
|
+
type: "content_block_delta",
|
|
309
|
+
index: tb.blockIndex,
|
|
310
|
+
delta: { type: "input_json_delta", partial_json: tc.function.arguments },
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
emitEnd() {
|
|
318
|
+
if (this.finished)
|
|
319
|
+
return "";
|
|
320
|
+
this.finished = true;
|
|
321
|
+
let out = this.ensureStarted();
|
|
322
|
+
if (this.textBlockOpen) {
|
|
323
|
+
out += this.sse("content_block_stop", { type: "content_block_stop", index: this.textBlockIndex });
|
|
324
|
+
this.textBlockOpen = false;
|
|
325
|
+
}
|
|
326
|
+
for (const tb of this.toolBlocks.values()) {
|
|
327
|
+
out += this.sse("content_block_stop", { type: "content_block_stop", index: tb.blockIndex });
|
|
328
|
+
}
|
|
329
|
+
out += this.sse("message_delta", {
|
|
330
|
+
type: "message_delta",
|
|
331
|
+
delta: { stop_reason: this.finishReason, stop_sequence: null },
|
|
332
|
+
usage: {
|
|
333
|
+
input_tokens: this.inputTokens,
|
|
334
|
+
output_tokens: this.outputTokens,
|
|
335
|
+
...(this.cacheReadTokens > 0 ? { cache_read_input_tokens: this.cacheReadTokens } : {}),
|
|
336
|
+
},
|
|
337
|
+
});
|
|
338
|
+
out += this.sse("message_stop", { type: "message_stop" });
|
|
339
|
+
return out;
|
|
340
|
+
}
|
|
341
|
+
}
|