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.
@@ -0,0 +1,428 @@
1
+ import { createInterface } from "node:readline";
2
+ import { discoverLocalAccounts } from "./account-discovery.js";
3
+ import {} from "./config.js";
4
+ import { saveCredential } from "./credentials.js";
5
+ import { orchestratorKeyWarning } from "./models.js";
6
+ export const ONBOARDING_PRESETS = [
7
+ {
8
+ id: "deepseek",
9
+ label: "DeepSeek(官方推荐 · 高性价比编码)",
10
+ type: "openai-compatible",
11
+ protocol: "openai",
12
+ baseUrl: "https://api.deepseek.com",
13
+ defaultModel: "deepseek-chat",
14
+ compactModel: "deepseek-chat",
15
+ price: { input: 0.27, output: 1.1, cacheRead: 0.07 },
16
+ },
17
+ {
18
+ id: "anthropic",
19
+ label: "Anthropic Claude",
20
+ type: "anthropic-compatible",
21
+ protocol: "anthropic",
22
+ baseUrl: "https://api.anthropic.com",
23
+ defaultModel: "claude-sonnet-5-5",
24
+ compactModel: "claude-haiku-5-5",
25
+ price: { input: 3, output: 15, cacheRead: 0.3 },
26
+ },
27
+ {
28
+ id: "openai",
29
+ label: "OpenAI (GPT / Codex)",
30
+ type: "openai-compatible",
31
+ protocol: "openai",
32
+ baseUrl: "https://api.openai.com/v1",
33
+ defaultModel: "gpt-4.1",
34
+ compactModel: "gpt-4.1-mini",
35
+ price: { input: 2, output: 8, cacheRead: 0.5 },
36
+ },
37
+ {
38
+ id: "glm",
39
+ label: "智谱 GLM Coding Plan",
40
+ type: "openai-compatible",
41
+ protocol: "openai",
42
+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",
43
+ defaultModel: "glm-5.3",
44
+ compactModel: "glm-5.3-flash",
45
+ },
46
+ {
47
+ id: "kimi",
48
+ label: "Kimi / Moonshot",
49
+ type: "openai-compatible",
50
+ protocol: "openai",
51
+ baseUrl: "https://api.moonshot.cn/v1",
52
+ defaultModel: "kimi-k2.5",
53
+ compactModel: "moonshot-v1-8k",
54
+ },
55
+ {
56
+ id: "custom",
57
+ label: "自定义 OpenAI / Anthropic 兼容中转站",
58
+ type: "openai-compatible",
59
+ protocol: "openai",
60
+ baseUrl: "",
61
+ defaultModel: "",
62
+ },
63
+ ];
64
+ function splitSecretList(raw) {
65
+ if (!raw?.trim())
66
+ return [];
67
+ return [...new Set(raw.split(/[\r\n,;]+/).map((s) => s.trim()).filter(Boolean))];
68
+ }
69
+ function resolvePreset(id) {
70
+ return ONBOARDING_PRESETS.find((p) => p.id === id) ?? ONBOARDING_PRESETS[0];
71
+ }
72
+ export function applyOnboardingPlan(draft, current, input) {
73
+ if (!["native", "byok", "relay"].includes(input.mode)) {
74
+ throw new Error("onboarding mode 需要为 native、byok 或 relay。");
75
+ }
76
+ const redactAction = input.redactAction ?? current.proxy?.redact.action ?? "mask";
77
+ if (!["mask", "warn", "block"].includes(redactAction))
78
+ throw new Error("脱敏策略需要为 mask、warn 或 block。");
79
+ const strategy = input.strategy ?? "rotate";
80
+ if (strategy !== "order" && strategy !== "rotate")
81
+ throw new Error("路由策略需要为 order 或 rotate。");
82
+ const secrets = splitSecretList(input.secret);
83
+ const credIds = secrets.map((s) => saveCredential(s));
84
+ let summary = "";
85
+ const next = draft.apply((raw) => {
86
+ const rawOrch = (raw.orchestrator ?? { ...current.orchestrator });
87
+ const rawAgents = (raw.agents ?? { ...current.agents });
88
+ const rawProxy = (raw.proxy ?? current.proxy ?? {});
89
+ const rawBudget = (raw.budget ?? { ...current.budget });
90
+ if (input.perRunUsd !== undefined)
91
+ rawBudget.perRunUsd = input.perRunUsd;
92
+ if (input.mode === "native") {
93
+ raw.orchestrator = { ...rawOrch, apiKeyFromClaudeSettings: true };
94
+ raw.proxy = {
95
+ ...(current.proxy),
96
+ ...rawProxy,
97
+ enabled: input.enableProxy ?? true,
98
+ mode: "byok",
99
+ redact: { ...(current.proxy.redact), ...(rawProxy.redact ?? {}), enabled: true, action: redactAction },
100
+ };
101
+ summary = "已保留本机已有登录态/凭据并启用本地网关脱敏";
102
+ }
103
+ else if (input.mode === "relay") {
104
+ const relayUrl = input.relayUrl?.trim().replace(/\/+$/, "");
105
+ if (!relayUrl)
106
+ throw new Error("托管中转模式需要填写云端 Relay 地址(relayUrl)。");
107
+ const type = input.type ?? current.orchestrator.type ?? "anthropic-compatible";
108
+ const modelId = input.modelId?.trim() || (type === "anthropic-compatible" ? "claude-sonnet-5-5" : "gpt-4.1");
109
+ const cred = credIds[0] ?? current.proxy?.relay.credential;
110
+ raw.orchestrator = {
111
+ ...rawOrch,
112
+ type: type === "builtin" ? "anthropic-compatible" : type,
113
+ baseUrl: `${relayUrl}/${type === "openai-compatible" ? "openai" : "anthropic"}`,
114
+ modelId,
115
+ ...(cred ? { credential: cred } : {}),
116
+ };
117
+ raw.proxy = {
118
+ ...(current.proxy),
119
+ ...rawProxy,
120
+ enabled: input.enableProxy ?? true,
121
+ mode: "relay",
122
+ relay: {
123
+ url: relayUrl,
124
+ tokenEnv: rawProxy.relay?.tokenEnv ?? ["LEMMA_RELAY_TOKEN"],
125
+ ...(cred ? { credential: cred } : {}),
126
+ routeMembers: true,
127
+ },
128
+ redact: { ...(current.proxy.redact), ...(rawProxy.redact ?? {}), enabled: true, action: redactAction },
129
+ };
130
+ summary = `已接入云端托管平台(${relayUrl}),全部成员统一走 Relay 结算`;
131
+ }
132
+ else {
133
+ const preset = resolvePreset(input.preset);
134
+ const type = input.type ?? preset.type;
135
+ const baseUrl = (input.baseUrl?.trim() || preset.baseUrl).replace(/\/+$/, "");
136
+ if (!baseUrl)
137
+ throw new Error("请填写服务商 API Base URL。");
138
+ const modelId = input.modelId?.trim() || preset.defaultModel;
139
+ if (!modelId)
140
+ throw new Error("请填写默认模型 ID。");
141
+ const protocol = type === "anthropic-compatible" ? "anthropic" : "openai";
142
+ const primaryCred = credIds[0] ?? current.orchestrator.credential;
143
+ raw.orchestrator = {
144
+ ...rawOrch,
145
+ type,
146
+ baseUrl,
147
+ modelId,
148
+ ...(primaryCred ? { credential: primaryCred } : {}),
149
+ ...(preset.price ? { price: preset.price } : {}),
150
+ };
151
+ const prevUpstreams = rawProxy.upstreams ?? current.proxy.upstreams;
152
+ const nextUpstreams = {
153
+ ...prevUpstreams,
154
+ [protocol]: {
155
+ ...prevUpstreams[protocol],
156
+ baseUrl,
157
+ ...(credIds.length ? { credentials: credIds } : {}),
158
+ },
159
+ };
160
+ const bridgeEnabled = Boolean(input.enableBridge && type === "openai-compatible");
161
+ const compactModel = input.compactModel?.trim() || preset.compactModel;
162
+ const existingGroups = rawProxy.groups ?? {};
163
+ const targetGroup = {
164
+ strategy,
165
+ targets: [
166
+ {
167
+ name: preset.id,
168
+ protocol,
169
+ baseUrl,
170
+ model: modelId,
171
+ ...(credIds.length ? { credentials: credIds } : { apiKeyEnv: prevUpstreams[protocol]?.apiKeyEnv }),
172
+ },
173
+ ],
174
+ };
175
+ raw.proxy = {
176
+ ...(current.proxy),
177
+ ...rawProxy,
178
+ enabled: input.enableProxy ?? true,
179
+ mode: "byok",
180
+ redact: { ...(current.proxy.redact), ...(rawProxy.redact ?? {}), enabled: true, action: redactAction },
181
+ ...(compactModel ? { compactModel } : {}),
182
+ upstreams: nextUpstreams,
183
+ groups: {
184
+ ...existingGroups,
185
+ [protocol]: targetGroup,
186
+ ...(bridgeEnabled
187
+ ? {
188
+ anthropic: {
189
+ strategy,
190
+ targets: [
191
+ {
192
+ name: `${preset.id}-bridge`,
193
+ protocol: "openai",
194
+ baseUrl,
195
+ model: modelId,
196
+ ...(credIds.length ? { credentials: credIds } : { apiKeyEnv: prevUpstreams.openai?.apiKeyEnv }),
197
+ },
198
+ ],
199
+ },
200
+ }
201
+ : {}),
202
+ },
203
+ ...(bridgeEnabled
204
+ ? {
205
+ anthropicBridge: {
206
+ enabled: true,
207
+ baseUrl,
208
+ ...(credIds.length ? { credentials: credIds } : {}),
209
+ modelMap: {
210
+ "claude-sonnet-5-5": modelId,
211
+ "claude-opus-5-5": modelId,
212
+ "claude-haiku-5-5": compactModel ?? modelId,
213
+ },
214
+ },
215
+ }
216
+ : {}),
217
+ };
218
+ // 同步启用 API 编程成员(如 DeepSeek),使开箱即有总控 + 编程成员协同
219
+ if (type === "openai-compatible" && rawAgents.deepseek?.api) {
220
+ rawAgents.deepseek = {
221
+ ...rawAgents.deepseek,
222
+ enabled: true,
223
+ defaultModel: modelId,
224
+ models: rawAgents.deepseek.models?.length
225
+ ? rawAgents.deepseek.models
226
+ : [{ id: modelId, tier: "standard", ...(preset.price ? { price: preset.price } : {}) }],
227
+ api: {
228
+ ...rawAgents.deepseek.api,
229
+ baseUrl,
230
+ ...(credIds.length ? { credentials: credIds } : {}),
231
+ },
232
+ };
233
+ raw.agents = rawAgents;
234
+ }
235
+ summary = `已配置 ${preset.label}(${modelId})· 网关${strategy === "order" ? "主备容灾" : "粘性轮转"}${credIds.length > 1 ? `(${credIds.length} Key 池)` : ""}${bridgeEnabled ? " + Claude 桥接" : ""}`;
236
+ }
237
+ raw.budget = rawBudget;
238
+ });
239
+ return { next, summary };
240
+ }
241
+ export function needsFirstRunOnboarding(config, flags) {
242
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
243
+ return false;
244
+ if (flags.has("--no-onboarding") || process.env.CI || process.env.LEMMA_NO_ONBOARDING === "1")
245
+ return false;
246
+ return Boolean(orchestratorKeyWarning(config.orchestrator));
247
+ }
248
+ function formatAccountLine(a) {
249
+ const icon = a.detected ? "●" : "○";
250
+ return ` ${icon} ${a.provider.padEnd(9)} ${a.detected ? `${a.authMode}${a.keyCount > 1 ? ` ×${a.keyCount}` : ""} · ${a.source}` : "未检测到"}`;
251
+ }
252
+ export function createBootPrompter() {
253
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
254
+ return {
255
+ question(title) {
256
+ return new Promise((resolve) => rl.question(`${title}: `, (ans) => resolve(ans.trim())));
257
+ },
258
+ close() {
259
+ rl.close();
260
+ },
261
+ };
262
+ }
263
+ export async function runTerminalOnboarding(deps) {
264
+ const { config, draftFactory, ask, select, commit, log } = deps;
265
+ const discovered = discoverLocalAccounts(config);
266
+ const scanLines = discovered.length
267
+ ? ["本机已有方案扫描结果:", ...discovered.map(formatAccountLine)]
268
+ : undefined;
269
+ const requireSelect = async (options) => {
270
+ const picked = await select(options);
271
+ if (picked === undefined)
272
+ throw new Error("配置已取消,未保存。");
273
+ return picked;
274
+ };
275
+ let modeChoice;
276
+ if (select) {
277
+ const picked = await select({
278
+ title: "欢迎使用 Lemma · 引理 — 请选择接入方式",
279
+ lines: scanLines,
280
+ items: [
281
+ { value: "byok", label: "自带 API Key / Coding Plan(推荐)", description: "支持多 Key 防 429 粘性轮转池" },
282
+ { value: "relay", label: "云端托管平台(Hosted Relay)", description: "单一 Token 驱动全团队" },
283
+ { value: "native", label: "复用本机已有 CLI / 环境变量", description: "保留现有登录态并启用本地网关脱敏" },
284
+ { value: "skip", label: "暂不配置,稍后再说", description: "随时可输入 /onboarding 或 /setup" },
285
+ ],
286
+ });
287
+ if (!picked || picked === "skip") {
288
+ log("已跳过引导;随时可输入 /onboarding 或 /setup 进行配置。");
289
+ return false;
290
+ }
291
+ modeChoice = picked;
292
+ }
293
+ else {
294
+ log("\n欢迎使用 Lemma · 引理(多 Agent 编码协同 + 本地统一代理网关)");
295
+ if (discovered.length) {
296
+ log("本机已有方案扫描结果:");
297
+ for (const item of discovered)
298
+ log(formatAccountLine(item));
299
+ }
300
+ log("\n请选择接入方式(直接回车跳过本次引导):");
301
+ log(" 1) 自带 API Key / Coding Plan(支持粘贴多 Key 组成防 429 粘性轮转池,推荐)");
302
+ log(" 2) 接入云端托管平台(Hosted Relay,单一 Token 驱动全团队)");
303
+ log(" 3) 复用本机已有 CLI 登录态 / 环境变量并仅启用本地网关脱敏");
304
+ const raw = (await ask({ title: "输入选项 [1/2/3,留空跳过]" })).trim();
305
+ if (!raw) {
306
+ log("已跳过引导;随时可输入 /onboarding 或 /setup 进行配置。");
307
+ return false;
308
+ }
309
+ modeChoice = raw === "2" ? "relay" : raw === "3" ? "native" : "byok";
310
+ }
311
+ const askRedact = async () => {
312
+ if (select) {
313
+ const picked = await requireSelect({
314
+ title: "选择出站敏感信息脱敏策略",
315
+ items: [
316
+ { value: "mask", label: "mask · 自动打码脱敏(推荐)", description: "发现密钥/Token 后替换为占位符再出站" },
317
+ { value: "warn", label: "warn · 仅告警放行", description: "记录脱敏警告但不改动请求内容" },
318
+ { value: "block", label: "block · 直接阻断出站", description: "检测到敏感信息时拒绝转发请求" },
319
+ ],
320
+ });
321
+ return picked === "warn" || picked === "block" ? picked : "mask";
322
+ }
323
+ const redactChoice = (await ask({ title: "出站敏感信息脱敏策略 [mask/warn/block,默认 mask]", value: "mask" })).trim().toLowerCase();
324
+ return redactChoice === "warn" || redactChoice === "block" ? redactChoice : "mask";
325
+ };
326
+ let plan;
327
+ if (modeChoice === "relay") {
328
+ const relayUrl = (await ask({ title: "云端 Relay 地址(例如 https://relay.example.com)" })).trim();
329
+ if (!relayUrl)
330
+ throw new Error("未填写 Relay 地址,已取消引导。");
331
+ const secret = await ask({ title: "输入平台 Token(隐藏输入,将存入 ~/.lemma/credentials.json)", secret: true });
332
+ const modelId = (await ask({ title: "总控默认模型 ID(留空默认 claude-sonnet-5-5)", value: "claude-sonnet-5-5" })).trim();
333
+ plan = {
334
+ mode: "relay",
335
+ relayUrl,
336
+ secret,
337
+ modelId: modelId || "claude-sonnet-5-5",
338
+ redactAction: await askRedact(),
339
+ enableProxy: true,
340
+ };
341
+ }
342
+ else if (modeChoice === "native") {
343
+ plan = {
344
+ mode: "native",
345
+ enableProxy: true,
346
+ redactAction: await askRedact(),
347
+ };
348
+ }
349
+ else {
350
+ let preset;
351
+ if (select) {
352
+ const presetId = await requireSelect({
353
+ title: "选择模型 / Coding Plan 服务商",
354
+ items: ONBOARDING_PRESETS.map((p) => ({
355
+ value: p.id,
356
+ label: p.label,
357
+ description: p.defaultModel ? `${p.defaultModel} · ${p.baseUrl}` : "自定义地址与模型",
358
+ })),
359
+ });
360
+ preset = resolvePreset(presetId);
361
+ }
362
+ else {
363
+ log("\n可选预设厂商:");
364
+ ONBOARDING_PRESETS.forEach((p, idx) => log(` ${idx + 1}) ${p.label}`));
365
+ const presetRaw = (await ask({ title: "选择预设编号 [1-6,默认 1 DeepSeek]", value: "1" })).trim();
366
+ const idx = Math.max(0, Math.min(ONBOARDING_PRESETS.length - 1, (Number(presetRaw) || 1) - 1));
367
+ preset = ONBOARDING_PRESETS[idx];
368
+ }
369
+ const baseUrl = preset.id === "custom" ? (await ask({ title: "填写 API Base URL" })).trim() : preset.baseUrl;
370
+ const modelId = (await ask({ title: `默认模型 ID${preset.defaultModel ? `(默认 ${preset.defaultModel})` : ""}`, value: preset.defaultModel })).trim() || preset.defaultModel;
371
+ const secret = await ask({ title: "输入 API Key(支持逗号分隔多把 Key 组成防 429 池,隐藏输入)", secret: true });
372
+ let strategy;
373
+ if (select) {
374
+ const picked = await requireSelect({
375
+ title: "选择多通道 / 多 Key 路由策略",
376
+ items: [
377
+ { value: "rotate", label: "rotate · 粘性轮转(推荐)", description: "按会话哈希绑定通道,遇到 429 自动切换并冷却" },
378
+ { value: "order", label: "order · 主备容灾", description: "优先主通道,故障时按序降级到备用通道" },
379
+ ],
380
+ });
381
+ strategy = picked === "order" ? "order" : "rotate";
382
+ }
383
+ else {
384
+ const strategyRaw = (await ask({ title: "多通道/多 Key 路由策略:rotate(粘性轮转) / order(主备容灾)[默认 rotate]", value: "rotate" })).trim().toLowerCase();
385
+ strategy = strategyRaw === "order" ? "order" : "rotate";
386
+ }
387
+ const hasClaudeCli = discovered.some((a) => a.provider === "claude");
388
+ let enableBridge = false;
389
+ if (preset.type === "openai-compatible" && hasClaudeCli) {
390
+ if (select) {
391
+ const br = await requireSelect({
392
+ title: "检测到本机有 Claude CLI:是否启用轻量协议桥接?",
393
+ lines: ["启用后,可用当前 OpenAI 兼容 API 直接驱动本机 Claude CLI 成员"],
394
+ items: [
395
+ { value: "no", label: "暂不启用", description: "Claude CLI 保留原有登录态" },
396
+ { value: "yes", label: "启用协议桥接", description: "由本地代理将 Anthropic 请求转为 OpenAI 兼容格式" },
397
+ ],
398
+ });
399
+ enableBridge = br === "yes";
400
+ }
401
+ else {
402
+ const br = (await ask({ title: "检测到本机有 Claude CLI:是否启用轻量协议桥接以该 API 驱动 Claude CLI?[y/N]", value: "n" })).trim().toLowerCase();
403
+ enableBridge = br === "y" || br === "yes";
404
+ }
405
+ }
406
+ plan = {
407
+ mode: "byok",
408
+ preset: preset.id,
409
+ type: preset.type,
410
+ baseUrl,
411
+ modelId,
412
+ secret,
413
+ strategy,
414
+ enableBridge,
415
+ enableProxy: true,
416
+ redactAction: await askRedact(),
417
+ };
418
+ }
419
+ const draft = draftFactory();
420
+ const { next, summary } = applyOnboardingPlan(draft, config, plan);
421
+ await commit(draft, next, true);
422
+ log(`✓ 初始化完成:${summary}`);
423
+ log("你可以直接尝试输入:");
424
+ log(" • 帮我梳理当前仓库的整体架构和核心模块");
425
+ log(" • 给关键模块补齐单元测试并运行验证");
426
+ log(" • /agents 查看可用成员 · /web 查看本地后台观测面板");
427
+ return true;
428
+ }