agent-loft 0.2.42 → 0.2.44

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
@@ -43,6 +43,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
43
43
  - 回复逐字显示,markdown 和代码高亮,思考过程和工具调用可以折叠;每条回复下方显示用时、费用和完成时间,可以复制,也可以「从这里分叉」成一条新会话(原会话不动);自己发的消息也能一键复制。
44
44
  - 授权卡、提问卡直接在页面上点。
45
45
  - 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,开新会话或切换目录时清理。
46
+ - 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
46
47
  - 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
47
48
  - 新对话页:点大标题里的目录名,在目录树里逐层选工作目录;输入框上方选 agent,右下角选模型和思考程度。会话进行中用 `/agent` 切换 agent,模型和思考程度随时可换。
48
49
  - 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
@@ -66,7 +67,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
66
67
  - **定时任务**:像 ChatGPT 的 Tasks,侧栏「最近」上面的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选聊天 / 工作模式和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
67
68
  - **技能(skills)**:设置 → 技能。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。每人管自己的,不做分享和技能广场(以前从别人那装过的照常能用,可以卸载)。**使用**:工作模式下 agent 遇到对得上的事自己用;在输入框或定时任务的「要做的事」里打 `@` 选技能,点名这次用哪个(聊天模式下会把技能内容直接附上);飞书里发 `/skills` 看能 @ 哪些。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
68
69
  - **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
69
- - 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,可以缩放到窗口或按原始大小看、全屏(手机上也能,iPhone 上是铺满页面)、「只看不控制」、发送 Ctrl+Alt+Del 之类的组合键。手机上有两种手势(右上角切换,「?」看说明):**触控板模式**(默认)屏幕上有个指针,单指滑动移动、轻点单击、双指轻点右键、长按后拖动是按住左键拖、双指滑动滚动;**触摸模式**点哪就点哪。两种模式都能双指捏合在本地放大画面(放大后小按钮也点得准,右下角「还原」),画面下面一排 Esc / Tab / Ctrl / Alt / Win / 方向键,Ctrl、Alt、Win 点一下会粘住,带给下一个按键或点击;键盘按钮弹出软键盘打字,中文输入法也能用。Linux 上 agent-loft 在有人连时用 x11vnc 共享当前的桌面(Xorg 会话;只听 127.0.0.1、随机端口、每次随机密码,需要 `sudo apt install x11vnc`),没人连着 30 分钟后停掉;macOS 上在 设置 → 远程控制 里改用「已有的 VNC 服务」,接系统自带的屏幕共享:填 VNC 密码,或者屏幕共享没开 VNC 密码时填 Mac 的用户名和登录密码(苹果认证,由服务端登录)。
70
+ - 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,工具栏上选画质:流畅 / 标准(默认)/ 高清由服务端把画面缩小到长边 1280 / 1920 / 2560、只把变了的地方压成 JPEG 发过来(macOS 屏幕共享只给无损的 ZRLE,5K 屏一整屏 30MB,原样转发隔着公网几秒一帧),原画是原样转发、只适合局域网;可以缩放到窗口或按原始大小看、全屏(手机上也能,iPhone 上是铺满页面)、「只看不控制」、发送 Ctrl+Alt+Del 之类的组合键。手机上有两种手势(右上角切换,「?」看说明):**触控板模式**(默认)屏幕上有个指针,单指滑动移动、轻点单击、双指轻点右键、长按后拖动是按住左键拖、双指滑动滚动;**触摸模式**点哪就点哪。两种模式都能双指捏合在本地放大画面(放大后小按钮也点得准,右下角「还原」),画面下面一排 Esc / Tab / Ctrl / Alt / Win / 方向键,Ctrl、Alt、Win 点一下会粘住,带给下一个按键或点击;键盘按钮弹出软键盘打字,中文输入法也能用。Linux 上 agent-loft 在有人连时用 x11vnc 共享当前的桌面(Xorg 会话;只听 127.0.0.1、随机端口、每次随机密码,需要 `sudo apt install x11vnc`),没人连着 30 分钟后停掉;macOS 上在 设置 → 远程控制 里改用「已有的 VNC 服务」,接系统自带的屏幕共享:填 VNC 密码,或者屏幕共享没开 VNC 密码时填 Mac 的用户名和登录密码(苹果认证,由服务端登录)。
70
71
  - 终端:新终端开在当前对话的工作目录里,可以开多个标签;`Ctrl+Shift+C` / `Ctrl+Shift+V` 复制粘贴。`` Ctrl+` `` 在对话下面拉出终端面板(高度可拖动),面板和远程控制里的是同一批终端。关掉页面、手机切到后台、断线都不结束 shell,重新打开时接着用、补上错过的输出,别的设备上也能接上;没有页面连着超过 30 分钟(设置里可改)才结束,点标签上的 × 立即结束。依赖可选的原生模块 `node-pty`:Linux 上安装时要现场编译(需要 `make`、`g++`、`python3`),没装好时终端用不了,其他功能照常。手机上单指上下滑翻看历史(在 less、vim 里是翻页),长按选中文字、接着拖动扩大选区,再点「复制」;终端下面多一排 Esc / Tab / Ctrl / Alt / 方向键 / Home / End / PgUp / PgDn / 粘贴。iOS 上软键盘弹出来时这排键会垫到键盘上面。
71
72
  - 管理员能用;成员要管理员在 设置 → 用户 里单独「开通远程控制」。终端、桌面在 设置 → 远程控制 里各有总开关。
72
73
  - **飞书账号绑定**:设置 → 账号 → 飞书账号 →「生成绑定码」,再在飞书私聊机器人发 `/bind 绑定码`(10 分钟内有效,群里发不算)。绑定后这个私聊就是你的个人会话:用你的记忆,`/sessions` 只列你的会话,`/web` 只能接上你自己的 Web 会话,管理员在 Web 上也看不到它。必须本人在两边各操作一次,管理员不能替人绑定(只能解除),否则就能借飞书读到别人的记忆。
@@ -183,6 +184,8 @@ src/
183
184
  skills-bridge.ts 技能工具在主进程这头:建 / 改技能(弹授权卡)、skill_request 代发带密钥的请求
184
185
  terminals.ts 网页终端:用 node-pty 起 shell、留最近的输出给重连补发、没人连着到点结束、权限收回时结束
185
186
  desktop.ts 远程桌面:找这台机器的 X 桌面、按需起 x11vnc(或用已有的 VNC 服务)、没人连着到点停掉
187
+ vnc-auth.ts 由服务端登录 VNC(苹果认证、VNC 密码、不用认证),对页面装成不用认证的
188
+ vnc-transcode.ts 远程桌面转码:服务端当 VNC 客户端收全分辨率画面,缩小、只把变了的格子压成 JPEG 按 Tight 发给页面
186
189
  pairing.ts uploads.ts commands.ts …
187
190
  mcp/
188
191
  memory-server.ts 记忆工具(remember / forget / search_past_chats)的 stdio MCP 服务,两个 agent 共用
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.42",
3
+ "version": "0.2.44",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -53,6 +53,7 @@
53
53
  "dompurify": "^3.2.0",
54
54
  "marked": "^16.0.0",
55
55
  "qrcode": "^1.5.4",
56
+ "sharp": "^0.35.5",
56
57
  "tsx": "^4.20.6",
57
58
  "ws": "^8.18.0"
58
59
  },
@@ -11,6 +11,8 @@ import { approve, listApproved, listPending, revoke } from "../../core/pairing.j
11
11
  import { getConversation, listConversations, updateConversation } from "../../core/store.js";
12
12
  import { addScheduled, clearScheduled, removeScheduled } from "../../core/scheduled.js";
13
13
  import { resolveUploadFile, saveBuffer, sniff, uploadKeyOf } from "../../core/uploads.js";
14
+ import { mentions, replyFileType, resolveReplyFile } from "../../core/reply-files.js";
15
+ import { HTML_CSP, HTML_MAX, htmlDocument } from "../../core/visualize.js";
14
16
  import {
15
17
  createUser,
16
18
  getUser,
@@ -133,6 +135,82 @@ function serveUpload(res: ServerResponse, user: User, requested: string, downloa
133
135
  fs.createReadStream(file).pipe(res);
134
136
  }
135
137
 
138
+ // ---------- agent 回复里提到的文件 ----------
139
+
140
+ /** 每条会话 agent 回复的全文(从 agent 记录里读,比较慢):缓存一会儿,一屏好几张图不用每张都读一遍 */
141
+ const replyTextCache = new Map<string, { at: number; text: string }>();
142
+
143
+ async function historyReplyText(key: string): Promise<string> {
144
+ const messages = await hub.history(key);
145
+ const text = messages.filter((m) => m.role === "assistant").map((m) => m.text).join("\n");
146
+ replyTextCache.delete(key);
147
+ replyTextCache.set(key, { at: Date.now(), text });
148
+ // 只留最近的几十条会话
149
+ for (const k of replyTextCache.keys()) {
150
+ if (replyTextCache.size <= 50) break;
151
+ replyTextCache.delete(k);
152
+ }
153
+ return text;
154
+ }
155
+
156
+ /** 这条会话的 agent 回复里写没写过这个路径。缓存里没有、缓存又不是刚读的,就重读一次再说 */
157
+ async function replyMentions(key: string, requested: string): Promise<boolean> {
158
+ if (mentions(hub.recentReplyText(key), requested)) return true;
159
+ const cached = replyTextCache.get(key);
160
+ if (cached && mentions(cached.text, requested)) return true;
161
+ if (cached && Date.now() - cached.at < 3000) return false;
162
+ return mentions(await historyReplyText(key), requested);
163
+ }
164
+
165
+ /**
166
+ * 回复里的文件:stat=1 只回名字和大小;其余返回内容,支持 Range(视频拖进度、iOS 放视频都要它)。
167
+ * 图片、PDF、音视频按类型 inline,别的一律当下载 —— HTML 之类不能在本站域名下被当网页打开
168
+ */
169
+ function serveReplyFile(req: IncomingMessage, res: ServerResponse, file: string, opts: { stat: boolean; download: boolean }): void {
170
+ const st = fs.statSync(file);
171
+ const name = path.basename(file);
172
+ if (opts.stat) {
173
+ sendJson(res, 200, { name, path: file, size: st.size, mtime: st.mtimeMs });
174
+ return;
175
+ }
176
+ const type = replyFileType(file);
177
+ const inline = !opts.download && !!type;
178
+ const headers: Record<string, string | number> = {
179
+ ...SECURITY_HEADERS,
180
+ "Content-Type": inline ? type! : "application/octet-stream",
181
+ "Content-Disposition": `${inline ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(name)}`,
182
+ "Accept-Ranges": "bytes",
183
+ "Cache-Control": "private, no-cache",
184
+ "Last-Modified": new Date(st.mtimeMs).toUTCString(),
185
+ };
186
+ if (type === "application/pdf") {
187
+ // 预览窗里用 iframe 嵌 PDF:要允许本站嵌入。Chrome 带 sandbox 的文档不显示 PDF,这里不加
188
+ // (所有接口的响应事先都带上了 SECURITY_HEADERS,见 server.ts,这里得把那个也去掉)
189
+ delete headers["X-Frame-Options"];
190
+ res.removeHeader("X-Frame-Options");
191
+ headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'self'";
192
+ } else {
193
+ headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox";
194
+ }
195
+ const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range ?? ""));
196
+ if (range && (range[1] || range[2])) {
197
+ let start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2]));
198
+ let end = range[1] && range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
199
+ if (start >= st.size || start > end) {
200
+ res.writeHead(416, { ...headers, "Content-Range": `bytes */${st.size}` });
201
+ res.end();
202
+ return;
203
+ }
204
+ start = Math.max(0, start);
205
+ end = Math.max(start, end);
206
+ res.writeHead(206, { ...headers, "Content-Range": `bytes ${start}-${end}/${st.size}`, "Content-Length": end - start + 1 });
207
+ fs.createReadStream(file, { start, end }).pipe(res);
208
+ return;
209
+ }
210
+ res.writeHead(200, { ...headers, "Content-Length": st.size });
211
+ fs.createReadStream(file).pipe(res);
212
+ }
213
+
136
214
  // ---------- 飞书扫码创建应用 ----------
137
215
 
138
216
  type Registration = {
@@ -761,6 +839,34 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
761
839
  });
762
840
  return;
763
841
  }
842
+ // agent 回复里提到的文件:只认回复里写过的路径,敏感文件(私钥、凭据…)不给
843
+ if (sub === "file" && method === "GET") {
844
+ const requested = url.searchParams.get("path") ?? "";
845
+ const file = resolveReplyFile(requested, conv.cwd);
846
+ if (!file || !(await replyMentions(key, requested))) throw new HttpError(404, "文件不存在,或者不能查看");
847
+ serveReplyFile(req, res, file, { stat: url.searchParams.get("stat") === "1", download: url.searchParams.get("download") === "1" });
848
+ return;
849
+ }
850
+ // 回复里的 HTML(Codex visualize 画的图表、agent 写的网页):套好外壳放进沙箱显示,规矩和上面一样
851
+ if (sub === "html" && method === "GET") {
852
+ const requested = url.searchParams.get("path") ?? "";
853
+ const file = resolveReplyFile(requested, conv.cwd);
854
+ if (!file || !/\.html?$/i.test(file) || !(await replyMentions(key, requested))) throw new HttpError(404, "文件不存在,或者不能查看");
855
+ if (fs.statSync(file).size > HTML_MAX) throw new HttpError(413, "文件太大,下载下来看吧");
856
+ const doc = Buffer.from(htmlDocument(fs.readFileSync(file, "utf8"), path.basename(file)));
857
+ // 要能嵌进对话里:去掉所有响应默认带的 X-Frame-Options(见 server.ts)
858
+ res.removeHeader("X-Frame-Options");
859
+ res.writeHead(200, {
860
+ "X-Content-Type-Options": "nosniff",
861
+ "Referrer-Policy": "no-referrer",
862
+ "Content-Security-Policy": HTML_CSP,
863
+ "Content-Type": "text/html; charset=utf-8",
864
+ "Content-Length": doc.length,
865
+ "Cache-Control": "private, no-cache",
866
+ });
867
+ res.end(doc);
868
+ return;
869
+ }
764
870
  if (sub === "upload" && method === "POST") {
765
871
  const data = await readBody(req, 50 * 1024 * 1024);
766
872
  const name = url.searchParams.get("name") ?? undefined;
@@ -5,10 +5,11 @@ import net from "node:net";
5
5
  import type { IncomingMessage, ServerResponse } from "node:http";
6
6
  import type { Duplex } from "node:stream";
7
7
  import type { WebSocket, WebSocketServer } from "ws";
8
- import { canUseDesktop, desktopAvailability, desktopTarget, desktopViewer } from "../../core/desktop.js";
8
+ import { canUseDesktop, desktopAvailability, desktopTarget, desktopViewer, type DesktopTarget } from "../../core/desktop.js";
9
9
  import { canUseRemote, isAdmin, type User } from "../../core/users.js";
10
10
  import { config } from "../../core/config.js";
11
- import { ardLogin, ByteReader, serveNoAuth } from "../../core/vnc-ard.js";
11
+ import { ByteReader, serveNoAuth, vncLogin } from "../../core/vnc-auth.js";
12
+ import { isDesktopQuality, loadSharp, transcode, type DesktopQuality } from "../../core/vnc-transcode.js";
12
13
  import { sessionUser } from "./auth.js";
13
14
  import { HttpError, sendJson } from "./http.js";
14
15
  import { terminalStatus } from "./terminal.js";
@@ -97,8 +98,11 @@ function reject(socket: Duplex, status: string): void {
97
98
  socket.destroy();
98
99
  }
99
100
 
100
- /** /ws/desktop 的握手:user 已经由调用方核对过登录和 Origin */
101
- export function upgradeDesktop(wss: WebSocketServer, req: IncomingMessage, socket: Duplex, head: Buffer, user: User, token: string): void {
101
+ /**
102
+ * /ws/desktop 的握手:user 已经由调用方核对过登录和 Origin。
103
+ * ?q= 是画质:smooth / standard / high 由服务端缩小、压成 JPEG 再发(vnc-transcode.ts);original 或不带是原样转发
104
+ */
105
+ export function upgradeDesktop(wss: WebSocketServer, req: IncomingMessage, socket: Duplex, head: Buffer, user: User, token: string, url: URL): void {
102
106
  if (!canUseDesktop(user)) return reject(socket, "403 Forbidden");
103
107
  if (clients.size >= MAX_CLIENTS) return reject(socket, "429 Too Many Requests");
104
108
  // 下面要等 x11vnc 起来(最多 10 秒):这期间浏览器断开的话,socket 上没人接 error 会把进程带崩
@@ -114,7 +118,9 @@ export function upgradeDesktop(wss: WebSocketServer, req: IncomingMessage, socke
114
118
  tcp.once("connect", () => {
115
119
  if (socket.destroyed) return void tcp.destroy();
116
120
  socket.off("error", onError);
121
+ const q = url.searchParams.get("q");
117
122
  wss.handleUpgrade(req, socket, head, (ws) => {
123
+ if (isDesktopQuality(q)) return void transcodeSession(ws, tcp, token, target, q);
118
124
  if (!target.username) return bridge(ws, tcp, token);
119
125
  void loginThenBridge(ws, tcp, token, target.username, target.password);
120
126
  });
@@ -148,7 +154,7 @@ async function loginThenBridge(ws: WebSocket, tcp: net.Socket, token: string, us
148
154
  fromPage.fail(err);
149
155
  }, LOGIN_TIMEOUT);
150
156
  try {
151
- const login = ardLogin(fromVnc, (b) => tcp.write(b), username, password);
157
+ const login = vncLogin(fromVnc, (b) => tcp.write(b), { username, password });
152
158
  await serveNoAuth(fromPage, (b) => ws.readyState === ws.OPEN && ws.send(b, { binary: true }), login);
153
159
  } catch (err) {
154
160
  console.error("[桌面] 苹果认证失败:", err instanceof Error ? err.message : err);
@@ -165,6 +171,63 @@ async function loginThenBridge(ws: WebSocket, tcp: net.Socket, token: string, us
165
171
  bridge(ws, tcp, token, fromVnc.rest(), fromPage.rest());
166
172
  }
167
173
 
174
+ function isLoopback(host: string): boolean {
175
+ const h = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
176
+ return h === "localhost" || h === "::1" || /^127\./.test(h);
177
+ }
178
+
179
+ /** 转码:服务端连 VNC、缩小画面压成 JPEG 发给页面 */
180
+ async function transcodeSession(ws: WebSocket, tcp: net.Socket, token: string, target: DesktopTarget, quality: DesktopQuality): Promise<void> {
181
+ // 握手前那个「回 502」的已经用不上了(socket 交给 WebSocket 了)
182
+ tcp.removeAllListeners("error");
183
+ tcp.on("error", () => tcp.destroy());
184
+ // 压 JPEG 的 sharp 在这台机器上装不上:退回原样转发(原画),别让页面一直重连
185
+ try {
186
+ await loadSharp();
187
+ } catch (err) {
188
+ console.error("[桌面] 加载 sharp 失败,画质设置不起作用,按原画转发:", err instanceof Error ? err.message : err);
189
+ if (!target.username) return bridge(ws, tcp, token);
190
+ return loginThenBridge(ws, tcp, token, target.username, target.password);
191
+ }
192
+ tcp.removeAllListeners("error");
193
+ tcp.setNoDelay(true);
194
+ const client: DesktopClient = { ws, tcp, token, alive: true };
195
+ clients.add(client);
196
+ desktopViewer(1);
197
+ const fromVnc = new ByteReader();
198
+ const fromPage = new ByteReader();
199
+ tcp.on("data", (d: Buffer) => fromVnc.push(d));
200
+ tcp.on("close", () => fromVnc.fail(new Error("VNC 服务断开了连接")));
201
+ tcp.on("error", () => fromVnc.fail(new Error("VNC 服务断开了连接")));
202
+ ws.on("message", (d: Buffer) => fromPage.push(d));
203
+ ws.on("close", () => fromPage.fail(new Error("页面断开了")));
204
+ ws.on("error", () => fromPage.fail(new Error("页面断开了")));
205
+ ws.on("pong", () => (client.alive = true));
206
+ const timer = setTimeout(() => {
207
+ const err = new Error("VNC 服务没有回应");
208
+ fromVnc.fail(err);
209
+ fromPage.fail(err);
210
+ }, LOGIN_TIMEOUT);
211
+ try {
212
+ await transcode({
213
+ vnc: { reader: fromVnc, write: (b) => void (tcp.destroyed || tcp.write(b)) },
214
+ page: { reader: fromPage, write: (b) => void (ws.readyState === ws.OPEN && ws.send(b, { binary: true })), backlog: () => ws.bufferedAmount },
215
+ creds: { username: target.username, password: target.password },
216
+ quality,
217
+ local: isLoopback(target.host),
218
+ onReady: () => clearTimeout(timer),
219
+ });
220
+ } catch (err) {
221
+ const msg = err instanceof Error ? err.message : String(err);
222
+ if (!/页面断开了/.test(msg)) console.error("[桌面] 转码会话结束:", msg);
223
+ // 认证失败的原因已经告诉页面了:等它收到再关
224
+ if (ws.readyState === ws.OPEN) setTimeout(() => ws.close(4000, "桌面连接已断开"), 200);
225
+ } finally {
226
+ clearTimeout(timer);
227
+ drop(client);
228
+ }
229
+ }
230
+
168
231
  /** pending:握手时多读进来、还没转发的字节 */
169
232
  function bridge(ws: WebSocket, tcp: net.Socket, token: string, pendingVnc?: Buffer, pendingPage?: Buffer): void {
170
233
  const client: DesktopClient = { ws, tcp, token, alive: true };
@@ -489,7 +489,7 @@ export async function startWeb(): Promise<void> {
489
489
  }
490
490
  const token = cookies(req)[COOKIE] ?? "";
491
491
  if (url.pathname === "/ws/term") return upgradeTerminal(wss!, req, socket, head, user, token, url);
492
- if (url.pathname === "/ws/desktop") return upgradeDesktop(wss!, req, socket, head, user, token);
492
+ if (url.pathname === "/ws/desktop") return upgradeDesktop(wss!, req, socket, head, user, token, url);
493
493
  wss!.handleUpgrade(req, socket, head, (ws) => {
494
494
  const client: Client = { ws, subs: new Set(), alive: true, token, user, visible: false, viewing: null, seen: Date.now() };
495
495
  clients.add(client);
@@ -214,7 +214,7 @@ async function startX11vnc(display: string): Promise<Vnc> {
214
214
  return v;
215
215
  }
216
216
 
217
- /** username:有就是苹果认证,由服务端登录(见 vnc-ard.ts),页面不用密码 */
217
+ /** username:有就是苹果认证,由服务端登录(见 vnc-auth.ts),页面不用密码 */
218
218
  export type DesktopTarget = { host: string; port: number; password: string; username?: string };
219
219
 
220
220
  /** 要连桌面了:拿到 VNC 服务的地址和密码,必要时先把 x11vnc 起来 */
package/src/core/hub.ts CHANGED
@@ -403,6 +403,20 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
403
403
  return buf.filter((e) => e.seq > since);
404
404
  }
405
405
 
406
+ /**
407
+ * 缓冲区里 agent 回复的文字(含进行中这一轮已经流出来的)。刚出的回复 agent 的记录里可能还没写进去,
408
+ * 查回复里提到过哪些文件时和历史一起看
409
+ */
410
+ recentReplyText(key: string): string {
411
+ const parts: string[] = [];
412
+ let streaming = "";
413
+ for (const { ev } of this.buffers.get(key) ?? []) {
414
+ if (ev.type === "delta") streaming += ev.text;
415
+ else if (ev.type === "text" || ev.type === "result") parts.push(ev.text);
416
+ }
417
+ return [...parts, streaming].join("\n");
418
+ }
419
+
406
420
  /** 正在进行的这一轮(从最后一条用户消息起),给刚打开页面的客户端补画用。 */
407
421
  liveTurn(key: string): EventEnvelope[] {
408
422
  if (!this.isBusy(key)) return [];
@@ -0,0 +1,142 @@
1
+ // agent 回复里提到的文件:网页上点开预览 / 下载。
2
+ //
3
+ // 只放行这条会话的 agent 回复里真的写过的路径(防止拼个地址就读服务器上任意文件),
4
+ // 再挡掉密钥、凭据一类的敏感文件 —— agent 写过也不给看。
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { home } from "../home.js";
9
+ import { uploadsRoot } from "./uploads.js";
10
+
11
+ /** 路径里出现这些目录名就不给看(私钥、云凭据、密码库…) */
12
+ const SENSITIVE_DIRS = new Set([".ssh", ".gnupg", ".aws", ".azure", ".kube", ".docker", ".password-store", ".gcloud"]);
13
+
14
+ /** 家目录下这些位置不给看(相对家目录) */
15
+ const SENSITIVE_HOME = [
16
+ ".config/gcloud",
17
+ ".config/gh",
18
+ ".claude/.credentials.json",
19
+ ".codex/auth.json",
20
+ ".netrc",
21
+ ".git-credentials",
22
+ ".npmrc",
23
+ ".pypirc",
24
+ ];
25
+
26
+ /** 系统里不给看的 */
27
+ const SENSITIVE_SYSTEM = ["/proc", "/sys", "/dev", "/etc/shadow", "/etc/gshadow", "/etc/sudoers", "/etc/sudoers.d"];
28
+
29
+ /** 文件名:.env(示例文件除外)、私钥、证书私钥、密钥库 */
30
+ function sensitiveName(name: string): boolean {
31
+ const n = name.toLowerCase();
32
+ if (/^\.env(\.|$)/.test(n) && !/\.(example|sample|template)$/.test(n)) return true;
33
+ if (/^id_(rsa|dsa|ecdsa|ed25519)/.test(n)) return true;
34
+ return /\.(pem|key|p12|pfx|jks|keystore|kdbx)$/.test(n);
35
+ }
36
+
37
+ function within(file: string, dir: string): boolean {
38
+ return file === dir || file.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
39
+ }
40
+
41
+ export function isSensitivePath(file: string): boolean {
42
+ const parts = file.split(path.sep);
43
+ if (parts.some((p) => SENSITIVE_DIRS.has(p))) return true;
44
+ if (sensitiveName(path.basename(file))) return true;
45
+ const userHome = os.homedir();
46
+ if (SENSITIVE_HOME.some((p) => within(file, path.join(userHome, p)))) return true;
47
+ if (SENSITIVE_SYSTEM.some((p) => within(file, p))) return true;
48
+ // agent-loft 自己的配置和数据(飞书密钥、账号、登录态…);上传的附件除外,那些本来就能看
49
+ return within(file, home) && !within(file, uploadsRoot);
50
+ }
51
+
52
+ /** 「file:///a/b」「~/a」「相对路径」→ 绝对路径(相对路径按会话的工作目录算) */
53
+ export function expandPath(p: string, cwd: string): string {
54
+ let s = p.trim();
55
+ if (s.startsWith("file://")) {
56
+ s = s.slice("file://".length);
57
+ try {
58
+ s = decodeURIComponent(s);
59
+ } catch {
60
+ // 编码坏了就按原样
61
+ }
62
+ }
63
+ if (s === "~" || s.startsWith("~/")) s = path.join(os.homedir(), s.slice(1));
64
+ return path.resolve(cwd, s);
65
+ }
66
+
67
+ /**
68
+ * 解析成可以给前端看的真实文件路径:存在、是普通文件、解析符号链接前后都不敏感。不行返回 undefined
69
+ */
70
+ export function resolveReplyFile(p: string, cwd: string): string | undefined {
71
+ if (!p.trim() || p.includes("\0")) return undefined;
72
+ try {
73
+ const abs = expandPath(p, cwd);
74
+ if (isSensitivePath(abs)) return undefined;
75
+ const real = fs.realpathSync(abs);
76
+ if (isSensitivePath(real)) return undefined;
77
+ return fs.statSync(real).isFile() ? real : undefined;
78
+ } catch {
79
+ return undefined;
80
+ }
81
+ }
82
+
83
+ /** 回复里百分号编码的路径(链接地址常见)也解开一份,两种写法都能对上 */
84
+ function withDecoded(text: string): string {
85
+ if (!text.includes("%")) return text;
86
+ const decoded = text.replace(/(?:%[0-9a-f]{2})+/gi, (m) => {
87
+ try {
88
+ return decodeURIComponent(m);
89
+ } catch {
90
+ return m;
91
+ }
92
+ });
93
+ return decoded === text ? text : `${text}\n${decoded}`;
94
+ }
95
+
96
+ /** 路径里能出现的字符:前后挨着这些就说明只对上了别的路径的一截(比如 a.ts 对上 src/a.ts) */
97
+ const PATH_CHAR = /[\p{L}\p{N}_\-./~@+]/u;
98
+
99
+ /** text 里有没有完整地写着 p(不是别的路径的一部分) */
100
+ export function mentions(text: string, p: string): boolean {
101
+ const needle = p.trim();
102
+ if (!needle) return false;
103
+ const hay = withDecoded(text);
104
+ for (let i = hay.indexOf(needle); i >= 0; i = hay.indexOf(needle, i + 1)) {
105
+ const before = hay[i - 1];
106
+ const after = hay[i + needle.length];
107
+ // 末尾的「.」是句号,不算路径的一部分
108
+ const afterOk = !after || !PATH_CHAR.test(after) || (after === "." && !PATH_CHAR.test(hay[i + needle.length + 1] ?? " "));
109
+ if ((!before || !PATH_CHAR.test(before)) && afterOk) return true;
110
+ }
111
+ return false;
112
+ }
113
+
114
+ const TYPES: Record<string, string> = {
115
+ png: "image/png",
116
+ jpg: "image/jpeg",
117
+ jpeg: "image/jpeg",
118
+ gif: "image/gif",
119
+ webp: "image/webp",
120
+ avif: "image/avif",
121
+ bmp: "image/bmp",
122
+ ico: "image/x-icon",
123
+ svg: "image/svg+xml",
124
+ pdf: "application/pdf",
125
+ mp4: "video/mp4",
126
+ m4v: "video/mp4",
127
+ webm: "video/webm",
128
+ mov: "video/quicktime",
129
+ mp3: "audio/mpeg",
130
+ m4a: "audio/mp4",
131
+ aac: "audio/aac",
132
+ wav: "audio/wav",
133
+ ogg: "audio/ogg",
134
+ oga: "audio/ogg",
135
+ opus: "audio/ogg",
136
+ flac: "audio/flac",
137
+ };
138
+
139
+ /** 浏览器里直接打开的类型;其余(包括 HTML)一律当下载 / 纯文本,不在本站域名下当网页执行 */
140
+ export function replyFileType(file: string): string | undefined {
141
+ return TYPES[path.extname(file).slice(1).toLowerCase()];
142
+ }
@@ -7,7 +7,7 @@ import path from "node:path";
7
7
  import { dataDir } from "../home.js";
8
8
  import type { AttachmentInfo, AttachmentKind, SavedAttachment } from "./types.js";
9
9
 
10
- const uploadsRoot = path.join(dataDir, "uploads");
10
+ export const uploadsRoot = path.join(dataDir, "uploads");
11
11
 
12
12
  export function uploadsDirFor(key: string): string {
13
13
  return path.join(uploadsRoot, encodeURIComponent(key));
@@ -0,0 +1,123 @@
1
+ // 回复里的 HTML:Codex 的 visualize 插件画的图表(回复里单独一行 visualize{"path":"…"}),
2
+ // 以及 agent 写出来的普通 HTML 文件。网页上放进沙箱 iframe 里显示。
3
+ //
4
+ // visualize 写的是 HTML 片段,要套上插件自带的样式和脚本(和插件的 scripts/render.py 一样)才是完整的页面。
5
+ // 插件装在本机 Codex 的目录里,找不到就用一份最小的样式兜底。
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+
10
+ /** 和 visualize 插件约定的一样:图表只能从这几个 CDN 加载资源,不能联网请求别的 */
11
+ const RESOURCES = [
12
+ "blob:",
13
+ "data:",
14
+ "https://cdnjs.cloudflare.com",
15
+ "https://cdn.jsdelivr.net",
16
+ "https://esm.sh",
17
+ "https://fonts.bunny.net",
18
+ "https://fonts.googleapis.com",
19
+ "https://fonts.gstatic.com",
20
+ "https://unpkg.com",
21
+ ].join(" ");
22
+
23
+ /**
24
+ * 沙箱(不带 allow-same-origin):页面是个匿名的源,读不到本站的登录态、调不了本站接口;
25
+ * connect-src 只给 blob / data,也就没法把东西发出去
26
+ */
27
+ export const HTML_CSP = [
28
+ "sandbox allow-scripts",
29
+ "default-src 'none'",
30
+ `script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${RESOURCES}`,
31
+ `style-src 'unsafe-inline' ${RESOURCES}`,
32
+ `img-src ${RESOURCES}`,
33
+ `font-src ${RESOURCES}`,
34
+ `media-src ${RESOURCES}`,
35
+ "worker-src blob:",
36
+ "connect-src blob: data:",
37
+ "frame-src 'none'",
38
+ "object-src 'none'",
39
+ "base-uri 'none'",
40
+ "form-action 'none'",
41
+ "frame-ancestors 'self'",
42
+ ].join("; ");
43
+
44
+ /** 太大的不显示(插件自己限制片段 1 MB) */
45
+ export const HTML_MAX = 2 * 1024 * 1024;
46
+
47
+ const FRAGMENT_PLACEHOLDER = "<!--__INLINE_VISUALIZATION_FRAGMENT__-->";
48
+ const DOCUMENT_MARKUP = /<!doctype\s|<\s*(?:html|head|body)(?:\s|>)/i;
49
+
50
+ /** 插件目录:$CODEX_HOME/plugins/cache/<来源>/visualize/<版本>/skills/visualize/assets,有多个版本取最新的 */
51
+ function findAssets(): string | undefined {
52
+ const cache = path.join(process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex"), "plugins", "cache");
53
+ const found: { dir: string; version: string }[] = [];
54
+ try {
55
+ for (const source of fs.readdirSync(cache)) {
56
+ const base = path.join(cache, source, "visualize");
57
+ let versions: string[] = [];
58
+ try {
59
+ versions = fs.readdirSync(base);
60
+ } catch {
61
+ continue;
62
+ }
63
+ for (const version of versions) {
64
+ const dir = path.join(base, version, "skills", "visualize", "assets");
65
+ if (fs.existsSync(path.join(dir, "visualize.css"))) found.push({ dir, version });
66
+ }
67
+ }
68
+ } catch {
69
+ return undefined;
70
+ }
71
+ found.sort((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }));
72
+ return found.at(-1)?.dir;
73
+ }
74
+
75
+ /** 没装插件时的兜底:插件约定的几个常用变量 */
76
+ const FALLBACK_CSS = `:root{color-scheme:light dark;--background:transparent;--foreground:light-dark(rgb(26 28 31),rgb(255 255 255));--muted-foreground:light-dark(rgb(26 28 31/50%),rgb(255 255 255/50%));--border:light-dark(rgb(0 0 0/10%),rgb(255 255 255/12%));--card:color-mix(in oklab,var(--foreground) 5%,transparent);--primary:light-dark(rgb(51 156 255),rgb(131 195 255));--viz-series-1:#339cff;--viz-series-2:#f59e0b;--viz-series-3:#10b981;--viz-series-4:#ef4444;--viz-series-5:#8b5cf6}
77
+ body{margin:0;font:14px/1.5 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;color:var(--foreground)}
78
+ .text-small{font-size:12px}.text-muted{color:var(--muted-foreground)}.tabular-nums{font-variant-numeric:tabular-nums}
79
+ .viz-row{display:flex;justify-content:space-between;gap:8px;align-items:baseline}`;
80
+
81
+ /** 把高度告诉外面的页面(iframe 跟着内容变高),见 web/views/file-preview.js */
82
+ const SIZE_REPORTER = `<script>(()=>{const post=()=>parent!==window&&parent.postMessage({type:"aloft-html-size",height:Math.ceil(document.documentElement.scrollHeight)},"*");new ResizeObserver(post).observe(document.documentElement);addEventListener("load",post);post()})()</script>`;
83
+
84
+ /**
85
+ * 给网页显示用的完整 HTML。片段套上插件的外壳;本来就是完整页面的原样,只在末尾加上报高度的脚本。
86
+ * 背景透明,和对话的底色融在一起
87
+ */
88
+ export function htmlDocument(source: string, title: string): string {
89
+ if (DOCUMENT_MARKUP.test(source)) {
90
+ const at = source.search(/<\/body\s*>/i);
91
+ return at >= 0 ? source.slice(0, at) + SIZE_REPORTER + source.slice(at) : source + SIZE_REPORTER;
92
+ }
93
+ const assets = findAssets();
94
+ let css = FALLBACK_CSS;
95
+ let body = source;
96
+ if (assets) {
97
+ try {
98
+ css = fs.readFileSync(path.join(assets, "visualize.css"), "utf8");
99
+ const kit = fs.readFileSync(path.join(assets, "visualize.html"), "utf8");
100
+ body = kit.includes(FRAGMENT_PLACEHOLDER) ? kit.replace(FRAGMENT_PLACEHOLDER, () => source) : source + kit;
101
+ } catch {
102
+ css = FALLBACK_CSS;
103
+ body = source;
104
+ }
105
+ }
106
+ const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!);
107
+ return `<!doctype html>
108
+ <html lang="zh-CN">
109
+ <head>
110
+ <meta charset="utf-8">
111
+ <meta name="viewport" content="width=device-width, initial-scale=1">
112
+ <meta name="referrer" content="no-referrer">
113
+ <title>${esc(title)}</title>
114
+ <style>${css}
115
+ :root{--color-background-primary:transparent;background:transparent!important}html>body{padding:0;margin:0}</style>
116
+ </head>
117
+ <body>
118
+ ${body}
119
+ ${SIZE_REPORTER}
120
+ </body>
121
+ </html>
122
+ `;
123
+ }