lemma-agent 1.1.2 → 1.1.4

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/admin.js CHANGED
@@ -8,7 +8,7 @@ import { extname, join, normalize } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { agentAdapter } from "./agents.js";
10
10
  import { memberKey, memberToolNames } from "./api-member.js";
11
- import { applyChange, cleanChanges, dropChange } from "./change-ops.js";
11
+ import { applyChange, buildChangeDeliveryDraft, cleanChanges, dropChange, formatChangeRevisionPrompt } from "./change-ops.js";
12
12
  import { commitManagedRepo, fetchManagedRepo, GitWorkbench, inspectRepoCommit, inspectRepoGraph, listManagedRepos, pullManagedRepo, pushManagedRepo, resolvePushGate, setGitPushPolicy, } from "./git-workbench.js";
13
13
  import { Operations, operationList, resolveOperation } from "./operations.js";
14
14
  import { CostLedger, Resources, resourceSnapshot } from "./resources.js";
@@ -532,11 +532,19 @@ async function createAdminBinding(options, startedAt) {
532
532
  items.sort((a, b) => a.id - b.id);
533
533
  return { items, hasMore };
534
534
  }
535
- /** 后台派工列表:进行中的在前,带最近的实时输出 */
535
+ /** 后台派工列表:进行中的在前,带最近的实时输出与运行子状态 */
536
536
  function jobList() {
537
537
  return Object.values(jobs)
538
538
  .sort((a, b) => Number(b.status === "running") - Number(a.status === "running") || b.startedAt - a.startedAt)
539
- .map((j) => ({ ...j, waiter: undefined, output: j.status === "running" ? app.jobs.recent(j.id).slice(-20) : undefined }));
539
+ .map((j) => {
540
+ const rt = j.status === "running" ? app.jobs.runtimeState(j.id) : undefined;
541
+ return {
542
+ ...j,
543
+ waiter: undefined,
544
+ output: j.status === "running" ? app.jobs.recent(j.id).slice(-20) : undefined,
545
+ ...(rt ? { runtimeState: rt.state, runtimeDetail: rt.detail } : {}),
546
+ };
547
+ });
540
548
  }
541
549
  /**
542
550
  * 协作拓扑:总调度 → 成员 → 会话(泳道)→ 每次派工(时间条),加上「基于某次改动」的依赖。
@@ -1392,10 +1400,48 @@ async function createAdminBinding(options, startedAt) {
1392
1400
  options.notify?.(`后台网页:${r.message}`);
1393
1401
  return sendJson(res, r.ok ? 200 : 409, r);
1394
1402
  }
1395
- const changeAction = url.pathname.match(/^\/api\/changes\/([^/]+)\/(apply|drop)$/);
1403
+ const changeDraft = url.pathname.match(/^\/api\/changes\/([^/]+)\/draft$/);
1404
+ if (changeDraft && req.method === "GET") {
1405
+ const id = decodeURIComponent(changeDraft[1]);
1406
+ const change = changes.get(id);
1407
+ if (!change)
1408
+ throw new HttpError(404, `找不到改动 ${id}`);
1409
+ return sendJson(res, 200, buildChangeDeliveryDraft(change));
1410
+ }
1411
+ const changeAction = url.pathname.match(/^\/api\/changes\/([^/]+)\/(apply|drop|revise)$/);
1396
1412
  if (changeAction && req.method === "POST") {
1397
- await readControlBody(req);
1413
+ const body = await readControlBody(req, 32768);
1398
1414
  const id = decodeURIComponent(changeAction[1]);
1415
+ if (changeAction[2] === "revise") {
1416
+ const target = changes.get(id);
1417
+ if (!target)
1418
+ throw new HttpError(404, `找不到改动 ${id}`);
1419
+ if (target.status !== "pending" && target.status !== "conflict") {
1420
+ throw new HttpError(409, `改动 #${id} 当前状态为 ${target.status},无法打回修改`);
1421
+ }
1422
+ const rawComments = Array.isArray(body.comments) ? body.comments.slice(0, 50) : [];
1423
+ const comments = rawComments
1424
+ .map((item) => {
1425
+ if (!item || typeof item !== "object")
1426
+ return undefined;
1427
+ const rec = item;
1428
+ const noteText = typeof rec.note === "string" ? rec.note.trim().slice(0, 1000) : "";
1429
+ if (!noteText)
1430
+ return undefined;
1431
+ const file = typeof rec.file === "string" ? rec.file.trim().slice(0, 300) || undefined : undefined;
1432
+ const line = typeof rec.line === "number" && Number.isFinite(rec.line) && rec.line > 0 ? Math.trunc(rec.line) : undefined;
1433
+ return { file, line, note: noteText };
1434
+ })
1435
+ .filter((x) => Boolean(x));
1436
+ const overallNote = typeof body.note === "string" ? body.note.trim().slice(0, 2000) : "";
1437
+ if (!comments.length && !overallNote) {
1438
+ throw new HttpError(400, "请至少填写一条修改意见或行级批注");
1439
+ }
1440
+ const prompt = formatChangeRevisionPrompt(target, comments, overallNote);
1441
+ await root.submit({ type: "input", content: prompt, whenBusy: "followUp" }, context);
1442
+ options.notify?.(`后台网页:已将改动 #${id} 打回修改(${comments.length} 条批注)`);
1443
+ return sendJson(res, 200, { ok: true, changeId: id, commentCount: comments.length });
1444
+ }
1399
1445
  const r = changeAction[2] === "apply" ? await applyChange(changes, id) : await dropChange(changes, id);
1400
1446
  if (!r.ok)
1401
1447
  throw new HttpError(r.message.startsWith("找不到") ? 404 : 409, r.message);
@@ -1,5 +1,89 @@
1
1
  import { applyRange, removeWorktree, git } from "./git.js";
2
2
  import { integrationStale, integrationGit } from "./integration-git.js";
3
+ function inferCommitType(task) {
4
+ const t = task.toLowerCase();
5
+ if (/(fix|bug|修复|报错|异常|崩溃|故障)/.test(t))
6
+ return "fix";
7
+ if (/(test|spec|单测|测试|覆盖)/.test(t))
8
+ return "test";
9
+ if (/(doc|readme|文档|说明|注释)/.test(t))
10
+ return "docs";
11
+ if (/(refactor|cleanup|重构|清理|整理|拆分)/.test(t))
12
+ return "refactor";
13
+ if (/(chore|build|ci|deps|升级|依赖|发布)/.test(t))
14
+ return "chore";
15
+ return "feat";
16
+ }
17
+ function shellDoubleQuote(value) {
18
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, "\\$").replace(/`/g, "\\`")}"`;
19
+ }
20
+ /** 根据人工在 Diff 中的行级批注生成结构化打回修改指令 */
21
+ export function formatChangeRevisionPrompt(change, comments, note) {
22
+ const cleaned = comments
23
+ .map((c) => ({
24
+ file: c.file?.trim() || undefined,
25
+ line: typeof c.line === "number" && Number.isFinite(c.line) && c.line > 0 ? Math.trunc(c.line) : undefined,
26
+ note: c.note.trim(),
27
+ }))
28
+ .filter((c) => c.note.length > 0);
29
+ const summary = note?.trim();
30
+ const lines = [
31
+ `[网页 Diff 审查打回] 请针对改动 #${change.id}(成员 ${change.agent} · 分支 ${change.branch})进行定点修改:`,
32
+ `原任务:${change.task}`,
33
+ ...(summary ? [`总体审查意见:${summary}`] : []),
34
+ ...(cleaned.length
35
+ ? [
36
+ "逐行/逐文件批注:",
37
+ ...cleaned.map((c) => {
38
+ const loc = c.file ? (c.line ? `\`${c.file}:${c.line}\`` : `\`${c.file}\``) : "整体改动";
39
+ return `- ${loc}: ${c.note}`;
40
+ }),
41
+ ]
42
+ : []),
43
+ `请优先续接该任务对应的成员会话或基于改动 #${change.id} 所在范围返工并运行验证,勿修改无关文件。`,
44
+ ];
45
+ return lines.join("\n");
46
+ }
47
+ /** 基于改动元信息、盲审/集成报告与文件统计生成 Commit Message 与 PR 草稿 */
48
+ export function buildChangeDeliveryDraft(change) {
49
+ const cleanTask = change.task.replace(/\s+/g, " ").trim() || `apply change #${change.id}`;
50
+ const prefix = inferCommitType(cleanTask);
51
+ const shortSubject = cleanTask.length > 60 ? `${cleanTask.slice(0, 57)}...` : cleanTask;
52
+ const commitTitle = `${prefix}(${change.agent}): ${shortSubject}`;
53
+ const fileSummary = change.files.slice(0, 12).map((f) => `- ${f.path} (+${f.add} -${f.del})`);
54
+ if (change.files.length > 12)
55
+ fileSummary.push(`- ... 其余 ${change.files.length - 12} 个文件`);
56
+ const reports = change.integration?.reports ?? [];
57
+ const reportLines = reports.map((r) => `- [${r.passed ? "PASS" : "FAIL"}] ${r.name}`);
58
+ if (change.verification && !reports.length) {
59
+ reportLines.push(`- [${change.verification.passed ? "PASS" : "FAIL"}] verification (${change.verification.head.slice(0, 7)})`);
60
+ }
61
+ const commitBodyParts = [
62
+ `Change: #${change.id} (${change.agent} · branch ${change.branch})`,
63
+ `Stats: ${change.files.length} files, +${change.add} -${change.del}`,
64
+ ...(fileSummary.length ? ["Files:", ...fileSummary] : []),
65
+ ...(reportLines.length ? ["Checks:", ...reportLines] : []),
66
+ ];
67
+ const commitBody = commitBodyParts.join("\n");
68
+ const commitMessage = `${commitTitle}\n\n${commitBody}`;
69
+ const prTitle = `[Lemma #${change.id}] ${shortSubject}`;
70
+ const prBody = [
71
+ "## 变更目标",
72
+ cleanTask,
73
+ "",
74
+ `## 改动文件 (${change.files.length} 个文件, +${change.add} / -${change.del})`,
75
+ ...(fileSummary.length ? fileSummary : ["- (无文件列表)"]),
76
+ "",
77
+ "## 验证与集成报告",
78
+ ...(reportLines.length ? reportLines : ["- 已通过人工工作区审查,待合并后提交验证"]),
79
+ "",
80
+ "## 协作来源",
81
+ `- 执行成员:\`${change.agent}\`${change.model ? ` (\`${change.model}\`)` : ""}`,
82
+ `- 改动分支:\`${change.branch}\`(改动 #${change.id})`,
83
+ ].join("\n");
84
+ const ghCommand = `gh pr create --title ${shellDoubleQuote(prTitle)} --body ${shellDoubleQuote(prBody.replace(/\r?\n/g, "\\n"))}`;
85
+ return { commitTitle, commitBody, commitMessage, prTitle, prBody, ghCommand };
86
+ }
3
87
  function find(store, id) {
4
88
  return id ? store.get(id) : undefined;
5
89
  }
@@ -1,6 +1,40 @@
1
1
  // 启动本机 AI CLI 子进程:提示词走 stdin(避免 Windows 命令行转义问题),
2
2
  // 支持超时、中止(杀整个进程树)和逐行输出回调。
3
3
  import { spawn } from "node:child_process";
4
+ const OSC_TITLE_RE = /\x1b\](?:0|2);([^\x07\x1b]*)(?:\x07|\x1b\\)/g;
5
+ const ANSI_ESCAPE_RE = /\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
6
+ function cleanCliLine(raw) {
7
+ const titles = [];
8
+ for (const m of raw.matchAll(OSC_TITLE_RE)) {
9
+ const t = m[1]?.trim();
10
+ if (t)
11
+ titles.push(t);
12
+ }
13
+ const text = raw.replace(ANSI_ESCAPE_RE, "").replace(/\s+/g, " ").trim();
14
+ return { text, titles };
15
+ }
16
+ /** 根据 CLI 子进程 stdout/stderr/OSC 标题识别细粒度实时状态 */
17
+ export function detectCliRuntimeState(line, stream) {
18
+ const { text, titles } = cleanCliLine(line);
19
+ const probe = [text, ...titles].filter(Boolean).join(" | ");
20
+ if (!probe)
21
+ return undefined;
22
+ if (/\b(?:not logged in|login required|authentication failed|invalid api key|token expired|unauthorized)\b|please run\b.*\blogin\b|登录已过期|未登录|需要登录/i.test(probe)) {
23
+ return { state: "auth_expired", detail: (text || titles[0] || "登录态失效").slice(0, 140) };
24
+ }
25
+ if (/\b(?:rate[- ]?limit|too many requests|quota exceeded|overloaded|retry-after)\b|\b429\b/i.test(probe)) {
26
+ return { state: "rate_limited", detail: (text || titles[0] || "触发限流").slice(0, 140) };
27
+ }
28
+ if (/\((?:y\/n|Y\/n|y\/N)\)|\[(?:Y\/n|y\/N|y\/n)\]|waiting for input|press enter to|do you want to|allow .*?\?|confirm to proceed|approve\?/i.test(probe)) {
29
+ return { state: "waiting_input", detail: (text || titles[0] || "等待确认/输入").slice(0, 140) };
30
+ }
31
+ if (stream === "stdout" &&
32
+ (/\b(?:reading|writing|editing|running|searching|thinking|tool_use|content_block)\b/i.test(text) ||
33
+ (text.startsWith("{") && text.includes('"type"')))) {
34
+ return { state: "working", detail: text.slice(0, 120) };
35
+ }
36
+ return undefined;
37
+ }
4
38
  /** Windows 上 kill() 只杀外层进程,需要 taskkill /T 杀掉整棵进程树 */
5
39
  function killTree(pid) {
6
40
  if (pid === undefined)
package/dist/dispatch.js CHANGED
@@ -7,7 +7,7 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
7
7
  import { defineDoc, LiveDoc } from "@earendil-works/pi-durable";
8
8
  import { agentAdapter } from "./agents.js";
9
9
  import { Board, taskBrief } from "./board.js";
10
- import { cleanEnv, runCli } from "./cli-runner.js";
10
+ import { cleanEnv, detectCliRuntimeState, runCli } from "./cli-runner.js";
11
11
  import { autonomyChecksForRoot } from "./config.js";
12
12
  import { WORKTREE_CONVENTION_FILES } from "./conventions.js";
13
13
  import { addWorktree, commitAll, git, linkIgnoredDirs, numstat, repoRoot, snapshot } from "./git.js";
@@ -594,6 +594,7 @@ export async function runDispatch(kind, command, deps, args, io, label = kind) {
594
594
  callId: io.callId,
595
595
  model,
596
596
  });
597
+ let lastRuntimeAlert;
597
598
  try {
598
599
  result = await runCli({
599
600
  command: command[0],
@@ -604,6 +605,19 @@ export async function runDispatch(kind, command, deps, args, io, label = kind) {
604
605
  timeoutMs: agent.timeoutMinutes * 60_000,
605
606
  signal: io.signal,
606
607
  onLine: (line, stream) => {
608
+ const detected = detectCliRuntimeState(line, stream);
609
+ if (detected) {
610
+ io.onRuntimeState?.(detected.state, detected.detail);
611
+ if (detected.state !== "working" && detected.state !== lastRuntimeAlert) {
612
+ lastRuntimeAlert = detected.state;
613
+ const label = detected.state === "waiting_input"
614
+ ? "CLI 等待交互确认"
615
+ : detected.state === "auth_expired"
616
+ ? "CLI 登录/凭据异常"
617
+ : "CLI 触发上游限流";
618
+ io.output(`[${label}] ${detected.detail}\n`);
619
+ }
620
+ }
607
621
  if (stream !== "stdout")
608
622
  return;
609
623
  const p = adapter.progress(line);
package/dist/jobs.js CHANGED
@@ -43,6 +43,7 @@ export function clip(text, max) {
43
43
  export class JobHub extends EventEmitter {
44
44
  controllers = new Map();
45
45
  lines = new Map();
46
+ states = new Map();
46
47
  /** 正在执行的会话:同一个会话不能同时被两次派工续接 */
47
48
  busySessions = new Map();
48
49
  /** 进程正在关闭:被打断的派工不收尾,重启后续接 */
@@ -56,8 +57,21 @@ export class JobHub extends EventEmitter {
56
57
  release(id) {
57
58
  const entry = this.controllers.get(id);
58
59
  this.controllers.delete(id);
60
+ this.states.delete(id);
59
61
  return entry?.by;
60
62
  }
63
+ setRuntimeState(id, state, detail) {
64
+ const prev = this.states.get(id);
65
+ if (prev?.state === state && prev?.detail === detail)
66
+ return;
67
+ this.states.set(id, { state, ...(detail ? { detail } : {}), updatedAt: Date.now() });
68
+ this.emit("state", id, state, detail);
69
+ if (prev?.state !== state)
70
+ this.changed();
71
+ }
72
+ runtimeState(id) {
73
+ return this.states.get(id);
74
+ }
61
75
  running(id) {
62
76
  return this.controllers.has(id);
63
77
  }
package/dist/main.js CHANGED
@@ -782,7 +782,7 @@ export async function startMain(overrides) {
782
782
  if (line === "/help") {
783
783
  log(MEMBER_HELP);
784
784
  log(TASK_HELP);
785
- log("/fast [成员ID|readonly] <任务> 单跳快路直连 · /projects 项目管理 · /project use|init|remove · /sessions 管理会话 · /tasks 分工 · /jobs 后台任务 · /model 选择当前总控模型 · /web 网页 · /exit 退出");
785
+ log("/fast [成员ID|readonly] <任务> 单跳快路直连 · /projects 项目管理 · /project use|init|remove · /clear 新空会话(旧会话保留在 /resume)· /resume 恢复会话 · /sessions 管理会话 · /tasks 分工 · /jobs 后台任务 · /model 选择当前总控模型 · /web 网页 · /exit 退出");
786
786
  log("/ready 就绪队列 · /workflow status|pause|resume 协作控制 · Enter 发送 · Ctrl+J 换行 · 滚轮/PgUp/PgDn 翻阅 · Ctrl+Home/End 到顶/最新 · Alt+End 最新 · Ctrl+K 会话 · Alt+C 关系树 · Ctrl+L 模型 · Ctrl+T 任务面板 · Ctrl+E 工具详情 · Alt+T 思考");
787
787
  log("/history 补载更早记录 · /thinking 展开/收起思考 · Ctrl+Shift+F 搜索已加载记录;思考仅展示服务实际返回的内容。");
788
788
  return true;
@@ -850,6 +850,19 @@ export async function startMain(overrides) {
850
850
  await sessionCommand(line);
851
851
  return true;
852
852
  }
853
+ if (line === "/clear" || line.startsWith("/clear ")) {
854
+ const rest = line.slice(6).trim();
855
+ await sessionCommand(rest ? `/session new ${rest}` : "/session new");
856
+ return true;
857
+ }
858
+ if (line === "/resume" || line.startsWith("/resume ")) {
859
+ const target = line.slice(7).trim();
860
+ if (target)
861
+ await sessionCommand(`/session use ${target}`);
862
+ else
863
+ await showTerminalConversations();
864
+ return true;
865
+ }
853
866
  if (line === "/conversations") {
854
867
  await showTerminalConversations();
855
868
  return true;
@@ -1314,10 +1327,10 @@ export async function startMain(overrides) {
1314
1327
  if (switchingSession && text !== "/exit" && text !== "/quit")
1315
1328
  return log(c.dim("正在切换,命令未执行,请稍后重试。"));
1316
1329
  // Task-owned 子对话由原派工管理,只允许查看或返回,不改变它的执行。
1317
- const readCommand = /^(?:\/help|\/history|\/thinking|\/ready|\/main|\/conversations|\/tree|\/taskgraph|\/conversation|\/id|\/projects?|\/sessions?|\/members|\/tasks|\/goal|\/jobs|\/changes|\/diff|\/usage|\/agents|\/web|\/learn|\/repair|\/exit|\/quit)(?:\s|$)/.test(text) && !/^\/jobs\s+cancel/.test(text);
1330
+ const readCommand = /^(?:\/help|\/history|\/thinking|\/ready|\/main|\/clear|\/resume|\/conversations|\/tree|\/taskgraph|\/conversation|\/id|\/projects?|\/sessions?|\/members|\/tasks|\/goal|\/jobs|\/changes|\/diff|\/usage|\/agents|\/web|\/learn|\/repair|\/exit|\/quit)(?:\s|$)/.test(text) && !/^\/jobs\s+cancel/.test(text);
1318
1331
  if (readingChild && !readCommand)
1319
1332
  return log(c.yellow("子对话为只读查看;请先 /main 返回总控再执行控制命令。"));
1320
- const bindsView = /^\/(?:sessions?|conversations|tree|main)(?:\s|$)/.test(text);
1333
+ const bindsView = /^\/(?:sessions?|conversations|tree|main|clear|resume)(?:\s|$)/.test(text);
1321
1334
  if (!bindsView)
1322
1335
  activeTerminalCommands++;
1323
1336
  try {
@@ -1432,8 +1445,26 @@ export async function startMain(overrides) {
1432
1445
  const [jobs, budget] = await Promise.all([activeApp.harness.snapshot(Jobs, context), activeApp.harness.snapshot(RunBudget, context)]);
1433
1446
  if (!current())
1434
1447
  return;
1435
- ui.setStatus({ busy, jobs: Object.values(jobs?.jobs ?? {}).filter((j) => j.status === "running").map((j) => `${j.id} ${j.agent}`),
1436
- spent: budget?.spent ?? 0, budget: config.budget.perRunUsd, pending: pendingChanges(activeApp.changes).length });
1448
+ const proxySnap = activeApp.proxy.snapshot();
1449
+ ui.setStatus({
1450
+ busy,
1451
+ jobs: Object.values(jobs?.jobs ?? {})
1452
+ .filter((j) => j.status === "running")
1453
+ .map((j) => {
1454
+ const rt = activeApp.jobs.runtimeState(j.id)?.state;
1455
+ const tag = rt === "waiting_input" ? " [等输入]" : rt === "auth_expired" ? " [需登录]" : rt === "rate_limited" ? " [限流]" : "";
1456
+ return `${j.id} ${j.agent}${tag}`;
1457
+ }),
1458
+ spent: budget?.spent ?? 0,
1459
+ budget: config.budget.perRunUsd,
1460
+ pending: pendingChanges(activeApp.changes).length,
1461
+ proxy: {
1462
+ enabled: proxySnap.enabled,
1463
+ cooled: proxySnap.pool.cooledKeys.length,
1464
+ retries: proxySnap.totals.retries,
1465
+ blocked: proxySnap.totals.blocked,
1466
+ },
1467
+ });
1437
1468
  } while (refreshAgain && current());
1438
1469
  }
1439
1470
  catch (error) {
@@ -61,7 +61,14 @@ export function applyOrchestratorDraft(draft, current, input) {
61
61
  const secret = input.secret?.trim();
62
62
  const local = secret ? saveCredential(secret) : current.orchestrator.credential;
63
63
  return draft.apply((raw) => {
64
- raw.orchestrator = { ...current.orchestrator, ...api, modelId, credential: local, ...(local ? { apiKeyFromClaudeSettings: false, apiKeyEnv: [] } : {}) };
64
+ raw.orchestrator = {
65
+ ...current.orchestrator,
66
+ ...api,
67
+ modelId,
68
+ credential: local,
69
+ ...(api.type !== "anthropic-compatible" ? { apiKeyFromClaudeSettings: false } : {}),
70
+ ...(local ? { apiKeyFromClaudeSettings: false, apiKeyEnv: [] } : {}),
71
+ };
65
72
  });
66
73
  }
67
74
  export function applyAutonomyDraft(draft, current, input) {
package/dist/models.js CHANGED
@@ -17,7 +17,7 @@ export function resolveOrchestratorKey(config) {
17
17
  const local = readCredential(config.credential);
18
18
  if (local)
19
19
  return local;
20
- if (config.apiKeyFromClaudeSettings)
20
+ if (config.apiKeyFromClaudeSettings && config.type === "anthropic-compatible")
21
21
  return claudeSettingsEnv().token;
22
22
  return undefined;
23
23
  }
@@ -30,7 +30,7 @@ function keySource(config) {
30
30
  return `环境变量 ${name}`;
31
31
  if (readCredential(config.credential))
32
32
  return "本机凭据文件";
33
- if (config.apiKeyFromClaudeSettings) {
33
+ if (config.apiKeyFromClaudeSettings && config.type === "anthropic-compatible") {
34
34
  const claude = claudeSettingsEnv();
35
35
  if (claude.token)
36
36
  return "~/.claude/settings.json(与 Claude CLI 共用)";
@@ -42,7 +42,7 @@ function keySource(config) {
42
42
  export function orchestratorKeyWarning(config) {
43
43
  if (config.type === "builtin" || resolveOrchestratorKey(config))
44
44
  return undefined;
45
- if (config.apiKeyFromClaudeSettings) {
45
+ if (config.apiKeyFromClaudeSettings && config.type === "anthropic-compatible") {
46
46
  const claude = claudeSettingsEnv();
47
47
  if (claude.error)
48
48
  return `总控无法从 ~/.claude/settings.json 读取密钥(JSON 语法错误:${claude.error});请修复该文件或运行 /setup 配置总控凭据。`;
@@ -12,6 +12,7 @@ export const ONBOARDING_PRESETS = [
12
12
  baseUrl: "https://api.deepseek.com",
13
13
  defaultModel: "deepseek-chat",
14
14
  compactModel: "deepseek-chat",
15
+ apiKeyEnv: ["DEEPSEEK_API_KEY", "PI_ORCHESTRATOR_API_KEY"],
15
16
  price: { input: 0.27, output: 1.1, cacheRead: 0.07 },
16
17
  },
17
18
  {
@@ -22,6 +23,7 @@ export const ONBOARDING_PRESETS = [
22
23
  baseUrl: "https://api.anthropic.com",
23
24
  defaultModel: "claude-sonnet-5-5",
24
25
  compactModel: "claude-haiku-5-5",
26
+ apiKeyEnv: ["ANTHROPIC_API_KEY", "PI_ORCHESTRATOR_API_KEY"],
25
27
  price: { input: 3, output: 15, cacheRead: 0.3 },
26
28
  },
27
29
  {
@@ -32,6 +34,7 @@ export const ONBOARDING_PRESETS = [
32
34
  baseUrl: "https://api.openai.com/v1",
33
35
  defaultModel: "gpt-4.1",
34
36
  compactModel: "gpt-4.1-mini",
37
+ apiKeyEnv: ["OPENAI_API_KEY", "PI_ORCHESTRATOR_API_KEY"],
35
38
  price: { input: 2, output: 8, cacheRead: 0.5 },
36
39
  },
37
40
  {
@@ -42,6 +45,7 @@ export const ONBOARDING_PRESETS = [
42
45
  baseUrl: "https://open.bigmodel.cn/api/paas/v4",
43
46
  defaultModel: "glm-5.3",
44
47
  compactModel: "glm-5.3-flash",
48
+ apiKeyEnv: ["ZHIPU_API_KEY", "GLM_API_KEY", "PI_ORCHESTRATOR_API_KEY"],
45
49
  },
46
50
  {
47
51
  id: "kimi",
@@ -51,6 +55,7 @@ export const ONBOARDING_PRESETS = [
51
55
  baseUrl: "https://api.moonshot.cn/v1",
52
56
  defaultModel: "kimi-k2.5",
53
57
  compactModel: "moonshot-v1-8k",
58
+ apiKeyEnv: ["MOONSHOT_API_KEY", "KIMI_API_KEY", "PI_ORCHESTRATOR_API_KEY"],
54
59
  },
55
60
  {
56
61
  id: "custom",
@@ -59,6 +64,7 @@ export const ONBOARDING_PRESETS = [
59
64
  protocol: "openai",
60
65
  baseUrl: "",
61
66
  defaultModel: "",
67
+ apiKeyEnv: ["PI_ORCHESTRATOR_API_KEY"],
62
68
  },
63
69
  ];
64
70
  function splitSecretList(raw) {
@@ -105,15 +111,25 @@ export function applyOnboardingPlan(draft, current, input) {
105
111
  if (!relayUrl)
106
112
  throw new Error("托管中转模式需要填写云端 Relay 地址(relayUrl)。");
107
113
  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 = {
114
+ const effectiveType = type === "builtin" ? "anthropic-compatible" : type;
115
+ const targetBase = `${relayUrl}/${effectiveType === "openai-compatible" ? "openai" : "anthropic"}`;
116
+ const sameEndpoint = current.orchestrator.type === effectiveType &&
117
+ (current.orchestrator.baseUrl ?? "").replace(/\/+$/, "") === targetBase;
118
+ const modelId = input.modelId?.trim() || (effectiveType === "anthropic-compatible" ? "claude-sonnet-5-5" : "gpt-4.1");
119
+ const cred = credIds[0] ?? current.proxy?.relay.credential ?? (sameEndpoint ? current.orchestrator.credential : undefined);
120
+ const nextOrch = {
111
121
  ...rawOrch,
112
- type: type === "builtin" ? "anthropic-compatible" : type,
113
- baseUrl: `${relayUrl}/${type === "openai-compatible" ? "openai" : "anthropic"}`,
122
+ type: effectiveType,
123
+ baseUrl: targetBase,
114
124
  modelId,
115
- ...(cred ? { credential: cred } : {}),
125
+ apiKeyFromClaudeSettings: false,
126
+ apiKeyEnv: cred ? [] : ["LEMMA_RELAY_TOKEN", "PI_ORCHESTRATOR_API_KEY"],
116
127
  };
128
+ if (cred)
129
+ nextOrch.credential = cred;
130
+ else
131
+ delete nextOrch.credential;
132
+ raw.orchestrator = nextOrch;
117
133
  raw.proxy = {
118
134
  ...(current.proxy),
119
135
  ...rawProxy,
@@ -139,15 +155,23 @@ export function applyOnboardingPlan(draft, current, input) {
139
155
  if (!modelId)
140
156
  throw new Error("请填写默认模型 ID。");
141
157
  const protocol = type === "anthropic-compatible" ? "anthropic" : "openai";
142
- const primaryCred = credIds[0] ?? current.orchestrator.credential;
143
- raw.orchestrator = {
158
+ const sameEndpoint = current.orchestrator.type === type &&
159
+ (current.orchestrator.baseUrl ?? "").replace(/\/+$/, "") === baseUrl;
160
+ const primaryCred = credIds[0] ?? (sameEndpoint ? current.orchestrator.credential : undefined);
161
+ const nextOrch = {
144
162
  ...rawOrch,
145
163
  type,
146
164
  baseUrl,
147
165
  modelId,
148
- ...(primaryCred ? { credential: primaryCred } : {}),
166
+ apiKeyFromClaudeSettings: type === "anthropic-compatible" && credIds.length === 0 ? Boolean(rawOrch.apiKeyFromClaudeSettings) : false,
167
+ apiKeyEnv: credIds.length > 0 ? [] : (preset.apiKeyEnv ?? ["PI_ORCHESTRATOR_API_KEY"]),
149
168
  ...(preset.price ? { price: preset.price } : {}),
150
169
  };
170
+ if (primaryCred)
171
+ nextOrch.credential = primaryCred;
172
+ else
173
+ delete nextOrch.credential;
174
+ raw.orchestrator = nextOrch;
151
175
  const prevUpstreams = rawProxy.upstreams ?? current.proxy.upstreams;
152
176
  const nextUpstreams = {
153
177
  ...prevUpstreams,
package/dist/proxy.js CHANGED
@@ -180,6 +180,7 @@ export class StickyKeyPool {
180
180
  sticky = new Map();
181
181
  cooldown = new Map();
182
182
  rrCursor = new Map();
183
+ channelStats = new Map();
183
184
  now;
184
185
  affinityFile;
185
186
  constructor(now = () => Date.now(), affinityFile) {
@@ -285,8 +286,35 @@ export class StickyKeyPool {
285
286
  const wrapped = keys.map((k) => ({ cooldownId: keyHashOf(k), raw: k }));
286
287
  return this.pickFromCandidates(poolId, wrapped, sessionKey, stickyEnabled, "rotate").map((w) => w.raw);
287
288
  }
288
- markSuccessById(poolId, sessionKey, cooldownId, ttlSeconds, stickyEnabled) {
289
+ ensureChannelStat(poolId, cooldownId, meta) {
290
+ const ck = this.cooldownKey(poolId, cooldownId);
291
+ let stat = this.channelStats.get(ck);
292
+ if (!stat) {
293
+ stat = {
294
+ poolId,
295
+ keyHash: cooldownId,
296
+ label: meta?.label || poolId,
297
+ protocol: meta?.protocol || (poolId.startsWith("proto:") ? poolId.slice(6) : "unknown"),
298
+ successes: 0,
299
+ failures: 0,
300
+ failovers: 0,
301
+ };
302
+ this.channelStats.set(ck, stat);
303
+ }
304
+ else {
305
+ if (meta?.label)
306
+ stat.label = meta.label;
307
+ if (meta?.protocol)
308
+ stat.protocol = meta.protocol;
309
+ }
310
+ return stat;
311
+ }
312
+ markSuccessById(poolId, sessionKey, cooldownId, ttlSeconds, stickyEnabled, meta) {
289
313
  this.cooldown.delete(this.cooldownKey(poolId, cooldownId));
314
+ const stat = this.ensureChannelStat(poolId, cooldownId, meta);
315
+ stat.successes++;
316
+ if (meta?.failover)
317
+ stat.failovers++;
290
318
  if (stickyEnabled && sessionKey && ttlSeconds > 0) {
291
319
  const stickKey = `${poolId}\0${sessionKey}`;
292
320
  if (this.sticky.size >= MAX_STICKY_ENTRIES && !this.sticky.has(stickKey)) {
@@ -298,8 +326,10 @@ export class StickyKeyPool {
298
326
  this.persist();
299
327
  }
300
328
  }
301
- markFailedById(poolId, sessionKey, cooldownId, cooldownMs) {
329
+ markFailedById(poolId, sessionKey, cooldownId, cooldownMs, meta) {
302
330
  this.cooldown.set(this.cooldownKey(poolId, cooldownId), this.now() + cooldownMs);
331
+ const stat = this.ensureChannelStat(poolId, cooldownId, meta);
332
+ stat.failures++;
303
333
  if (sessionKey) {
304
334
  const stickKey = `${poolId}\0${sessionKey}`;
305
335
  if (this.sticky.get(stickKey)?.keyHash === cooldownId) {
@@ -327,9 +357,24 @@ export class StickyKeyPool {
327
357
  const sep = ck.indexOf("\0");
328
358
  const poolId = sep >= 0 ? ck.slice(0, sep) : ck;
329
359
  const cooldownId = sep >= 0 ? ck.slice(sep + 1) : "";
330
- cooledKeys.push({ poolId, keyHash: cooldownId, remainingSec: Math.ceil((until - t) / 1000) });
360
+ const stat = this.channelStats.get(ck);
361
+ cooledKeys.push({ poolId, ...(stat?.label ? { label: stat.label } : {}), keyHash: cooldownId, remainingSec: Math.ceil((until - t) / 1000) });
331
362
  }
332
- return { activeStickyCount, cooledKeys };
363
+ const channels = [...this.channelStats.entries()].map(([ck, stat]) => {
364
+ const until = this.cooldown.get(ck) ?? 0;
365
+ const remainingSec = until > t ? Math.ceil((until - t) / 1000) : 0;
366
+ return {
367
+ poolId: stat.poolId,
368
+ label: stat.label,
369
+ protocol: stat.protocol,
370
+ healthy: remainingSec === 0,
371
+ remainingSec,
372
+ successes: stat.successes,
373
+ failures: stat.failures,
374
+ failovers: stat.failovers,
375
+ };
376
+ });
377
+ return { activeStickyCount, cooledKeys, channels };
333
378
  }
334
379
  }
335
380
  function medianOf(nums) {
@@ -1090,7 +1135,11 @@ export class LocalProxy {
1090
1135
  });
1091
1136
  if (upstreamRes.ok) {
1092
1137
  if (!useRelay) {
1093
- this.keyPool.markSuccessById(poolId, sessionKey, cand.cooldownId, stickyCfg.ttlSeconds, stickyCfg.enabled);
1138
+ this.keyPool.markSuccessById(poolId, sessionKey, cand.cooldownId, stickyCfg.ttlSeconds, stickyCfg.enabled, {
1139
+ label: cand.label,
1140
+ protocol: cand.protocol,
1141
+ failover: attempt > 0,
1142
+ });
1094
1143
  }
1095
1144
  finalResponse = upstreamRes;
1096
1145
  winningCandidate = cand;
@@ -1114,13 +1163,19 @@ export class LocalProxy {
1114
1163
  }
1115
1164
  if (!useRelay && attempt + 1 < maxAttempts && shouldFailoverStatus(upstreamRes.status, errText)) {
1116
1165
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1117
- this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs);
1166
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs, {
1167
+ label: cand.label,
1168
+ protocol: cand.protocol,
1169
+ });
1118
1170
  retries++;
1119
1171
  break;
1120
1172
  }
1121
1173
  if (!useRelay && shouldFailoverStatus(upstreamRes.status, errText)) {
1122
1174
  const cooldownMs = parseRetryAfterMs(upstreamRes.headers, errText, stickyCfg.cooldownSeconds, now());
1123
- this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs);
1175
+ this.keyPool.markFailedById(poolId, sessionKey, cand.cooldownId, cooldownMs, {
1176
+ label: cand.label,
1177
+ protocol: cand.protocol,
1178
+ });
1124
1179
  }
1125
1180
  finalResponse = new Response(errText, { status: upstreamRes.status, headers: upstreamRes.headers });
1126
1181
  winningCandidate = cand;
package/dist/terminal.js CHANGED
@@ -38,7 +38,9 @@ export const TERMINAL_COMMANDS = [
38
38
  ["apply", "应用改动"],
39
39
  ["drop", "丢弃改动"],
40
40
  ["clean", "清理工作副本"],
41
- ["new", "新上下文"],
41
+ ["new", "同会话重置模型上下文(保留历史/分工表/改动)"],
42
+ ["clear", "开启空上下文新会话(旧会话保留在 /resume,后台任务继续)"],
43
+ ["resume", "搜索并恢复历史会话或子对话(同 Ctrl+K)"],
42
44
  ["exit", "退出"],
43
45
  ["quit", "退出"],
44
46
  ["sessions", "列出隔离会话"],
@@ -425,7 +427,14 @@ export class AgentTerminal {
425
427
  const tools = (this.view?.tools ?? this.view?.live.tools ?? []).filter((tool) => !["done", "error", "aborted", "interrupted"].includes(tool.status)), queued = tools.filter((tool) => ["waiting", "sleeping", "pending"].includes(tool.status)).length;
426
428
  const inbox = this.view?.live.inbox.length ?? 0;
427
429
  const activity = `${tools.length ? ` · 工具 ${tools.length}${queued ? `(等待 ${queued})` : ""}` : ""}${inbox ? ` · 待处理消息 ${inbox}` : ""}${s.jobs.length ? ` · 后台 ${s.jobs.map((job) => terminalLabel(job)).join(" / ")}` : ""}`;
428
- return terminalRow(` ${state}${activity}`, `成员 ${budget} · 待合并 ${s.pending}`, width);
430
+ const proxyHint = s.proxy?.enabled
431
+ ? s.proxy.cooled > 0
432
+ ? ` · ${c.yellow(`冷却 ${s.proxy.cooled}`)}`
433
+ : s.proxy.retries > 0
434
+ ? ` · 切流 ${s.proxy.retries}`
435
+ : ""
436
+ : "";
437
+ return terminalRow(` ${state}${activity}`, `成员 ${budget} · 待合并 ${s.pending}${proxyHint}`, width);
429
438
  }
430
439
  start() {
431
440
  if (this.started || this.stopped)
package/dist/tools.js CHANGED
@@ -85,6 +85,7 @@ function createJobTask(deps, commands, onSettled) {
85
85
  },
86
86
  memo: (name, candidate) => (candidate === undefined ? runtime.memo(name, context) : runtime.memo(name, candidate, context)),
87
87
  output: (chunk) => hub.output(input.job, chunk),
88
+ onRuntimeState: (state, detail) => hub.setRuntimeState(input.job, state, detail),
88
89
  details: async (value) => {
89
90
  await runtime.commit(async (tx) => {
90
91
  const job = (await tx.doc(Jobs)).jobs[input.job];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemma-agent",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
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"
package/web/js/gitlens.js CHANGED
@@ -18,16 +18,49 @@ const CHANGE_LABEL = { running: "进行中", pending: "待合并", conflict: "
18
18
  const CHANGE_PILL = { running: "running", pending: "pending", conflict: "error", applied: "done", empty: "aborted", dropped: "aborted" };
19
19
  const GATE_ACTION_LABEL = { commit: "提交确认", push: "推送确认", force_push: "风险强推 / 分叉", pull: "分叉拉取" };
20
20
 
21
- /** 统一差异 → 带行号的着色视图(先转义,不信任内容) */
22
- export function renderDiff(text) {
21
+ /** 统一差异 → 带行号的着色视图(先转义,不信任内容;支持可选行级批注) */
22
+ export function renderDiff(text, opts = {}) {
23
23
  if (!text.trim()) return `<div class="empty-inline"><span class="dot"></span>没有差异</div>`;
24
24
  const out = [];
25
25
  let oldNo = 0;
26
26
  let newNo = 0;
27
+ let currentFile = "";
28
+ const commentable = Boolean(opts.commentable && opts.changeId);
29
+ const comments = Array.isArray(opts.comments) ? opts.comments : [];
30
+ const active = opts.activeTarget;
31
+
32
+ const renderLineExtras = (file, line) => {
33
+ if (!commentable || !file || !line) return "";
34
+ const items = comments.filter((c) => c.file === file && Number(c.line) === Number(line));
35
+ const commentRows = items
36
+ .map(
37
+ (c) => `<div class="df-comment-row">
38
+ <span class="mono muted">${esc(c.file)}:${esc(String(c.line))}</span>
39
+ <span class="df-comment-text">${esc(c.note)}</span>
40
+ <button type="button" class="linkish tiny" data-del-comment="${esc(opts.changeId)}" data-comment-id="${esc(c.id)}">删除</button>
41
+ </div>`,
42
+ )
43
+ .join("");
44
+ const isEditing = active && active.changeId === opts.changeId && active.file === file && Number(active.line) === Number(line);
45
+ const editor = isEditing
46
+ ? `<div class="df-comment-form" data-comment-box="${esc(opts.changeId)}">
47
+ <input type="text" class="df-comment-input" data-n="inlineCommentInput" placeholder="输入对该行 (${esc(file)}:${esc(String(line))}) 的修改批注,Enter 保存…" />
48
+ <button type="button" class="primary-btn tiny" data-save-comment="${esc(opts.changeId)}" data-file="${esc(file)}" data-line="${esc(String(line))}">保存批注</button>
49
+ <button type="button" class="ghost-btn tiny" data-cancel-comment="1">取消</button>
50
+ </div>`
51
+ : "";
52
+ return commentRows + editor;
53
+ };
54
+
55
+ const commentBtn = (file, line) =>
56
+ commentable && file && line
57
+ ? `<button type="button" class="df-comment-btn" title="在此行添加批注" data-comment-line="${esc(opts.changeId)}" data-file="${esc(file)}" data-line="${esc(String(line))}">+</button>`
58
+ : "";
59
+
27
60
  for (const line of text.split("\n")) {
28
61
  if (line.startsWith("diff --git")) {
29
- const file = line.replace(/^diff --git a\/(.+?) b\/.+$/, "$1");
30
- out.push(`<div class="df-file">${esc(file)}</div>`);
62
+ currentFile = line.replace(/^diff --git a\/(.+?) b\/.+$/, "$1");
63
+ out.push(`<div class="df-file">${esc(currentFile)}</div>`);
31
64
  continue;
32
65
  }
33
66
  if (/^(index |--- |\+\+\+ |new file mode|deleted file mode|similarity|rename )/.test(line)) continue;
@@ -38,10 +71,22 @@ export function renderDiff(text) {
38
71
  out.push(`<div class="df-hunk"><span></span><span></span><code>${esc(line)}</code></div>`);
39
72
  continue;
40
73
  }
41
- if (line.startsWith("+")) out.push(`<div class="df-line add"><span></span><span>${newNo++}</span><code>${esc(line)}</code></div>`);
42
- else if (line.startsWith("-")) out.push(`<div class="df-line del"><span>${oldNo++}</span><span></span><code>${esc(line)}</code></div>`);
43
- else if (line.startsWith("\\")) out.push(`<div class="df-line meta"><span></span><span></span><code>${esc(line)}</code></div>`);
44
- else if (line.length || oldNo) out.push(`<div class="df-line"><span>${oldNo++}</span><span>${newNo++}</span><code>${esc(line || " ")}</code></div>`);
74
+ if (line.startsWith("+")) {
75
+ const ln = newNo++;
76
+ out.push(`<div class="df-line add${commentable ? " commentable" : ""}" data-diff-file="${esc(currentFile)}" data-diff-line="${ln}"><span></span><span>${ln}</span><code>${commentBtn(currentFile, ln)}${esc(line)}</code></div>`);
77
+ out.push(renderLineExtras(currentFile, ln));
78
+ } else if (line.startsWith("-")) {
79
+ const ln = oldNo++;
80
+ out.push(`<div class="df-line del${commentable ? " commentable" : ""}" data-diff-file="${esc(currentFile)}" data-diff-line="${ln}"><span>${ln}</span><span></span><code>${commentBtn(currentFile, ln)}${esc(line)}</code></div>`);
81
+ out.push(renderLineExtras(currentFile, ln));
82
+ } else if (line.startsWith("\\")) {
83
+ out.push(`<div class="df-line meta"><span></span><span></span><code>${esc(line)}</code></div>`);
84
+ } else if (line.length || oldNo) {
85
+ oldNo++;
86
+ const ln = newNo++;
87
+ out.push(`<div class="df-line${commentable ? " commentable" : ""}" data-diff-file="${esc(currentFile)}" data-diff-line="${ln}"><span>${oldNo - 1}</span><span>${ln}</span><code>${commentBtn(currentFile, ln)}${esc(line || " ")}</code></div>`);
88
+ out.push(renderLineExtras(currentFile, ln));
89
+ }
45
90
  }
46
91
  return `<div class="diff">${out.join("")}</div>`;
47
92
  }
@@ -202,6 +247,9 @@ export function createChangesView() {
202
247
  let loadingDetail = false;
203
248
  let divergedPrompt = null; // { branch, remote, ahead, behind, error } | null
204
249
  let lastGateSig = "";
250
+ const changeComments = new Map(); // changeId -> Array<{ id, file, line, note }>
251
+ let activeCommentTarget = null; // { changeId, file, line } | null
252
+ const changeDrafts = new Map(); // changeId -> ChangeDeliveryDraft
205
253
 
206
254
  function renderGraphRowsHtml(laneRows, maxLanes, emptyMsg) {
207
255
  return laneRows.length
@@ -552,13 +600,15 @@ export function createChangesView() {
552
600
  }).join("") : `<div class="empty-inline"><span class="dot"></span>没有文件变更</div>`}
553
601
  </div>
554
602
  <h3 class="eyebrow">${selectedFile ? `Diff · ${esc(selectedFile)}` : "Diff 视图"}</h3>
555
- <div data-n="diff">${d.diff ? renderDiff(d.diff) : `<div class="empty-inline"><span class="dot"></span>无文本差异(可能是二进制或未跟踪空文件)</div>`}${d.truncated ? `<p class="footnote">差异超过 350KB 已截断,可点击上方单个文件查看局部 Diff。</p>` : ""}</div>
603
+ <div data-n="diff">${d.diff ? renderDiff(d.diff, primaryChange ? { commentable: actionable, changeId: primaryChange.id, comments: changeComments.get(primaryChange.id) ?? [], activeTarget: activeCommentTarget } : {}) : `<div class="empty-inline"><span class="dot"></span>无文本差异(可能是二进制或未跟踪空文件)</div>`}${d.truncated ? `<p class="footnote">差异超过 350KB 已截断,可点击上方单个文件查看局部 Diff。</p>` : ""}</div>
556
604
  </div>`;
557
605
  bindInspectorEvents(box, primaryChange, d.isWorktree);
558
606
  }
559
607
 
560
608
  function renderLinkedChangeBanner(c, actionable, dispatch) {
561
609
  const cmd = (verb) => `/${verb} ${c.id}`;
610
+ const comments = changeComments.get(c.id) ?? [];
611
+ const draft = changeDrafts.get(c.id);
562
612
  return `<div class="change-msg gl-change-card">
563
613
  <div class="gl-change-card-top">
564
614
  <strong>Lemma 改动 #${esc(c.id)}</strong>
@@ -569,10 +619,25 @@ export function createChangesView() {
569
619
  ${c.message ? `<p>${esc(c.message)}</p>` : ""}
570
620
  <div class="row-actions">
571
621
  ${actionable ? `<button type="button" class="primary-btn tiny" data-apply-change="${esc(c.id)}">合并到主目录</button>` : ""}
622
+ ${actionable ? `<button type="button" class="ghost-btn tiny" data-revise-change="${esc(c.id)}">${comments.length ? `打回修改 (${comments.length} 条批注)` : "打回修改"}</button>` : ""}
623
+ ${c.status !== "dropped" ? `<button type="button" class="ghost-btn tiny" data-draft-change="${esc(c.id)}">Commit / PR 草稿</button>` : ""}
572
624
  ${c.branch && c.status !== "dropped" ? `<button type="button" class="ghost-btn tiny" data-push-branch="${esc(c.branch)}">推送分支到远端</button>` : ""}
573
625
  ${actionable ? `<button type="button" class="ghost-btn tiny" data-drop-change="${esc(c.id)}">丢弃改动</button>` : ""}
574
626
  ${actionable ? `<button type="button" class="copy-cmd mono" data-copy="${cmd("apply")}">${cmd("apply")}</button>` : ""}
575
627
  </div>
628
+ ${
629
+ comments.length
630
+ ? `<div class="gl-comment-summary"><span>待提交批注 ${comments.length} 条(点击 Diff 代码行左侧 + 可继续添加)</span><button type="button" class="linkish tiny" data-clear-comments="${esc(c.id)}">清空</button></div>`
631
+ : ""
632
+ }
633
+ ${
634
+ draft
635
+ ? `<div class="gl-draft-box">
636
+ <div class="gl-draft-head"><strong>交付草稿(Commit / PR)</strong><div class="row-actions"><button type="button" class="ghost-btn tiny" data-copy-draft="${esc(c.id)}" data-kind="commit">复制 Commit</button><button type="button" class="ghost-btn tiny" data-copy-draft="${esc(c.id)}" data-kind="pr">复制 PR</button><button type="button" class="ghost-btn tiny" data-copy-draft="${esc(c.id)}" data-kind="gh">复制 gh 命令</button></div></div>
637
+ <pre class="gl-draft-pre mono">${esc(draft.commitMessage)}</pre>
638
+ </div>`
639
+ : ""
640
+ }
576
641
  ${c.integration ? `<div class="gl-int-sub"><strong>联合集成 · ${esc(c.integration.status)}${c.integration.supersededBy ? `(已被 #${esc(c.integration.supersededBy)} 替代)` : ""}</strong><p>来源:${c.integration.sources.map((s) => `<a href="#/changes/${esc(s.id)}">#${esc(s.id)}</a>`).join(" + ")}</p>${(c.integration.reports ?? []).map((rp) => `<details><summary>${esc(rp.name)} · ${rp.passed ? "通过" : "失败"}</summary><pre>${esc(rp.output || "没有输出")}</pre></details>`).join("")}${!c.integration.supersededBy && !["applied", "dropped"].includes(c.status) ? `<div class="row-actions">${["conflict", "failed"].includes(c.integration.status) ? `<button type="button" class="primary-btn tiny" data-int-repair="${esc(c.id)}">派成员修复</button>` : ""}${!["preparing", "merging", "repairing", "testing"].includes(c.integration.status) ? `<button type="button" class="ghost-btn tiny" data-int-rerun="${esc(c.id)}">重跑集成检查</button>` : ""}</div>` : ""}</div>` : ""}
577
642
  </div>`;
578
643
  }
@@ -586,8 +651,8 @@ export function createChangesView() {
586
651
  ${renderLinkedChangeBanner(c, actionable, dispatch)}
587
652
  <h3 class="eyebrow">改了哪些文件 <span class="eyebrow-note">${c.files.length} 个 · +${c.add} −${c.del}</span></h3>
588
653
  <div class="file-list">${c.files.length ? c.files.map((f) => `<div class="file-row"><span class="mono">${esc(f.path)}</span>${diffBlocksHtml(f.add, f.del)}</div>`).join("") : `<div class="empty-inline"><span class="dot"></span>没有修改文件</div>`}</div>
589
- <h3 class="eyebrow">差异</h3>
590
- <div>${d.error ? `<div class="change-msg err">${esc(d.error)}</div>` : renderDiff(d.diff)}</div>
654
+ <h3 class="eyebrow">差异${actionable ? ` <span class="eyebrow-note">鼠标悬停代码行点击 + 可写行级批注</span>` : ""}</h3>
655
+ <div>${d.error ? `<div class="change-msg err">${esc(d.error)}</div>` : renderDiff(d.diff, { commentable: actionable, changeId: c.id, comments: changeComments.get(c.id) ?? [], activeTarget: activeCommentTarget })}</div>
591
656
  </div>`;
592
657
  }
593
658
 
@@ -802,6 +867,108 @@ export function createChangesView() {
802
867
  const cid = repairBtn.dataset.intRepair;
803
868
  const it = (store.state?.integrations ?? []).find((x) => x.id === cid) ?? store.changes.find((x) => x.id === cid)?.integration;
804
869
  if (it) openRepairIntegrationDialog({ ...it, id: cid }, store.state?.agents ?? []);
870
+ return;
871
+ }
872
+ const addLineBtn = target.closest("[data-comment-line]");
873
+ if (addLineBtn) {
874
+ activeCommentTarget = {
875
+ changeId: addLineBtn.dataset.commentLine,
876
+ file: addLineBtn.dataset.file,
877
+ line: Number(addLineBtn.dataset.line),
878
+ };
879
+ renderInspector();
880
+ root.querySelector('[data-n="inlineCommentInput"]')?.focus();
881
+ return;
882
+ }
883
+ if (target.closest("[data-cancel-comment]")) {
884
+ activeCommentTarget = null;
885
+ renderInspector();
886
+ return;
887
+ }
888
+ const saveCommentBtn = target.closest("[data-save-comment]");
889
+ if (saveCommentBtn) {
890
+ const cid = saveCommentBtn.dataset.saveComment;
891
+ const inp = root.querySelector('[data-n="inlineCommentInput"]');
892
+ const noteText = inp?.value?.trim() ?? "";
893
+ if (!noteText) { inp?.focus(); return; }
894
+ const list = changeComments.get(cid) ?? [];
895
+ list.push({
896
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
897
+ file: saveCommentBtn.dataset.file,
898
+ line: Number(saveCommentBtn.dataset.line),
899
+ note: noteText,
900
+ });
901
+ changeComments.set(cid, list);
902
+ activeCommentTarget = null;
903
+ renderInspector();
904
+ return;
905
+ }
906
+ const delCommentBtn = target.closest("[data-del-comment]");
907
+ if (delCommentBtn) {
908
+ const cid = delCommentBtn.dataset.delComment;
909
+ const commentId = delCommentBtn.dataset.commentId;
910
+ const nextList = (changeComments.get(cid) ?? []).filter((x) => x.id !== commentId);
911
+ if (nextList.length) changeComments.set(cid, nextList);
912
+ else changeComments.delete(cid);
913
+ renderInspector();
914
+ return;
915
+ }
916
+ const clearCommentsBtn = target.closest("[data-clear-comments]");
917
+ if (clearCommentsBtn) {
918
+ changeComments.delete(clearCommentsBtn.dataset.clearComments);
919
+ renderInspector();
920
+ return;
921
+ }
922
+ const reviseBtn = target.closest("[data-revise-change]");
923
+ if (reviseBtn) {
924
+ const cid = reviseBtn.dataset.reviseChange;
925
+ const comments = changeComments.get(cid) ?? [];
926
+ let note = "";
927
+ if (!comments.length) {
928
+ note = window.prompt(`输入对改动 #${cid} 的修改意见(或在下方 Diff 行点击 + 添加行级批注):`) ?? "";
929
+ if (!note.trim()) return;
930
+ }
931
+ reviseBtn.disabled = true;
932
+ try {
933
+ const r = await post(`/api/changes/${encodeURIComponent(cid)}/revise`, { comments, note });
934
+ changeComments.delete(cid);
935
+ toast(`已将改动 #${cid} 打回修改(${r.commentCount ?? comments.length} 条批注)`);
936
+ renderInspector();
937
+ } catch (err) {
938
+ toast(err.message);
939
+ } finally {
940
+ reviseBtn.disabled = false;
941
+ }
942
+ return;
943
+ }
944
+ const draftBtn = target.closest("[data-draft-change]");
945
+ if (draftBtn) {
946
+ const cid = draftBtn.dataset.draftChange;
947
+ draftBtn.disabled = true;
948
+ try {
949
+ const draft = await getJson(`/api/changes/${encodeURIComponent(cid)}/draft`);
950
+ changeDrafts.set(cid, draft);
951
+ if (!commitMessageDraft && draft.commitMessage) commitMessageDraft = draft.commitMessage;
952
+ renderInspector();
953
+ } catch (err) {
954
+ toast(err.message);
955
+ } finally {
956
+ draftBtn.disabled = false;
957
+ }
958
+ return;
959
+ }
960
+ const copyDraftBtn = target.closest("[data-copy-draft]");
961
+ if (copyDraftBtn) {
962
+ const draft = changeDrafts.get(copyDraftBtn.dataset.copyDraft);
963
+ if (!draft) return;
964
+ const kind = copyDraftBtn.dataset.kind;
965
+ copy(kind === "pr" ? draft.prBody : kind === "gh" ? draft.ghCommand : draft.commitMessage);
966
+ }
967
+ });
968
+ root.addEventListener("keydown", (e) => {
969
+ if (e.key === "Enter" && e.target instanceof HTMLInputElement && e.target.dataset.n === "inlineCommentInput") {
970
+ e.preventDefault();
971
+ root.querySelector("[data-save-comment]")?.click();
805
972
  }
806
973
  });
807
974
  root.addEventListener("input", (e) => {
package/web/js/views.js CHANGED
@@ -258,14 +258,23 @@ function overview() {
258
258
  const sync = store.live.tools
259
259
  .filter((t) => t.status !== "done" && isDispatch(t.name))
260
260
  .map((t) => ({ key: t.callId, agent: kindOf(t.name), task: callInfo(t.callId)?.task ?? "", since: slotStart.get(t.callId), last: String(t.output ?? "").trim().split("\n").at(-1) ?? "", tag: "" }));
261
- const jobs = runningJobs().map((j) => ({ key: j.callId, agent: j.agent, task: j.task, since: j.startedAt, last: (j.output ?? []).at(-1) ?? "", tag: j.id }));
261
+ const RT_BADGE = { waiting_input: "等待输入", auth_expired: "需重新登录", rate_limited: "触发限流" };
262
+ const jobs = runningJobs().map((j) => ({
263
+ key: j.callId,
264
+ agent: j.agent,
265
+ task: j.task,
266
+ since: j.startedAt,
267
+ last: (j.output ?? []).at(-1) ?? "",
268
+ tag: j.id,
269
+ rt: j.runtimeState && RT_BADGE[j.runtimeState] ? RT_BADGE[j.runtimeState] : "",
270
+ }));
262
271
  const rows = [...sync, ...jobs];
263
272
  box.hidden = !rows.length;
264
273
  if (!rows.length) return;
265
274
  box.innerHTML = `<span class="strip-head"><span class="pulse-dot"></span>正在执行 ${rows.length}</span>${rows
266
275
  .map(
267
276
  (r) => `<button type="button" class="strip-item" data-call="${esc(r.key)}" style="--c:${agentColor(r.agent)}">
268
- <b>${esc(AGENT_LABEL[r.agent] ?? r.agent)}${r.tag ? ` · ${esc(r.tag)}` : ""}</b>
277
+ <b>${esc(AGENT_LABEL[r.agent] ?? r.agent)}${r.tag ? ` · ${esc(r.tag)}` : ""}${r.rt ? ` <span class="pill" data-s="pending">${esc(r.rt)}</span>` : ""}</b>
269
278
  <span class="strip-task">${esc(short(r.task, 40))}</span>
270
279
  <span class="strip-last">${esc(short(r.last, 50))}</span>
271
280
  <time>${r.since ? duration(Date.now() - r.since) : ""}</time>
@@ -1356,6 +1365,7 @@ function usage() {
1356
1365
  const ps = state.proxyStatus ?? null;
1357
1366
  const psTotals = ps?.totals ?? { requests: 0, retries: 0, blocked: 0, redacted: 0 };
1358
1367
  const psCooled = ps?.pool?.cooledKeys ?? [];
1368
+ const psChannels = ps?.pool?.channels ?? [];
1359
1369
  const psAccounts = ps?.discoveredAccounts ?? [];
1360
1370
  const psModels = ps?.models ?? [];
1361
1371
  const psRedactions = ps?.recentRedactions ?? [];
@@ -1373,9 +1383,17 @@ function usage() {
1373
1383
  <div class="kpis kpis-4">
1374
1384
  <div class="kpi"><div class="kpi-top"><span class="kpi-label">网关请求</span></div><strong>${num(psTotals.requests)}</strong><span class="kpi-sub">故障切换 / 重试 ${num(psTotals.retries)} 次</span></div>
1375
1385
  <div class="kpi"><div class="kpi-top"><span class="kpi-label">隐私脱敏</span></div><strong>${num(psTotals.redacted)}</strong><span class="kpi-sub">敏感拦截 ${num(psTotals.blocked)} 次</span></div>
1376
- <div class="kpi"><div class="kpi-top"><span class="kpi-label">冷却密钥</span></div><strong>${num(psCooled.length)}</strong><span class="kpi-sub">${psCooled.length ? psCooled.map((k) => `${esc(k.poolId)} (${k.remainingSec}s)`).join(" · ") : "全部 Key 健康"}</span></div>
1386
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">冷却密钥</span></div><strong>${num(psCooled.length)}</strong><span class="kpi-sub">${psCooled.length ? psCooled.map((k) => `${esc(k.label || k.poolId)} (${k.remainingSec}s)`).join(" · ") : "全部 Key 健康"}</span></div>
1377
1387
  <div class="kpi"><div class="kpi-top"><span class="kpi-label">本机已发现账号</span></div><strong>${num(psAccounts.filter((a) => a.detected).length)} / ${num(psAccounts.length)}</strong><span class="kpi-sub">${psAccounts.length ? psAccounts.map((a) => `${esc(a.provider)}:${a.detected ? esc(a.authMode) : "无"}`).join(" · ") : "已关闭扫描"}</span></div>
1378
1388
  </div>
1389
+ ${
1390
+ psChannels.length
1391
+ ? `<div class="table-wrap" style="margin-top:12px"><table class="table">
1392
+ <thead><tr><th>通道池</th><th>目标</th><th>协议</th><th>健康状态</th><th class="num">成功</th><th class="num">限流/失败</th><th class="num">切流接管</th></tr></thead>
1393
+ <tbody>${psChannels.map((ch) => `<tr><td class="mono">${esc(ch.poolId)}</td><td>${esc(ch.label)}</td><td class="mono">${esc(ch.protocol)}</td><td>${ch.healthy ? `<span class="pill" data-s="done">健康</span>` : `<span class="pill" data-s="pending">冷却 ${ch.remainingSec}s</span>`}</td><td class="num mono">${num(ch.successes)}</td><td class="num mono">${num(ch.failures)}</td><td class="num mono">${num(ch.failovers)}</td></tr>`).join("")}</tbody>
1394
+ </table></div>`
1395
+ : ""
1396
+ }
1379
1397
  ${
1380
1398
  psModels.length
1381
1399
  ? `<div class="table-wrap" style="margin-top:12px"><table class="table">
package/web/style.css CHANGED
@@ -5199,6 +5199,77 @@ pre {
5199
5199
  align-items: center;
5200
5200
  gap: 8px;
5201
5201
  }
5202
+ .df-comment-btn {
5203
+ opacity: 0;
5204
+ border: 1px solid var(--line);
5205
+ background: var(--panel);
5206
+ color: var(--signal);
5207
+ border-radius: 4px;
5208
+ width: 16px;
5209
+ height: 16px;
5210
+ line-height: 14px;
5211
+ padding: 0;
5212
+ margin-right: 6px;
5213
+ cursor: pointer;
5214
+ font-size: 11px;
5215
+ }
5216
+ .df-line.commentable:hover .df-comment-btn,
5217
+ .df-comment-btn:focus-visible {
5218
+ opacity: 1;
5219
+ }
5220
+ .df-comment-row {
5221
+ display: flex;
5222
+ align-items: center;
5223
+ gap: 8px;
5224
+ padding: 4px 12px 4px 96px;
5225
+ background: color-mix(in srgb, var(--signal) 9%, var(--panel));
5226
+ border-left: 2px solid var(--signal);
5227
+ font-size: 12px;
5228
+ }
5229
+ .df-comment-text {
5230
+ flex: 1 1 auto;
5231
+ }
5232
+ .df-comment-form {
5233
+ display: flex;
5234
+ align-items: center;
5235
+ gap: 6px;
5236
+ padding: 6px 12px 6px 96px;
5237
+ background: var(--bg-soft, rgba(128, 128, 128, 0.08));
5238
+ }
5239
+ .df-comment-input {
5240
+ flex: 1 1 auto;
5241
+ min-width: 180px;
5242
+ }
5243
+ .gl-comment-summary {
5244
+ display: flex;
5245
+ align-items: center;
5246
+ justify-content: space-between;
5247
+ font-size: 12px;
5248
+ color: var(--signal);
5249
+ }
5250
+ .gl-draft-box {
5251
+ padding: 8px 10px;
5252
+ border: 1px solid var(--line);
5253
+ border-radius: 8px;
5254
+ background: var(--panel);
5255
+ display: grid;
5256
+ gap: 6px;
5257
+ }
5258
+ .gl-draft-head {
5259
+ display: flex;
5260
+ flex-wrap: wrap;
5261
+ align-items: center;
5262
+ justify-content: space-between;
5263
+ gap: 6px;
5264
+ font-size: 12px;
5265
+ }
5266
+ .gl-draft-pre {
5267
+ margin: 0;
5268
+ white-space: pre-wrap;
5269
+ font-size: 12px;
5270
+ max-height: 180px;
5271
+ overflow: auto;
5272
+ }
5202
5273
  .gl-int-sub {
5203
5274
  padding-top: 8px;
5204
5275
  border-top: 1px dashed var(--line);