lemma-agent 0.0.0-stage → 1.0.0

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.
Files changed (79) hide show
  1. package/README.md +121 -2
  2. package/bin/lemma.mjs +42 -0
  3. package/dist/acceptance.js +63 -0
  4. package/dist/admin.js +1482 -0
  5. package/dist/agents.js +245 -0
  6. package/dist/api-member.js +537 -0
  7. package/dist/app.js +161 -0
  8. package/dist/board.js +185 -0
  9. package/dist/business-tools.js +153 -0
  10. package/dist/change-ops.js +91 -0
  11. package/dist/changes.js +46 -0
  12. package/dist/cli-runner.js +106 -0
  13. package/dist/code-tools.js +396 -0
  14. package/dist/coding-benchmark-fixtures.js +1049 -0
  15. package/dist/coding-benchmark-suite.js +1252 -0
  16. package/dist/collaboration-benchmark.js +349 -0
  17. package/dist/config.js +392 -0
  18. package/dist/context-benchmark.js +91 -0
  19. package/dist/conventions.js +282 -0
  20. package/dist/conversation.js +39 -0
  21. package/dist/credentials.js +44 -0
  22. package/dist/deliverables.js +43 -0
  23. package/dist/digest.js +129 -0
  24. package/dist/dispatch.js +801 -0
  25. package/dist/execution-settings.js +24 -0
  26. package/dist/git-workbench.js +800 -0
  27. package/dist/git.js +149 -0
  28. package/dist/integration-git.js +108 -0
  29. package/dist/integrations.js +557 -0
  30. package/dist/jobs.js +100 -0
  31. package/dist/lead.js +263 -0
  32. package/dist/learning.js +36 -0
  33. package/dist/main.js +1402 -0
  34. package/dist/mcp-settings.js +45 -0
  35. package/dist/mcp-tools.js +102 -0
  36. package/dist/member-settings.js +245 -0
  37. package/dist/model-selection.js +48 -0
  38. package/dist/models.js +145 -0
  39. package/dist/native-selectors.js +45 -0
  40. package/dist/native-terminal-components.js +100 -0
  41. package/dist/ood-benchmark.js +660 -0
  42. package/dist/operations.js +21 -0
  43. package/dist/printer.js +113 -0
  44. package/dist/repair.js +102 -0
  45. package/dist/resources.js +31 -0
  46. package/dist/result-summary.js +8 -0
  47. package/dist/results.js +41 -0
  48. package/dist/scope.js +114 -0
  49. package/dist/sessions.js +95 -0
  50. package/dist/settings.js +30 -0
  51. package/dist/task-commands.js +37 -0
  52. package/dist/task-lifecycle.js +49 -0
  53. package/dist/task-readiness.js +22 -0
  54. package/dist/task-recovery.js +116 -0
  55. package/dist/task-review.js +70 -0
  56. package/dist/task-workflow.js +424 -0
  57. package/dist/terminal-layout.js +27 -0
  58. package/dist/terminal-state.js +145 -0
  59. package/dist/terminal.js +800 -0
  60. package/dist/tool-settings.js +111 -0
  61. package/dist/tools.js +1043 -0
  62. package/dist/ux-telemetry.js +127 -0
  63. package/dist/view.js +114 -0
  64. package/package.json +79 -6
  65. package/web/index.html +136 -0
  66. package/web/js/conversations.js +312 -0
  67. package/web/js/dag.js +495 -0
  68. package/web/js/drawer.js +139 -0
  69. package/web/js/editors.js +424 -0
  70. package/web/js/gitlens.js +844 -0
  71. package/web/js/main.js +152 -0
  72. package/web/js/sankey.js +476 -0
  73. package/web/js/store.js +291 -0
  74. package/web/js/ticket.js +151 -0
  75. package/web/js/timeline.js +183 -0
  76. package/web/js/topology.js +454 -0
  77. package/web/js/util.js +232 -0
  78. package/web/js/views.js +1496 -0
  79. package/web/style.css +5299 -0
@@ -0,0 +1,1496 @@
1
+ // 后台各页面。每个页面:mount(root, params) 渲染,update(kind, payload) 响应数据变化,unmount() 清理。
2
+ import { openDispatch } from "./drawer.js";
3
+ import { bindDagPanelEvents, classifyTopology, renderReviewLoopPanel, renderScopeMatrix, renderTaskDag } from "./dag.js";
4
+ import { openAutonomyEditor, openCreateIntegrationDialog, openLimitsEditor, openMemberEditor, openOrchestratorEditor, openRecoverDialog, openRepairIntegrationDialog, openResolveOperationDialog, runControlAction } from "./editors.js";
5
+ import { createChangesView } from "./gitlens.js";
6
+ import { METRICS, MODES, RANGES, Sankey } from "./sankey.js";
7
+ import { buildRuns, callInfo, dispatchRows, isDispatch, loadEarlier, pendingChanges, runningJobs, store } from "./store.js";
8
+ import { topology } from "./topology.js";
9
+ import { Ticket, slotStart } from "./ticket.js";
10
+ import { Timeline } from "./timeline.js";
11
+ import {
12
+ AGENT_LABEL,
13
+ FAILURE_LABEL,
14
+ KINDS,
15
+ STATUS_LABEL,
16
+ agentColor,
17
+ ago,
18
+ duration,
19
+ el,
20
+ esc,
21
+ kindOf,
22
+ markdown,
23
+ money,
24
+ num,
25
+ short,
26
+ stamp,
27
+ toast,
28
+ getJson,
29
+ post,
30
+ } from "./util.js";
31
+
32
+ const RUN_LABEL = { running: "进行中", background: "后台进行中", done: "完成", partial: "有失败", error: "失败", aborted: "已中止", open: "未完成" };
33
+ const PILL = { running: "running", background: "running", done: "done", partial: "error", error: "error", aborted: "aborted", interrupted: "aborted", open: "aborted" };
34
+ const EXEC_PATH = {
35
+ readonly: { label: "只读直查", cls: "p-readonly" },
36
+ fast: { label: "单跳快路", cls: "p-fast" },
37
+ team: { label: "多 Agent 协同", cls: "p-team" },
38
+ chat: { label: "直接对话", cls: "p-chat" },
39
+ };
40
+ function execPathBadge(path) {
41
+ const meta = EXEC_PATH[path];
42
+ return meta ? `<span class="path-badge ${meta.cls}">${meta.label}</span>` : "";
43
+ }
44
+
45
+ function empty(text) {
46
+ return `<div class="empty-state">${esc(text)}</div>`;
47
+ }
48
+ function agentTag(kind) {
49
+ return `<span class="agent-tag" style="--c:${agentColor(kind)}"><i></i>${esc(AGENT_LABEL[kind] ?? kind)}</span>`;
50
+ }
51
+ const TIER = { economy: "经济", standard: "标准", premium: "强力" };
52
+ /** 成员可选的模型:档位、默认、用了多少次,支持一键设为默认 */
53
+ function modelList(agent) {
54
+ if (!agent.models?.length) return `<div class="model-list"><span class="muted">没有配置模型清单,使用 CLI 自己的默认模型</span></div>`;
55
+ const stats = (store.state?.modelStats ?? []).filter((m) => m.agent === agent.kind);
56
+ const canEdit = store.state?.canEditSettings;
57
+ return `<div class="model-list">${agent.models
58
+ .map((m) => {
59
+ const st = stats.find((x) => x.model === m.id);
60
+ const isDef = m.id === agent.defaultModel;
61
+ return `<div class="model-row" data-tier="${m.tier}">
62
+ <span class="tier">${TIER[m.tier] ?? m.tier}</span>
63
+ <span class="model-id mono">${esc(m.id)}${isDef ? `<em>默认</em>` : canEdit ? `<button type="button" class="linkish tiny" data-set-model="${esc(agent.kind)}" data-model="${esc(m.id)}">设为默认</button>` : ""}</span>
64
+ <span class="mono muted">${st ? `${st.total} 次 · ${money(st.cost)}${st.estimated ? "≈" : ""}` : "未使用"}</span>
65
+ <span class="model-note">${esc(m.note ?? "")}</span>
66
+ </div>`;
67
+ })
68
+ .join("")}</div>`;
69
+ }
70
+
71
+ /** 改动编号链接,带状态颜色 */
72
+ function changeLink(id) {
73
+ const c = store.changes.find((x) => x.id === id);
74
+ const s = c?.status ?? "pending";
75
+ return `<a class="change-link" data-s="${esc(s)}" href="#/changes/${esc(id)}" title="${esc({ pending: "待合并", conflict: "有冲突", applied: "已合并", empty: "无改动", dropped: "已丢弃", running: "进行中" }[s] ?? s)}">#${esc(id)}</a>`;
76
+ }
77
+ function totals() {
78
+ const stats = store.state?.agentStats ?? {};
79
+ const t = { total: 0, done: 0, error: 0, aborted: 0, cost: 0, durationMs: 0 };
80
+ for (const s of Object.values(stats)) {
81
+ t.total += s.total;
82
+ t.done += s.done;
83
+ t.error += s.error;
84
+ t.aborted += s.aborted;
85
+ t.cost += s.cost;
86
+ t.durationMs += s.durationMs;
87
+ }
88
+ return t;
89
+ }
90
+
91
+ // =====================================================================
92
+ // 总览
93
+ // =====================================================================
94
+ const PREF_KEY = "pi-agent-routes-view";
95
+ function loadPrefs() {
96
+ try {
97
+ return { mode: "member", metric: "count", range: "all", ...JSON.parse(localStorage.getItem(PREF_KEY) ?? "{}") };
98
+ } catch {
99
+ return { mode: "member", metric: "count", range: "all" };
100
+ }
101
+ }
102
+ function savePrefs(prefs) {
103
+ try {
104
+ localStorage.setItem(PREF_KEY, JSON.stringify(prefs));
105
+ } catch {
106
+ /* 忽略 */
107
+ }
108
+ }
109
+ function segButtons(entries, current) {
110
+ return entries.map(([k, label]) => `<button type="button" data-k="${k}" class="${k === current ? "on" : ""}">${label}</button>`).join("");
111
+ }
112
+
113
+ // ---------- 小图:24 小时柱状迷你图、分段条 ----------
114
+ function hourly(rows, hours = 24) {
115
+ const now = Date.now();
116
+ const buckets = Array.from({ length: hours }, () => 0);
117
+ for (const d of rows) {
118
+ if (!d.at) continue;
119
+ const i = hours - 1 - Math.floor((now - d.at) / 3_600_000);
120
+ if (i >= 0 && i < hours) buckets[i]++;
121
+ }
122
+ return buckets;
123
+ }
124
+ function sparkBars(values, color = "var(--signal)") {
125
+ const max = Math.max(1, ...values);
126
+ const w = 4;
127
+ const gap = 2;
128
+ const h = 30;
129
+ const bars = values
130
+ .map((v, i) => {
131
+ if (!v) return `<rect x="${i * (w + gap)}" y="${h - 1}" width="${w}" height="1" style="fill:var(--line)"/>`;
132
+ const bh = Math.max(3, (v / max) * h);
133
+ return `<rect x="${i * (w + gap)}" y="${h - bh}" width="${w}" height="${bh}" rx="1" style="fill:${color};opacity:${0.45 + 0.55 * (i / values.length)}"><title>${v} 次</title></rect>`;
134
+ })
135
+ .join("");
136
+ return `<svg class="spark" viewBox="0 0 ${values.length * (w + gap) - gap} ${h}" preserveAspectRatio="none" aria-hidden="true">${bars}</svg>`;
137
+ }
138
+ function segBar(parts) {
139
+ const total = parts.reduce((s, p) => s + p.value, 0);
140
+ if (!total) return `<div class="segbar empty"></div>`;
141
+ return `<div class="segbar">${parts
142
+ .filter((p) => p.value > 0)
143
+ .map((p) => `<i style="flex:${p.value};background:${p.color}" title="${esc(p.label)} ${esc(p.text ?? p.value)}"></i>`)
144
+ .join("")}</div>`;
145
+ }
146
+
147
+ function overview() {
148
+ let root;
149
+ let sankey;
150
+ const tickets = new Map();
151
+ return {
152
+ title: "总览",
153
+ sub: "",
154
+ mount(r) {
155
+ root = r;
156
+ root.innerHTML = "";
157
+ const prefs = loadPrefs();
158
+ const routes = el("section", "card routes-card");
159
+ routes.innerHTML = `<header class="card-head">
160
+ <div class="card-heading"><h2 class="card-title">路由分配</h2><div class="card-sub" data-n="routeSum"></div></div>
161
+ <div class="route-controls">
162
+ <div class="seg" data-n="mode" title="统计维度">${segButtons(Object.entries(MODES).map(([k, m]) => [k, m.label]), prefs.mode)}</div>
163
+ <div class="seg" data-n="metric" title="带子宽度按什么算">${segButtons(Object.entries(METRICS).map(([k, m]) => [k, m.label]), prefs.metric)}</div>
164
+ <div class="seg" data-n="range" title="时间范围">${segButtons(Object.entries(RANGES).map(([k, m]) => [k, m.label]), prefs.range)}</div>
165
+ </div>
166
+ </header>
167
+ <div class="card-body chart-body"></div>`;
168
+ const body = routes.querySelector(".chart-body");
169
+ sankey = new Sankey();
170
+ sankey.mode = prefs.mode in MODES ? prefs.mode : "member";
171
+ sankey.metric = prefs.metric in METRICS ? prefs.metric : "count";
172
+ sankey.range = prefs.range in RANGES ? prefs.range : "all";
173
+ body.append(sankey.node);
174
+ const apply = () => {
175
+ for (const seg of routes.querySelectorAll(".seg")) {
176
+ const value = prefs[seg.dataset.n];
177
+ for (const b of seg.querySelectorAll("button")) b.classList.toggle("on", b.dataset.k === value);
178
+ }
179
+ sankey.render(true);
180
+ this.routeSummary();
181
+ this.activity();
182
+ };
183
+ routes.querySelector(".route-controls").addEventListener("click", (e) => {
184
+ const b = e.target instanceof Element ? e.target.closest(".seg button") : null;
185
+ if (!b) return;
186
+ const which = b.closest(".seg").dataset.n;
187
+ prefs[which] = b.dataset.k;
188
+ savePrefs(prefs);
189
+ sankey[which] = b.dataset.k;
190
+ apply();
191
+ });
192
+ // 正在执行:只在有派工(同步或后台)在跑时出现,一行一个
193
+ const strip = el("div", "ov-strip");
194
+ strip.dataset.n = "strip";
195
+ strip.hidden = true;
196
+ root.prepend(strip);
197
+ root.append(routes);
198
+ const act = el("section", "card act-card");
199
+ act.innerHTML = `<header class="card-head"><div class="card-heading"><h2 class="card-title">派工活动</h2><div class="card-sub" data-n="actSum"></div></div><div class="act-legend" data-n="actLegend"></div></header><div class="card-body" data-n="act"></div>`;
200
+ root.append(act);
201
+ // 路由图占满窗口剩下的高度(给下面的活动图留出位置)
202
+ const fit = () => {
203
+ const top = body.getBoundingClientRect().top + (root.closest(".content")?.scrollTop ?? 0);
204
+ sankey.height = Math.round(window.innerHeight - top - 64 - act.offsetHeight - 18);
205
+ };
206
+ this.fit = () => {
207
+ fit();
208
+ sankey.render(true);
209
+ };
210
+ addEventListener("resize", this.fit);
211
+ requestAnimationFrame(() => this.fit());
212
+ apply();
213
+ this.update("all");
214
+ },
215
+ unmount() {
216
+ sankey?.destroy();
217
+ tickets.clear();
218
+ if (this.fit) removeEventListener("resize", this.fit);
219
+ },
220
+ update(kind) {
221
+ const q = (n) => root.querySelector(`[data-n="${n}"]`);
222
+ const strip = q("strip");
223
+ const wasHidden = strip?.hidden;
224
+ this.strip(strip);
225
+ // 执行条出现 / 消失会改变路由图可用的高度
226
+ if (strip && wasHidden !== strip.hidden) this.fit?.();
227
+ if (kind === "job-output") return;
228
+ // 按次数看时,计时刷新不改变流向,跳过;按耗时看时每秒更新带子宽度
229
+ if (kind !== "tick" || sankey.metric === "time") sankey.render();
230
+ this.routeSummary();
231
+ if (kind !== "tick" && kind !== "live") this.activity();
232
+ },
233
+ /** 派工活动:和路由图同一个时间范围;按成员着色的堆叠柱 */
234
+ activity() {
235
+ const box = root.querySelector('[data-n="act"]');
236
+ if (!box) return;
237
+ const mode = sankey.range === "hour" ? "hour" : sankey.range === "day" ? "day" : "week";
238
+ const rows = dispatchRows();
239
+ const chart = activityChart(rows, mode);
240
+ box.innerHTML = chart.html;
241
+ const span = { hour: "最近 1 小时 · 每 5 分钟", day: "最近 24 小时 · 每小时", week: "最近 14 天 · 每天" }[mode];
242
+ root.querySelector('[data-n="actSum"]').innerHTML = `<span><b>${chart.total}</b> 次派工</span><span>${span}</span>`;
243
+ const from = Date.now() - ({ hour: 3_600_000, day: 86_400_000, week: 14 * 86_400_000 }[mode]);
244
+ const used = KINDS.filter((k) => rows.some((d) => d.agent === k && (d.at ?? 0) >= from));
245
+ root.querySelector('[data-n="actLegend"]').innerHTML = used.map((k) => `<span><i style="background:${agentColor(k)}"></i>${esc(AGENT_LABEL[k] ?? k)}</span>`).join("");
246
+ },
247
+ /** 正在执行的派工:成员、任务、计时、最近一行输出;点开看详情 */
248
+ strip(box) {
249
+ if (!box) return;
250
+ const sync = store.live.tools
251
+ .filter((t) => t.status !== "done" && isDispatch(t.name))
252
+ .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: "" }));
253
+ 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 }));
254
+ const rows = [...sync, ...jobs];
255
+ box.hidden = !rows.length;
256
+ if (!rows.length) return;
257
+ box.innerHTML = `<span class="strip-head"><span class="pulse-dot"></span>正在执行 ${rows.length}</span>${rows
258
+ .map(
259
+ (r) => `<button type="button" class="strip-item" data-call="${esc(r.key)}" style="--c:${agentColor(r.agent)}">
260
+ <b>${esc(AGENT_LABEL[r.agent] ?? r.agent)}${r.tag ? ` · ${esc(r.tag)}` : ""}</b>
261
+ <span class="strip-task">${esc(short(r.task, 40))}</span>
262
+ <span class="strip-last">${esc(short(r.last, 50))}</span>
263
+ <time>${r.since ? duration(Date.now() - r.since) : ""}</time>
264
+ </button>`,
265
+ )
266
+ .join("")}`;
267
+ if (!box.dataset.bound) {
268
+ box.dataset.bound = "1";
269
+ box.addEventListener("click", (e) => {
270
+ const b = e.target instanceof Element ? e.target.closest("[data-call]") : null;
271
+ if (b) openDispatch(b.dataset.call);
272
+ });
273
+ }
274
+ },
275
+ routeSummary() {
276
+ const box = root.querySelector('[data-n="routeSum"]');
277
+ if (!box) return;
278
+ const s = sankey.summary();
279
+ const t = totals();
280
+ const budget = store.state?.budget;
281
+ const runs = buildRuns().filter((r) => !r.divider);
282
+ const roCount = runs.filter((r) => r.execPath === "readonly").length;
283
+ const fastCount = runs.filter((r) => r.execPath === "fast").length;
284
+ const teamCount = runs.filter((r) => r.execPath === "team").length;
285
+ const pathBits = [
286
+ roCount ? `只读直查 <b>${roCount}</b>` : "",
287
+ fastCount ? `单跳快路 <b>${fastCount}</b>` : "",
288
+ teamCount ? `多 Agent 协同 <b>${teamCount}</b>` : "",
289
+ ].filter(Boolean).join(" · ");
290
+ box.innerHTML = s?.total
291
+ ? `<span><b>${s.total}</b> 次派工</span>${s.rate !== null ? `<span><b>${s.rate}%</b> 成功</span>` : ""}${s.running ? `<span class="live"><b>${s.running}</b> 执行中</span>` : ""}<span><b>${money(t.cost)}</b> 花费</span>${budget?.perRunUsd != null && budget.runKey ? `<span>本轮 ${money(budget.spent)} / ${money(budget.perRunUsd)}</span>` : ""}${pathBits ? `<span>${pathBits}</span>` : ""}`
292
+ : `<span>${RANGES[sankey.range].label === "全部" ? "还没有派工" : `最近 ${RANGES[sankey.range].label} 没有派工`}</span>${pathBits ? `<span>${pathBits}</span>` : ""}`;
293
+ },
294
+ };
295
+ }
296
+
297
+ function runRow(run) {
298
+ const text = run.user ? short(run.user.text, 90) : "(输入在更早的历史里)";
299
+ return `<a class="run-row" href="#/runs/${run.id}" data-id="${run.id}">
300
+ <span class="run-top"><time>${stamp(run.at)}</time><span class="run-top-r">${run.execPath && run.execPath !== "chat" ? execPathBadge(run.execPath) : ""}<span class="pill" data-s="${PILL[run.status]}">${RUN_LABEL[run.status]}</span></span></span>
301
+ <span class="run-input">${esc(text)}</span>
302
+ <span class="run-foot">${run.agents.map(agentTag).join("")}<span class="run-meta">${run.dispatchCount ? `派工 ${run.dispatchCount}` : "直接回答"}${run.endAt && run.at ? ` · ${duration(run.endAt - run.at)}` : ""}</span></span>
303
+ </a>`;
304
+ }
305
+
306
+ // =====================================================================
307
+ // 项目:共同目标 + 分工表 + 角色
308
+ // =====================================================================
309
+ const COLUMNS = [
310
+ { s: "todo", label: "待办" },
311
+ { s: "doing", label: "进行中" },
312
+ { s: "review", label: "待验收" },
313
+ { s: "blocked", label: "受阻" },
314
+ { s: "done", label: "完成" },
315
+ ];
316
+
317
+ function shortPath(p) {
318
+ const parts = String(p ?? "").split(/[\\/]/).filter(Boolean);
319
+ return parts.length >= 2 ? parts.slice(-2).join("/") : parts[0] ?? "";
320
+ }
321
+
322
+ function taskCard(t, all, readinessMap, dispatch, openMore = false) {
323
+ const deps = t.deps.map((d) => all.find((x) => x.id === d)).filter(Boolean);
324
+ const waiting = deps.filter((dependency) => dependency.status !== "done");
325
+ const readiness = readinessMap?.get(t.id);
326
+ const waitReasons = t.status === "todo" && readiness && !readiness.ready ? readiness.reasons : [];
327
+ const recoverable = ["todo", "blocked"].includes(t.status) && t.lastAttempt;
328
+ const chips = [];
329
+
330
+ if (waiting.length) chips.push(`<span class="tc-chip warn">⏳ 等 ${waiting.map((d) => esc(d.id)).join("、")}</span>`);
331
+ else if (waitReasons.length) chips.push(`<span class="tc-chip warn" title="${esc(waitReasons.join(";"))}">⏳ 等待前置</span>`);
332
+ else if (t.status === "todo") chips.push(`<span class="tc-chip ready">${t.automation ? "⚡ 就绪 · 自动" : "● 就绪"}</span>`);
333
+
334
+ if (t.scope && (t.scope.allow?.length || t.scope.forbid?.length)) {
335
+ const tip = `${t.scope.allow?.length ? `允许: ${t.scope.allow.join(", ")}` : "允许: 不限"}${t.scope.forbid?.length ? `\n禁止: ${t.scope.forbid.join(", ")}` : ""}`;
336
+ chips.push(`<span class="tc-chip mono" title="${esc(tip)}">🔒 ${esc(t.scope.allow?.[0] ?? t.scope.forbid?.[0])}</span>`);
337
+ }
338
+ if (t.verification) {
339
+ const vTip = t.verification.checks.map((c) => `${c.name}:${c.passed ? "通过" : "失败"}${c.evidence ? ` · ${c.evidence}` : ""}`).join("\n");
340
+ chips.push(`<span class="tc-chip ${t.verification.passed ? "ok" : "err"}" title="${esc(vTip)}">${t.verification.passed ? "✓ 机检通过" : "✗ 机检未通过"}</span>`);
341
+ }
342
+ const latestCheck = t.checksByMember?.at(-1);
343
+ if (t.review) {
344
+ const v = t.review.verdict;
345
+ const cls = v === "accepted" ? "ok" : ["rework", "blocked", "rejected"].includes(v) ? "err" : "warn";
346
+ const label = v === "accepted" ? (t.reviewer?.blind ? "✓ 盲审通过" : "✓ 复核通过") : `${t.reviewer?.blind ? "🕶 盲审" : "🔎 复核"} · ${esc(v)}`;
347
+ chips.push(`<span class="tc-chip ${cls}" title="${esc(t.review.evidence ?? "")}">${label}</span>`);
348
+ } else if (t.reviewer) {
349
+ const st = latestCheck?.status ?? "待交付";
350
+ const cls = st === "accepted" ? "ok" : ["rework", "blocked", "failed"].includes(st) ? "err" : "";
351
+ const prefix = t.reviewer.blind ? "🕶 盲审" : "🔎 复核";
352
+ const who = AGENT_LABEL[t.reviewer.member] ?? t.reviewer.member;
353
+ chips.push(`<span class="tc-chip ${cls}" title="${esc(latestCheck?.evidence ?? "")}">${prefix} · ${esc(who)}${latestCheck ? ` (${esc(st)})` : ""}</span>`);
354
+ }
355
+ if (t.automation && t.status !== "done") {
356
+ chips.push(`<span class="tc-chip">⚡ 自动 · 返工≤${esc(String(t.automation.maxReworks))}</span>`);
357
+ }
358
+ if (t.recoveries?.length) {
359
+ const lastRec = t.recoveries.at(-1);
360
+ chips.push(`<span class="tc-chip" title="${esc(`${lastRec.action} → ${lastRec.member} · ${lastRec.status}`)}">↻ 已交接${t.recoveries.length > 1 ? ` ×${t.recoveries.length}` : ""}</span>`);
361
+ }
362
+ if (t.integrationId) {
363
+ chips.push(`<span class="tc-chip">⇄ 集成 ${changeLink(t.integrationId)}</span>`);
364
+ }
365
+
366
+ const detailLines = [];
367
+ if (t.review?.evidence) detailLines.push(`<p><strong>复核意见</strong><span>${esc(t.review.evidence)}</span></p>`);
368
+ else if (latestCheck?.evidence) detailLines.push(`<p><strong>独立复核</strong><span>${esc(latestCheck.evidence)}</span></p>`);
369
+ if (t.verification?.checks?.length) {
370
+ detailLines.push(`<p><strong>机器检查</strong><span>${t.verification.checks.map((c) => `${c.passed ? "✓" : "✗"} ${esc(c.name)}`).join(" · ")}</span></p>`);
371
+ }
372
+ if (t.recoveries?.length) {
373
+ const rec = t.recoveries.at(-1);
374
+ detailLines.push(`<p><strong>交接记录</strong><span class="mono">${esc(rec.action)} → ${esc(rec.member)} (${esc(rec.status)})</span></p>`);
375
+ }
376
+ if (t.latestResult) detailLines.push(`<p><strong>关联派工</strong><span class="mono">${esc(t.latestResult)}</span></p>`);
377
+ if (t.notes?.length) {
378
+ const cleanNote = t.notes.at(-1).replace(/^\S+ \S+ /, "");
379
+ if (cleanNote && cleanNote !== t.review?.evidence) detailLines.push(`<p><strong>备注</strong><span>${esc(cleanNote)}</span></p>`);
380
+ }
381
+
382
+ const hasFoot = deps.length || t.changes.length || dispatch?.key;
383
+ return `<article class="task-card" data-task-id="${esc(t.id)}" data-s="${t.status}">
384
+ <header class="tc-head">
385
+ <div class="tc-head-l"><span class="tc-id mono">${esc(t.id)}</span>${t.role ? `<span class="role-chip">${esc(t.role)}</span>` : ""}</div>
386
+ ${t.owner ? `<div class="tc-owner">${agentTag(t.owner)}</div>` : ""}
387
+ </header>
388
+ <h3 class="tc-title" title="${esc(t.title)}">${esc(t.title)}</h3>
389
+ ${t.acceptance ? `<div class="tc-accept" title="${esc(t.acceptance)}"><p><span>验收</span>${esc(t.acceptance)}</p></div>` : ""}
390
+ ${chips.length ? `<div class="tc-badges">${chips.join("")}</div>` : ""}
391
+ ${detailLines.length ? `<details class="tc-more" data-task-id="${esc(t.id)}"${openMore ? " open" : ""}><summary>回执与记录</summary><div class="tc-more-body">${detailLines.join("")}</div></details>` : ""}
392
+ ${recoverable ? `<div class="task-actions"><button type="button" class="ghost-btn tiny" data-recover-task="${esc(t.id)}">恢复 / 交接</button><button type="button" class="copy-cmd mono" data-copy="/task inspect ${esc(t.id)}" title="复制终端诊断命令">/task inspect ${esc(t.id)}</button></div>` : ""}
393
+ ${
394
+ hasFoot
395
+ ? `<footer class="tc-foot">
396
+ <div class="tc-foot-l">${deps.map((d) => `<span class="dep" data-s="${d.status}" title="${esc(d.title)}">← ${esc(d.id)}</span>`).join("")}${t.changes.map((c) => changeLink(c)).join("")}</div>
397
+ ${dispatch?.key ? `<button type="button" class="tc-open-btn" data-open-task-dispatch="${esc(dispatch.key)}">派工详情 →</button>` : ""}
398
+ </footer>`
399
+ : ""
400
+ }
401
+ </article>`;
402
+ }
403
+
404
+ function project() {
405
+ let root;
406
+ let statusFilter = "all";
407
+ return {
408
+ title: "项目",
409
+ sub: "",
410
+ mount(r) {
411
+ root = r;
412
+ statusFilter = "all";
413
+ root.addEventListener("click", async (e) => {
414
+ const target = e.target instanceof Element ? e.target : null;
415
+ if (!target) return;
416
+ const filterBtn = target.closest("[data-task-filter]");
417
+ if (filterBtn && !filterBtn.disabled) {
418
+ statusFilter = filterBtn.dataset.taskFilter;
419
+ this.update("filter");
420
+ return;
421
+ }
422
+ const dispBtn = target.closest("[data-open-task-dispatch]");
423
+ if (dispBtn) {
424
+ openDispatch(dispBtn.dataset.openTaskDispatch);
425
+ return;
426
+ }
427
+ const wfBtn = target.closest("[data-wf-action]");
428
+ if (wfBtn) {
429
+ wfBtn.disabled = true;
430
+ try {
431
+ const act = wfBtn.dataset.wfAction;
432
+ await runControlAction("/api/workflow", { action: act }, act === "pause" ? "自动协作已暂停" : "自动协作已恢复");
433
+ } catch (err) { toast(err.message); wfBtn.disabled = false; }
434
+ return;
435
+ }
436
+ const recBtn = target.closest("[data-recover-task]");
437
+ if (recBtn) {
438
+ const task = (store.state?.project?.tasks ?? []).find((x) => x.id === recBtn.dataset.recoverTask);
439
+ if (task) openRecoverDialog(task, store.state?.agents ?? []);
440
+ return;
441
+ }
442
+ if (target.closest("[data-create-int]")) {
443
+ openCreateIntegrationDialog(store.changes);
444
+ return;
445
+ }
446
+ const rerunBtn = target.closest("[data-int-rerun]");
447
+ if (rerunBtn) {
448
+ rerunBtn.disabled = true;
449
+ try { await runControlAction(`/api/integrations/${encodeURIComponent(rerunBtn.dataset.intRerun)}/rerun`, {}, "已重跑联合集成检查"); }
450
+ catch (err) { toast(err.message); rerunBtn.disabled = false; }
451
+ return;
452
+ }
453
+ const repairBtn = target.closest("[data-int-repair]");
454
+ if (repairBtn) {
455
+ const it = (store.state?.integrations ?? []).find((x) => x.id === repairBtn.dataset.intRepair);
456
+ if (it) openRepairIntegrationDialog(it, store.state?.agents ?? []);
457
+ return;
458
+ }
459
+ const applyIntBtn = target.closest("[data-int-apply]");
460
+ if (applyIntBtn) {
461
+ const id = applyIntBtn.dataset.intApply;
462
+ if (!confirm(`确认将联合集成 #${id} 合并到主目录?操作只写工作区文件,不自动 commit。`)) return;
463
+ applyIntBtn.disabled = true;
464
+ try { await runControlAction(`/api/changes/${encodeURIComponent(id)}/apply`, {}, `联合集成 #${id} 已应用到主目录`); }
465
+ catch (err) { toast(err.message); applyIntBtn.disabled = false; }
466
+ return;
467
+ }
468
+ const cancelIntBtn = target.closest("[data-int-cancel]");
469
+ if (cancelIntBtn) {
470
+ const id = cancelIntBtn.dataset.intCancel;
471
+ if (!confirm(`确认取消联合集成 #${id}?来源分支改动会保留。`)) return;
472
+ cancelIntBtn.disabled = true;
473
+ try { await runControlAction(`/api/integrations/${encodeURIComponent(id)}/cancel`, {}, `已取消联合集成 #${id}`); }
474
+ catch (err) { toast(err.message); cancelIntBtn.disabled = false; }
475
+ return;
476
+ }
477
+ const opBtn = target.closest("[data-resolve-op]");
478
+ if (opBtn) {
479
+ const op = (store.state?.operations ?? []).find((x) => x.id === opBtn.dataset.resolveOp);
480
+ if (op) openResolveOperationDialog(op);
481
+ }
482
+ });
483
+ this.update("all");
484
+ },
485
+ update(kind) {
486
+ if (kind === "tick" || kind === "live" || kind === "items" || kind === "job-output" || kind === "usage") return;
487
+ const p = store.state?.project;
488
+ if (!p) {
489
+ root.innerHTML = empty("加载中…");
490
+ return;
491
+ }
492
+ const openMoreIds = new Set([...root.querySelectorAll(".tc-more[open]")].map((el) => el.dataset.taskId));
493
+ const tasks = p.tasks.filter((t) => t.status !== "dropped");
494
+ const count = (s) => tasks.filter((t) => t.status === s).length;
495
+ const done = count("done");
496
+ const doing = count("doing");
497
+ const review = count("review");
498
+ const blocked = count("blocked");
499
+ const pct = tasks.length ? Math.round((done / tasks.length) * 100) : 0;
500
+ const segW = (n) => (tasks.length ? ((n / tasks.length) * 100).toFixed(2) : 0);
501
+ const available = new Set((store.state.agents ?? []).filter((a) => a.available).map((a) => a.kind));
502
+ const uncertain = (store.state.operations ?? []).filter((operation) => operation.method === "POST" && ["pending", "unknown"].includes(operation.status));
503
+ const resources = store.state.resources ?? { running: [], queued: [], reservedUsd: 0 };
504
+ const wfPaused = !!store.state.workflow?.paused;
505
+ const readinessList = store.state.readyTasks ?? [];
506
+ const readinessMap = new Map(readinessList.map((r) => [r.id, r]));
507
+ const readyList = readinessList.filter((r) => r.ready);
508
+ const activeIntegrations = (store.state.integrations ?? []).filter((it) => !it.supersededBy && it.changeStatus !== "dropped");
509
+ const pendingBranchCount = store.changes.filter((c) => !c.integration && ["pending", "conflict"].includes(c.status)).length;
510
+ const canCreateInt = pendingBranchCount >= 2;
511
+ const dispatchByTask = new Map();
512
+ for (const d of store.dispatches ?? []) {
513
+ if (d.taskId && !dispatchByTask.has(d.taskId)) dispatchByTask.set(d.taskId, d);
514
+ }
515
+ const cardHtml = (t) => taskCard(t, p.tasks, readinessMap, dispatchByTask.get(t.id), openMoreIds.has(t.id));
516
+
517
+ if (statusFilter !== "all" && !count(statusFilter)) statusFilter = "all";
518
+
519
+ const activeCols = COLUMNS.filter((c) => c.s !== "done")
520
+ .map((c) => ({ ...c, list: tasks.filter((t) => t.status === c.s) }))
521
+ .filter((c) => c.list.length > 0);
522
+ const doneList = tasks.filter((t) => t.status === "done");
523
+
524
+ let boardBody = "";
525
+ if (!tasks.length) {
526
+ boardBody = `<div class="empty-inline"><span class="dot"></span>项目级、多步骤的任务,总调度会先拆成任务写进分工表(每项有角色、负责人、依赖和验收标准),再按依赖顺序派工。</div>`;
527
+ } else if (statusFilter !== "all") {
528
+ const col = COLUMNS.find((c) => c.s === statusFilter);
529
+ const list = tasks.filter((t) => t.status === statusFilter);
530
+ boardBody = `<div class="board-band-head" data-s="${col.s}"><span class="band-title"><i></i>${col.label}</span><em>${list.length} 项</em></div>
531
+ <div class="task-grid">${list.map(cardHtml).join("")}</div>`;
532
+ } else {
533
+ const parts = [];
534
+ if (activeCols.length === 1) {
535
+ const only = activeCols[0];
536
+ parts.push(`<div class="board-band-head" data-s="${only.s}"><span class="band-title"><i></i>${only.label}</span><em>${only.list.length} 项</em></div>
537
+ <div class="task-grid">${only.list.map(cardHtml).join("")}</div>`);
538
+ } else if (activeCols.length > 1) {
539
+ parts.push(`<div class="kanban" style="--cols:${activeCols.length}">${activeCols
540
+ .map((col) => `<div class="kanban-col" data-s="${col.s}"><div class="kanban-head"><span>${col.label}</span><em>${col.list.length}</em></div><div class="kanban-list">${col.list.map(cardHtml).join("")}</div></div>`)
541
+ .join("")}</div>`);
542
+ }
543
+ if (doneList.length) {
544
+ parts.push(`<div class="${activeCols.length ? "board-done-band" : ""}">
545
+ <div class="board-band-head" data-s="done"><span class="band-title"><i></i>已完成</span><em>${doneList.length} 项</em></div>
546
+ <div class="task-grid">${doneList.map(cardHtml).join("")}</div>
547
+ </div>`);
548
+ }
549
+ boardBody = parts.join("");
550
+ }
551
+
552
+ const scopeHtml = renderScopeMatrix(p.tasks);
553
+ const reviewLoopHtml = renderReviewLoopPanel(p.tasks, store.dispatches);
554
+ const rolesHtml = `
555
+ <section class="card">
556
+ <header class="card-head"><div class="card-heading"><h2 class="card-title">角色分工</h2><div class="card-sub">按角色选成员与回退顺序(配置于 pi-agent.config.json)</div></div></header>
557
+ <div class="table-wrap"><table class="table"><thead><tr><th>角色</th><th>成员(首选 → 备选)</th><th class="hide-sm">模型</th><th>负责</th><th class="num">任务</th></tr></thead>
558
+ <tbody>${(p.roles ?? [])
559
+ .map((r) => {
560
+ const chain = [r.agent, ...(r.fallback ?? [])];
561
+ const pick = chain.find((k) => available.has(k));
562
+ return `<tr><td><span class="role-chip">${esc(r.name)}</span></td>
563
+ <td>${chain.map((k) => `<span class="${k === pick ? "" : "dim-agent"}">${agentTag(k)}</span>`).join('<span class="muted"> → </span>')}</td>
564
+ <td class="hide-sm">${r.model ? `<span class="model-chip">${esc(r.model)}</span>` : `<span class="muted">成员默认</span>`}</td>
565
+ <td class="muted">${esc(r.note ?? "")}</td>
566
+ <td class="num mono">${tasks.filter((t) => t.role === r.name).length}</td></tr>`;
567
+ })
568
+ .join("")}</tbody></table></div>
569
+ </section>`;
570
+
571
+ root.innerHTML = `
572
+ <section class="proj-stats">
573
+ <div class="proj-stat">
574
+ <div class="proj-stat-top"><span>任务进度</span><em class="proj-pct ${pct === 100 && tasks.length ? "done" : ""}">${tasks.length ? `${pct}%` : "0%"}</em></div>
575
+ <strong><b>${done}</b> / ${tasks.length} ${tasks.length ? (doing ? `· ${doing} 进行中` : review ? `· ${review} 待验收` : blocked ? `· ${blocked} 受阻` : "全部完成") : "等待拆解"}</strong>
576
+ <div class="proj-bar" title="完成 ${done} · 待验收 ${review} · 进行中 ${doing} · 受阻 ${blocked}">
577
+ <i class="s-done" style="width:${segW(done)}%"></i><i class="s-review" style="width:${segW(review)}%"></i><i class="s-doing" style="width:${segW(doing)}%"></i><i class="s-blocked" style="width:${segW(blocked)}%"></i>
578
+ </div>
579
+ </div>
580
+ <div class="proj-stat">
581
+ <div class="proj-stat-top"><span>自动推进</span><button type="button" class="${wfPaused ? "primary-btn" : "ghost-btn"} tiny" data-wf-action="${wfPaused ? "resume" : "pause"}">${wfPaused ? "恢复推进" : "暂停"}</button></div>
582
+ <strong><b class="${wfPaused ? "" : "live"}">${wfPaused ? "已暂停" : "运行中"}</b> · 就绪 ${readyList.length}</strong>
583
+ <p class="proj-stat-sub">运行 ${resources.running.length} · 排队 ${resources.queued.length} · 预留 $${Number(resources.reservedUsd).toFixed(4)}</p>
584
+ </div>
585
+ <div class="proj-stat">
586
+ <div class="proj-stat-top"><span>多分支集成</span>${canCreateInt ? `<button type="button" class="ghost-btn tiny" data-create-int="1">+ 发起联合集成</button>` : `<span class="proj-chip">${pendingBranchCount} 待合分支</span>`}</div>
587
+ <strong>${activeIntegrations.length ? `<b>${activeIntegrations.length}</b> 项集成任务` : `<b>${pendingBranchCount}</b> 个待处理分支`}</strong>
588
+ <p class="proj-stat-sub">${activeIntegrations.length ? "可在下方查看集成检查状态与修复冲突" : canCreateInt ? "支持合流多个隔离分支并运行全套验收" : "存在 2 个及以上未合并分支后可发起"}</p>
589
+ </div>
590
+ <div class="proj-stat">
591
+ <div class="proj-stat-top"><span>最终目标</span><code class="path-pill" title="${esc(p.goalPath)}">${esc(shortPath(p.goalPath))}</code></div>
592
+ <strong>${p.goal ? (/待你确认/.test(p.goal) ? `<span class="pill" data-s="pending">总调度起草 · 待确认</span>` : `<b>已设定</b> 目标文档`) : `<span class="muted">尚未设定</span>`}</strong>
593
+ <p class="proj-stat-sub">${p.goal ? "成员每次派工都会自动携带 GOAL.md" : "告知总调度项目目标即可起草并同步成员"}</p>
594
+ </div>
595
+ </section>
596
+ ${uncertain.length ? `<section class="card"><header class="card-head"><h2 class="card-title err-t">外部操作待核对</h2></header><div class="card-body">${uncertain.map((operation) => `<div class="job-row"><span class="mono">${esc(operation.id)}</span><span>${esc(operation.member)}/${esc(operation.tool)}</span><span class="job-task">${esc(operation.failure?.message ?? "请求已发出但尚无确定回执")}</span><button type="button" class="ghost-btn tiny" data-resolve-op="${esc(operation.id)}">人工核对</button></div>`).join("")}<p class="muted">核对远端状态前禁止重复提交同一接口。</p></div></section>` : ""}
597
+ ${resources.queued.length ? `<section class="card"><header class="card-head"><div class="card-heading"><h2 class="card-title">资源排队与就绪队列</h2></div></header><div class="card-body">${resources.queued.map((claim) => `<div class="job-row"><span class="pill" data-s="running">排队中</span><span>${esc(claim.member)}</span><span class="job-task">${esc(claim.reason ?? "等待可用名额")}</span></div>`).join("")}</div></section>` : ""}
598
+ ${activeIntegrations.length ? `<section class="card"><header class="card-head"><div class="card-heading"><h2 class="card-title">多分支联合集成与联调</h2><div class="card-sub">合并多个隔离分支并运行全套检查 · 冲突时可直接派成员修现场</div></div>${canCreateInt ? `<button type="button" class="ghost-btn tiny" data-create-int="1">+ 发起联合集成</button>` : ""}</header><div class="card-body">${activeIntegrations.slice(0, 6).map((it) => {
599
+ const st = it.status ?? it.changeStatus;
600
+ const pillState = st === "passed" || it.changeStatus === "applied" ? "done" : ["preparing", "merging", "repairing", "testing"].includes(st) ? "running" : st === "cancelled" ? "aborted" : "error";
601
+ const srcs = (it.sources ?? []).map((s) => `<a href="#/changes/${esc(s.id)}">#${esc(s.id)}</a>`).join(" + ");
602
+ const runningInt = ["preparing", "merging", "repairing", "testing"].includes(st);
603
+ const canApply = st === "passed" && it.changeStatus !== "applied";
604
+ const canRepair = ["conflict", "failed"].includes(st);
605
+ return `<div class="job-row int-row"><a class="mono" href="#/changes/${esc(it.id)}">#${esc(it.id)}</a><span class="pill" data-s="${pillState}">${esc(it.changeStatus === "applied" ? "已合并" : st)}</span><span class="job-task">来源 ${srcs}${it.repair ? ` · 修复自 #${esc(it.repair.fromId)}(${esc(it.repair.member)})` : ""}${it.conflicts?.length ? ` · 冲突:${esc(it.conflicts.join("、"))}` : ""}${it.message ? ` · <span class="muted">${esc(short(it.message, 80))}</span>` : ""}</span><div class="row-actions">${canApply ? `<button type="button" class="primary-btn tiny" data-int-apply="${esc(it.id)}">应用到主目录</button>` : ""}${canRepair ? `<button type="button" class="ghost-btn tiny" data-int-repair="${esc(it.id)}">派人修复</button>` : ""}${!runningInt && it.changeStatus !== "applied" ? `<button type="button" class="ghost-btn tiny" data-int-rerun="${esc(it.id)}">重跑检查</button>` : ""}${runningInt ? `<button type="button" class="ghost-btn tiny" data-int-cancel="${esc(it.id)}">取消</button>` : ""}</div></div>`;
606
+ }).join("")}</div></section>` : ""}
607
+ ${p.goal ? `<section class="card goal-card"><header class="card-head"><div class="card-heading"><h2 class="card-title">最终目标(GOAL.md)</h2><div class="card-sub"><span class="mono" title="${esc(p.goalPath)}">${esc(shortPath(p.goalPath))}</span></div></div>${/待你确认/.test(p.goal) ? `<span class="pill" data-s="pending">总调度起草 · 待你确认</span>` : ""}</header><div class="card-body"><div class="md goal-md">${markdown(p.goal.replace(/^<!--[\s\S]*?-->\s*/, ""))}</div></div></section>` : ""}
608
+ <section class="card board-card">
609
+ <header class="card-head">
610
+ <div class="card-heading">
611
+ <h2 class="card-title">分工表</h2>
612
+ <div class="board-filters">${[
613
+ { k: "all", label: "全部", n: tasks.length },
614
+ ...COLUMNS.map((c) => ({ k: c.s, label: c.label, n: count(c.s) })),
615
+ ]
616
+ .map((f) => `<button type="button" class="board-filter${statusFilter === f.k ? " on" : ""}" data-task-filter="${f.k}" data-s="${f.k}" ${f.k !== "all" && !f.n ? "disabled" : ""}><span>${f.label}</span><em>${f.n}</em></button>`)
617
+ .join("")}</div>
618
+ </div>
619
+ <div class="row-actions">
620
+ <code class="path-pill" title="${esc(p.assignPath)}">${esc(shortPath(p.assignPath))}</code>
621
+ ${tasks.length ? `<a class="ghost-btn tiny" href="#/dag">查看任务图谱 (DAG) →</a>` : ""}
622
+ </div>
623
+ </header>
624
+ <div class="card-body">${boardBody}</div>
625
+ </section>
626
+ ${reviewLoopHtml ? `<div data-n="reviewLoopWrap">${reviewLoopHtml}</div>` : ""}
627
+ ${scopeHtml}${rolesHtml}`;
628
+ const loopWrap = root.querySelector('[data-n="reviewLoopWrap"]');
629
+ if (loopWrap) bindDagPanelEvents(loopWrap);
630
+ },
631
+ };
632
+ }
633
+
634
+ // =====================================================================
635
+ // 任务图谱(DAG)
636
+ // =====================================================================
637
+ function dag() {
638
+ let root;
639
+ let topoData = null;
640
+ let loadedOnce = false;
641
+ let loading = false;
642
+ let timer = null;
643
+ let lastSig = "";
644
+
645
+ async function load() {
646
+ if (!root || loading) return;
647
+ loading = true;
648
+ try {
649
+ topoData = await getJson("/api/topology?limit=200");
650
+ } catch {
651
+ /* 断线或未就绪时回退 store.state 渲染 */
652
+ } finally {
653
+ loadedOnce = true;
654
+ loading = false;
655
+ render();
656
+ }
657
+ }
658
+ const reload = (delay = 180) => {
659
+ clearTimeout(timer);
660
+ timer = setTimeout(load, delay);
661
+ };
662
+
663
+ function render() {
664
+ if (!root) return;
665
+ if (!topoData && !store.state && !loadedOnce) return;
666
+ const tasks = topoData?.tasks ?? store.state?.project?.tasks ?? [];
667
+ const integrations = (topoData?.integrations ?? store.state?.integrations ?? []).filter((it) => !it.supersededBy && it.changeStatus !== "dropped");
668
+ const readinessList = topoData?.readyTasks ?? store.state?.readyTasks ?? [];
669
+ const sig = JSON.stringify([tasks, integrations, readinessList]);
670
+ if (sig === lastSig) return;
671
+ lastSig = sig;
672
+
673
+ const readinessMap = new Map(readinessList.map((r) => [r.id, r]));
674
+ const active = tasks.filter((t) => t.status !== "dropped");
675
+ const done = active.filter((t) => t.status === "done").length;
676
+ const doing = active.filter((t) => t.status === "doing" || t.status === "review").length;
677
+ const reviewCount = active.filter((t) => !!t.reviewer).length;
678
+ const blindCount = active.filter((t) => t.reviewer?.blind).length;
679
+ const scopedCount = active.filter((t) => t.scope && (t.scope.allow?.length || t.scope.forbid?.length)).length;
680
+ const topoInfo = classifyTopology(tasks, integrations);
681
+
682
+ const statsEl = root.querySelector('[data-n="stats"]');
683
+ if (statsEl) {
684
+ statsEl.innerHTML = [
685
+ ["协作模式", `<b>${esc(topoInfo.title)}</b>`],
686
+ ["任务进度", active.length ? `<b>${done}</b> / ${active.length}${doing ? `(<b>${doing}</b> 活跃)` : ""}` : "等待拆解"],
687
+ ["独立复核 / 盲审", blindCount ? `<b>${reviewCount}</b> 项(含 <b>${blindCount}</b> 盲审)` : `<b>${reviewCount}</b> 项`],
688
+ ["路径隔离 / 集成", `<b>${scopedCount}</b> 锁域 · <b>${integrations.length}</b> 集成`],
689
+ ]
690
+ .map(([k, v]) => `<div class="topo-stat"><span>${k}</span><strong>${v}</strong></div>`)
691
+ .join("");
692
+ }
693
+ const subEl = root.querySelector('[data-n="sub"]');
694
+ if (subEl) subEl.textContent = topoInfo.detail;
695
+
696
+ const stageEl = root.querySelector('[data-n="stage"]');
697
+ if (!stageEl) return;
698
+ renderTaskDag(stageEl, {
699
+ tasks,
700
+ integrations,
701
+ readinessMap,
702
+ onSelectTask: (t) => {
703
+ const bar = (topoData?.bars ?? []).filter((b) => b.taskId === t.id).at(-1);
704
+ const dispatch = bar ?? store.dispatches.find((d) => d.taskId === t.id);
705
+ if (dispatch?.key) openDispatch(dispatch.key);
706
+ else location.hash = "#/project";
707
+ },
708
+ });
709
+ }
710
+
711
+ return {
712
+ title: "任务图谱 (DAG)",
713
+ sub: "多 Agent 依赖拓扑、盲审关系与集成汇流一览",
714
+ mount(r) {
715
+ root = r;
716
+ lastSig = "";
717
+ loadedOnce = false;
718
+ root.innerHTML = `<div class="topo-stats cols-4" data-n="stats"></div>
719
+ <section class="card dag-card">
720
+ <header class="card-head">
721
+ <div class="card-heading">
722
+ <h2 class="card-title">多 Agent 任务依赖与协作图谱(DAG)</h2>
723
+ <div class="card-sub" data-n="sub">悬停高亮上下游,点节点查看派工详情</div>
724
+ </div>
725
+ <div class="row-actions">
726
+ <a class="ghost-btn tiny" href="#/project">分工表 →</a>
727
+ <a class="ghost-btn tiny" href="#/topology">查看协作时间线 →</a>
728
+ </div>
729
+ </header>
730
+ <div class="card-body dag-stage" data-n="stage"><div class="empty-inline"><span class="dot"></span>加载中…</div></div>
731
+ </section>`;
732
+ render();
733
+ load();
734
+ },
735
+ unmount() {
736
+ clearTimeout(timer);
737
+ root = null;
738
+ },
739
+ update(kind) {
740
+ if (!root) return;
741
+ if (kind === "tick" || kind === "live" || kind === "items" || kind === "job-output" || kind === "usage") return;
742
+ render();
743
+ if (kind === "all" || kind === "state" || kind === "dispatches" || kind === "changes" || kind === "jobs") reload(180);
744
+ },
745
+ };
746
+ }
747
+
748
+ // =====================================================================
749
+ // 运行记录
750
+ // =====================================================================
751
+ function runs() {
752
+ let root;
753
+ let selected = null; // 选中的运行 id;null = 跟随最新
754
+ let timeline = null;
755
+ let shownId = null;
756
+ return {
757
+ title: "运行记录",
758
+ sub: "",
759
+ mount(r, params) {
760
+ root = r;
761
+ selected = params[0] ?? null;
762
+ root.innerHTML = `<div class="runs-layout">
763
+ <section class="card run-list"><header class="card-head"><h2 class="card-title">运行</h2><span class="card-note" data-n="count"></span></header>
764
+ <div class="run-scroll" data-n="list"></div></section>
765
+ <section class="card run-detail" data-n="detail"></section>
766
+ </div>`;
767
+ this.update("all");
768
+ },
769
+ unmount() {
770
+ timeline = null;
771
+ shownId = null;
772
+ },
773
+ update(kind) {
774
+ if (kind === "tick" || kind === "state" || kind === "dispatches" || kind === "job-output") {
775
+ if (timeline && (kind === "tick" || kind === "job-output")) timeline.live(store.live, shownId === this.latestId);
776
+ return;
777
+ }
778
+ const all = buildRuns();
779
+ const real = all.filter((x) => !x.divider);
780
+ this.latestId = real.at(-1)?.id;
781
+ const list = root.querySelector('[data-n="list"]');
782
+ const target = selected ?? this.latestId;
783
+ root.querySelector('[data-n="count"]').textContent = `${real.length} 次${store.hasMore ? "(已加载部分)" : ""}`;
784
+ if (kind !== "live" || real.some((x) => x.status === "running")) {
785
+ const html = all
786
+ .slice()
787
+ .reverse()
788
+ .map((run) => (run.divider ? `<div class="run-divider">${esc(run.label)}</div>` : runRow(run)))
789
+ .join("");
790
+ list.innerHTML = (html || empty("还没有运行记录。在终端里输入任务开始。")) + (store.hasMore ? `<button class="ghost-btn load-more" type="button">加载更早的记录</button>` : "");
791
+ list.querySelector(`[data-id="${CSS.escape(String(target))}"]`)?.classList.add("active");
792
+ list.querySelector(".load-more")?.addEventListener("click", async (e) => {
793
+ e.currentTarget.disabled = true;
794
+ try {
795
+ const n = await loadEarlier();
796
+ toast(n ? `加载了 ${n} 条更早的记录` : "没有更早的记录了");
797
+ } catch (err) {
798
+ toast(`加载失败:${err.message}`);
799
+ }
800
+ });
801
+ }
802
+ this.detail(real.find((x) => x.id === target), kind);
803
+ },
804
+ detail(run, kind) {
805
+ const box = root.querySelector('[data-n="detail"]');
806
+ if (!run) {
807
+ timeline = null;
808
+ shownId = null;
809
+ box.innerHTML = empty(store.loaded ? "选择左侧的一次运行查看详情" : "加载中…");
810
+ return;
811
+ }
812
+ const current = run.id === this.latestId;
813
+ if (shownId !== run.id) {
814
+ shownId = run.id;
815
+ timeline = new Timeline();
816
+ box.innerHTML = `<header class="detail-head"><div><h2 class="eyebrow">运行详情</h2><p class="detail-title"></p></div><span class="pill" data-n="pill"></span></header><div class="detail-meta" data-n="meta"></div>`;
817
+ box.querySelector(".detail-title").textContent = run.user ? short(run.user.text, 120) : "(输入在更早的历史里)";
818
+ const scroll = el("div", "detail-scroll");
819
+ scroll.append(timeline.node);
820
+ box.append(scroll);
821
+ timeline.add(run.items);
822
+ } else {
823
+ const scroll = box.querySelector(".detail-scroll");
824
+ const near = scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight < 160;
825
+ timeline.add(run.items, { animate: kind === "items" });
826
+ if (near && kind === "items") scroll.scrollTop = scroll.scrollHeight;
827
+ }
828
+ const pill = box.querySelector('[data-n="pill"]');
829
+ pill.dataset.s = PILL[run.status];
830
+ pill.textContent = RUN_LABEL[run.status];
831
+ box.querySelector('[data-n="meta"]').innerHTML = [
832
+ execPathBadge(run.execPath),
833
+ `开始 ${stamp(run.at)}`,
834
+ run.endAt && run.at ? `耗时 ${duration(run.endAt - run.at)}` : "",
835
+ run.dispatchCount ? `派工 ${run.dispatchCount} 次` : "没有派工",
836
+ run.agents.length ? run.agents.map(agentTag).join("") : "",
837
+ ]
838
+ .filter(Boolean)
839
+ .join('<span class="sep"></span>');
840
+ timeline.live(store.live, current);
841
+ },
842
+ };
843
+ }
844
+
845
+ // =====================================================================
846
+ // 派工明细
847
+ // =====================================================================
848
+ function dispatches() {
849
+ let root;
850
+ const filter = { agent: "all", status: "all", q: "" };
851
+ return {
852
+ title: "派工明细",
853
+ sub: "",
854
+ mount(r, params) {
855
+ root = r;
856
+ filter.agent = KINDS.includes(params[0]) ? params[0] : "all";
857
+ filter.status = ["running", "done", "error", "aborted", "open"].includes(params[1]) ? params[1] : "all";
858
+ root.innerHTML = `<section class="card">
859
+ <div class="toolbar">
860
+ <div class="seg" data-n="agents"></div>
861
+ <select class="select" data-n="status" aria-label="按状态筛选">
862
+ <option value="all">全部状态</option><option value="running">执行中</option><option value="done">完成</option>
863
+ <option value="error">失败</option><option value="aborted">中止 / 中断</option><option value="open">无结果</option>
864
+ </select>
865
+ <input class="search" data-n="q" type="search" placeholder="搜索任务、会话、目录…" />
866
+ <span class="card-note" data-n="count"></span>
867
+ </div>
868
+ <div class="table-wrap"><table class="table">
869
+ <thead><tr><th>时间</th><th>成员</th><th class="hide-sm">模型</th><th class="w-task">任务</th><th>状态</th><th class="num">耗时</th><th class="num hide-sm">花费</th><th class="hide-sm">改动</th></tr></thead>
870
+ <tbody data-n="rows"></tbody>
871
+ </table></div>
872
+ </section>`;
873
+ const seg = root.querySelector('[data-n="agents"]');
874
+ seg.innerHTML = ["all", ...KINDS].map((k) => `<button type="button" data-k="${esc(k)}" style="--c:${k === "all" ? "var(--ink)" : agentColor(k)}">${k === "all" ? "全部" : esc(AGENT_LABEL[k] ?? k)}</button>`).join("");
875
+ seg.addEventListener("click", (e) => {
876
+ const b = e.target instanceof Element ? e.target.closest("button") : null;
877
+ if (!b) return;
878
+ filter.agent = b.dataset.k;
879
+ this.update("all");
880
+ });
881
+ root.querySelector('[data-n="status"]').value = filter.status;
882
+ root.querySelector('[data-n="status"]').addEventListener("change", (e) => {
883
+ filter.status = e.target.value;
884
+ this.update("all");
885
+ });
886
+ root.querySelector('[data-n="q"]').addEventListener("input", (e) => {
887
+ filter.q = e.target.value.trim().toLowerCase();
888
+ this.update("all");
889
+ });
890
+ root.querySelector('[data-n="rows"]').addEventListener("click", (e) => {
891
+ if (e.target instanceof Element && e.target.closest("button")) return;
892
+ const tr = e.target instanceof Element ? e.target.closest("tr[data-id]") : null;
893
+ if (tr) openDispatch(tr.dataset.id);
894
+ });
895
+ this.update("all");
896
+ },
897
+ update(kind) {
898
+ if (kind === "state") root.querySelector('[data-n="agents"]').innerHTML = ["all", ...KINDS].map((k) => `<button type="button" data-k="${esc(k)}" style="--c:${k === "all" ? "var(--ink)" : agentColor(k)}">${k === "all" ? "全部" : esc(AGENT_LABEL[k] ?? k)}</button>`).join("");
899
+ for (const b of root.querySelectorAll('[data-n="agents"] button')) b.classList.toggle("on", b.dataset.k === filter.agent);
900
+ const all = dispatchRows();
901
+ const rows = all.filter((d) => {
902
+ if (filter.agent !== "all" && d.agent !== filter.agent) return false;
903
+ if (filter.status !== "all") {
904
+ if (filter.status === "aborted" ? !(d.status === "aborted" || d.status === "interrupted") : d.status !== filter.status) return false;
905
+ }
906
+ if (filter.q && ![d.task, d.sessionId, d.cwd, d.callId].some((v) => String(v ?? "").toLowerCase().includes(filter.q))) return false;
907
+ return true;
908
+ });
909
+ root.querySelector('[data-n="count"]').textContent = `${rows.length} / ${all.length}`;
910
+ const tbody = root.querySelector('[data-n="rows"]');
911
+ if (!rows.length) {
912
+ tbody.innerHTML = `<tr class="empty-row"><td colspan="8">${all.length ? "没有符合条件的派工" : "还没有派工记录"}</td></tr>`;
913
+ return;
914
+ }
915
+ tbody.innerHTML = rows
916
+ .map((d) => {
917
+ const started = d.slot ? slotStart.get(d.callId) : undefined;
918
+ const took = d.status === "running" && started ? duration(Date.now() - started) : duration(d.durationMs);
919
+ return `<tr data-id="${esc(d.key ?? d.callId)}" data-s="${d.status}">
920
+ <td class="mono">${stamp(d.at)}</td>
921
+ <td>${agentTag(d.agent)}</td>
922
+ <td class="hide-sm">${d.model ? `<span class="model-chip">${esc(d.model)}</span>` : `<span class="muted">—</span>`}</td>
923
+ <td class="w-task"><span class="cell-task">${d.readonly ? `<span class="resume-tag">只读直查</span>` : d.fastPath ? `<span class="resume-tag">${d.escalated ? "快路已升级" : "单跳快路"}</span>` : ""}${d.callId?.startsWith("checker:") ? `<span class="resume-tag">独立复核</span>` : d.callId?.startsWith("integration-repair:") ? `<span class="resume-tag">集成修复</span>` : d.callId?.startsWith("workflow:") ? `<span class="resume-tag">自动推进</span>` : ""}${d.resume ? `<span class="resume-tag">续接</span>` : ""}${d.basedOn ? `<span class="resume-tag">基于 #${esc(d.basedOn)}</span>` : ""}${esc(short(d.task, 140) || "—")}</span></td>
924
+ <td><span class="pill" data-s="${PILL[d.status]}">${STATUS_LABEL[d.status]}</span></td>
925
+ <td class="num mono">${took}</td>
926
+ <td class="num mono hide-sm" title="${d.costEstimated ? "按单价估算" : ""}">${money(d.cost)}${d.costEstimated ? "≈" : ""}</td>
927
+ <td class="hide-sm">${d.changeId ? changeLink(d.changeId) : `<span class="muted">—</span>`}</td>
928
+ </tr>`;
929
+ })
930
+ .join("");
931
+ },
932
+ };
933
+ }
934
+
935
+ // =====================================================================
936
+ // 改动(GitLens 提交图谱与推送工作台)
937
+ // =====================================================================
938
+ const changes = createChangesView;
939
+
940
+ // =====================================================================
941
+ // Agent 规范:各家 CLI 的规范 / 配置文件
942
+ // =====================================================================
943
+ const OWNER_LABEL = { claude: "Claude", codex: "Codex", gemini: "Gemini", shared: "通用", "pi-agent": "Lemma" };
944
+ const KIND_LABEL = { instructions: "说明", settings: "设置", subagent: "子 agent", command: "命令", skill: "技能", mcp: "MCP", project: "项目" };
945
+ const KIND_ORDER = ["project", "instructions", "settings", "mcp", "subagent", "command", "skill"];
946
+
947
+ function conventions() {
948
+ let root;
949
+ let data = null;
950
+ let selected = null;
951
+ let query = "";
952
+ const cache = new Map();
953
+ return {
954
+ title: "Agent 规范",
955
+ sub: "",
956
+ async mount(r, params) {
957
+ root = r;
958
+ selected = params.length ? decodeURIComponent(params.join("/")) : null;
959
+ root.innerHTML = empty("扫描中…");
960
+ await this.load();
961
+ },
962
+ async load() {
963
+ try {
964
+ data = await getJson("/api/conventions");
965
+ } catch (err) {
966
+ root.innerHTML = empty(`扫描失败:${err.message}`);
967
+ return;
968
+ }
969
+ this.render();
970
+ },
971
+ update() {},
972
+ render() {
973
+ const d = data;
974
+ const label = { claude: "Claude", codex: "Codex", gemini: "Gemini" };
975
+ const fileChip = (f) =>
976
+ `<a class="conv-chip" href="#/conventions/${encodeURIComponent(f.id)}" title="${esc(f.id)}"><span class="scope-tag">${f.scope === "user" ? "用户" : "项目"}</span>${esc(f.rel)}${f.size === 0 ? `<em class="muted">空</em>` : ""}${f.rules === "synced" ? `<em class="ok-t">规则 ✓</em>` : f.rules ? `<em class="err-t">规则${f.rules === "stale" ? "过期" : "缺失"}</em>` : ""}</a>`;
977
+ const members = ["claude", "codex", "gemini"]
978
+ .map((k) => {
979
+ const m = d.members[k];
980
+ const hasProject = m.instructions.some((f) => f.scope === "project" && f.size > 0);
981
+ return `<section class="card conv-member" style="--c:${agentColor(k)}">
982
+ <header class="agent-head"><span class="lamp"></span><h2>${label[k]}</h2><span class="pill" data-s="${hasProject ? "done" : "error"}">${hasProject ? "有项目说明" : "缺项目说明"}</span></header>
983
+ <div class="conv-label">会读到的说明</div>
984
+ <div class="conv-chips">${m.instructions.map(fileChip).join("") || `<span class="muted">没有</span>`}</div>
985
+ <div class="figures conv-figs">
986
+ <div><span>设置</span><strong>${m.settings.length}</strong></div>
987
+ <div><span>技能</span><strong>${m.skills}</strong></div>
988
+ <div><span>命令</span><strong>${m.commands}</strong></div>
989
+ <div><span>子 agent</span><strong>${m.subagents}</strong></div>
990
+ </div>
991
+ </section>`;
992
+ })
993
+ .join("");
994
+ const checks = d.checks
995
+ .map(
996
+ (c) => `<div class="conv-check" data-level="${c.level}"><span class="conv-icon">${c.level === "warn" ? "!" : c.level === "ok" ? "✓" : "i"}</span>
997
+ <div><strong>${esc(c.title)}</strong>${c.detail ? `<p>${esc(c.detail)}</p>` : ""}${c.files?.length ? `<p class="conv-files">${c.files.map((id) => `<a href="#/conventions/${encodeURIComponent(id)}">${esc(id.replace(/^user:/, "~/").replace(/^project:/, ""))}</a>`).join("")}</p>` : ""}</div></div>`,
998
+ )
999
+ .join("");
1000
+ root.innerHTML = `
1001
+ <div class="conv-members">${members}</div>
1002
+ <section class="card">
1003
+ <header class="card-head"><div class="card-heading"><h2 class="card-title">检查</h2><div class="card-sub">共同规则:${d.rules.exists ? `<span class="mono">.pi-agent/RULES.md</span>(${esc(d.rules.hash ?? "")})` : "还没有,终端 /rules init 生成模板"}</div></div>
1004
+ <button type="button" class="ghost-btn" data-n="rescan">重新扫描</button></header>
1005
+ <div class="card-body conv-checks">${checks}</div>
1006
+ </section>
1007
+ <section class="card">
1008
+ <header class="card-head"><div class="card-heading"><h2 class="card-title">文件</h2><div class="card-sub">项目:<span class="mono">${esc(d.project)}</span> 用户:<span class="mono">${esc(d.home)}</span></div></div>
1009
+ <input class="search" data-n="q" type="search" placeholder="搜索文件、技能…" value="${esc(query)}" /></header>
1010
+ <div class="conv-browser">
1011
+ <div class="conv-tree" data-n="tree"></div>
1012
+ <div class="conv-preview" data-n="preview"></div>
1013
+ </div>
1014
+ </section>`;
1015
+ root.querySelector('[data-n="rescan"]').addEventListener("click", () => {
1016
+ cache.clear();
1017
+ this.load();
1018
+ });
1019
+ root.querySelector('[data-n="q"]').addEventListener("input", (e) => {
1020
+ query = e.target.value.trim().toLowerCase();
1021
+ this.tree();
1022
+ });
1023
+ this.tree();
1024
+ this.preview();
1025
+ },
1026
+ tree() {
1027
+ const box = root.querySelector('[data-n="tree"]');
1028
+ const files = data.files.filter((f) => !query || `${f.rel} ${f.name ?? ""} ${f.description ?? ""}`.toLowerCase().includes(query));
1029
+ const groups = [];
1030
+ for (const scope of ["project", "user"]) {
1031
+ for (const owner of ["pi-agent", "claude", "codex", "gemini", "shared"]) {
1032
+ const list = files.filter((f) => f.scope === scope && f.owner === owner).sort((a, b) => KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) || a.rel.localeCompare(b.rel));
1033
+ if (!list.length) continue;
1034
+ groups.push(`<div class="conv-group"><div class="conv-group-head">${scope === "user" ? "用户" : "项目"} · ${OWNER_LABEL[owner]}<em>${list.length}</em></div>${list
1035
+ .map(
1036
+ (f) => `<a class="conv-item${f.id === selected ? " active" : ""}" href="#/conventions/${encodeURIComponent(f.id)}" title="${esc(f.description ?? f.rel)}">
1037
+ <span class="conv-kind" data-kind="${f.kind}">${KIND_LABEL[f.kind]}</span><span class="conv-name">${esc(f.kind === "skill" || f.kind === "subagent" || f.kind === "command" ? (f.name ?? f.rel) : f.rel)}</span>${f.size === 0 ? `<em class="muted">空</em>` : ""}</a>`,
1038
+ )
1039
+ .join("")}</div>`);
1040
+ }
1041
+ }
1042
+ box.innerHTML = groups.join("") || `<div class="empty-inline"><span class="dot"></span>没有匹配的文件</div>`;
1043
+ },
1044
+ async preview() {
1045
+ const box = root.querySelector('[data-n="preview"]');
1046
+ const f = data.files.find((x) => x.id === selected) ?? data.files.find((x) => x.kind === "instructions" && x.size > 0) ?? data.files[0];
1047
+ if (!f) {
1048
+ box.innerHTML = empty("没有找到任何规范文件");
1049
+ return;
1050
+ }
1051
+ box.innerHTML = `<div class="conv-preview-head"><div><span class="conv-kind" data-kind="${f.kind}">${KIND_LABEL[f.kind]}</span> <strong class="mono">${esc(f.scope === "user" ? `~/${f.rel}` : f.rel)}</strong></div>
1052
+ <span class="muted mono">${(f.size / 1024).toFixed(1)} KB · ${ago(f.mtime)}</span></div>
1053
+ ${f.description ? `<p class="conv-desc">${esc(f.description)}</p>` : ""}
1054
+ <div data-n="body"><div class="empty-inline"><span class="dot"></span>读取中…</div></div>`;
1055
+ let res = cache.get(f.id);
1056
+ if (!res) {
1057
+ try {
1058
+ res = await getJson(`/api/conventions/file?id=${encodeURIComponent(f.id)}`);
1059
+ cache.set(f.id, res);
1060
+ } catch (err) {
1061
+ res = { text: "", error: err.message };
1062
+ }
1063
+ }
1064
+ const body = box.querySelector('[data-n="body"]');
1065
+ if (!body) return;
1066
+ if (res.error) body.innerHTML = `<div class="change-msg err">${esc(res.error)}</div>`;
1067
+ else if (!res.text.trim()) body.innerHTML = `<div class="empty-inline"><span class="dot"></span>空文件</div>`;
1068
+ else if (/\.(md|mdc)$/i.test(f.rel)) body.innerHTML = `<div class="md conv-md">${markdown(res.text.replace(/<!--[\s\S]*?-->/g, ""))}</div>`;
1069
+ else body.innerHTML = `<pre class="conv-code"><code>${esc(res.text)}</code></pre>`;
1070
+ if (res.truncated) body.insertAdjacentHTML("beforeend", `<p class="footnote">文件太大,只显示了前一部分。</p>`);
1071
+ },
1072
+ };
1073
+ }
1074
+
1075
+ // =====================================================================
1076
+ // 成员
1077
+ // =====================================================================
1078
+ function agents() {
1079
+ let root;
1080
+ return {
1081
+ title: "成员",
1082
+ sub: "",
1083
+ mount(r) {
1084
+ root = r;
1085
+ root.addEventListener("click", async (e) => {
1086
+ const target = e.target instanceof Element ? e.target : null;
1087
+ if (!target) return;
1088
+ if (target.closest("[data-add-agent]")) {
1089
+ openMemberEditor(null);
1090
+ return;
1091
+ }
1092
+ const editBtn = target.closest("[data-edit-agent]");
1093
+ if (editBtn) {
1094
+ const a = (store.state?.agents ?? []).find((x) => x.kind === editBtn.dataset.editAgent);
1095
+ if (a) openMemberEditor(a);
1096
+ return;
1097
+ }
1098
+ const toggleBtn = target.closest("[data-toggle-agent]");
1099
+ if (toggleBtn) {
1100
+ const kind = toggleBtn.dataset.toggleAgent;
1101
+ const a = (store.state?.agents ?? []).find((x) => x.kind === kind);
1102
+ if (!a) return;
1103
+ toggleBtn.disabled = true;
1104
+ try {
1105
+ await runControlAction(`/api/agents/${encodeURIComponent(kind)}`, { quick: true, enabled: !a.enabled }, `${a.label} 已${a.enabled ? "停用" : "启用"}`);
1106
+ } catch (err) { toast(err.message); toggleBtn.disabled = false; }
1107
+ return;
1108
+ }
1109
+ const modelBtn = target.closest("[data-set-model]");
1110
+ if (modelBtn) {
1111
+ const kind = modelBtn.dataset.setModel;
1112
+ const modelId = modelBtn.dataset.model;
1113
+ modelBtn.disabled = true;
1114
+ try {
1115
+ await runControlAction(`/api/agents/${encodeURIComponent(kind)}`, { quick: true, defaultModel: modelId }, `已切换默认模型为 ${modelId}`);
1116
+ } catch (err) { toast(err.message); modelBtn.disabled = false; }
1117
+ }
1118
+ });
1119
+ this.update("all");
1120
+ },
1121
+ update(kind) {
1122
+ if (kind === "tick") return;
1123
+ const list = store.state?.agents;
1124
+ if (!list) {
1125
+ root.innerHTML = empty("加载中…");
1126
+ return;
1127
+ }
1128
+ const canEdit = !!store.state?.canEditSettings;
1129
+ const stats = store.state.agentStats ?? {};
1130
+ const busy = new Set(store.live.tools.filter((t) => t.status === "running").map((t) => kindOf(t.name)));
1131
+ const anyBusy = !!store.live.busy || runningJobs().length > 0;
1132
+ root.innerHTML = `
1133
+ ${canEdit ? `<div class="page-toolbar"><span class="muted">支持在线启停、切换默认模型与新增/修改 API 成员(密钥仅写不回显;有运行中任务时请先完成或中止)。</span><button type="button" class="primary-btn tiny" data-add-agent="1"${anyBusy ? ` disabled title="有任务正在运行,请先等待结束或中止"` : ""}>+ 新增 API 成员</button></div>` : ""}
1134
+ <div class="agent-grid">${list
1135
+ .map((a) => {
1136
+ const s = stats[a.kind] ?? { total: 0, done: 0, error: 0, aborted: 0, open: 0, durationMs: 0, timed: 0, cost: 0 };
1137
+ const state = !a.available ? "off" : busy.has(a.kind) ? "busy" : "idle";
1138
+ const finished = s.done + s.error + s.aborted;
1139
+ const figures = [
1140
+ ["派工", s.total],
1141
+ ["完成", s.done],
1142
+ ["失败", s.error],
1143
+ ["中止", s.aborted],
1144
+ ["成功率", finished ? `${Math.round((s.done / finished) * 100)}%` : "—"],
1145
+ ["平均耗时", s.timed ? duration(s.durationMs / s.timed) : "—"],
1146
+ ["累计花费", money(s.cost)],
1147
+ ["最近", s.lastAt ? ago(s.lastAt) : "—"],
1148
+ ];
1149
+ const config = [
1150
+ ...(a.api
1151
+ ? [
1152
+ ["接入方式", `API 成员(Pi 子对话)· <code>${esc(a.api.type)}</code> · ${esc(a.api.host)}`],
1153
+ ["密钥", esc(a.api.keySource)],
1154
+ ["工具", esc([...(a.api.tools ?? []), ...(a.api.codeTools ?? [])].join(" / ") || "未授予文件或命令工具")],
1155
+ ["工作方式", a.workspace === "none" ? "领域协作 · 无 Git 工作区" : "代码工作区"],
1156
+ ]
1157
+ : []),
1158
+ [
1159
+ a.api ? "启动命令" : "启动命令",
1160
+ a.api
1161
+ ? `<span class="muted">不需要 CLI</span>`
1162
+ : a.command?.length
1163
+ ? `<button type="button" class="cmd-chip" data-copy="${esc(a.command.join(" "))}" title="${esc(a.command.join(" "))}(点击复制)"><span>${esc(a.command.map((p) => p.split(/[\\/]/).pop()).join(" "))}</span></button>`
1164
+ : `<span class="muted">${esc(a.reason ?? "未找到")}</span>`,
1165
+ ],
1166
+ ["附加参数", a.extraArgs.length ? `<code>${esc(a.extraArgs.join(" "))}</code>` : "—"],
1167
+ ["超时", `${a.timeoutMinutes} 分钟`],
1168
+ ["输出上限", `${num(a.maxOutputChars)} 字符`],
1169
+ ["会话续接", a.canResume ? "支持" : "不支持"],
1170
+ ["启用", a.enabled ? "是" : "否(配置中禁用)"],
1171
+ ];
1172
+ return `<section class="card agent-card" data-state="${state}" style="--c:${agentColor(a.kind)}">
1173
+ <header class="agent-head"><span class="lamp"></span><h2>${esc(a.label)}</h2>
1174
+ <div class="row-actions">${canEdit ? `<button type="button" class="ghost-btn tiny" data-toggle-agent="${esc(a.kind)}">${a.enabled ? "停用" : "启用"}</button><button type="button" class="ghost-btn tiny" data-edit-agent="${esc(a.kind)}">编辑</button>` : ""}<span class="pill" data-s="${state === "busy" ? "running" : state === "off" ? "error" : "done"}">${state === "busy" ? "执行中" : state === "off" ? "不可用" : "可用"}</span></div></header>
1175
+ <p class="agent-desc">${esc(a.available ? a.description : a.reason)}</p>
1176
+ <div class="figures">${figures.map(([k, v]) => `<div><span>${k}</span><strong>${esc(v)}</strong></div>`).join("")}</div>
1177
+ ${segBar([
1178
+ { value: s.done, color: "var(--ok)", label: "完成" },
1179
+ { value: s.error, color: "var(--danger)", label: "失败" },
1180
+ { value: s.aborted, color: "var(--muted)", label: "中止" },
1181
+ ])}
1182
+ ${modelList(a)}
1183
+ <dl class="kvs">${config.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join("")}</dl>
1184
+ <a class="card-link" href="#/dispatches/${a.kind}">查看 ${esc(a.label)} 的派工 →</a>
1185
+ </section>`;
1186
+ })
1187
+ .join("")}</div>`;
1188
+ },
1189
+ };
1190
+ }
1191
+
1192
+ // =====================================================================
1193
+ // CLI 会话
1194
+ // =====================================================================
1195
+ function sessions() {
1196
+ let root;
1197
+ let agent = "all";
1198
+ return {
1199
+ title: "成员会话",
1200
+ sub: "",
1201
+ mount(r) {
1202
+ root = r;
1203
+ root.innerHTML = `<section class="card"><div class="toolbar"><div class="seg" data-n="agents"></div><span class="card-note" data-n="count"></span></div>
1204
+ <div class="table-wrap"><table class="table"><thead><tr><th>成员</th><th>会话 ID</th><th>目录</th><th>最近使用</th><th class="num hide-sm">派工</th><th>续接命令</th></tr></thead><tbody data-n="rows"></tbody></table></div></section>`;
1205
+ const seg = root.querySelector('[data-n="agents"]');
1206
+ seg.innerHTML = ["all", ...KINDS].map((k) => `<button type="button" data-k="${esc(k)}" style="--c:${k === "all" ? "var(--ink)" : agentColor(k)}">${k === "all" ? "全部" : esc(AGENT_LABEL[k] ?? k)}</button>`).join("");
1207
+ seg.addEventListener("click", (e) => {
1208
+ const b = e.target instanceof Element ? e.target.closest("button") : null;
1209
+ if (!b) return;
1210
+ agent = b.dataset.k;
1211
+ this.update("all");
1212
+ });
1213
+ this.update("all");
1214
+ },
1215
+ update(kind) {
1216
+ if (kind === "tick" || kind === "live") return;
1217
+ if (kind === "state") root.querySelector('[data-n="agents"]').innerHTML = ["all", ...KINDS].map((k) => `<button type="button" data-k="${esc(k)}" style="--c:${k === "all" ? "var(--ink)" : agentColor(k)}">${k === "all" ? "全部" : esc(AGENT_LABEL[k] ?? k)}</button>`).join("");
1218
+ for (const b of root.querySelectorAll('[data-n="agents"] button')) b.classList.toggle("on", b.dataset.k === agent);
1219
+ const all = store.state?.sessions ?? [];
1220
+ const list = all.filter((s) => agent === "all" || s.agent === agent);
1221
+ root.querySelector('[data-n="count"]').textContent = `${list.length} / ${all.length}`;
1222
+ root.querySelector('[data-n="rows"]').innerHTML = list.length
1223
+ ? list
1224
+ .map(
1225
+ (s) => `<tr>
1226
+ <td>${agentTag(s.agent)}</td>
1227
+ <td><button type="button" class="linkish mono" data-copy="${esc(s.id)}" title="复制">${esc(s.id)}</button></td>
1228
+ <td class="mono dim" title="${esc(s.cwd)}">${esc(s.cwd)}</td>
1229
+ <td title="${esc(stamp(s.updatedAt))}">${ago(s.updatedAt)}</td>
1230
+ <td class="num mono hide-sm">${s.uses}</td>
1231
+ <td>${s.resume ? `<button type="button" class="copy-cmd mono" data-copy="${esc(s.resume)}" title="在 ${esc(s.cwd)} 里执行">${esc(s.resume)}</button>` : "—"}</td>
1232
+ </tr>`,
1233
+ )
1234
+ .join("")
1235
+ : `<tr class="empty-row"><td colspan="6">${store.state ? "还没有会话" : "加载中…"}</td></tr>`;
1236
+ },
1237
+ };
1238
+ }
1239
+
1240
+ // =====================================================================
1241
+ // 用量
1242
+ // =====================================================================
1243
+ /** 活动柱状图:按小时(24 根)或按天(14 根),每根按成员堆叠 */
1244
+ function activityChart(rows, mode) {
1245
+ const hours = mode === "day";
1246
+ const minutes = mode === "hour";
1247
+ const n = minutes ? 12 : hours ? 24 : 14;
1248
+ const span = minutes ? 300_000 : hours ? 3_600_000 : 86_400_000;
1249
+ const now = new Date();
1250
+ // 对齐到 5 分钟 / 整点 / 当天零点,最后一根是"当前这一段"
1251
+ const end = minutes
1252
+ ? Math.ceil((now.getTime() + 1) / 300_000) * 300_000
1253
+ : hours
1254
+ ? new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1).getTime()
1255
+ : new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime();
1256
+ const buckets = Array.from({ length: n }, (_, i) => ({ start: end - (n - i) * span, by: Object.fromEntries(KINDS.map((k) => [k, 0])), total: 0 }));
1257
+ for (const d of rows) {
1258
+ if (!d.at) continue;
1259
+ const i = n - 1 - Math.floor((end - 1 - d.at) / span);
1260
+ if (i < 0 || i >= n) continue;
1261
+ buckets[i].by[d.agent] = (buckets[i].by[d.agent] ?? 0) + 1;
1262
+ buckets[i].total++;
1263
+ }
1264
+ const max = Math.max(1, ...buckets.map((b) => b.total));
1265
+ const W = 100 / n;
1266
+ const hm = (t) => `${String(new Date(t).getHours()).padStart(2, "0")}:${String(new Date(t).getMinutes()).padStart(2, "0")}`;
1267
+ const label = (b, i) => {
1268
+ const d = new Date(b.start);
1269
+ if (minutes) return i % 3 === 0 ? hm(b.start) : "";
1270
+ if (hours) return i % 3 === 0 ? `${String(d.getHours()).padStart(2, "0")}:00` : "";
1271
+ return i % 2 === 0 || n <= 7 ? `${d.getMonth() + 1}/${d.getDate()}` : "";
1272
+ };
1273
+ const cols = buckets
1274
+ .map((b, i) => {
1275
+ const segs = KINDS.filter((k) => b.by[k] > 0)
1276
+ .map((k) => `<i style="flex:${b.by[k]};background:${agentColor(k)}"></i>`)
1277
+ .join("");
1278
+ const tip = `${minutes ? `${hm(b.start)}–${hm(b.start + span)}` : hours ? `${String(new Date(b.start).getHours()).padStart(2, "0")}:00–${String(new Date(b.start + span).getHours()).padStart(2, "0")}:00` : `${new Date(b.start).getMonth() + 1} 月 ${new Date(b.start).getDate()} 日`}:${b.total} 次${b.total ? `(${KINDS.filter((k) => b.by[k]).map((k) => `${AGENT_LABEL[k]} ${b.by[k]}`).join("、")})` : ""}`;
1279
+ return `<div class="act-col" style="width:${W}%" title="${esc(tip)}">
1280
+ <div class="act-bar" style="height:${(b.total / max) * 100}%">${segs}</div>
1281
+ <span class="act-label">${label(b, i)}</span>
1282
+ </div>`;
1283
+ })
1284
+ .join("");
1285
+ const total = buckets.reduce((s, b) => s + b.total, 0);
1286
+ return { html: `<div class="act-chart"><div class="act-grid"><span>${max}</span><span>${max >= 2 ? Math.round(max / 2) : ""}</span><span>0</span></div><div class="act-cols">${cols}</div></div>`, total };
1287
+ }
1288
+
1289
+ function usage() {
1290
+ let root;
1291
+ let mode = "day";
1292
+ return {
1293
+ title: "用量",
1294
+ sub: "",
1295
+ mount(r) {
1296
+ root = r;
1297
+ root.addEventListener("click", (e) => {
1298
+ const b = e.target instanceof Element ? e.target.closest('[data-n="actMode"] button') : null;
1299
+ if (!b) return;
1300
+ mode = b.dataset.k;
1301
+ this.update("all");
1302
+ });
1303
+ this.update("all");
1304
+ },
1305
+ update(kind) {
1306
+ if (kind === "tick" || kind === "live") return;
1307
+ const state = store.state;
1308
+ if (!state) {
1309
+ root.innerHTML = empty("加载中…");
1310
+ return;
1311
+ }
1312
+ const models = state.usage;
1313
+ const stats = state.agentStats ?? {};
1314
+ const sum = (f) => models.reduce((s, u) => s + f(u), 0);
1315
+ const input = sum((u) => u.input);
1316
+ const output = sum((u) => u.output);
1317
+ const cacheRead = sum((u) => u.cacheRead);
1318
+ const orchCost = sum((u) => u.cost);
1319
+ const t = totals();
1320
+ const hit = input + cacheRead ? Math.round((cacheRead / (input + cacheRead)) * 100) : null;
1321
+ const act = activityChart(dispatchRows(), mode);
1322
+ const maxTotal = Math.max(1, ...KINDS.map((k) => stats[k]?.total ?? 0));
1323
+ const maxTime = Math.max(1, ...KINDS.map((k) => stats[k]?.durationMs ?? 0));
1324
+ const maxCost = Math.max(1e-9, ...KINDS.map((k) => stats[k]?.cost ?? 0));
1325
+ const inline = (v, max, color, text) => `<span class="inline-bar"><i style="width:${max ? Math.max(v ? 3 : 0, (v / max) * 100) : 0}%;background:${color}"></i></span><span class="mono">${text}</span>`;
1326
+ const ux = state.uxTelemetry ?? null;
1327
+ const uxZeroTouch = ux?.zeroTouchRate == null ? "—" : `${Math.round(ux.zeroTouchRate * 100)}%`;
1328
+ const uxUnblock = ux?.meanTimeToUnblockMs == null ? "—" : duration(ux.meanTimeToUnblockMs);
1329
+ const uxPostEdit = ux?.postApplyEditRate == null ? "—" : `${Math.round(ux.postApplyEditRate * 100)}%`;
1330
+ const uxCardHtml = `
1331
+ <section class="card" data-card="ux-telemetry">
1332
+ <header class="card-head">
1333
+ <div class="card-heading">
1334
+ <h2 class="card-title">人机协同体验(UX 第六维指标)</h2>
1335
+ <div class="card-sub">追踪零干预直通率、人工解阻平均耗时与合入后二次修改率</div>
1336
+ </div>
1337
+ <span class="card-note">累计事件 ${ux ? num(ux.totalEvents) : "0"}</span>
1338
+ </header>
1339
+ <div class="card-body">
1340
+ <div class="kpis kpis-4">
1341
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">零干预直通率</span></div><strong>${uxZeroTouch}</strong><span class="kpi-sub">${ux ? `${ux.zeroTouchTasks} / ${ux.totalTasksStarted} 任务直通` : "暂无任务遥测"}</span></div>
1342
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">人工解阻平均耗时</span></div><strong>${uxUnblock}</strong><span class="kpi-sub">${ux ? `${ux.unblockCount} 次人工解阻` : "暂无解阻记录"}</span></div>
1343
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">合入后二次修改率</span></div><strong>${uxPostEdit}</strong><span class="kpi-sub">${ux ? `手动改 ${num(ux.postApplyEditedLines)} / 合入 ${num(ux.appliedLines)} 行` : "暂无合入统计"}</span></div>
1344
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">UX 持久化事件</span></div><strong>${ux ? num(ux.totalEvents) : "0"}</strong><span class="kpi-sub">${ux && ux.totalEvents > 0 ? "已记录于 session.sqlite" : "等待任务流触发"}</span></div>
1345
+ </div>
1346
+ </div>
1347
+ </section>`;
1348
+ root.innerHTML = `
1349
+ <div class="kpis kpis-4">
1350
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">总调度 tokens</span></div><strong>${num(input + output)}</strong><span class="kpi-sub">输入 ${num(input)} · 输出 ${num(output)}</span></div>
1351
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">缓存命中</span></div><strong>${hit === null ? "—" : `${hit}%`}</strong><span class="kpi-sub">缓存读 ${num(cacheRead)} tokens</span></div>
1352
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">花费</span></div><strong>${money(t.cost + orchCost)}</strong><span class="kpi-sub">成员 ${money(t.cost)} · 总调度 ${orchCost ? money(orchCost) : "—"}</span></div>
1353
+ <div class="kpi"><div class="kpi-top"><span class="kpi-label">成员累计耗时</span></div><strong>${duration(t.durationMs)}</strong><span class="kpi-sub">${t.total} 次派工</span></div>
1354
+ </div>
1355
+ ${uxCardHtml}
1356
+ <section class="card">
1357
+ <header class="card-head"><div class="card-heading"><h2 class="card-title">派工活动</h2><div class="card-sub"><span><b>${act.total}</b> 次 · ${mode === "day" ? "最近 24 小时,每小时" : "最近 14 天,每天"}</span></div></div>
1358
+ <div class="act-legend">${KINDS.map((k) => `<span><i style="background:${agentColor(k)}"></i>${esc(AGENT_LABEL[k] ?? k)}</span>`).join("")}</div>
1359
+ <div class="seg" data-n="actMode">${segButtons([["day", "24 小时"], ["week", "14 天"]], mode)}</div></header>
1360
+ <div class="card-body">${act.html}</div>
1361
+ </section>
1362
+ <section class="card">
1363
+ <header class="card-head"><h2 class="card-title">成员明细</h2><span class="card-note">花费:Claude 自报;Codex、Gemini 按配置的单价估算,没配单价计为 0</span></header>
1364
+ <div class="table-wrap"><table class="table">
1365
+ <thead><tr><th>成员</th><th>派工</th><th class="hide-sm">完成 / 失败 / 中止</th><th>成功率</th><th class="hide-sm">平均耗时</th><th>累计耗时</th><th>花费</th></tr></thead>
1366
+ <tbody>${KINDS.map((k) => {
1367
+ const s = stats[k] ?? { total: 0, done: 0, error: 0, aborted: 0, durationMs: 0, timed: 0, cost: 0 };
1368
+ const finished = s.done + s.error + s.aborted;
1369
+ return `<tr>
1370
+ <td>${agentTag(k)}</td>
1371
+ <td class="cell-bar">${inline(s.total, maxTotal, agentColor(k), `${s.total}`)}</td>
1372
+ <td class="mono hide-sm"><span class="ok-t">${s.done}</span> / <span class="err-t">${s.error}</span> / ${s.aborted}</td>
1373
+ <td class="mono">${finished ? `${Math.round((s.done / finished) * 100)}%` : "—"}</td>
1374
+ <td class="mono hide-sm">${s.timed ? duration(s.durationMs / s.timed) : "—"}</td>
1375
+ <td class="cell-bar">${inline(s.durationMs, maxTime, agentColor(k), duration(s.durationMs))}</td>
1376
+ <td class="cell-bar">${inline(s.cost, maxCost, agentColor(k), money(s.cost))}</td>
1377
+ </tr>`;
1378
+ }).join("")}</tbody>
1379
+ </table></div>
1380
+ </section>
1381
+ <section class="card">
1382
+ <header class="card-head"><div class="card-heading"><h2 class="card-title">按模型对比</h2><div class="card-sub">总调度派工时选的模型;≈ 表示按配置的单价估算</div></div></header>
1383
+ <div class="table-wrap"><table class="table">
1384
+ <thead><tr><th>成员</th><th>模型</th><th class="num">派工</th><th class="num">成功率</th><th class="num hide-sm">平均耗时</th><th class="num">花费</th><th class="num hide-sm">每次平均</th></tr></thead>
1385
+ <tbody>${
1386
+ (state.modelStats ?? []).length
1387
+ ? state.modelStats
1388
+ .map((m) => {
1389
+ const fin = m.done + m.error;
1390
+ return `<tr><td>${agentTag(m.agent)}</td><td><span class="model-chip">${esc(m.model)}</span></td><td class="num mono">${m.total}</td><td class="num mono">${fin ? `${Math.round((m.done / fin) * 100)}%` : "—"}</td><td class="num mono hide-sm">${m.timed ? duration(m.durationMs / m.timed) : "—"}</td><td class="num mono">${money(m.cost)}${m.estimated ? "≈" : ""}</td><td class="num mono hide-sm">${m.total ? money(m.cost / m.total) : "—"}</td></tr>`;
1391
+ })
1392
+ .join("")
1393
+ : `<tr class="empty-row"><td colspan="7">还没有派工</td></tr>`
1394
+ }</tbody>
1395
+ </table></div>
1396
+ </section>
1397
+ <section class="card">
1398
+ <header class="card-head"><h2 class="card-title">总调度模型</h2><span class="card-note">${esc(state.orchestrator.describe)}</span></header>
1399
+ <div class="table-wrap"><table class="table"><thead><tr><th>模型</th><th class="num">输入</th><th class="num">输出</th><th class="num">缓存读</th><th class="num hide-sm">缓存写</th><th class="num">花费</th></tr></thead>
1400
+ <tbody>${models.length ? models.map((u) => `<tr><td class="mono">${esc(u.model)}</td><td class="num mono">${num(u.input)}</td><td class="num mono">${num(u.output)}</td><td class="num mono">${num(u.cacheRead)}</td><td class="num mono hide-sm">${num(u.cacheWrite)}</td><td class="num mono">${u.cost ? money(u.cost) : "—"}</td></tr>`).join("") : `<tr class="empty-row"><td colspan="6">还没有用量</td></tr>`}</tbody></table></div>
1401
+ <p class="footnote">花费按模型定价计算;自定义的中转站模型没有定价时显示为 —。</p>
1402
+ </section>`;
1403
+ },
1404
+ };
1405
+ }
1406
+
1407
+ // =====================================================================
1408
+ // 配置
1409
+ // =====================================================================
1410
+ function config() {
1411
+ let root;
1412
+ return {
1413
+ title: "配置",
1414
+ sub: "",
1415
+ mount(r) {
1416
+ root = r;
1417
+ root.addEventListener("click", (e) => {
1418
+ const target = e.target instanceof Element ? e.target : null;
1419
+ if (!target || !store.state) return;
1420
+ if (target.closest("[data-edit-orch]")) openOrchestratorEditor(store.state.orchestrator);
1421
+ else if (target.closest("[data-edit-limits]")) openLimitsEditor(store.state);
1422
+ else if (target.closest("[data-edit-autonomy]")) openAutonomyEditor(store.state.autonomy);
1423
+ });
1424
+ this.update("all");
1425
+ },
1426
+ update(kind) {
1427
+ if (kind !== "all" && kind !== "state" && kind !== "snapshot") return;
1428
+ const s = store.state;
1429
+ if (!s) {
1430
+ root.innerHTML = empty("加载中…");
1431
+ return;
1432
+ }
1433
+ const canEdit = !!s.canEditSettings;
1434
+ const o = s.orchestrator;
1435
+ const ex = s.execution ?? { maxConcurrent: 8, perMember: 4, perService: 8 };
1436
+ const dl = (rows) => `<dl class="kvs wide">${rows.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join("")}</dl>`;
1437
+ const code = (v) => `<code>${esc(v)}</code>`;
1438
+ root.innerHTML = `
1439
+ <section class="card"><header class="card-head"><h2 class="card-title">进程</h2></header>
1440
+ <div class="card-body">${dl([
1441
+ ["配置文件", `<button type="button" class="linkish mono" data-copy="${esc(s.configPath)}">${esc(s.configPath)}</button>`],
1442
+ ["工作目录", code(s.workdir)],
1443
+ ["会话存储", code(s.storage)],
1444
+ ["历史条目", num(s.entries)],
1445
+ ["进程", `pid ${s.pid} · 已运行 ${duration(Date.now() - s.startedAt)}`],
1446
+ ])}</div></section>
1447
+ <section class="card"><header class="card-head"><h2 class="card-title">总调度</h2>${canEdit ? `<button type="button" class="ghost-btn tiny" data-edit-orch="1">编辑总控</button>` : ""}</header>
1448
+ <div class="card-body">${dl([
1449
+ ["协议", code(o.type)],
1450
+ ["模型", code(o.modelId)],
1451
+ ["地址", o.host ? code(o.host) : "—"],
1452
+ ["密钥来源", /未找到|解析失败/.test(o.keySource ?? "") ? `<span class="err-t">${esc(o.keySource)}</span>` : esc(o.keySource)],
1453
+ ["最多轮数", o.maxTurns],
1454
+ ])}</div></section>
1455
+ <section class="card"><header class="card-head"><h2 class="card-title">成员</h2><a class="ghost-btn tiny" href="#/agents">前往成员管理</a></header>
1456
+ <div class="table-wrap"><table class="table"><thead><tr><th>成员</th><th>状态</th><th>接入方式</th><th>参数 / 工具</th><th class="num">超时</th><th class="num hide-sm">输出上限</th></tr></thead>
1457
+ <tbody>${s.agents
1458
+ .map((a) => {
1459
+ const how = a.api ? `API · ${esc(a.api.type)} · ${esc(a.api.host)}<br><span class="muted">密钥:${esc(a.api.keySource)}</span>` : "本机 CLI";
1460
+ const args = a.api
1461
+ ? esc([...(a.api.tools ?? []), ...(a.api.codeTools ?? [])].join(" / ") || "未授予文件或命令工具")
1462
+ : esc(a.extraArgs.join(" ") || "—");
1463
+ return `<tr><td>${agentTag(a.kind)}</td><td class="nowrap">${a.available ? "可用" : `<span class="muted">${esc(a.reason)}</span>`}</td><td>${how}</td><td class="mono">${args}</td><td class="num mono">${a.timeoutMinutes}m</td><td class="num mono hide-sm">${num(a.maxOutputChars)}</td></tr>`;
1464
+ })
1465
+ .join("")}</tbody></table></div></section>
1466
+ <section class="card"><header class="card-head"><h2 class="card-title">工作区隔离、并发与预算</h2>${canEdit ? `<button type="button" class="ghost-btn tiny" data-edit-limits="1">编辑并发与预算</button>` : ""}</header>
1467
+ <div class="card-body">${dl([
1468
+ ["工作区隔离", s.isolation?.enabled ? "开启:每次新派工在独立的 git worktree 里干活,合并后才进主目录" : "关闭:成员直接在工作目录里改文件"],
1469
+ ["挂进 worktree 的目录", (s.isolation?.linkDirs ?? []).map((d) => code(d)).join(" ") || "—"],
1470
+ ["并发上限", `团队 ${ex.maxConcurrent} 路 · 单成员 ${ex.perMember} 路 · 同服务 ${ex.perService} 路`],
1471
+ ["单次运行花费上限", s.budget?.perRunUsd != null ? `${money(s.budget.perRunUsd)}(超过后不再派工)` : "不限"],
1472
+ ["每次派工预留", s.budget?.reservePerDispatchUsd ? `${money(s.budget.reservePerDispatchUsd)}(估计)` : "关闭"],
1473
+ ["总调度单价", s.orchestrator.price ? `输入 $${s.orchestrator.price.input} · 输出 $${s.orchestrator.price.output} / 百万 tokens` : "未配置(总调度花费显示为 —)"],
1474
+ ])}</div></section>
1475
+ <section class="card"><header class="card-head"><h2 class="card-title">子调度与自动验收</h2>${canEdit ? `<button type="button" class="ghost-btn tiny" data-edit-autonomy="1">编辑自动验收</button>` : ""}</header>
1476
+ <div class="card-body">${dl([
1477
+ ["子调度", s.lead?.enabled === false ? "关闭" : "开启:总调度可以用 delegate_to_lead 把较大的子目标整块交给子负责人(只有一层,花费算在同一轮里)"],
1478
+ [
1479
+ "自动验收",
1480
+ s.autonomy?.enabled
1481
+ ? s.autonomy.checks?.length
1482
+ ? s.autonomy.checks.map((c) => `${esc(c.name)}:${code([c.command, ...(c.args ?? [])].join(" "))}${c.timeoutSeconds ? ` · ${c.timeoutSeconds}s` : ""}`).join("<br>")
1483
+ : "开启,但没有配置验收命令"
1484
+ : "关闭",
1485
+ ],
1486
+ ["自动修复", s.autonomy?.enabled ? `验收失败时在同一会话里最多修 ${s.autonomy.maxRepairAttempts} 次` : "关闭"],
1487
+ ["返回总调度的结果长度", s.autonomy?.enabled ? `最多 ${num(s.autonomy.resultMaxChars)} 字符` : "按成员的输出上限"],
1488
+ ["已验证的修复记录", s.autonomy?.learning?.lessons?.length ? `${s.autonomy.learning.lessons.length} 条` : "还没有"],
1489
+ ])}</div></section>
1490
+ <section class="card"><header class="card-head"><h2 class="card-title">启动子 CLI 前去掉的环境变量</h2></header>
1491
+ <div class="card-body chips">${s.stripEnv.map((p) => `<code>${esc(p)}</code>`).join("")}</div></section>`;
1492
+ },
1493
+ };
1494
+ }
1495
+
1496
+ export const VIEWS = { overview, project, dag, topology, runs, dispatches, changes, agents, conventions, sessions, usage, config };