agent-loft 0.2.51 → 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,19 +45,20 @@ 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」)。
52
53
  - 滚动和 ChatGPT 一样:发出的问题顶到最上面、下面留白,回复长到屏幕底部才跟着往下滚;回复过程中自己滚动了就不再自动滚,下次发消息再恢复。
53
54
  - 定时发送:右上角「更多」→「定时发送」,默认排在 5 小时额度重置后 5 分钟(弹窗里提示 5 小时 / 7 天额度的重置时间),由服务端到点发出,关掉页面也会发。适合额度用完、要等刷新才能接着干活的时候。
54
- - 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书机器人各占一行(右键看历史会话);项目名、有分叉的会话后面有个小三角,点一下折叠 / 展开(折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;会话标题由 agent 自动生成,双击重命名;鼠标移到会话上,标题后显示对应的专家图标。
55
- - **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;电脑和手机上弹窗都固定高度,结果在内部滚动;↑↓ 选、回车打开。
55
+ - 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书机器人各占一行(右键看历史会话);项目名、有分叉的会话后面有个小三角,点一下折叠 / 展开(折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;会话标题由 agent 自动生成,双击重命名;鼠标移到会话上,行尾显示对应的专家图标;定时任务的时钟图标始终放在最右侧。
56
+ - **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;电脑和手机上弹窗都固定高度,结果在内部滚动,手机上从底部展开;↑↓ 选、回车打开。
56
57
  - 会话页顶部标题前是专家的头像,鼠标停上去或点一下,看专家的说明、模型、能力和当前工作目录。
57
58
  - 附件可以直接拖到聊天区任意位置上传。
58
- - 回复过程中接着发的消息排队,标着「排队中」,上一条回复完自动接着处理;点「撤销并编辑」图标把排队消息放回输入框;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
59
+ - 回复过程中接着发的消息排队,标着「排队中」,隐藏底部的复制和回退按钮,上一条回复完自动接着处理;点「撤销并编辑」图标把排队消息放回输入框;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
59
60
  - 用户消息的复制按钮后有「回退到此处」图标:把这条消息及附件放回输入框,并删除它及之后的聊天内容,重新发送时从之前的上下文继续。
60
- - 太长的消息先收起,点「展开显示」看全文;对话里有至少 3 条用户消息时,右侧显示快速定位尺,电脑上鼠标移入查看消息开头、点击跳转;手机上滚动时显示,停下约 1.2 秒后隐藏,点刻度跳转。
61
+ - 太长的消息先收起,点「展开显示」看全文;对话里有至少 3 条用户消息时,右侧显示快速定位尺,电脑上鼠标移入查看消息开头、点击跳转;手机上手动滚动时显示短轨道,按住拖动可预览问题和位置,松手跳转,停止操作约 1.6 秒后隐藏。
61
62
  - 回复底部的 token 数自动按大小显示为 K、M 等单位。
62
63
  - 侧栏按页加载:每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
63
64
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
@@ -71,7 +72,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
71
72
  - **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
72
73
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
73
74
  - **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex` 换专家会开新会话)。**内置专家**:Claude Code、Codex,就是 agent 原装的样子(原装提示词、机器上的技能和 MCP、所有工具)。**自定义专家**每人管自己的,可以配:
74
- - 头像(自己上传,没传就用引擎的图标)、引擎(Claude / Codex,建好后不能换)、默认模型和思考程度(从模型列表里选);
75
+ - 头像(点头像区域的加号上传;未上传时,会话中用引擎的图标)、引擎(Claude / Codex,建好后不能换)、默认模型和思考程度(从模型列表里选);
75
76
  - 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
76
77
  - 权限,勾选:联网搜索、读网页,以及文件权限(一级包含一级):都不勾就是**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
77
78
  - 带不带个人记忆,默认工作目录,新对话页上的欢迎语和快捷提问;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.51",
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
  // ---------- 命令结果 ----------
@@ -950,12 +950,14 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
950
950
  const seq = hub.currentSeq();
951
951
  // 进行中的这一轮,agent 的记录里可能已经写进去了一部分,和 live 重复:
952
952
  // 记录里最后一条用户消息就是这一轮的那条时,从它起砍掉,交给 live 来画
953
- const liveUser = live.find((e) => e.ev.type === "user")?.ev as { text?: string } | undefined;
954
- if (liveUser) {
953
+ const liveUser = live.find((e) => e.ev.type === "user" && !e.ev.queued)?.ev;
954
+ if (liveUser?.type === "user") {
955
+ const anchor = live.findLast((e) => e.ev.type === "user_anchor" && e.ev.id === liveUser.id)?.ev;
955
956
  const lastUser = messages.map((m) => m.role).lastIndexOf("user");
956
957
  const norm = (t: string) => t.replace(/\s+/g, " ").trim();
957
958
  const want = norm(liveUser.text ?? "");
958
- if (lastUser >= 0 && want && norm(messages[lastUser]!.text).startsWith(want.slice(0, 200))) {
959
+ const sameAnchor = anchor?.type === "user_anchor" && messages[lastUser]?.anchor === anchor.anchor;
960
+ if (lastUser >= 0 && (sameAnchor || (want && norm(messages[lastUser]!.text).startsWith(want.slice(0, 200))))) {
959
961
  messages = messages.slice(0, lastUser);
960
962
  }
961
963
  }
@@ -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 照着做 */
package/src/core/hub.ts CHANGED
@@ -500,24 +500,21 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
500
500
  return [...parts, streaming].join("\n");
501
501
  }
502
502
 
503
- /** 正在进行的这一轮(从最后一条用户消息起),给刚打开页面的客户端补画用。 */
503
+ /** 正在进行的这一轮及尚未处理的输入,给刚打开页面的客户端补画用。 */
504
504
  liveTurn(key: string): EventEnvelope[] {
505
505
  if (!this.isBusy(key)) return [];
506
506
  const buf = this.buffers.get(key) ?? [];
507
- let start = buf.length;
508
- for (let i = buf.length - 1; i >= 0; i--) {
509
- const t = buf[i]!.ev.type;
510
- if (t === "user") {
511
- start = i;
512
- break;
513
- }
514
- if (t === "result" || t === "error") {
515
- start = i + 1;
516
- break;
517
- }
518
- if (i === 0) start = 0;
519
- }
520
- return buf.slice(start);
507
+ const start = buf.findLastIndex(({ ev }) => ev.type === "result" || ev.type === "error") + 1;
508
+ const fifo = this.turnFifo.get(key) ?? [];
509
+ const active = fifo[0]?.id;
510
+ const inputs = new Set(fifo.map((entry) => entry.id));
511
+ for (const [id, waiting] of this.pendingInputs.get(key) ?? []) if (!waiting.cancelled) inputs.add(id);
512
+ return buf.filter(({ ev }, i) => i >= start || (
513
+ (ev.type === "user" || ev.type === "queue" || ev.type === "user_anchor") && inputs.has(ev.id!)
514
+ )).map((env) => (
515
+ // 下一轮的输入可能早在上一轮结束之前就收到了,重放时它已经不再排队。
516
+ env.ev.type === "user" && env.ev.id === active ? { ...env, ev: { ...env.ev, queued: false } } : env
517
+ ));
521
518
  }
522
519
 
523
520
  isBusy(key: string): boolean {
@@ -183,6 +183,7 @@
183
183
  .avatar-preview {
184
184
  width: 56px;
185
185
  height: 56px;
186
+ padding: 0;
186
187
  border-radius: 50%;
187
188
  border: 1px dashed var(--border);
188
189
  background: var(--bg-soft);
@@ -198,6 +199,7 @@
198
199
  }
199
200
 
200
201
  .avatar-preview img {
202
+ display: block;
201
203
  width: 100%;
202
204
  height: 100%;
203
205
  object-fit: cover;
@@ -208,17 +210,6 @@
208
210
  height: 28px;
209
211
  }
210
212
 
211
- .avatar-emoji {
212
- font-size: 28px;
213
- line-height: 1;
214
- }
215
-
216
- .avatar-btns {
217
- display: flex;
218
- flex-direction: column;
219
- gap: 6px;
220
- }
221
-
222
- .avatar-btns .btn[hidden] {
213
+ .avatar-field .btn[hidden] {
223
214
  display: none;
224
215
  }