lemma-agent 0.0.0-stage → 1.0.1

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 (80) hide show
  1. package/README.md +140 -2
  2. package/bin/lemma.mjs +60 -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 +1459 -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/projects.js +282 -0
  45. package/dist/repair.js +102 -0
  46. package/dist/resources.js +31 -0
  47. package/dist/result-summary.js +8 -0
  48. package/dist/results.js +41 -0
  49. package/dist/scope.js +114 -0
  50. package/dist/sessions.js +95 -0
  51. package/dist/settings.js +32 -0
  52. package/dist/task-commands.js +37 -0
  53. package/dist/task-lifecycle.js +49 -0
  54. package/dist/task-readiness.js +22 -0
  55. package/dist/task-recovery.js +116 -0
  56. package/dist/task-review.js +70 -0
  57. package/dist/task-workflow.js +424 -0
  58. package/dist/terminal-layout.js +27 -0
  59. package/dist/terminal-state.js +145 -0
  60. package/dist/terminal.js +800 -0
  61. package/dist/tool-settings.js +111 -0
  62. package/dist/tools.js +1043 -0
  63. package/dist/ux-telemetry.js +127 -0
  64. package/dist/view.js +114 -0
  65. package/package.json +80 -6
  66. package/web/index.html +136 -0
  67. package/web/js/conversations.js +312 -0
  68. package/web/js/dag.js +495 -0
  69. package/web/js/drawer.js +139 -0
  70. package/web/js/editors.js +424 -0
  71. package/web/js/gitlens.js +844 -0
  72. package/web/js/main.js +152 -0
  73. package/web/js/sankey.js +476 -0
  74. package/web/js/store.js +291 -0
  75. package/web/js/ticket.js +151 -0
  76. package/web/js/timeline.js +183 -0
  77. package/web/js/topology.js +454 -0
  78. package/web/js/util.js +232 -0
  79. package/web/js/views.js +1496 -0
  80. package/web/style.css +5299 -0
package/web/js/main.js ADDED
@@ -0,0 +1,152 @@
1
+ // 后台入口:路由、顶栏状态、导航计数、主题,以及把数据变化分发给当前页面。
2
+ import { closeDrawer } from "./drawer.js";
3
+ import { buildRuns, connect, pendingChanges, runningJobs, store, subscribe } from "./store.js";
4
+ import { noteSlots } from "./ticket.js";
5
+ import { $, $$, FAILURE_LABEL, copy, post, toast } from "./util.js";
6
+ import { VIEWS } from "./views.js";
7
+ import "./conversations.js";
8
+
9
+ const content = $("#content");
10
+ let view = null;
11
+ let viewName = "";
12
+
13
+ // ---------- 路由:#/页面/参数 ----------
14
+ function route() {
15
+ const [name, ...params] = location.hash.replace(/^#\/?/, "").split("/").filter(Boolean);
16
+ const target = VIEWS[name] ? name : "overview";
17
+ const key = `${target}/${params.join("/")}`;
18
+ if (key === viewName) return;
19
+ view?.unmount?.();
20
+ viewName = key;
21
+ view = VIEWS[target]();
22
+ closeDrawer();
23
+ $("#pageTitle").textContent = view.title;
24
+ $("#pageSub").textContent = view.sub;
25
+ document.title = `${view.title} · Lemma 后台`;
26
+ for (const a of $$("#nav a")) a.classList.toggle("active", a.dataset.view === target);
27
+ content.replaceChildren();
28
+ content.scrollTop = 0;
29
+ view.mount(content, params);
30
+ }
31
+ addEventListener("hashchange", route);
32
+
33
+ // ---------- 顶栏 / 导航 ----------
34
+ function renderChrome() {
35
+ const { live, state } = store;
36
+ $("#pageSub").textContent = view?.sub ?? "";
37
+ const status = $("#status");
38
+ const running = live.tools.filter((t) => t.status === "running" && t.name.startsWith("ask_")).length;
39
+ const inbox = live.inbox ?? [];
40
+ const steers = inbox.filter((i) => i.mode === "steer").length;
41
+ const queued = inbox.length - steers;
42
+ const jobs = runningJobs().length;
43
+ const waiting = `${steers ? ` · 插话 ${steers}` : ""}${queued ? ` · 排队 ${queued}` : ""}${jobs ? ` · 后台 ${jobs}` : ""}`;
44
+ // 失败之后做过「重置上下文」(最后一条记录是重置分隔线):上一轮的失败已经不相关了
45
+ const resetSince = store.items.at(-1)?.type === "divider" && store.items.at(-1)?.label === "新的上下文";
46
+ const failure = resetSince ? undefined : live.runFailure;
47
+ if (live.busy) {
48
+ status.dataset.state = "busy";
49
+ $("#statusText").textContent = `调度中 · 第 ${live.turns + 1} 轮${running ? ` · ${running} 名成员执行中` : ""}${live.retry ? " · 模型重试中" : ""}${waiting}`;
50
+ } else if (jobs) {
51
+ status.dataset.state = "busy";
52
+ $("#statusText").textContent = `后台执行中 · ${jobs} 项(总调度空闲,结果回来后自动继续)`;
53
+ } else if (failure && failure.reason !== "aborted") {
54
+ status.dataset.state = "failed";
55
+ // 服务商内容检查拦下整段上下文时,续跑没用,提示重置上下文
56
+ const blocked = failure.reason === "model_error" && /violate .*(terms|usage polic)|blocked as it seems|content (policy|filter)|内容(安全|审核|政策)/i.test(failure.detail ?? "");
57
+ $("#statusText").textContent = blocked ? "上一轮被模型服务商拦截:点「重置上下文」恢复" : `上一轮未完成:${FAILURE_LABEL[failure.reason] ?? failure.reason}`;
58
+ } else {
59
+ status.dataset.state = "idle";
60
+ $("#statusText").textContent = failure ? "待命 · 上一轮已中止" : "待命";
61
+ }
62
+ $("#stopBtn").hidden = !live.busy;
63
+ const counts = {
64
+ runs: buildRuns().filter((r) => !r.divider).length + (store.hasMore ? "+" : ""),
65
+ dispatches: store.dispatches.length || "",
66
+ changes: pendingChanges().length || "",
67
+ project: (() => {
68
+ const tasks = (state?.project?.tasks ?? []).filter((t) => t.status !== "dropped");
69
+ return tasks.length ? `${tasks.filter((t) => t.status === "done").length}/${tasks.length}` : "";
70
+ })(),
71
+ sessions: state?.sessions.length || "",
72
+ dag: (() => {
73
+ const tasks = (state?.project?.tasks ?? []).filter((t) => t.status === "doing" || t.status === "review");
74
+ return tasks.length ? `${tasks.length} 活跃` : "";
75
+ })(),
76
+ topology: runningJobs().length ? `后台 ${runningJobs().length}` : "",
77
+ };
78
+ for (const [k, v] of Object.entries(counts)) $(`[data-count="${k}"]`).textContent = v ? String(v) : "";
79
+ }
80
+
81
+ subscribe((kind, payload) => {
82
+ if (kind === "conn") {
83
+ const conn = $("#conn");
84
+ conn.dataset.state = store.connected ? "open" : "lost";
85
+ conn.textContent = store.connected ? "已连接终端" : "与终端断开,重连中";
86
+ return;
87
+ }
88
+ if (kind === "live" || kind === "snapshot") noteSlots(store.live.tools);
89
+ renderChrome();
90
+ if (kind === "snapshot") {
91
+ // 重新连上终端(比如终端重启了):整页重建
92
+ viewName = "";
93
+ route();
94
+ return;
95
+ }
96
+ view?.update(kind, payload);
97
+ });
98
+
99
+ // 每秒刷新计时(执行中的派工、运行时长)
100
+ setInterval(() => {
101
+ if (store.live.busy || runningJobs().length) view?.update("tick");
102
+ }, 1000);
103
+
104
+ // ---------- 控制 ----------
105
+ $("#stopBtn").addEventListener("click", async () => {
106
+ try {
107
+ await post("/api/abort");
108
+ toast("已中止本轮");
109
+ } catch (err) {
110
+ toast(`中止失败:${err.message}`);
111
+ }
112
+ });
113
+ $("#resetBtn").addEventListener("click", async () => {
114
+ if (!confirm("只重置当前总控上下文?记录仍保留在当前对话中,任务和用量不会分开。需要独立聊天与后台数据,请取消后点“新对话”。")) return;
115
+ try {
116
+ await post("/api/reset", { expectedSession: store.state?.conversation?.id });
117
+ toast("已开始新的上下文");
118
+ } catch (err) {
119
+ toast(`操作失败:${err.message}`);
120
+ }
121
+ });
122
+ document.addEventListener("click", (e) => {
123
+ const target = e.target instanceof Element ? e.target.closest("[data-copy]") : null;
124
+ if (target) {
125
+ e.preventDefault();
126
+ copy(target.getAttribute("data-copy"));
127
+ }
128
+ });
129
+
130
+ // ---------- 主题 ----------
131
+ function applyTheme(theme) {
132
+ if (theme) document.documentElement.dataset.theme = theme;
133
+ else delete document.documentElement.dataset.theme;
134
+ }
135
+ try {
136
+ applyTheme(localStorage.getItem("pi-agent-theme"));
137
+ } catch {
138
+ /* 无存储权限时跟随系统 */
139
+ }
140
+ $("#themeToggle").addEventListener("click", () => {
141
+ const current = document.documentElement.dataset.theme ?? (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
142
+ const next = current === "light" ? "dark" : "light";
143
+ applyTheme(next);
144
+ try {
145
+ localStorage.setItem("pi-agent-theme", next);
146
+ } catch {
147
+ /* 忽略 */
148
+ }
149
+ });
150
+
151
+ route();
152
+ connect();
@@ -0,0 +1,476 @@
1
+ // 派工流向图(桑基图):总调度 → 各成员 → 结果。
2
+ // 经典桑基样式:细实色竖条做节点,名称和数值写在竖条旁边,带子是浅色半透明、彼此交叠;
3
+ // 列名放在底部。带子按成员着色,结果由右侧竖条的颜色区分。
4
+ // 只有正在执行的线路带流光;结构不变时就地更新几何,变化平滑、动画不跳。
5
+ // 自带极简布局,无依赖。
6
+ import { dispatchRows } from "./store.js";
7
+ import { slotStart } from "./ticket.js";
8
+ import { AGENT_LABEL, KINDS, agentColor, duration, el, esc, money } from "./util.js";
9
+
10
+ const SVG_NS = "http://www.w3.org/2000/svg";
11
+ const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
12
+
13
+ const OUTCOMES = [
14
+ { id: "done", label: "完成", color: "var(--ok)" },
15
+ { id: "running", label: "执行中", color: "var(--run)" },
16
+ { id: "error", label: "失败", color: "var(--danger)" },
17
+ { id: "aborted", label: "中止", color: "var(--muted)" },
18
+ { id: "open", label: "无结果", color: "var(--muted)" },
19
+ ];
20
+ const outcomeOf = (status) => (status === "interrupted" ? "aborted" : OUTCOMES.some((o) => o.id === status) ? status : "open");
21
+
22
+ function elapsed(d) {
23
+ if (d.status !== "running") return d.durationMs ?? 0;
24
+ const started = slotStart.get(d.callId);
25
+ return started ? Date.now() - started : 0;
26
+ }
27
+
28
+ export const MODES = {
29
+ member: { label: "按成员" },
30
+ role: { label: "按协作角色" },
31
+ };
32
+ export const METRICS = {
33
+ count: { label: "次数", value: () => 1, fmt: (v) => `${Math.round(v)} 次` },
34
+ time: { label: "耗时", value: elapsed, fmt: (v) => duration(v) },
35
+ cost: { label: "花费", value: (d) => d.cost ?? 0, fmt: (v) => money(v) },
36
+ };
37
+ const COLLAB_ROLES = [
38
+ { id: "exec", label: "直接执行交付", color: "var(--claude)" },
39
+ { id: "workflow", label: "Durable 依赖推进", color: "var(--signal)" },
40
+ { id: "checker", label: "独立盲审 / 复核", color: "var(--gemini)" },
41
+ { id: "repair", label: "集成联调修复", color: "var(--lead)" },
42
+ { id: "recovery", label: "受阻任务恢复", color: "var(--codex)" },
43
+ ];
44
+ function roleOfDispatch(d) {
45
+ const cid = String(d.callId ?? "");
46
+ if (cid.startsWith("checker:")) return COLLAB_ROLES[2];
47
+ if (cid.startsWith("integration-repair:")) return COLLAB_ROLES[3];
48
+ if (cid.startsWith("recovery:")) return COLLAB_ROLES[4];
49
+ if (cid.startsWith("workflow:")) return COLLAB_ROLES[1];
50
+ return COLLAB_ROLES[0];
51
+ }
52
+ export const RANGES = {
53
+ all: { label: "全部", ms: Infinity },
54
+ day: { label: "24h", ms: 86_400_000 },
55
+ hour: { label: "1h", ms: 3_600_000 },
56
+ };
57
+ const COLUMNS = [
58
+ { col: 1, label: "调度" },
59
+ { col: 2, label: "成员 / 角色" },
60
+ { col: 3, label: "结果" },
61
+ ];
62
+
63
+ let uid = 0;
64
+
65
+ export class Sankey {
66
+ constructor() {
67
+ this.id = `sk${++uid}`;
68
+ this.mode = "member";
69
+ this.metric = "count";
70
+ this.range = "all";
71
+ this.node = el("div", "sankey");
72
+ this.svg = document.createElementNS(SVG_NS, "svg");
73
+ this.svg.setAttribute("class", "sk-svg");
74
+ this.svg.setAttribute("role", "img");
75
+ this.empty = el("div", "sk-empty");
76
+ this.tip = el("div", "sk-tip");
77
+ this.tip.hidden = true;
78
+ this.node.append(this.svg, this.empty, this.tip);
79
+ this.signature = "";
80
+ this.model = null;
81
+ this.observer = new ResizeObserver(() => this.render(true));
82
+ this.observer.observe(this.node);
83
+ this.bindEvents();
84
+ }
85
+
86
+ destroy() {
87
+ this.observer.disconnect();
88
+ }
89
+
90
+ /** 给卡片头部用的摘要 */
91
+ summary() {
92
+ const m = this.model;
93
+ if (!m) return null;
94
+ const s = m.totals;
95
+ const finished = s.done + s.error + s.aborted;
96
+ return { total: s.count, running: s.running, rate: finished ? Math.round((s.done / finished) * 100) : null };
97
+ }
98
+
99
+ // ---------------- 数据 ----------------
100
+ compute() {
101
+ const now = Date.now();
102
+ const window = RANGES[this.range].ms;
103
+ const rows = dispatchRows().filter((d) => window === Infinity || !d.at || now - d.at <= window);
104
+ const value = METRICS[this.metric].value;
105
+ const nodes = new Map();
106
+ const links = new Map();
107
+ const totals = { count: 0, running: 0, done: 0, error: 0, aborted: 0 };
108
+ const node = (id, label, color, col, href) => {
109
+ if (!nodes.has(id)) nodes.set(id, { id, label, color, col, href, value: 0, inV: 0, outV: 0, stats: blank() });
110
+ return nodes.get(id);
111
+ };
112
+ const link = (from, to, color, d, v) => {
113
+ const id = `${from}>${to}`;
114
+ let l = links.get(id);
115
+ if (!l) links.set(id, (l = { id, from, to, color, value: 0, hotValue: 0, hot: false, stats: blank() }));
116
+ l.value += v;
117
+ tally(l.stats, d);
118
+ if (d.status === "running") {
119
+ l.hot = true;
120
+ l.hotValue += v;
121
+ }
122
+ };
123
+ for (const d of rows) {
124
+ const v = value(d);
125
+ const outcome = OUTCOMES.find((o) => o.id === outcomeOf(d.status));
126
+ totals.count++;
127
+ if (outcome.id === "running") totals.running++;
128
+ else if (outcome.id === "done") totals.done++;
129
+ else if (outcome.id === "error") totals.error++;
130
+ else if (outcome.id === "aborted") totals.aborted++;
131
+ const roleMode = this.mode === "role";
132
+ const role = roleMode ? roleOfDispatch(d) : null;
133
+ const a = roleMode ? `r:${role.id}` : `a:${d.agent}`;
134
+ const o = `o:${outcome.id}`;
135
+ const srcId = roleMode && ["workflow", "checker", "repair"].includes(role.id) ? "durable" : "orch";
136
+ node(srcId, srcId === "durable" ? "Durable 自动流转" : "总调度", srcId === "durable" ? "var(--signal)" : "var(--orch)", 1, "#/dispatches");
137
+ node(a, roleMode ? role.label : AGENT_LABEL[d.agent] ?? d.agent, roleMode ? role.color : agentColor(d.agent), 2, roleMode ? "#/dispatches" : `#/dispatches/${d.agent}`);
138
+ node(o, outcome.label, outcome.color, 3, `#/dispatches/all/${outcome.id}`);
139
+ for (const n of [srcId, a, o]) tally(nodes.get(n).stats, d);
140
+ const edgeColor = roleMode ? role.color : agentColor(d.agent);
141
+ link(srcId, a, edgeColor, d, v);
142
+ link(a, o, edgeColor, d, v);
143
+ }
144
+ for (const [id, l] of links) if (l.value <= 0) links.delete(id);
145
+ for (const l of links.values()) {
146
+ nodes.get(l.from).outV += l.value;
147
+ nodes.get(l.to).inV += l.value;
148
+ }
149
+ for (const [id, n] of nodes) {
150
+ n.value = Math.max(n.inV, n.outV);
151
+ if (n.value <= 0) nodes.delete(id);
152
+ }
153
+ const order = (n) => (n.col === 1 ? (n.id === "orch" ? 0 : 1) : n.col === 2 ? (this.mode === "role" ? COLLAB_ROLES.findIndex((r) => `r:${r.id}` === n.id) : KINDS.indexOf(n.id.slice(2))) : n.col === 3 ? OUTCOMES.findIndex((o) => `o:${o.id}` === n.id) : 0);
154
+ const list = [...nodes.values()].sort((x, y) => x.col - y.col || order(x) - order(y));
155
+ const grand = list.filter((n) => n.col === 1).reduce((s, n) => s + n.value, 0);
156
+ for (const n of list) n.share = grand ? n.value / grand : 0;
157
+ return { nodes: list, links: [...links.values()], rows: rows.length, totals };
158
+ }
159
+
160
+ // ---------------- 布局 ----------------
161
+ layout(model, width) {
162
+ const narrow = width < 620;
163
+ const barW = narrow ? 8 : 10;
164
+ const H = this.height ? Math.max(narrow ? 300 : 340, this.height) : narrow ? 300 : 340;
165
+ const padT = 4;
166
+ const padB = 30; // 底部列名
167
+ const gap = narrow ? 14 : 18;
168
+ const colX = new Map([
169
+ [1, 0],
170
+ [2, Math.round((width - barW) / 2)],
171
+ [3, width - barW],
172
+ ]);
173
+ const byCol = new Map(COLUMNS.map((c) => [c.col, model.nodes.filter((n) => n.col === c.col)]));
174
+ let k = Infinity;
175
+ for (const list of byCol.values()) {
176
+ if (!list.length) continue;
177
+ const total = list.reduce((s, n) => s + n.value, 0);
178
+ k = Math.min(k, (H - padT - padB - gap * (list.length - 1)) / total);
179
+ }
180
+ for (const [col, list] of byCol) {
181
+ for (const n of list) n.h = Math.max(2, n.value * k);
182
+ const used = list.reduce((s, n) => s + n.h, 0) + gap * Math.max(0, list.length - 1);
183
+ let y = padT + (H - padT - padB - used) / 2;
184
+ for (const n of list) {
185
+ n.x = colX.get(col);
186
+ n.y = y;
187
+ n.w = barW;
188
+ // 前两列标签在竖条右边,最后一列在左边
189
+ n.lx = col === 3 ? n.x - 8 : n.x + barW + 8;
190
+ n.anchor = col === 3 ? "end" : "start";
191
+ n.ly = n.y + n.h / 2;
192
+ y += n.h + gap;
193
+ }
194
+ }
195
+ const byId = new Map(model.nodes.map((n) => [n.id, n]));
196
+ // 出线按目标的上下顺序、入线按来源的上下顺序堆叠,减少交叉
197
+ const outOff = new Map();
198
+ const inOff = new Map();
199
+ for (const l of model.links.slice().sort((a, b) => byId.get(a.to).y - byId.get(b.to).y)) {
200
+ l.h = Math.max(1, l.value * k);
201
+ l.sy = byId.get(l.from).y + (outOff.get(l.from) ?? 0);
202
+ outOff.set(l.from, (outOff.get(l.from) ?? 0) + l.value * k);
203
+ }
204
+ for (const l of model.links.slice().sort((a, b) => byId.get(a.from).y - byId.get(b.from).y)) {
205
+ const s = byId.get(l.from);
206
+ const t = byId.get(l.to);
207
+ l.ty = t.y + (inOff.get(l.to) ?? 0);
208
+ inOff.set(l.to, (inOff.get(l.to) ?? 0) + l.value * k);
209
+ const x0 = s.x + s.w;
210
+ const x1 = t.x;
211
+ const cx = (x0 + x1) / 2;
212
+ const { sy, ty, h } = l;
213
+ l.band = `M${x0} ${sy}C${cx} ${sy} ${cx} ${ty} ${x1} ${ty}L${x1} ${ty + h}C${cx} ${ty + h} ${cx} ${sy + h} ${x0} ${sy + h}Z`;
214
+ }
215
+ const flows = [];
216
+ const oRun = byId.get("o:running");
217
+ if (oRun) {
218
+ for (const mid of byCol.get(2) ?? []) {
219
+ const outRun = model.links.find((l) => l.from === mid.id && l.to === "o:running");
220
+ if (!outRun) continue;
221
+ const hotIns = model.links
222
+ .filter((l) => l.to === mid.id && l.hotValue > 0)
223
+ .sort((a, b) => byId.get(a.from).y - byId.get(b.from).y);
224
+ if (!hotIns.length) continue;
225
+ const totalHot = hotIns.reduce((s, l) => s + l.hotValue, 0);
226
+ let syOff = 0;
227
+ let tyOff = 0;
228
+ for (const inL of hotIns) {
229
+ const share = totalHot > 0 ? inL.hotValue / totalHot : 1 / hotIns.length;
230
+ const sliceH = outRun.h * share;
231
+ const yMidOut = outRun.sy + syOff + sliceH / 2;
232
+ const yEnd = outRun.ty + tyOff + sliceH / 2;
233
+ syOff += sliceH;
234
+ tyOff += sliceH;
235
+ const src = byId.get(inL.from);
236
+ const padIn = Math.min(inL.h * 0.25, 2);
237
+ const yMidIn = Math.max(inL.ty + padIn, Math.min(inL.ty + inL.h - padIn, yMidOut));
238
+ const ratio = inL.h > 0 ? (yMidIn - inL.ty) / inL.h : 0.5;
239
+ const yStart = inL.sy + ratio * inL.h;
240
+ const x0 = src.x + src.w;
241
+ const x1 = mid.x;
242
+ const x2 = mid.x + mid.w;
243
+ const x3 = oRun.x;
244
+ const cx01 = (x0 + x1) / 2;
245
+ const cx23 = (x2 + x3) / 2;
246
+ const bridge =
247
+ Math.abs(yMidIn - yMidOut) < 0.25
248
+ ? `L${x2} ${yMidOut}`
249
+ : `C${(x1 + x2) / 2} ${yMidIn} ${(x1 + x2) / 2} ${yMidOut} ${x2} ${yMidOut}`;
250
+ const path = `M${x0} ${yStart}C${cx01} ${yStart} ${cx01} ${yMidIn} ${x1} ${yMidIn}${bridge}C${cx23} ${yMidOut} ${cx23} ${yEnd} ${x3} ${yEnd}`;
251
+ const w = Math.max(1.5, Math.min(sliceH * 0.32, inL.h * 0.32, 3.5));
252
+ flows.push({ id: `${inL.from}>${mid.id}>o:running`, from: inL.from, mid: mid.id, to: "o:running", color: inL.color, path, w });
253
+ }
254
+ }
255
+ }
256
+ const axis = [
257
+ { label: COLUMNS[0].label, x: 0, anchor: "start" },
258
+ { label: COLUMNS[1].label, x: colX.get(2) + barW / 2, anchor: "middle" },
259
+ { label: COLUMNS[2].label, x: width, anchor: "end" },
260
+ ];
261
+ return { nodes: model.nodes, links: model.links, flows, H, narrow, axis };
262
+ }
263
+
264
+ // ---------------- 绘制 ----------------
265
+ render(force = false) {
266
+ const width = this.node.clientWidth;
267
+ if (!width) return;
268
+ const model = this.compute();
269
+ this.model = model;
270
+ const has = model.links.length > 0;
271
+ this.svg.style.display = has ? "" : "none";
272
+ this.empty.hidden = has;
273
+ if (!has) {
274
+ this.signature = "";
275
+ this.empty.innerHTML =
276
+ model.rows === 0
277
+ ? this.range === "all"
278
+ ? `<strong>还没有派工</strong><span>在终端里下发任务后,这里显示任务从总调度流向各成员、再到结果的分布。</span>`
279
+ : `<strong>最近 ${RANGES[this.range].label} 没有派工</strong><span>切换到"全部"查看完整历史。</span>`
280
+ : `<strong>这个指标下没有数据</strong><span>只有 Claude 会报告花费,Codex、Gemini 不报告。</span>`;
281
+ return;
282
+ }
283
+ const g = this.layout(model, width);
284
+ const fmt = METRICS[this.metric].fmt;
285
+ // 执行中的连续流线跨越中间列,因此活动链路集合也是结构的一部分
286
+ const signature = `${width}x${g.H}|${g.nodes.map((n) => n.id).join(",")}|${g.links.map((l) => `${l.id}${l.hot ? "*" : ""}`).join(",")}|${g.flows.map((f) => f.id).join(",")}`;
287
+ this.svg.setAttribute("aria-label", `派工流向:${g.nodes.map((n) => `${n.label} ${fmt(n.value)}`).join(",")}`);
288
+
289
+ if (force || signature !== this.signature) {
290
+ this.signature = signature;
291
+ this.svg.setAttribute("viewBox", `0 0 ${width} ${g.H}`);
292
+ this.svg.style.height = `${g.H}px`;
293
+ const links = g.links
294
+ .map(
295
+ (l) => `<g class="sk-link${l.hot ? " hot" : ""}" data-link="${esc(l.id)}" style="--c:${l.color}">
296
+ <path class="sk-band" style="d:path('${l.band}')"/>
297
+ </g>`,
298
+ )
299
+ .join("");
300
+ const nodes = g.nodes
301
+ .map(
302
+ (n) => `<g class="sk-node${n.href ? " link" : ""}${n.stats.running ? " hot" : ""}" data-node="${esc(n.id)}" style="--c:${n.color}">
303
+ <rect class="sk-bar" x="${n.x}" width="${n.w}" rx="1.5" style="y:${n.y}px;height:${n.h}px"/>
304
+ </g>`,
305
+ )
306
+ .join("");
307
+ const flows = g.flows
308
+ .map(
309
+ (f) => `<g class="sk-flow-wrap" data-flow="${esc(f.id)}" data-from="${esc(f.from)}" data-mid="${esc(f.mid)}" data-to="${esc(f.to)}" style="--c:${f.color}">
310
+ <path class="sk-flow-track" style="d:path('${f.path}')"/>
311
+ ${!reduceMotion ? `<path class="sk-flow" style="d:path('${f.path}');stroke-width:${f.w}px"/>` : ""}
312
+ </g>`,
313
+ )
314
+ .join("");
315
+ const labels = g.nodes
316
+ .map(
317
+ (n) => `<text class="sk-label" data-label="${esc(n.id)}" x="${n.lx}" y="0" text-anchor="${n.anchor}" dominant-baseline="central" style="transform:translateY(${n.ly}px)"><tspan class="sk-name">${esc(n.label)}</tspan><tspan class="sk-val" dx="6">${esc(fmt(n.value))}</tspan></text>`,
318
+ )
319
+ .join("");
320
+ const axis = g.axis.map((a) => `<text class="sk-axis" x="${a.x}" y="${g.H - 6}" text-anchor="${a.anchor}">${a.label}</text>`).join("");
321
+ this.svg.innerHTML = `<g class="sk-links">${links}</g><g class="sk-nodes">${nodes}</g><g class="sk-flows">${flows}</g><g class="sk-labels">${labels}</g>${axis}`;
322
+ } else {
323
+ // 结构没变:只更新几何和数值(CSS transition 让变化平滑,流光动画不中断)
324
+ for (const l of g.links) {
325
+ const node = this.svg.querySelector(`[data-link="${CSS.escape(l.id)}"]`);
326
+ if (!node) continue;
327
+ node.querySelector(".sk-band").style.d = `path('${l.band}')`;
328
+ }
329
+ for (const f of g.flows) {
330
+ const wrap = this.svg.querySelector(`[data-flow="${CSS.escape(f.id)}"]`);
331
+ if (!wrap) continue;
332
+ const track = wrap.querySelector(".sk-flow-track");
333
+ if (track) track.style.d = `path('${f.path}')`;
334
+ const flow = wrap.querySelector(".sk-flow");
335
+ if (flow) {
336
+ flow.style.d = `path('${f.path}')`;
337
+ flow.style.strokeWidth = `${f.w}px`;
338
+ }
339
+ }
340
+ for (const n of g.nodes) {
341
+ const node = this.svg.querySelector(`[data-node="${CSS.escape(n.id)}"]`);
342
+ if (!node) continue;
343
+ node.classList.toggle("hot", n.stats.running > 0);
344
+ const bar = node.querySelector(".sk-bar");
345
+ bar.style.y = `${n.y}px`;
346
+ bar.style.height = `${n.h}px`;
347
+ const label = this.svg.querySelector(`[data-label="${CSS.escape(n.id)}"]`);
348
+ if (label) {
349
+ label.style.transform = `translateY(${n.ly}px)`;
350
+ label.querySelector(".sk-val").textContent = fmt(n.value);
351
+ }
352
+ }
353
+ }
354
+ if (this.hovered) this.showTip(this.hovered.kind, this.hovered.id, this.hovered.x, this.hovered.y);
355
+ }
356
+
357
+ // ---------------- 交互:悬停高亮 + 提示,点击跳到派工明细 ----------------
358
+ bindEvents() {
359
+ this.svg.addEventListener("pointermove", (e) => {
360
+ const target = e.target instanceof Element ? e.target.closest("[data-link],[data-node]") : null;
361
+ if (!target) return this.clearHover();
362
+ const kind = target.hasAttribute("data-link") ? "link" : "node";
363
+ const id = target.getAttribute(kind === "link" ? "data-link" : "data-node");
364
+ const box = this.node.getBoundingClientRect();
365
+ this.hovered = { kind, id, x: e.clientX - box.left, y: e.clientY - box.top };
366
+ this.highlight(kind, id);
367
+ this.showTip(kind, id, this.hovered.x, this.hovered.y);
368
+ });
369
+ this.svg.addEventListener("pointerleave", () => this.clearHover());
370
+ this.svg.addEventListener("click", (e) => {
371
+ const target = e.target instanceof Element ? e.target.closest("[data-link],[data-node]") : null;
372
+ if (!target) return;
373
+ const href = target.hasAttribute("data-node") ? this.nodeHref(target.getAttribute("data-node")) : this.linkHref(target.getAttribute("data-link"));
374
+ if (href) location.hash = href;
375
+ });
376
+ }
377
+
378
+ nodeHref(id) {
379
+ return this.model?.nodes.find((n) => n.id === id)?.href;
380
+ }
381
+ linkHref(id) {
382
+ const [from, to] = id.split(">");
383
+ if (from.startsWith("a:") && to.startsWith("o:")) return `#/dispatches/${from.slice(2)}/${to.slice(2)}`;
384
+ if (to.startsWith("a:")) return `#/dispatches/${to.slice(2)}`;
385
+ return "#/dispatches";
386
+ }
387
+
388
+ highlight(kind, id) {
389
+ this.svg.classList.add("focus");
390
+ const ends = kind === "link" ? id.split(">") : [id];
391
+ for (const node of this.svg.querySelectorAll("[data-link]")) {
392
+ const lid = node.getAttribute("data-link");
393
+ const [from, to] = lid.split(">");
394
+ node.classList.toggle("on", kind === "link" ? lid === id : from === id || to === id);
395
+ }
396
+ for (const node of this.svg.querySelectorAll("[data-node]")) {
397
+ const nid = node.getAttribute("data-node");
398
+ const linked = kind === "node" && this.model.links.some((l) => (l.from === id && l.to === nid) || (l.to === id && l.from === nid));
399
+ const on = ends.includes(nid) || linked;
400
+ node.classList.toggle("on", on);
401
+ this.svg.querySelector(`[data-label="${CSS.escape(nid)}"]`)?.classList.toggle("on", on);
402
+ }
403
+ for (const flow of this.svg.querySelectorAll("[data-flow]")) {
404
+ const from = flow.getAttribute("data-from");
405
+ const mid = flow.getAttribute("data-mid");
406
+ const to = flow.getAttribute("data-to");
407
+ const on = kind === "link" ? `${from}>${mid}` === id || `${mid}>${to}` === id : from === id || mid === id || to === id;
408
+ flow.classList.toggle("on", on);
409
+ }
410
+ }
411
+
412
+ clearHover() {
413
+ this.hovered = null;
414
+ this.svg.classList.remove("focus");
415
+ for (const n of this.svg.querySelectorAll(".on")) n.classList.remove("on");
416
+ this.tip.hidden = true;
417
+ }
418
+
419
+ showTip(kind, id, x, y) {
420
+ const model = this.model;
421
+ if (!model) return;
422
+ const fmt = METRICS[this.metric].fmt;
423
+ let title;
424
+ let stats;
425
+ let value;
426
+ let share = "";
427
+ if (kind === "link") {
428
+ const l = model.links.find((v) => v.id === id);
429
+ if (!l) return this.clearHover();
430
+ const from = model.nodes.find((n) => n.id === l.from);
431
+ const to = model.nodes.find((n) => n.id === l.to);
432
+ title = `<i style="background:${from.color}"></i>${esc(from.label)}<span class="arrow">→</span><i style="background:${to.color}"></i>${esc(to.label)}`;
433
+ stats = l.stats;
434
+ value = l.value;
435
+ if (from.outV > 0) share = `占 ${esc(from.label)} 的 ${Math.round((l.value / from.outV) * 100)}%`;
436
+ } else {
437
+ const n = model.nodes.find((v) => v.id === id);
438
+ if (!n) return this.clearHover();
439
+ title = `<i style="background:${n.color}"></i>${esc(n.label)}`;
440
+ stats = n.stats;
441
+ value = n.value;
442
+ share = `占全部的 ${Math.round(n.share * 100)}%`;
443
+ }
444
+ const avg = stats.timed ? duration(stats.time / stats.timed) : "—";
445
+ this.tip.innerHTML = `<div class="sk-tip-title">${title}</div>
446
+ <div class="sk-tip-main">${esc(fmt(value))}<span>${esc(share)}</span></div>
447
+ <dl class="sk-tip-grid">
448
+ <dt>派工</dt><dd>${stats.count} 次</dd>
449
+ <dt>平均耗时</dt><dd>${avg}</dd>
450
+ <dt>花费</dt><dd>${money(stats.cost)}</dd>
451
+ ${stats.running ? `<dt>执行中</dt><dd class="hot">${stats.running}</dd>` : ""}
452
+ </dl>
453
+ <div class="sk-tip-hint">点击查看这些派工</div>`;
454
+ this.tip.hidden = false;
455
+ const box = this.node.getBoundingClientRect();
456
+ const tw = this.tip.offsetWidth;
457
+ const th = this.tip.offsetHeight;
458
+ const left = Math.min(Math.max(4, x + 16), box.width - tw - 4);
459
+ const top = y + th + 24 > box.height ? Math.max(0, y - th - 14) : y + 18;
460
+ this.tip.style.transform = `translate(${left}px, ${top}px)`;
461
+ }
462
+ }
463
+
464
+ function blank() {
465
+ return { count: 0, time: 0, timed: 0, cost: 0, running: 0 };
466
+ }
467
+ function tally(stats, d) {
468
+ stats.count++;
469
+ const t = elapsed(d);
470
+ if (t > 0) {
471
+ stats.time += t;
472
+ stats.timed++;
473
+ }
474
+ stats.cost += d.cost ?? 0;
475
+ if (d.status === "running") stats.running++;
476
+ }