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/config.js CHANGED
@@ -107,10 +107,10 @@ const DEFAULTS = {
107
107
  proxy: {
108
108
  enabled: false,
109
109
  mode: "byok",
110
- relay: { tokenEnv: ["LEMMA_RELAY_TOKEN"] },
110
+ relay: { tokenEnv: ["LEMMA_RELAY_TOKEN"], routeMembers: true },
111
111
  captureCli: { claude: true, codex: true, gemini: true },
112
112
  sticky: { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 },
113
- redact: { enabled: true, restoreInResponse: false, allowlist: [], customPatterns: [] },
113
+ redact: { enabled: true, action: "mask", restoreInResponse: false, allowlist: [], customPatterns: [] },
114
114
  upstreams: {
115
115
  anthropic: { baseUrl: "https://api.anthropic.com", apiKeyEnv: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] },
116
116
  openai: { baseUrl: "https://api.openai.com", apiKeyEnv: ["OPENAI_API_KEY"] },
@@ -294,6 +294,19 @@ function normalizeProxyUpstream(raw, fallback, label) {
294
294
  throw new Error(`${label}.credentials 包含无效的本机凭据 ID。`);
295
295
  return merged;
296
296
  }
297
+ function normalizeModelMap(raw, label) {
298
+ if (raw === undefined)
299
+ return undefined;
300
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
301
+ throw new Error(`${label} 需要为字符串映射对象。`);
302
+ const out = {};
303
+ for (const [k, v] of Object.entries(raw)) {
304
+ if (!k.trim() || typeof v !== "string" || !v.trim())
305
+ throw new Error(`${label} 的键和目标模型 ID 需要非空字符串。`);
306
+ out[k.trim()] = v.trim();
307
+ }
308
+ return Object.keys(out).length ? out : undefined;
309
+ }
297
310
  export function normalizeProxy(raw) {
298
311
  const d = DEFAULTS.proxy;
299
312
  if (raw !== undefined && (typeof raw !== "object" || raw === null || Array.isArray(raw)))
@@ -310,6 +323,8 @@ export function normalizeProxy(raw) {
310
323
  throw new Error("proxy.relay.tokenEnv 需要字符串数组。");
311
324
  if (relayInput.credential !== undefined && (typeof relayInput.credential !== "string" || !/^local-[a-f0-9-]{36}$/.test(relayInput.credential)))
312
325
  throw new Error("proxy.relay.credential 无效。");
326
+ if (relayInput.routeMembers !== undefined && typeof relayInput.routeMembers !== "boolean")
327
+ throw new Error("proxy.relay.routeMembers 需要为布尔值。");
313
328
  const relayUrl = relayInput.url !== undefined ? validateHttpUrl(relayInput.url, "proxy.relay.url") : undefined;
314
329
  if ((input.enabled ?? d.enabled) && mode === "relay" && !relayUrl)
315
330
  throw new Error("启用 relay 模式时需要配置 proxy.relay.url。");
@@ -322,6 +337,9 @@ export function normalizeProxy(raw) {
322
337
  throw new Error("proxy.sticky 配置无效(ttlSeconds 需 >= 0,cooldownSeconds 需 >= 1)。");
323
338
  }
324
339
  const redactIn = input.redact ?? {};
340
+ const redactAction = redactIn.action ?? d.redact.action;
341
+ if (redactAction !== "mask" && redactAction !== "warn" && redactAction !== "block")
342
+ throw new Error("proxy.redact.action 需要为 mask、warn 或 block。");
325
343
  const allowlist = redactIn.allowlist ?? d.redact.allowlist;
326
344
  if (!Array.isArray(allowlist) || allowlist.some((x) => typeof x !== "string"))
327
345
  throw new Error("proxy.redact.allowlist 需要字符串数组。");
@@ -342,19 +360,85 @@ export function normalizeProxy(raw) {
342
360
  throw new Error(`proxy.redact.customPatterns[${idx}].minLength 需要正整数。`);
343
361
  return { kind: p.kind, ...(p.prefix ? { prefix: p.prefix } : {}), ...(p.regex ? { regex: p.regex } : {}), ...(p.minLength ? { minLength: p.minLength } : {}) };
344
362
  });
363
+ const modelMap = normalizeModelMap(input.modelMap, "proxy.modelMap");
364
+ if (input.compactModel !== undefined && (typeof input.compactModel !== "string" || !input.compactModel.trim()))
365
+ throw new Error("proxy.compactModel 需要非空模型 ID。");
366
+ let anthropicBridge;
367
+ if (input.anthropicBridge !== undefined) {
368
+ if (!input.anthropicBridge || typeof input.anthropicBridge !== "object" || Array.isArray(input.anthropicBridge))
369
+ throw new Error("proxy.anthropicBridge 需要为对象。");
370
+ if (typeof input.anthropicBridge.enabled !== "boolean")
371
+ throw new Error("proxy.anthropicBridge.enabled 需要为布尔值。");
372
+ const up = normalizeProxyUpstream(input.anthropicBridge, {}, "proxy.anthropicBridge");
373
+ const bridgeMap = normalizeModelMap(input.anthropicBridge.modelMap, "proxy.anthropicBridge.modelMap");
374
+ anthropicBridge = { enabled: input.anthropicBridge.enabled, ...up, ...(bridgeMap ? { modelMap: bridgeMap } : {}) };
375
+ }
376
+ let groups;
377
+ if (input.groups !== undefined) {
378
+ if (!input.groups || typeof input.groups !== "object" || Array.isArray(input.groups))
379
+ throw new Error("proxy.groups 需要为对象。");
380
+ const outGroups = {};
381
+ for (const proto of ["anthropic", "openai", "gemini"]) {
382
+ const g = input.groups[proto];
383
+ if (g === undefined)
384
+ continue;
385
+ if (!g || typeof g !== "object" || Array.isArray(g))
386
+ throw new Error(`proxy.groups.${proto} 需要为对象。`);
387
+ if (g.strategy !== "order" && g.strategy !== "rotate")
388
+ throw new Error(`proxy.groups.${proto}.strategy 需要为 order 或 rotate。`);
389
+ if (!Array.isArray(g.targets) || !g.targets.length)
390
+ throw new Error(`proxy.groups.${proto}.targets 需要非空数组。`);
391
+ outGroups[proto] = {
392
+ strategy: g.strategy,
393
+ targets: g.targets.map((t, idx) => {
394
+ const label = `proxy.groups.${proto}.targets[${idx}]`;
395
+ if (!t || typeof t !== "object" || typeof t.baseUrl !== "string")
396
+ throw new Error(`${label} 需要对象及 baseUrl。`);
397
+ if (t.protocol !== undefined && !["anthropic", "openai", "gemini"].includes(t.protocol))
398
+ throw new Error(`${label}.protocol 需要为 anthropic、openai 或 gemini。`);
399
+ if (t.name !== undefined && (typeof t.name !== "string" || !t.name.trim()))
400
+ throw new Error(`${label}.name 需要非空字符串。`);
401
+ if (t.model !== undefined && (typeof t.model !== "string" || !t.model.trim()))
402
+ throw new Error(`${label}.model 需要非空字符串。`);
403
+ const up = normalizeProxyUpstream(t, {}, label);
404
+ return {
405
+ ...(t.name ? { name: t.name.trim() } : {}),
406
+ ...(t.protocol ? { protocol: t.protocol } : {}),
407
+ baseUrl: validateHttpUrl(t.baseUrl, `${label}.baseUrl`),
408
+ ...(t.model ? { model: t.model.trim() } : {}),
409
+ ...(up.apiKeyEnv ? { apiKeyEnv: up.apiKeyEnv } : {}),
410
+ ...(up.apiKeys ? { apiKeys: up.apiKeys } : {}),
411
+ ...(up.credentials ? { credentials: up.credentials } : {}),
412
+ };
413
+ }),
414
+ };
415
+ }
416
+ if (Object.keys(outGroups).length)
417
+ groups = outGroups;
418
+ }
345
419
  const upIn = (input.upstreams ?? {});
346
420
  return {
347
421
  enabled: input.enabled ?? d.enabled,
348
422
  mode,
349
- relay: { ...(relayUrl ? { url: relayUrl } : {}), tokenEnv: [...tokenEnv], ...(relayInput.credential ? { credential: relayInput.credential } : {}) },
423
+ relay: {
424
+ ...(relayUrl ? { url: relayUrl } : {}),
425
+ tokenEnv: [...tokenEnv],
426
+ ...(relayInput.credential ? { credential: relayInput.credential } : {}),
427
+ routeMembers: relayInput.routeMembers ?? d.relay.routeMembers,
428
+ },
350
429
  captureCli: cap,
351
430
  sticky,
352
431
  redact: {
353
432
  enabled: redactIn.enabled ?? d.redact.enabled,
433
+ action: redactAction,
354
434
  restoreInResponse: redactIn.restoreInResponse ?? d.redact.restoreInResponse,
355
435
  allowlist: [...allowlist],
356
436
  customPatterns,
357
437
  },
438
+ ...(modelMap ? { modelMap } : {}),
439
+ ...(input.compactModel ? { compactModel: input.compactModel.trim() } : {}),
440
+ ...(anthropicBridge ? { anthropicBridge } : {}),
441
+ ...(groups ? { groups } : {}),
358
442
  upstreams: {
359
443
  anthropic: normalizeProxyUpstream(upIn.anthropic, d.upstreams.anthropic, "proxy.upstreams.anthropic"),
360
444
  openai: normalizeProxyUpstream(upIn.openai, d.upstreams.openai, "proxy.upstreams.openai"),
package/dist/main.js CHANGED
@@ -18,6 +18,8 @@ import { initRules, scanConventions, syncRules } from "./conventions.js";
18
18
  import { openApp } from "./app.js";
19
19
  import { loadConfig, sameConfigRepoRoot } from "./config.js";
20
20
  import { memberSettingsCommand, MEMBER_HELP } from "./member-settings.js";
21
+ import { createBootPrompter, needsFirstRunOnboarding, runTerminalOnboarding } from "./onboarding.js";
22
+ import { editSettings } from "./settings.js";
21
23
  import { clip, Jobs } from "./jobs.js";
22
24
  import { createOrchestratorModel, orchestratorKeyWarning } from "./models.js";
23
25
  import { controllerModels, nativeModelCatalog, selectControllerModel, restoreControllerModel } from "./model-selection.js";
@@ -169,6 +171,7 @@ export async function startMain(overrides) {
169
171
  collaboration: next.collaboration,
170
172
  execution: next.execution,
171
173
  budget: next.budget,
174
+ proxy: next.proxy,
172
175
  autonomy: sameConfigRepoRoot(runtime.config.workdir, next) ? next.autonomy : { ...next.autonomy, checks: [] },
173
176
  ...(controller ? { orchestrator: next.orchestrator } : {}),
174
177
  };
@@ -373,7 +376,7 @@ export async function startMain(overrides) {
373
376
  log(c.dim(`工作目录:${config.workdir}`));
374
377
  log(c.dim(`配置文件:${configPath}`));
375
378
  log(c.dim(`会话存储:${config.storage}`));
376
- log(c.dim("/setup 配置总控 · /agent add 添加成员 · /agents 查看成员 · /help 操作帮助"));
379
+ log(c.dim("/onboarding 引导初始化 · /setup 配置总控 · /agent add 添加成员 · /agents 查看成员 · /help 操作帮助"));
377
380
  if (admin)
378
381
  log(`${c.dim("后台网页:")}${c.cyan(admin.url)}`);
379
382
  for (const a of agents) {
@@ -381,7 +384,7 @@ export async function startMain(overrides) {
381
384
  }
382
385
  const authWarn = orchestratorKeyWarning(config.orchestrator);
383
386
  if (authWarn)
384
- log(c.yellow(`⚠ ${authWarn}`));
387
+ log(c.yellow(`⚠ ${authWarn}(可执行 /onboarding 快速初始化)`));
385
388
  }
386
389
  async function shutdown(code = 0) {
387
390
  if (closing)
@@ -655,6 +658,25 @@ export async function startMain(overrides) {
655
658
  }
656
659
  }
657
660
  async function command(line) {
661
+ if (line === "/onboarding") {
662
+ if (configuring || switchingSession || closing)
663
+ throw new Error("当前正在配置、切换或退出。");
664
+ configuring = true;
665
+ try {
666
+ await runTerminalOnboarding({
667
+ config,
668
+ draftFactory: () => editSettings(configPath),
669
+ ask: (prompt) => settingQuestion(prompt),
670
+ select: terminalUI ? (opts) => terminalUI.select(opts) : undefined,
671
+ commit: commitSettings,
672
+ log,
673
+ });
674
+ }
675
+ finally {
676
+ configuring = false;
677
+ }
678
+ return true;
679
+ }
658
680
  if (/^\/fast(?:\s|$)/.test(line)) {
659
681
  const rest = line.slice(5).trim();
660
682
  if (!rest) {
@@ -1470,6 +1492,26 @@ export async function startMain(overrides) {
1470
1492
  }
1471
1493
  else {
1472
1494
  await startWeb();
1495
+ if (needsFirstRunOnboarding(config, flags)) {
1496
+ const prompter = createBootPrompter();
1497
+ configuring = true;
1498
+ try {
1499
+ await runTerminalOnboarding({
1500
+ config,
1501
+ draftFactory: () => editSettings(configPath),
1502
+ ask: ({ title, secret }) => prompter.question(title, secret),
1503
+ commit: commitSettings,
1504
+ log,
1505
+ });
1506
+ }
1507
+ catch (error) {
1508
+ log(c.yellow(`引导未完成:${error instanceof Error ? error.message : String(error)}(稍后可执行 /onboarding 继续)`));
1509
+ }
1510
+ finally {
1511
+ configuring = false;
1512
+ prompter.close();
1513
+ }
1514
+ }
1473
1515
  const useTui = flags.has("--tui") && !flags.has("--plain") && process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== "dumb";
1474
1516
  if (useTui) {
1475
1517
  await startTui().catch(async (error) => {
@@ -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
+ }