agent-loft 0.2.52 → 0.2.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,7 +45,8 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
45
45
  - agent 做多步骤的活时列的任务清单显示在输入框上方,看得到做到第几项、正在做哪一项。
46
46
  - 授权卡、提问卡直接在页面上点。
47
47
  - 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,开新会话或切换目录时清理。
48
- - 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
48
+ - 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。
49
+ - **回复里的图**:专家和 agent 在回复里写 ```` ```chart ````(一段 JSON:折线、面积、柱状、饼图、散点)就画成可悬停的图,可以切到表格看具体数字;写 ```` ```mermaid ```` 画流程图、时序图等。跟着系统深浅色走,图库用到时才加载;飞书上 chart 换成表格。写法自动附在每个专家(包括内置的 Claude Code、Codex)的提示词里。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
49
50
  - 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
50
51
  - 新对话页:点大标题里的目录名,在固定高度的目录弹窗里逐层选工作目录,也能新建文件夹;输入框上方选专家,鼠标停在专家上看简介,右下角选模型和思考程度。对话从头到尾一个专家,要换专家就新建对话;模型和思考程度随时可换。
51
52
  - 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.52",
3
+ "version": "0.2.53",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -51,7 +51,9 @@
51
51
  "@xterm/addon-fit": "^0.11.0",
52
52
  "@xterm/xterm": "^6.0.0",
53
53
  "dompurify": "^3.2.0",
54
+ "echarts": "^6.1.0",
54
55
  "marked": "^16.0.0",
56
+ "mermaid": "^12.2.0",
55
57
  "qrcode": "^1.5.4",
56
58
  "sharp": "^0.35.5",
57
59
  "tsx": "^4.20.6",
@@ -17,7 +17,7 @@ import {
17
17
  type SDKUserMessage,
18
18
  } from "@anthropic-ai/claude-agent-sdk";
19
19
  import { agentEnvironment } from "../../core/agent-env.js";
20
- import { expertAppend, expertSystemPrompt, searchLabel } from "../../core/expert-prompt.js";
20
+ import { expertAppend, expertSystemPrompt, RICH_REPLY_LINES, searchLabel } from "../../core/expert-prompt.js";
21
21
  import { ACCESS_LEVELS, type ExpertAccess } from "../../core/experts.js";
22
22
  import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
23
23
  import { SKILLS_MCP_NAME, skillsMcpSpawn, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
@@ -219,9 +219,9 @@ export function expertOptions(opts: SessionOptions): Partial<Options> {
219
219
  const expert = opts.expert;
220
220
  if (!expert) {
221
221
  const mcpServers = loftMcp(opts);
222
- const append = [memory?.prompt, skills?.prompt].filter(Boolean).join("\n\n");
222
+ const append = [RICH_REPLY_LINES.join("\n"), memory?.prompt, skills?.prompt].filter(Boolean).join("\n\n");
223
223
  return {
224
- systemPrompt: { type: "preset", preset: "claude_code", ...(append ? { append } : {}), snapshot: false },
224
+ systemPrompt: { type: "preset", preset: "claude_code", append, snapshot: false },
225
225
  ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
226
226
  ...(skills?.pluginDir ? { plugins: [{ type: "local" as const, path: skills.pluginDir, skipMcpDiscovery: true }] } : {}),
227
227
  ...(skills && !skills.admin ? { skills: memberSkillAllowlist(skills, opts.cwd) } : {}),
@@ -447,12 +447,12 @@ export class CodexSession implements AgentSession {
447
447
  /**
448
448
  * 这个会话进程还没告诉过 Codex 专家和记忆:第一条消息后面附上 contextBlock。
449
449
  * 进程一换(专家改了、记忆改了、服务重启)就是新的 CodexSession,会再附一次最新的。
450
- * 内置专家、没有记忆和技能:什么都不附,和原装的一模一样。
450
+ * 内置专家没有记忆和技能时也要附:回复里能画图(```chart / ```mermaid)得告诉它。
451
451
  */
452
452
  private contextSent = false;
453
453
 
454
454
  private get contextPending(): boolean {
455
- return !this.contextSent && (!!this.opts.expert || !!this.opts.memory || codexSkillLines(this.opts.skills).length > 0);
455
+ return !this.contextSent;
456
456
  }
457
457
 
458
458
  private async openOnce(): Promise<string> {
@@ -7,6 +7,7 @@
7
7
  import { createEnvelope, type CardCtx, type EnvelopeAction } from "./envelope.js";
8
8
  import { answerTextOf, SETTLEMENT_LABEL, type Interaction } from "../../core/interactions.js";
9
9
  import { usageOf, type CommandEntry } from "../../core/command-catalog.js";
10
+ import { chartsToTables } from "../../core/charts.js";
10
11
  import type { ModelInfo, SessionSummary } from "../../core/types.js";
11
12
 
12
13
  function button(
@@ -173,9 +174,9 @@ export function progressCard(params: { steps: string[]; done?: boolean; footer?:
173
174
  ]);
174
175
  }
175
176
 
176
- /** 回复卡:飞书纯文本不渲染 markdown,所以回复必须走卡片。刻意做到最简。 */
177
+ /** 回复卡:飞书纯文本不渲染 markdown,所以回复必须走卡片。刻意做到最简。```chart 画不了,换成表格 */
177
178
  export function replyCard(text: string) {
178
- return card([{ tag: "markdown", content: clip(text, 4000) }]);
179
+ return card([{ tag: "markdown", content: clip(chartsToTables(text), 4000) }]);
179
180
  }
180
181
 
181
182
  // ---------- 命令结果 ----------
@@ -0,0 +1,107 @@
1
+ // 响应压缩:静态文件(前端和 vendor)、接口返回的 JSON。
2
+ //
3
+ // - 只压文本:图片、视频、压缩包本来就压过了,用户的文件(回复附件、上传)也不走这里。
4
+ // - 静态文件压一次存在内存里(按路径 + 修改时间 + 编码),之后直接给;同一个文件同时被要好几次也只压一次。
5
+ // - JSON 每次现压,太小的不压(省不了几个字节,白花 CPU)。
6
+ // - 都用 zlib 的异步接口(在线程池里跑),不卡事件循环。brotli 用中等档:最高档压 mermaid(5 MB)要好几秒。
7
+ // - WebSocket 不压:流式输出、终端都是又小又密的消息,每条连接一份压缩上下文不划算。
8
+ import zlib from "node:zlib";
9
+ import type { IncomingHttpHeaders } from "node:http";
10
+
11
+ export type Encoding = "br" | "gzip";
12
+
13
+ /** 比这小的不压 */
14
+ export const MIN_SIZE = 1024;
15
+
16
+ const TEXT_EXT = new Set([".js", ".mjs", ".css", ".html", ".svg", ".json", ".webmanifest", ".txt", ".map"]);
17
+
18
+ export function compressibleExt(ext: string): boolean {
19
+ return TEXT_EXT.has(ext.toLowerCase());
20
+ }
21
+
22
+ /** 按 Accept-Encoding 挑:br 优先,其次 gzip;q=0 表示不要 */
23
+ export function pickEncoding(headers: IncomingHttpHeaders): Encoding | undefined {
24
+ const raw = headers["accept-encoding"];
25
+ if (!raw) return undefined;
26
+ const accepted = new Map<string, number>();
27
+ for (const part of String(raw).split(",")) {
28
+ const [name, ...params] = part.trim().toLowerCase().split(";");
29
+ if (!name) continue;
30
+ const q = params.map((p) => /^\s*q=([\d.]+)\s*$/.exec(p)?.[1]).find((v) => v !== undefined);
31
+ accepted.set(name, q === undefined ? 1 : Number(q));
32
+ }
33
+ const ok = (name: string) => (accepted.get(name) ?? accepted.get("*") ?? 0) > 0;
34
+ if (ok("br")) return "br";
35
+ if (ok("gzip")) return "gzip";
36
+ return undefined;
37
+ }
38
+
39
+ function compress(data: Buffer, encoding: Encoding, level: "file" | "live"): Promise<Buffer> {
40
+ return new Promise((resolve, reject) => {
41
+ const done = (err: Error | null, out: Buffer) => (err ? reject(err) : resolve(out));
42
+ if (encoding === "br") {
43
+ const params = {
44
+ [zlib.constants.BROTLI_PARAM_QUALITY]: level === "file" ? 6 : 4,
45
+ [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
46
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: data.length,
47
+ };
48
+ zlib.brotliCompress(data, { params }, done);
49
+ } else zlib.gzip(data, { level: 6 }, done);
50
+ });
51
+ }
52
+
53
+ // ---------- 静态文件 ----------
54
+
55
+ /** 内存里最多存这么多压好的文件(全部前端 + vendor 压完不到 10 MB) */
56
+ const CACHE_MAX = 48 * 1024 * 1024;
57
+ const cache = new Map<string, Promise<Buffer>>();
58
+ const sizes = new Map<string, number>();
59
+ let cached = 0;
60
+
61
+ function evict(): void {
62
+ // Map 按插入顺序:最早放进去的先扔(用到时会挪到最后)
63
+ for (const key of cache.keys()) {
64
+ if (cached <= CACHE_MAX) return;
65
+ cached -= sizes.get(key) ?? 0;
66
+ sizes.delete(key);
67
+ cache.delete(key);
68
+ }
69
+ }
70
+
71
+ /** 压好的静态文件。文件改了(mtime / 大小变了)就是新的键,旧的慢慢被挤掉 */
72
+ export function compressedFile(file: string, mtimeMs: number, size: number, encoding: Encoding, read: () => Promise<Buffer>): Promise<Buffer> {
73
+ const key = `${encoding}:${mtimeMs}:${size}:${file}`;
74
+ const hit = cache.get(key);
75
+ if (hit) {
76
+ cache.delete(key);
77
+ cache.set(key, hit);
78
+ return hit;
79
+ }
80
+ const job = read().then((data) => compress(data, encoding, "file"));
81
+ cache.set(key, job);
82
+ job.then(
83
+ (out) => {
84
+ if (cache.get(key) !== job) return;
85
+ sizes.set(key, out.length);
86
+ cached += out.length;
87
+ evict();
88
+ },
89
+ () => cache.delete(key), // 失败了别记着,下次再试
90
+ );
91
+ return job;
92
+ }
93
+
94
+ /** 测试用 */
95
+ export function clearCompressCache(): void {
96
+ cache.clear();
97
+ sizes.clear();
98
+ cached = 0;
99
+ }
100
+
101
+ // ---------- 接口 JSON ----------
102
+
103
+ /** 现压一段文本;不值得压(太小、对方不收)就 undefined */
104
+ export async function compressLive(data: string, encoding: Encoding | undefined): Promise<Buffer | undefined> {
105
+ if (!encoding || Buffer.byteLength(data) < MIN_SIZE) return undefined;
106
+ return compress(Buffer.from(data), encoding, "live");
107
+ }
@@ -2,6 +2,7 @@
2
2
  import type { IncomingMessage, ServerResponse } from "node:http";
3
3
  import { config } from "../../core/config.js";
4
4
  import { pageCsp } from "../../core/servers.js";
5
+ import { compressLive, MIN_SIZE, pickEncoding } from "./compress.js";
5
6
 
6
7
  export class HttpError extends Error {
7
8
  constructor(
@@ -100,14 +101,27 @@ export async function readJsonBody<T = Record<string, unknown>>(req: IncomingMes
100
101
  }
101
102
  }
102
103
 
104
+ /** 返回 JSON。大于 1 KB、对方收压缩的就压一下(会话历史、消息分页这些长列表能小到几分之一) */
103
105
  export function sendJson(res: ServerResponse, status: number, body: unknown): void {
104
106
  const data = JSON.stringify(body);
105
- res.writeHead(status, {
106
- "Content-Type": "application/json; charset=utf-8",
107
- "Cache-Control": "no-store",
108
- "Content-Length": Buffer.byteLength(data),
109
- });
110
- res.end(data);
107
+ const headers = { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", Vary: "Accept-Encoding" };
108
+ const encoding = res.req ? pickEncoding(res.req.headers) : undefined;
109
+ const plain = () => {
110
+ res.writeHead(status, { ...headers, "Content-Length": Buffer.byteLength(data) });
111
+ res.end(data);
112
+ };
113
+ if (!encoding || Buffer.byteLength(data) < MIN_SIZE) return plain();
114
+ compressLive(data, encoding).then(
115
+ (out) => {
116
+ if (res.headersSent || res.destroyed) return;
117
+ if (!out) return plain();
118
+ res.writeHead(status, { ...headers, "Content-Encoding": encoding, "Content-Length": out.length });
119
+ res.end(out);
120
+ },
121
+ () => {
122
+ if (!res.headersSent && !res.destroyed) plain();
123
+ },
124
+ );
111
125
  }
112
126
 
113
127
  export const SECURITY_HEADERS: Record<string, string> = {
@@ -23,6 +23,7 @@ import { currentUser, handleApi, takeUploads } from "./api.js";
23
23
  import { authEvents, ensureSetupToken, sessionUser } from "./auth.js";
24
24
  import { canSeeKey, sessionVisibleTo } from "./access.js";
25
25
  import { cookies } from "./http.js";
26
+ import { compressedFile, compressibleExt, MIN_SIZE, pickEncoding } from "./compress.js";
26
27
  import { COOKIE } from "./api.js";
27
28
  import { HttpError, pageHeaders, sameOrigin, SECURITY_HEADERS, sendJson } from "./http.js";
28
29
  import { hasSubscriptions, pushToAll } from "./push.js";
@@ -59,6 +60,9 @@ const VENDOR: Record<string, () => string> = {
59
60
  "/vendor/xterm.js": () => pkgFile("@xterm/xterm", "lib/xterm.mjs"),
60
61
  "/vendor/xterm.css": () => pkgFile("@xterm/xterm", "css/xterm.css"),
61
62
  "/vendor/xterm-fit.js": () => pkgFile("@xterm/addon-fit", "lib/addon-fit.mjs"),
63
+ // 回复里的 ```chart / ```mermaid:都很大,用到时才用 <script> 加载(单文件 UMD,挂到 window 上)
64
+ "/vendor/echarts.js": () => pkgFile("echarts", "dist/echarts.min.js"),
65
+ "/vendor/mermaid.js": () => pkgFile("mermaid", "dist/mermaid.min.js"),
62
66
  };
63
67
 
64
68
  const MIME: Record<string, string> = {
@@ -96,12 +100,25 @@ function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: st
96
100
  res.end();
97
101
  return;
98
102
  }
99
- res.writeHead(200, {
100
- ...headers,
101
- "Content-Type": MIME[path.extname(file)] ?? "application/octet-stream",
102
- "Content-Length": stat.size,
103
- });
104
- fs.createReadStream(file).pipe(res);
103
+ const type = MIME[path.extname(file)] ?? "application/octet-stream";
104
+ // 文本压一下(压好的存在内存里);对方不收、太小、压失败了就原样给
105
+ const text = compressibleExt(path.extname(file));
106
+ const encoding = text && stat.size >= MIN_SIZE ? pickEncoding(req.headers) : undefined;
107
+ const raw = () => {
108
+ res.writeHead(200, { ...headers, "Content-Type": type, "Content-Length": stat.size, ...(text ? { Vary: "Accept-Encoding" } : {}) });
109
+ fs.createReadStream(file).pipe(res);
110
+ };
111
+ if (!encoding) return raw();
112
+ compressedFile(file, stat.mtimeMs, stat.size, encoding, () => fs.promises.readFile(file)).then(
113
+ (body) => {
114
+ if (res.headersSent || res.destroyed) return;
115
+ res.writeHead(200, { ...headers, "Content-Type": type, "Content-Encoding": encoding, "Content-Length": body.length, Vary: "Accept-Encoding" });
116
+ res.end(body);
117
+ },
118
+ () => {
119
+ if (!res.headersSent && !res.destroyed) raw();
120
+ },
121
+ );
105
122
  });
106
123
  }
107
124
 
@@ -0,0 +1,67 @@
1
+ // 回复里的 ```chart 代码块(格式见 core/expert-prompt.ts 的 RICH_REPLY_LINES,网页上由 web/lib/diagrams.js 画成图)。
2
+ // 飞书卡片画不了:换成一张 markdown 表格,数还在。JSON 不对就原样留着。
3
+
4
+ const FENCE = /^ {0,3}(`{3,}|~{3,})[ \t]*chart[ \t]*\n([\s\S]*?)\n {0,3}\1[ \t]*$/gim;
5
+
6
+ type Cell = string | number | null | undefined;
7
+
8
+ function fmt(v: unknown): string {
9
+ if (v === null || v === undefined || v === "") return "—";
10
+ const n = Number(v);
11
+ return Number.isFinite(n) ? n.toLocaleString("en-US") : String(v);
12
+ }
13
+
14
+ function esc(v: Cell): string {
15
+ return String(v ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ");
16
+ }
17
+
18
+ function table(head: Cell[], rows: Cell[][]): string {
19
+ return [`| ${head.map(esc).join(" | ")} |`, `|${head.map(() => " --- ").join("|")}|`, ...rows.map((r) => `| ${r.map(esc).join(" | ")} |`)].join("\n");
20
+ }
21
+
22
+ /** 一段 chart JSON 换成表格;看不懂就 undefined */
23
+ export function chartTable(json: string): string | undefined {
24
+ let raw: unknown;
25
+ try {
26
+ raw = JSON.parse(json);
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ if (!raw || typeof raw !== "object") return undefined;
31
+ const spec = raw as { type?: unknown; title?: unknown; x?: unknown; series?: unknown; data?: unknown; unit?: unknown; xName?: unknown };
32
+ const list = Array.isArray(spec.series) ? spec.series : Array.isArray(spec.data) ? [{ data: spec.data }] : [];
33
+ const series = list.map((s: { name?: unknown; data?: unknown }, i) => ({
34
+ name: s?.name ? String(s.name) : list.length > 1 ? `系列 ${i + 1}` : "数值",
35
+ data: Array.isArray(s?.data) ? (s.data as unknown[]) : [],
36
+ }));
37
+ const first = series[0];
38
+ if (!first) return undefined;
39
+ const type = String(spec.type ?? "line");
40
+ const x = Array.isArray(spec.x) ? spec.x.map((v) => String(v ?? "")) : [];
41
+ const unit = spec.unit ? `(${String(spec.unit)})` : "";
42
+ let body: string;
43
+ if (type === "pie") {
44
+ body = table(
45
+ ["", `${first.name}${unit}`],
46
+ first.data.map((p, j) => (p && typeof p === "object" && !Array.isArray(p) ? [String((p as { name?: unknown }).name ?? ""), fmt((p as { value?: unknown }).value)] : [x[j] ?? `#${j + 1}`, fmt(p)])),
47
+ );
48
+ } else if (type === "scatter") {
49
+ body = table(
50
+ ["", spec.xName ? String(spec.xName) : "x", `y${unit}`],
51
+ series.flatMap((s) => s.data.map((p) => (Array.isArray(p) ? [s.name, fmt(p[0]), fmt(p[1])] : [s.name, "—", "—"]))),
52
+ );
53
+ } else {
54
+ const n = Math.max(x.length, ...series.map((s) => s.data.length));
55
+ body = table(
56
+ [spec.xName ? String(spec.xName) : "", ...series.map((s) => `${s.name}${unit}`)],
57
+ Array.from({ length: n }, (_, i) => [x[i] ?? String(i + 1), ...series.map((s) => fmt(s.data[i]))]),
58
+ );
59
+ }
60
+ return spec.title ? `**📊 ${String(spec.title)}**\n\n${body}` : body;
61
+ }
62
+
63
+ /** 回复里的 ```chart 都换成表格(给画不了图的地方,比如飞书) */
64
+ export function chartsToTables(text: string): string {
65
+ if (!/chart/i.test(text)) return text;
66
+ return text.replace(FENCE, (whole, _fence: string, json: string) => chartTable(json) ?? whole);
67
+ }
@@ -64,6 +64,24 @@ function persona(expert: PromptExpert): string[] {
64
64
  return [`你是「${expert.name}」,用户通过 agent-loft 的网页或飞书和你对话。`, ...(expert.prompt ? ["", expert.prompt] : [])];
65
65
  }
66
66
 
67
+ /**
68
+ * 回复里能画的图:网页把 ```chart / ```mermaid 画出来(web/lib/diagrams.js),飞书把 chart 换成表格(core/charts.ts)。
69
+ * 所有专家、内置的 Claude Code / Codex 都给。格式改了这三处要一起改。
70
+ */
71
+ export const RICH_REPLY_LINES = [
72
+ "## 回复里的图表",
73
+ "",
74
+ "- 要展示趋势、对比、占比时,可以在回复里放一个 ```chart 代码块,网页上会画成图(飞书上显示成表格)。内容是一段 JSON,例如:",
75
+ " ```chart",
76
+ ' {"type":"line","title":"近 3 天访问量","x":["10-23","10-24","10-25"],"series":[{"name":"PV","data":[120,98,135]},{"name":"UV","data":[80,66,90]}],"unit":"次"}',
77
+ " ```",
78
+ ' - type:line 折线、area 面积、bar 柱状(加 "horizontal":true 横向)、pie 饼图(只有一组数据,data 写成 [{"name":"A","value":3}])、scatter 散点(data 写成 [[x,y]])。',
79
+ " - 可选:stack 堆叠(true)、xName x 轴名称、unit 数值单位、height 高度(像素,180–600)。",
80
+ " - 一张图最多 8 组数据,饼图最多 8 块;量级差很多的两种数据分成两张图;缺的数据写 null。只写合法 JSON,不要注释,不要省略号。",
81
+ "- 流程、时序、状态、结构关系可以用 ```mermaid 代码块画图。",
82
+ "- 只在图比文字更清楚时才画;几个数字用文字或表格就够了。",
83
+ ];
84
+
67
85
  /** Claude 自定义专家的整段系统提示(lean:换掉 Claude Code 原装的) */
68
86
  export function expertSystemPrompt(expert: PromptExpert, search: string | undefined, cwd: string, memory?: string): string {
69
87
  const base = [
@@ -73,6 +91,8 @@ export function expertSystemPrompt(expert: PromptExpert, search: string | undefi
73
91
  "",
74
92
  ...capabilityLines(expert, search, cwd),
75
93
  "",
94
+ ...RICH_REPLY_LINES,
95
+ "",
76
96
  `今天是 ${today()}。`,
77
97
  ].join("\n");
78
98
  return memory ? `${base}\n\n${memory}` : base;
@@ -80,7 +100,9 @@ export function expertSystemPrompt(expert: PromptExpert, search: string | undefi
80
100
 
81
101
  /** Claude 自定义专家选了「Claude Code 原装」:追加在原装提示后面的部分 */
82
102
  export function expertAppend(expert: PromptExpert, search: string | undefined, cwd: string): string {
83
- return [...persona(expert), "", "## 这个专家能做什么(agent-loft 按配置生成)", "", ...capabilityLines(expert, search, cwd)].join("\n");
103
+ return [...persona(expert), "", "## 这个专家能做什么(agent-loft 按配置生成)", "", ...capabilityLines(expert, search, cwd), "", ...RICH_REPLY_LINES].join(
104
+ "\n",
105
+ );
84
106
  }
85
107
 
86
108
  const OPEN = "<agent-loft-context>";
@@ -88,7 +110,7 @@ const CLOSE = "</agent-loft-context>";
88
110
 
89
111
  /**
90
112
  * Codex:附在会话进程第一条消息后面的背景。
91
- * expert 不给就是内置的 Codex 专家:只有记忆和技能清单,都没有就不附(返回空串)。
113
+ * expert 不给就是内置的 Codex 专家:只有记忆、技能清单和图表的写法。
92
114
  */
93
115
  export function contextBlock(
94
116
  expert: { prompt: PromptExpert; cwd: string } | undefined,
@@ -98,8 +120,8 @@ export function contextBlock(
98
120
  const head = expert
99
121
  ? [...persona(expert.prompt), "", "## 你能做什么(agent-loft 按这个专家的配置生成)", "", ...capabilityLines(expert.prompt, searchLabel("codex", expert.prompt), expert.cwd)]
100
122
  : [];
101
- const sections = [head, memory ? [memory] : [], skills].filter((s) => s.length > 0);
102
- return sections.length ? wrapContext(sections.flatMap((s, i) => (i ? ["", ...s] : s))) : "";
123
+ const sections = [head, RICH_REPLY_LINES, memory ? [memory] : [], skills].filter((s) => s.length > 0);
124
+ return wrapContext(sections.flatMap((s, i) => (i ? ["", ...s] : s)));
103
125
  }
104
126
 
105
127
  /** 包成 agent-loft 附上的背景:用户看不到(读历史、实时显示时都剥掉),agent 照着做 */
@@ -1507,3 +1507,88 @@ a.att-file:hover {
1507
1507
  padding: 12px 16px;
1508
1508
  box-sizing: border-box;
1509
1509
  }
1510
+
1511
+ /* ---------- 回复里的 ```chart / ```mermaid 画成的图(lib/diagrams.js) ---------- */
1512
+ .md .diagram {
1513
+ margin: 0.8em 0;
1514
+ border: 1px solid var(--border);
1515
+ border-radius: 10px;
1516
+ padding: 12px 12px 4px;
1517
+ }
1518
+
1519
+ .md .diagram.broken {
1520
+ border-style: dashed;
1521
+ padding-bottom: 12px;
1522
+ }
1523
+
1524
+ .diagram-title {
1525
+ font-size: 14px;
1526
+ font-weight: 600;
1527
+ margin-bottom: 8px;
1528
+ }
1529
+
1530
+ .diagram-body {
1531
+ width: 100%;
1532
+ min-height: 60px;
1533
+ }
1534
+
1535
+ .diagram.mermaid .diagram-body {
1536
+ overflow-x: auto;
1537
+ text-align: center;
1538
+ }
1539
+
1540
+ .diagram-svg {
1541
+ max-width: 100%;
1542
+ height: auto;
1543
+ }
1544
+
1545
+ .diagram-wait {
1546
+ height: 80px;
1547
+ display: flex;
1548
+ align-items: center;
1549
+ justify-content: center;
1550
+ font-size: 13px;
1551
+ color: var(--fg-faint);
1552
+ }
1553
+
1554
+ .diagram-error {
1555
+ font-size: 13px;
1556
+ color: var(--fg-soft);
1557
+ padding: 4px 0 8px;
1558
+ }
1559
+
1560
+ .md .diagram-table table {
1561
+ font-variant-numeric: tabular-nums;
1562
+ margin: 8px 0 0;
1563
+ }
1564
+
1565
+ .md .diagram-table td:not(:first-child) {
1566
+ text-align: right;
1567
+ }
1568
+
1569
+ .md .diagram .diagram-src {
1570
+ margin: 8px 0 0;
1571
+ }
1572
+
1573
+ .diagram-actions {
1574
+ display: flex;
1575
+ justify-content: flex-end;
1576
+ gap: 4px;
1577
+ margin-top: 4px;
1578
+ }
1579
+
1580
+ .md .diagram-btn {
1581
+ font-size: 12px;
1582
+ color: var(--fg-soft);
1583
+ background: none;
1584
+ border: 0;
1585
+ padding: 2px 6px;
1586
+ border-radius: 6px;
1587
+ cursor: pointer;
1588
+ }
1589
+
1590
+ .md .diagram-btn:hover,
1591
+ .md .diagram-btn.on {
1592
+ background: var(--bg-hover);
1593
+ color: var(--fg);
1594
+ }
@@ -0,0 +1,383 @@
1
+ import { h } from "./dom.js";
2
+
3
+ // 回复里的 ```chart(专家用一小段 JSON 描述的曲线图、柱状图、饼图)和 ```mermaid(流程图、时序图…)。
4
+ //
5
+ // - chart 只认数据,不认 ECharts 的原始配置:模型不容易写错,也不会带进能执行的东西(tooltip 的 formatter 能写 HTML)。
6
+ // 格式和提示词里教给模型的一致(src/core/expert-prompt.ts 的 RICH_REPLY_LINES),飞书那边降级成表格(src/core/charts.ts)。
7
+ // - mermaid 画成 SVG 后放进 <img>:图片里的 SVG 不会执行脚本,模型写坏了也伤不到页面。
8
+ // - ECharts、mermaid 都很大,滚到附近了才加载、才画;跟着系统的深浅色重画。
9
+
10
+ const MAX_SERIES = 8;
11
+ const MAX_POINTS = 5000;
12
+ const TYPES = new Set(["line", "area", "bar", "pie", "scatter"]);
13
+
14
+ /** 分类色:固定顺序,深色模式用各自那一档(都过了色盲区分度校验) */
15
+ const PALETTE = {
16
+ light: ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"],
17
+ dark: ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300", "#9085e9", "#e66767"],
18
+ };
19
+ const CHROME = {
20
+ light: { grid: "#e1e0d9", axis: "#c3c2b7", muted: "#898781", ring: "#ffffff" },
21
+ dark: { grid: "#2c2c2a", axis: "#383835", muted: "#898781", ring: "#212121" },
22
+ };
23
+
24
+ const darkQuery = matchMedia("(prefers-color-scheme: dark)");
25
+ const mode = () => (darkQuery.matches ? "dark" : "light");
26
+
27
+ /** 代码块是不是要画成图:返回语言,不是就 null */
28
+ export function diagramLang(code) {
29
+ const lang = /language-([\w+-]+)/.exec(code.className)?.[1]?.toLowerCase();
30
+ return lang === "chart" || lang === "mermaid" ? lang : null;
31
+ }
32
+
33
+ /**
34
+ * 把 <pre><code class="language-chart|mermaid"> 换成图。
35
+ * final = false:还在输出、内容不全,先放个占位,定下来了再画。
36
+ */
37
+ export function mountDiagram(pre, code, lang, final) {
38
+ const source = code.textContent;
39
+ if (!final) {
40
+ pre.replaceWith(h("div", { class: "diagram pending" }, h("div", { class: "diagram-wait" }, lang === "chart" ? "图表生成中…" : "图生成中…")));
41
+ return;
42
+ }
43
+ const body = h("div", { class: "diagram-body" });
44
+ const box = h("div", { class: `diagram ${lang}` });
45
+ box._lang = lang;
46
+ box._source = source;
47
+ box._body = body;
48
+ pre.replaceWith(box);
49
+ // 原来的代码块(带复制按钮)留着,点「源码」看
50
+ pre.classList.add("diagram-src");
51
+ pre.hidden = true;
52
+ const views = [];
53
+ if (lang === "chart") {
54
+ const spec = parseChart(source);
55
+ if (typeof spec === "string") return fail(box, pre, spec);
56
+ box._spec = spec;
57
+ if (spec.title) box.append(h("div", { class: "diagram-title" }, spec.title));
58
+ body.style.height = `${spec.height}px`;
59
+ const table = chartTable(spec);
60
+ table.hidden = true;
61
+ views.push(["表格", table]);
62
+ box.append(body, table);
63
+ } else box.append(body);
64
+ views.push(["源码", pre]);
65
+ box.append(
66
+ pre,
67
+ h(
68
+ "div",
69
+ { class: "diagram-actions" },
70
+ views.map(([label, el]) => {
71
+ const btn = h("button", { class: "diagram-btn" }, label);
72
+ btn.onclick = () => {
73
+ el.hidden = !el.hidden;
74
+ btn.classList.toggle("on", !el.hidden);
75
+ };
76
+ return btn;
77
+ }),
78
+ ),
79
+ );
80
+ lazyRender.observe(box);
81
+ }
82
+
83
+ function fail(box, pre, message) {
84
+ pre.hidden = false;
85
+ box.classList.add("broken");
86
+ box.append(h("div", { class: "diagram-error" }, message), pre);
87
+ }
88
+
89
+ const lazyRender = new IntersectionObserver(
90
+ (entries) => {
91
+ for (const e of entries) {
92
+ if (!e.isIntersecting) continue;
93
+ lazyRender.unobserve(e.target);
94
+ void draw(e.target);
95
+ }
96
+ },
97
+ { rootMargin: "800px 0px", scrollMargin: "800px 0px" },
98
+ );
99
+
100
+ /** 块被重画掉时调:还没画的别再画 */
101
+ export function unmountDiagrams(root) {
102
+ if (root.nodeType !== Node.ELEMENT_NODE) return;
103
+ for (const box of [...(root.matches(".diagram") ? [root] : []), ...root.querySelectorAll(".diagram")]) {
104
+ lazyRender.unobserve(box);
105
+ box._chart?.dispose();
106
+ }
107
+ }
108
+
109
+ async function draw(box) {
110
+ box.dataset.drawn = "1";
111
+ try {
112
+ if (box._lang === "chart") await drawChart(box);
113
+ else await drawMermaid(box);
114
+ } catch (err) {
115
+ box._body.replaceChildren(h("div", { class: "diagram-error" }, `画不出来:${err?.message ?? err}`));
116
+ const src = box.querySelector(".diagram-src");
117
+ if (src) src.hidden = false;
118
+ }
119
+ }
120
+
121
+ // 换了深浅色:画好的都重画一遍
122
+ darkQuery.addEventListener("change", () => {
123
+ for (const box of document.querySelectorAll(".diagram[data-drawn]")) void draw(box);
124
+ });
125
+
126
+ const scripts = {};
127
+ function loadScript(src, name) {
128
+ return (scripts[src] ??= new Promise((resolve, reject) => {
129
+ const s = document.createElement("script");
130
+ s.src = src;
131
+ s.onload = () => (window[name] ? resolve(window[name]) : reject(new Error(`${name} 没加载上`)));
132
+ s.onerror = () => {
133
+ delete scripts[src];
134
+ reject(new Error(`${name} 加载失败`));
135
+ };
136
+ document.head.append(s);
137
+ }));
138
+ }
139
+
140
+ // ---------- chart ----------
141
+
142
+ const num = (v) => (v === null || v === undefined || v === "" ? null : Number.isFinite(Number(v)) ? Number(v) : NaN);
143
+
144
+ /** 校验并整理 chart 的 JSON;不对就返回一句给人看的原因 */
145
+ export function parseChart(text) {
146
+ let raw;
147
+ try {
148
+ raw = JSON.parse(text);
149
+ } catch {
150
+ return "图表的 JSON 写得不对,显示原文";
151
+ }
152
+ if (!raw || typeof raw !== "object") return "图表的内容不是一个对象";
153
+ const type = String(raw.type ?? "line");
154
+ if (!TYPES.has(type)) return `不认识的图表类型「${type}」`;
155
+ const list = Array.isArray(raw.series) ? raw.series : raw.data ? [{ data: raw.data }] : [];
156
+ if (!list.length) return "图表没有数据(series)";
157
+ if (list.length > MAX_SERIES) return `一张图最多 ${MAX_SERIES} 组数据`;
158
+ const x = Array.isArray(raw.x) ? raw.x.map((v) => String(v ?? "")) : undefined;
159
+ const series = [];
160
+ let points = 0;
161
+ for (const [i, s] of list.entries()) {
162
+ const data = Array.isArray(s?.data) ? s.data : [];
163
+ points += data.length;
164
+ let values;
165
+ if (type === "scatter") {
166
+ values = data.map((p) => (Array.isArray(p) ? [num(p[0]), num(p[1])] : [NaN, NaN]));
167
+ if (values.some(([a, b]) => Number.isNaN(a) || Number.isNaN(b))) return "散点图的每个点要写成 [x, y]";
168
+ } else if (type === "pie") {
169
+ values = data.map((p, j) =>
170
+ p && typeof p === "object" && !Array.isArray(p) ? { name: String(p.name ?? ""), value: num(p.value) } : { name: x?.[j] ?? `#${j + 1}`, value: num(p) },
171
+ );
172
+ if (values.some((p) => p.value === null || Number.isNaN(p.value))) return "饼图的每一块都要有数值";
173
+ if (values.length > MAX_SERIES) return `饼图最多 ${MAX_SERIES} 块,小的合并成「其他」`;
174
+ } else {
175
+ values = data.map(num);
176
+ if (values.some(Number.isNaN)) return `第 ${i + 1} 组数据里有不是数字的值`;
177
+ }
178
+ series.push({ name: String(s?.name ?? (list.length > 1 ? `系列 ${i + 1}` : raw.title ?? "")), data: values });
179
+ }
180
+ if (points > MAX_POINTS) return `数据点太多(最多 ${MAX_POINTS} 个)`;
181
+ if (type === "pie" && series.length > 1) return "饼图只能有一组数据";
182
+ const longest = Math.max(...series.map((s) => s.data.length));
183
+ if (!["pie", "scatter"].includes(type) && x && x.length < longest) return "x 的个数比数据少";
184
+ const height = Math.min(Math.max(Number(raw.height) || (type === "pie" ? 280 : 300), 180), 600);
185
+ const str = (v) => (v === undefined || v === null ? "" : String(v).slice(0, 200));
186
+ return {
187
+ type,
188
+ title: str(raw.title),
189
+ x: x ?? (["pie", "scatter"].includes(type) ? undefined : Array.from({ length: longest }, (_, i) => String(i + 1))),
190
+ series,
191
+ unit: str(raw.unit),
192
+ xName: str(raw.xName),
193
+ stack: Boolean(raw.stack),
194
+ horizontal: type === "bar" && Boolean(raw.horizontal),
195
+ height,
196
+ };
197
+ }
198
+
199
+ function chartOption(spec) {
200
+ const m = mode();
201
+ const colors = PALETTE[m];
202
+ const c = CHROME[m];
203
+ const css = getComputedStyle(document.documentElement);
204
+ const ink = css.getPropertyValue("--fg-soft").trim() || "#5d5d5d";
205
+ const font = css.getPropertyValue("--font").trim() || "system-ui, sans-serif";
206
+ const text = { color: ink, fontFamily: font, fontSize: 12 };
207
+ const multi = spec.series.length > 1;
208
+ const base = {
209
+ color: colors,
210
+ backgroundColor: "transparent",
211
+ textStyle: text,
212
+ animationDuration: 400,
213
+ legend: multi || spec.type === "pie" ? { top: 0, left: 0, icon: "roundRect", itemWidth: 12, itemHeight: 12, textStyle: text } : undefined,
214
+ tooltip: {
215
+ confine: true,
216
+ backgroundColor: css.getPropertyValue("--bg").trim() || "#fff",
217
+ borderColor: css.getPropertyValue("--border").trim() || "#e5e5e5",
218
+ textStyle: { ...text, color: css.getPropertyValue("--fg").trim() || "#0d0d0d" },
219
+ valueFormatter: (v) => (v === null || v === undefined ? "—" : `${Number(v).toLocaleString()}${spec.unit ? ` ${spec.unit}` : ""}`),
220
+ },
221
+ };
222
+ if (spec.type === "pie") {
223
+ return {
224
+ ...base,
225
+ tooltip: { ...base.tooltip, trigger: "item" },
226
+ series: [
227
+ {
228
+ type: "pie",
229
+ name: spec.series[0].name,
230
+ radius: ["45%", "70%"],
231
+ center: ["50%", "55%"],
232
+ itemStyle: { borderColor: c.ring, borderWidth: 2, borderRadius: 4 },
233
+ label: { color: ink, formatter: "{b} {d}%" },
234
+ data: spec.series[0].data,
235
+ },
236
+ ],
237
+ };
238
+ }
239
+ const axis = (type, name) => ({
240
+ type,
241
+ name,
242
+ nameTextStyle: { color: c.muted },
243
+ axisLine: { lineStyle: { color: c.axis } },
244
+ axisTick: { show: false },
245
+ axisLabel: { color: c.muted },
246
+ splitLine: { show: type === "value", lineStyle: { color: c.grid } },
247
+ scale: type === "value" && spec.type === "scatter",
248
+ });
249
+ const category = axis("category", spec.xName);
250
+ category.data = spec.x;
251
+ const value = axis("value", spec.unit);
252
+ // 上面先放图例,再放 y 轴的单位,别叠在一起
253
+ const grid = { left: 8, right: 16, top: (multi ? 28 : 0) + (spec.unit && !spec.horizontal ? 28 : 12), bottom: 8, containLabel: true };
254
+ const series = spec.series.map((s) => {
255
+ const one = { name: s.name, data: s.data, emphasis: { focus: "series" } };
256
+ if (spec.type === "scatter") return { ...one, type: "scatter", symbolSize: 8, itemStyle: { borderColor: c.ring, borderWidth: 1 } };
257
+ if (spec.type === "bar") {
258
+ return {
259
+ ...one,
260
+ type: "bar",
261
+ stack: spec.stack ? "total" : undefined,
262
+ barMaxWidth: 28,
263
+ itemStyle: { borderRadius: spec.stack ? 0 : spec.horizontal ? [0, 4, 4, 0] : [4, 4, 0, 0], borderColor: c.ring, borderWidth: spec.stack ? 1 : 0 },
264
+ };
265
+ }
266
+ const few = s.data.length <= 40;
267
+ return {
268
+ ...one,
269
+ type: "line",
270
+ stack: spec.stack ? "total" : undefined,
271
+ showSymbol: few,
272
+ symbol: "circle",
273
+ symbolSize: 8,
274
+ lineStyle: { width: 2 },
275
+ itemStyle: { borderColor: c.ring, borderWidth: 2 },
276
+ areaStyle: spec.type === "area" ? { opacity: spec.stack ? 0.6 : 0.15 } : undefined,
277
+ connectNulls: false,
278
+ };
279
+ });
280
+ if (spec.type === "scatter") {
281
+ return { ...base, grid, tooltip: { ...base.tooltip, trigger: "item", valueFormatter: undefined }, xAxis: axis("value", spec.xName), yAxis: value, series };
282
+ }
283
+ const pointer = spec.type === "bar" ? { type: "shadow", shadowStyle: { color: "rgba(127,127,127,0.12)" } } : { type: "line", lineStyle: { color: c.axis } };
284
+ return {
285
+ ...base,
286
+ grid,
287
+ tooltip: { ...base.tooltip, trigger: "axis", axisPointer: pointer },
288
+ xAxis: spec.horizontal ? value : { ...category, boundaryGap: spec.type === "bar" },
289
+ yAxis: spec.horizontal ? { ...category, inverse: true } : value,
290
+ series,
291
+ };
292
+ }
293
+
294
+ async function drawChart(box) {
295
+ const echarts = await loadScript("/vendor/echarts.js", "echarts");
296
+ box._chart?.dispose();
297
+ const chart = echarts.init(box._body, null, { renderer: "svg" });
298
+ box._chart = chart;
299
+ chart.setOption(chartOption(box._spec));
300
+ // 跟着宽度变;块被删掉(不在页面上了)就释放
301
+ box._resize?.disconnect();
302
+ box._resize = new ResizeObserver(() => {
303
+ if (!box.isConnected) {
304
+ chart.dispose();
305
+ box._resize.disconnect();
306
+ } else chart.resize();
307
+ });
308
+ box._resize.observe(box._body);
309
+ }
310
+
311
+ /** 图的数据换成表格,给读屏和想看具体数字的人 */
312
+ function chartTable(spec) {
313
+ const fmt = (v) => (v === null ? "—" : Number(v).toLocaleString());
314
+ let head;
315
+ let rows;
316
+ if (spec.type === "pie") {
317
+ head = ["", spec.series[0].name || "数值"];
318
+ rows = spec.series[0].data.map((p) => [p.name, fmt(p.value)]);
319
+ } else if (spec.type === "scatter") {
320
+ head = ["", spec.xName || "x", spec.unit || "y"];
321
+ rows = spec.series.flatMap((s) => s.data.map(([a, b]) => [s.name, fmt(a), fmt(b)]));
322
+ } else {
323
+ head = [spec.xName, ...spec.series.map((s) => s.name || "数值")];
324
+ rows = spec.x.map((label, i) => [label, ...spec.series.map((s) => fmt(s.data[i] ?? null))]);
325
+ }
326
+ return h(
327
+ "div",
328
+ { class: "diagram-table" },
329
+ h("table", {}, h("thead", {}, h("tr", {}, head.map((c) => h("th", {}, c)))), h("tbody", {}, rows.map((r) => h("tr", {}, r.map((c) => h("td", {}, c)))))),
330
+ );
331
+ }
332
+
333
+ // ---------- mermaid ----------
334
+
335
+ let mermaidQueue = Promise.resolve();
336
+ let mermaidSeq = 0;
337
+ let mermaidTheme;
338
+
339
+ function drawMermaid(box) {
340
+ // mermaid 同一时间只能画一张(共用一个全局状态),排队
341
+ const job = mermaidQueue.then(async () => {
342
+ const mermaid = await loadScript("/vendor/mermaid.js", "mermaid");
343
+ const theme = mode() === "dark" ? "dark" : "default";
344
+ if (mermaidTheme !== theme) {
345
+ const font = getComputedStyle(document.documentElement).getPropertyValue("--font").trim();
346
+ mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme, fontFamily: font || undefined, htmlLabels: false, flowchart: { htmlLabels: false } });
347
+ mermaidTheme = theme;
348
+ }
349
+ const id = `aloft-mermaid-${++mermaidSeq}`;
350
+ let svg;
351
+ try {
352
+ ({ svg } = await mermaid.render(id, box._source));
353
+ } catch (err) {
354
+ throw new Error(String(err?.message ?? err).split("\n")[0] || "mermaid 语法不对");
355
+ } finally {
356
+ // 出错时 mermaid 会在 body 里留下一个画错的临时元素
357
+ document.getElementById(`d${id}`)?.remove();
358
+ document.getElementById(id)?.remove();
359
+ }
360
+ const img = svgImage(svg);
361
+ box._body.replaceChildren(img);
362
+ });
363
+ mermaidQueue = job.catch(() => {});
364
+ return job;
365
+ }
366
+
367
+ /** SVG 放进 <img>:按 viewBox 给出原始大小,窄屏上缩小 */
368
+ function svgImage(svg) {
369
+ const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
370
+ const root = doc.documentElement;
371
+ const vb = (root.getAttribute("viewBox") ?? "").split(/[\s,]+/).map(Number);
372
+ const width = vb.length === 4 && vb[2] > 0 ? Math.ceil(vb[2]) : undefined;
373
+ const height = vb.length === 4 && vb[3] > 0 ? Math.ceil(vb[3]) : undefined;
374
+ if (width && height) {
375
+ root.setAttribute("width", String(width));
376
+ root.setAttribute("height", String(height));
377
+ }
378
+ root.removeAttribute("style");
379
+ const data = new XMLSerializer().serializeToString(root);
380
+ const img = h("img", { class: "diagram-svg", alt: "图", src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(data)}` });
381
+ if (width) img.style.width = `${width}px`;
382
+ return img;
383
+ }
@@ -1,6 +1,7 @@
1
1
  import DOMPurify from "/vendor/purify.js";
2
2
  import hljs from "/vendor/hljs.js";
3
3
  import { marked } from "/vendor/marked.js";
4
+ import { diagramLang, mountDiagram, unmountDiagrams } from "./diagrams.js";
4
5
  import { h, toast } from "./dom.js";
5
6
 
6
7
  // ---------- markdown ----------
@@ -42,6 +43,7 @@ export function patchMarkdown(div, text, { live = false, enhance } = {}) {
42
43
  for (const b of blocks.splice(i)) {
43
44
  for (const n of b.nodes) {
44
45
  if (n.nodeType === Node.ELEMENT_NODE) for (const code of n.querySelectorAll("pre code")) lazyHighlight.unobserve(code);
46
+ unmountDiagrams(n);
45
47
  n.remove();
46
48
  }
47
49
  }
@@ -60,7 +62,7 @@ export function patchMarkdown(div, text, { live = false, enhance } = {}) {
60
62
  }
61
63
  }
62
64
 
63
- /** 链接新窗口打开;代码块加上语言 + 复制按钮的头,滚到附近了再高亮 */
65
+ /** 链接新窗口打开;代码块加上语言 + 复制按钮的头,滚到附近了再高亮;```chart / ```mermaid 画成图 */
64
66
  function decorate(root, highlight) {
65
67
  for (const a of root.querySelectorAll("a")) {
66
68
  a.target = "_blank";
@@ -72,7 +74,9 @@ function decorate(root, highlight) {
72
74
  const lang = /language-([\w+-]+)/.exec(code.className)?.[1] ?? "";
73
75
  const copy = h("button", { class: "copy-btn", onclick: () => copyText(code.textContent, copy) }, "复制");
74
76
  pre.prepend(h("div", { class: "code-head" }, h("span", {}, lang || "code"), copy));
75
- if (highlight) lazyHighlight.observe(code);
77
+ const diagram = diagramLang(code);
78
+ if (diagram) mountDiagram(pre, code, diagram, highlight);
79
+ else if (highlight) lazyHighlight.observe(code);
76
80
  }
77
81
  }
78
82