agent-loft 0.2.43 → 0.2.45

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」)。
@@ -56,10 +57,11 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
56
57
  - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
57
58
  - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
58
59
  - 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
60
+ - **网页多服务器切换**:在 设置 → 服务器 添加其他 agent-loft,再点「授权」到对方页面确认,侧栏左上角就能切换;各台分别登录,切走后保持连接,列表显示待处理数和运行状态,刷新后保留选择。几台需使用同一主域名下的 HTTPS 地址(例如 `mac.example.com`、`nas.example.com`)。在外层页面开启系统通知后,各台的提醒都能推到同一个主屏幕 App,点通知自动切到对应服务器和对话。见[使用指南](docs/产品介绍.md#在网页和手机上切换多台服务器)。
59
61
  - **系统通知**:Web 会话回复完成、出错、需要授权或提问时推送到手机 / 电脑(设置 → 通知 → 「在此设备开启通知」,可以发测试通知)。飞书会话由飞书提醒,正在前台看着的会话不推。需要 HTTPS 访问,iPhone 需 iOS 16.4+ 且从主屏幕图标打开。
60
62
  - **跨渠道同步**:飞书里的会话在 Web 上也能打开接着聊。同一个授权请求同时出现在飞书卡片和网页上,哪边先点算哪边,另一边自动变成「已处理」。
61
63
  - **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
62
- - **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
64
+ - **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
63
65
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
64
66
  - **聊天模式 / 工作模式**:右上角「更多」里的「聊天模式」,或者发 `/chat`、`/work`,同一条对话随时切换、上下文接着。聊天模式换成精简的系统提示,只留联网搜索,不加载技能、MCP、插件,不执行命令、不读写本机文件(文本附件的内容直接放进消息),每轮的固定开销小得多:实测一句话 Claude 约 1.6 万 → 2 千 token,Codex 约 2 万 → 1.2 万(Codex 的基础指令改不了)。适合日常聊天、查资料;要动手干活时切回工作模式。切换后第一轮要重建提示缓存,会贵一些;在工作模式里读过的大段内容还留在历史里。
65
67
  - **记忆**:像 ChatGPT 的记忆,设置 → 记忆。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 4 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理聊天模式的/只整理工作模式的;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话;第一次用时会把已有对话收录进来)。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.43",
3
+ "version": "0.2.45",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -11,6 +11,9 @@ 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";
16
+ import { cleanServers, ownFrameAncestors, shellInfo } from "../../core/servers.js";
14
17
  import {
15
18
  createUser,
16
19
  getUser,
@@ -70,7 +73,16 @@ import { handleTasksApi } from "./tasks-api.js";
70
73
  import { handleSkillsApi } from "./skills-api.js";
71
74
  import { handleTerminalApi } from "./terminal.js";
72
75
  import { handleDesktopApi, remoteStatus } from "./desktop.js";
73
- import { addSubscription, listSubscriptions, pushToAll, removeSubscription, removeSubscriptionsOf, vapidPublicKey } from "./push.js";
76
+ import {
77
+ addRelaySubscription,
78
+ addSubscription,
79
+ listSubscriptions,
80
+ pushToAll,
81
+ removeSubscription,
82
+ removeSubscriptionsOf,
83
+ vapidKeyPair,
84
+ vapidPublicKey,
85
+ } from "./push.js";
74
86
 
75
87
  export const COOKIE = "aim_session";
76
88
  const startedAt = Date.now();
@@ -133,6 +145,82 @@ function serveUpload(res: ServerResponse, user: User, requested: string, downloa
133
145
  fs.createReadStream(file).pipe(res);
134
146
  }
135
147
 
148
+ // ---------- agent 回复里提到的文件 ----------
149
+
150
+ /** 每条会话 agent 回复的全文(从 agent 记录里读,比较慢):缓存一会儿,一屏好几张图不用每张都读一遍 */
151
+ const replyTextCache = new Map<string, { at: number; text: string }>();
152
+
153
+ async function historyReplyText(key: string): Promise<string> {
154
+ const messages = await hub.history(key);
155
+ const text = messages.filter((m) => m.role === "assistant").map((m) => m.text).join("\n");
156
+ replyTextCache.delete(key);
157
+ replyTextCache.set(key, { at: Date.now(), text });
158
+ // 只留最近的几十条会话
159
+ for (const k of replyTextCache.keys()) {
160
+ if (replyTextCache.size <= 50) break;
161
+ replyTextCache.delete(k);
162
+ }
163
+ return text;
164
+ }
165
+
166
+ /** 这条会话的 agent 回复里写没写过这个路径。缓存里没有、缓存又不是刚读的,就重读一次再说 */
167
+ async function replyMentions(key: string, requested: string): Promise<boolean> {
168
+ if (mentions(hub.recentReplyText(key), requested)) return true;
169
+ const cached = replyTextCache.get(key);
170
+ if (cached && mentions(cached.text, requested)) return true;
171
+ if (cached && Date.now() - cached.at < 3000) return false;
172
+ return mentions(await historyReplyText(key), requested);
173
+ }
174
+
175
+ /**
176
+ * 回复里的文件:stat=1 只回名字和大小;其余返回内容,支持 Range(视频拖进度、iOS 放视频都要它)。
177
+ * 图片、PDF、音视频按类型 inline,别的一律当下载 —— HTML 之类不能在本站域名下被当网页打开
178
+ */
179
+ function serveReplyFile(req: IncomingMessage, res: ServerResponse, file: string, opts: { stat: boolean; download: boolean }): void {
180
+ const st = fs.statSync(file);
181
+ const name = path.basename(file);
182
+ if (opts.stat) {
183
+ sendJson(res, 200, { name, path: file, size: st.size, mtime: st.mtimeMs });
184
+ return;
185
+ }
186
+ const type = replyFileType(file);
187
+ const inline = !opts.download && !!type;
188
+ const headers: Record<string, string | number> = {
189
+ ...SECURITY_HEADERS,
190
+ "Content-Type": inline ? type! : "application/octet-stream",
191
+ "Content-Disposition": `${inline ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(name)}`,
192
+ "Accept-Ranges": "bytes",
193
+ "Cache-Control": "private, no-cache",
194
+ "Last-Modified": new Date(st.mtimeMs).toUTCString(),
195
+ };
196
+ if (type === "application/pdf") {
197
+ // 预览窗里用 iframe 嵌 PDF:要允许本站嵌入。Chrome 带 sandbox 的文档不显示 PDF,这里不加
198
+ // (所有接口的响应事先都带上了 SECURITY_HEADERS,见 server.ts,这里得把那个也去掉)
199
+ delete headers["X-Frame-Options"];
200
+ res.removeHeader("X-Frame-Options");
201
+ headers["Content-Security-Policy"] = `default-src 'none'; frame-ancestors ${ownFrameAncestors(config().servers)}`;
202
+ } else {
203
+ headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox";
204
+ }
205
+ const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range ?? ""));
206
+ if (range && (range[1] || range[2])) {
207
+ let start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2]));
208
+ let end = range[1] && range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
209
+ if (start >= st.size || start > end) {
210
+ res.writeHead(416, { ...headers, "Content-Range": `bytes */${st.size}` });
211
+ res.end();
212
+ return;
213
+ }
214
+ start = Math.max(0, start);
215
+ end = Math.max(start, end);
216
+ res.writeHead(206, { ...headers, "Content-Range": `bytes ${start}-${end}/${st.size}`, "Content-Length": end - start + 1 });
217
+ fs.createReadStream(file, { start, end }).pipe(res);
218
+ return;
219
+ }
220
+ res.writeHead(200, { ...headers, "Content-Length": st.size });
221
+ fs.createReadStream(file).pipe(res);
222
+ }
223
+
136
224
  // ---------- 飞书扫码创建应用 ----------
137
225
 
138
226
  type Registration = {
@@ -202,9 +290,17 @@ function publicConfig(): unknown {
202
290
  };
203
291
  }
204
292
 
205
- function applyConfig(input: Partial<AppConfig>): void {
293
+ /** selfOrigin:发起保存的页面的地址(多服务器列表里不能加自己) */
294
+ function applyConfig(input: Partial<AppConfig>, selfOrigin?: string): void {
206
295
  const current = config();
207
296
  const next = structuredClone(current);
297
+ if (input.servers !== undefined) {
298
+ try {
299
+ next.servers = cleanServers(input.servers, current.servers, selfOrigin);
300
+ } catch (err) {
301
+ throw new HttpError(400, err instanceof Error ? err.message : String(err));
302
+ }
303
+ }
208
304
  if (typeof input.workspaceRoot === "string" && input.workspaceRoot.trim()) next.workspaceRoot = input.workspaceRoot.trim();
209
305
  if (typeof input.approvalTimeoutMs === "number") next.approvalTimeoutMs = Math.max(60_000, input.approvalTimeoutMs);
210
306
  if (typeof input.sessionTtlMs === "number") next.sessionTtlMs = Math.max(0, input.sessionTtlMs);
@@ -565,6 +661,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
565
661
  pending,
566
662
  user: publicMe(user),
567
663
  remote: remoteStatus(user),
664
+ // 左上角切换服务器:没加别的服务器是 null
665
+ servers: shellInfo(config().servers),
568
666
  serverTime: Date.now(),
569
667
  });
570
668
  return;
@@ -593,6 +691,23 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
593
691
  }
594
692
  return;
595
693
  }
694
+ // 多服务器(core/servers.ts):外壳把这个浏览器的订阅连同签名密钥转给嵌着的各台(web/lib/shell.js),
695
+ // 各台直接推到手机上,不经过外壳。密钥只在加了别的服务器时给
696
+ if (p === "/api/push/relay-key" && method === "GET") {
697
+ if (!config().servers.list.length) throw new HttpError(404, "没有加别的服务器");
698
+ sendJson(res, 200, vapidKeyPair());
699
+ return;
700
+ }
701
+ if (p === "/api/push/relay" && method === "POST") {
702
+ const body = await readJsonBody<{ subscription?: unknown; vapid?: unknown; via?: unknown }>(req);
703
+ try {
704
+ const record = addRelaySubscription(body, String(req.headers["user-agent"] ?? ""), user.id, config().servers.embedders);
705
+ sendJson(res, 200, { ok: true, label: record.label });
706
+ } catch (err) {
707
+ throw new HttpError(400, err instanceof Error ? err.message : String(err));
708
+ }
709
+ return;
710
+ }
596
711
  if (p === "/api/push/unsubscribe" && method === "POST") {
597
712
  const body = await readJsonBody<{ endpoint?: string }>(req);
598
713
  sendJson(res, 200, { ok: removeSubscription(String(body.endpoint ?? ""), pushOwnedBy(user.id)) });
@@ -761,6 +876,34 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
761
876
  });
762
877
  return;
763
878
  }
879
+ // agent 回复里提到的文件:只认回复里写过的路径,敏感文件(私钥、凭据…)不给
880
+ if (sub === "file" && method === "GET") {
881
+ const requested = url.searchParams.get("path") ?? "";
882
+ const file = resolveReplyFile(requested, conv.cwd);
883
+ if (!file || !(await replyMentions(key, requested))) throw new HttpError(404, "文件不存在,或者不能查看");
884
+ serveReplyFile(req, res, file, { stat: url.searchParams.get("stat") === "1", download: url.searchParams.get("download") === "1" });
885
+ return;
886
+ }
887
+ // 回复里的 HTML(Codex visualize 画的图表、agent 写的网页):套好外壳放进沙箱显示,规矩和上面一样
888
+ if (sub === "html" && method === "GET") {
889
+ const requested = url.searchParams.get("path") ?? "";
890
+ const file = resolveReplyFile(requested, conv.cwd);
891
+ if (!file || !/\.html?$/i.test(file) || !(await replyMentions(key, requested))) throw new HttpError(404, "文件不存在,或者不能查看");
892
+ if (fs.statSync(file).size > HTML_MAX) throw new HttpError(413, "文件太大,下载下来看吧");
893
+ const doc = Buffer.from(htmlDocument(fs.readFileSync(file, "utf8"), path.basename(file)));
894
+ // 要能嵌进对话里:去掉所有响应默认带的 X-Frame-Options(见 server.ts)
895
+ res.removeHeader("X-Frame-Options");
896
+ res.writeHead(200, {
897
+ "X-Content-Type-Options": "nosniff",
898
+ "Referrer-Policy": "no-referrer",
899
+ "Content-Security-Policy": HTML_CSP.replace("frame-ancestors 'self'", `frame-ancestors ${ownFrameAncestors(config().servers)}`),
900
+ "Content-Type": "text/html; charset=utf-8",
901
+ "Content-Length": doc.length,
902
+ "Cache-Control": "private, no-cache",
903
+ });
904
+ res.end(doc);
905
+ return;
906
+ }
764
907
  if (sub === "upload" && method === "POST") {
765
908
  const data = await readBody(req, 50 * 1024 * 1024);
766
909
  const name = url.searchParams.get("name") ?? undefined;
@@ -868,7 +1011,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
868
1011
  if (p === "/api/config" && method === "PUT") {
869
1012
  const input = await readJsonBody<Partial<AppConfig>>(req);
870
1013
  await applyListen(req, input.web);
871
- applyConfig(input);
1014
+ applyConfig(input, typeof req.headers.origin === "string" ? req.headers.origin : undefined);
872
1015
  sendJson(res, 200, { ...(publicConfig() as object), network: networkInfo(req) });
873
1016
  return;
874
1017
  }
@@ -1,6 +1,7 @@
1
1
  // HTTP 小工具:不引框架,几十行就够用。
2
2
  import type { IncomingMessage, ServerResponse } from "node:http";
3
3
  import { config } from "../../core/config.js";
4
+ import { pageCsp } from "../../core/servers.js";
4
5
 
5
6
  export class HttpError extends Error {
6
7
  constructor(
@@ -116,3 +117,14 @@ export const SECURITY_HEADERS: Record<string, string> = {
116
117
  "Content-Security-Policy":
117
118
  "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",
118
119
  };
120
+
121
+ /**
122
+ * 页面(静态文件)的安全头:CSP 的 frame-src / frame-ancestors 跟着多服务器的设置走(core/servers.ts)。
123
+ * 允许被别的地址嵌时去掉 X-Frame-Options:它只有 DENY / SAMEORIGIN,说不了「这几个地址可以」
124
+ */
125
+ export function pageHeaders(): Record<string, string> {
126
+ const servers = config().servers;
127
+ const headers: Record<string, string> = { ...SECURITY_HEADERS, "Content-Security-Policy": pageCsp(servers) };
128
+ if (servers.embedders.length) delete headers["X-Frame-Options"];
129
+ return headers;
130
+ }
@@ -9,6 +9,8 @@ import crypto from "node:crypto";
9
9
  import path from "node:path";
10
10
  import { dataDir, readJson, writeJsonAtomic } from "../../home.js";
11
11
  import { legacyOwnerId } from "../../core/users.js";
12
+ import { config, onConfigChange } from "../../core/config.js";
13
+ import { selfName, validServerId } from "../../core/servers.js";
12
14
 
13
15
  export type PushSubscriptionRecord = {
14
16
  endpoint: string;
@@ -19,6 +21,25 @@ export type PushSubscriptionRecord = {
19
21
  lastOkAt?: number;
20
22
  /** 哪个用户开的(core/users.ts)。升级前的没有:第一次读到时认给迁移出来的那个管理员并记下 */
21
23
  userId?: string;
24
+ /** 多服务器的外壳转来的订阅,见下面的 addRelaySubscription */
25
+ relay?: RelayInfo;
26
+ };
27
+
28
+ type VapidKey = { publicKey: string; privateJwk: crypto.JsonWebKey };
29
+
30
+ /**
31
+ * 外壳转来的订阅:手机上只有添加到主屏幕的那个地址(外壳)能订阅推送,订阅是对着外壳那台的
32
+ * VAPID 公钥开的,这台推的时候也得用那把密钥签名,推送服务才认。点开通知回到外壳的页面,
33
+ * 地址里带上 srv=这台在外壳里的 id,由外壳切过来。
34
+ */
35
+ export type RelayInfo = {
36
+ vapid: VapidKey;
37
+ /** 外壳的地址 */
38
+ origin: string;
39
+ /** 这台在外壳列表里的 id */
40
+ server: string;
41
+ /** 外壳列表里这台的图标和名字,加在通知标题前面 */
42
+ label: string;
22
43
  };
23
44
 
24
45
  /** 按订阅的主人筛选:拿到的是订阅里记的 userId(可能没有) */
@@ -34,7 +55,7 @@ export type PushPayload = {
34
55
  };
35
56
 
36
57
  type Store = {
37
- vapid?: { publicKey: string; privateJwk: crypto.JsonWebKey };
58
+ vapid?: VapidKey;
38
59
  subscriptions: PushSubscriptionRecord[];
39
60
  };
40
61
 
@@ -44,6 +65,17 @@ const VAPID_SUBJECT = "https://github.com/qijieinnet/agent-loft";
44
65
 
45
66
  let store: Store | null = null;
46
67
 
68
+ /** 取消嵌入授权后,该外壳也不能再通过旧订阅收到通知。 */
69
+ function dropRevokedRelays(s: Store, embedders: string[]): boolean {
70
+ const before = s.subscriptions.length;
71
+ s.subscriptions = s.subscriptions.filter((x) => !x.relay || embedders.includes(x.relay.origin));
72
+ return s.subscriptions.length !== before;
73
+ }
74
+
75
+ onConfigChange((next) => {
76
+ if (store && dropRevokedRelays(store, next.servers.embedders)) persist();
77
+ });
78
+
47
79
  function load(): Store {
48
80
  if (!store) {
49
81
  store = readJson<Store>(FILE(), { subscriptions: [] });
@@ -53,7 +85,8 @@ function load(): Store {
53
85
  const owner = legacyOwnerId();
54
86
  const legacy = owner ? store.subscriptions.filter((x) => !x.userId) : [];
55
87
  for (const x of legacy) x.userId = owner;
56
- if (legacy.length > 0) writeJsonAtomic(FILE(), store);
88
+ const revoked = dropRevokedRelays(store, config().servers.embedders);
89
+ if (legacy.length > 0 || revoked) writeJsonAtomic(FILE(), store);
57
90
  }
58
91
  return store;
59
92
  }
@@ -91,8 +124,22 @@ export function vapidPublicKey(): string {
91
124
  return vapid().publicKey;
92
125
  }
93
126
 
94
- export function vapidHeader(endpoint: string): string {
95
- const { publicKey, privateKey } = vapid();
127
+ /**
128
+ * 这台的 VAPID 密钥对,给多服务器的外壳转给嵌着的各台(GET /api/push/relay-key)。
129
+ * 拿到它也只能推给已经知道订阅地址的设备:订阅地址和加密用的 p256dh / auth 只在开通知的那台浏览器
130
+ * 和收到订阅的服务端手里,别人的设备推不到
131
+ */
132
+ export function vapidKeyPair(): VapidKey {
133
+ vapid();
134
+ const { publicKey, privateJwk } = load().vapid!;
135
+ return { publicKey, privateJwk };
136
+ }
137
+
138
+ /** key:用别的密钥签(外壳转来的订阅),不给就用这台自己的 */
139
+ export function vapidHeader(endpoint: string, key?: VapidKey): string {
140
+ const { publicKey, privateKey } = key
141
+ ? { publicKey: key.publicKey, privateKey: crypto.createPrivateKey({ key: key.privateJwk, format: "jwk" }) }
142
+ : vapid();
96
143
  const header = b64url(Buffer.from(JSON.stringify({ typ: "JWT", alg: "ES256" })));
97
144
  const claims = b64url(
98
145
  Buffer.from(
@@ -162,6 +209,59 @@ export function addSubscription(sub: unknown, userAgent: string, userId?: string
162
209
  return record;
163
210
  }
164
211
 
212
+ function validVapid(v: unknown): v is VapidKey {
213
+ const key = v as { publicKey?: unknown; privateJwk?: crypto.JsonWebKey };
214
+ const jwk = key?.privateJwk;
215
+ if (typeof key?.publicKey !== "string" || !jwk || typeof jwk !== "object") return false;
216
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256" || typeof jwk.d !== "string" || typeof jwk.x !== "string" || typeof jwk.y !== "string") return false;
217
+ try {
218
+ crypto.createPrivateKey({ key: { kty: "EC", crv: "P-256", d: jwk.d, x: jwk.x, y: jwk.y }, format: "jwk" });
219
+ } catch {
220
+ return false;
221
+ }
222
+ return b64url(rawPublicKey(jwk)) === key.publicKey;
223
+ }
224
+
225
+ const clip = (v: unknown, max: number) => [...String(v ?? "").trim()].slice(0, max).join("");
226
+
227
+ /**
228
+ * 外壳转来的订阅(多服务器)。embedders:这台允许谁嵌,外壳得在里面 —— 订阅只能是嵌着这台的
229
+ * 外壳转来的,别的地址的不收。同一个订阅地址再转一次就换掉旧的(换了账号登录也是这样归新账号)
230
+ */
231
+ export function addRelaySubscription(
232
+ input: { subscription?: unknown; vapid?: unknown; via?: unknown },
233
+ userAgent: string,
234
+ userId: string,
235
+ embedders: string[],
236
+ ): PushSubscriptionRecord {
237
+ const sub = input.subscription;
238
+ if (!validSubscription(sub)) throw new Error("订阅信息不完整");
239
+ if (!validVapid(input.vapid)) throw new Error("推送密钥不对");
240
+ const via = (input.via ?? {}) as { origin?: unknown; server?: unknown; label?: unknown };
241
+ const origin = String(via.origin ?? "");
242
+ if (!embedders.includes(origin)) throw new Error(`这台没有允许 ${origin || "这个地址"} 嵌入,收不了它转来的通知订阅`);
243
+ const server = String(via.server ?? "");
244
+ if (!validServerId(server)) throw new Error("订阅信息不完整");
245
+ const { publicKey, privateJwk } = input.vapid;
246
+ const s = load();
247
+ const record: PushSubscriptionRecord = {
248
+ endpoint: sub.endpoint,
249
+ keys: { p256dh: sub.keys.p256dh, auth: sub.keys.auth },
250
+ label: `${describeUa(userAgent)} · 经 ${new URL(origin).host}`,
251
+ createdAt: Date.now(),
252
+ userId,
253
+ relay: {
254
+ vapid: { publicKey, privateJwk: { kty: "EC", crv: "P-256", d: privateJwk.d, x: privateJwk.x, y: privateJwk.y } },
255
+ origin,
256
+ server,
257
+ label: clip(via.label, 60),
258
+ },
259
+ };
260
+ s.subscriptions = [...s.subscriptions.filter((x) => x.endpoint !== sub.endpoint), record];
261
+ persist();
262
+ return record;
263
+ }
264
+
165
265
  export function removeSubscription(endpoint: string, mine?: OwnerFilter): boolean {
166
266
  const s = load();
167
267
  const before = s.subscriptions.length;
@@ -187,12 +287,36 @@ export function hasSubscriptions(): boolean {
187
287
 
188
288
  // ---------- 发送 ----------
189
289
 
290
+ const prefixed = (label: string, title: string) => (label ? `${label} · ${title}` : title);
291
+
292
+ /**
293
+ * 真正推出去的内容。加了别的服务器(这台是外壳)时标题前面带上这台的名字,好分清是哪台的;
294
+ * 外壳转来的订阅带上外壳列表里这台的名字,tag 加上这台的 id(各台的会话 key 可能撞上),
295
+ * 点开的地址带上 srv=这台的 id
296
+ */
297
+ export function payloadFor(sub: PushSubscriptionRecord, payload: PushPayload): PushPayload {
298
+ const relay = sub.relay;
299
+ if (!relay) {
300
+ const servers = config().servers;
301
+ if (!servers.list.length) return payload;
302
+ return { ...payload, title: prefixed(`${servers.selfIcon} ${selfName(servers)}`.trim(), payload.title) };
303
+ }
304
+ const url = new URL(payload.url ?? "/", "http://relay");
305
+ url.searchParams.set("srv", relay.server);
306
+ return {
307
+ ...payload,
308
+ title: prefixed(relay.label, payload.title),
309
+ ...(payload.tag ? { tag: `srv:${relay.server}:${payload.tag}` } : {}),
310
+ url: `${url.pathname}${url.search}${url.hash}`,
311
+ };
312
+ }
313
+
190
314
  async function sendOne(sub: PushSubscriptionRecord, payload: PushPayload): Promise<boolean> {
191
- const body = encryptPayload(Buffer.from(JSON.stringify(payload)), sub.keys.p256dh, sub.keys.auth);
315
+ const body = encryptPayload(Buffer.from(JSON.stringify(payloadFor(sub, payload))), sub.keys.p256dh, sub.keys.auth);
192
316
  const res = await fetch(sub.endpoint, {
193
317
  method: "POST",
194
318
  headers: {
195
- Authorization: vapidHeader(sub.endpoint),
319
+ Authorization: vapidHeader(sub.endpoint, sub.relay?.vapid),
196
320
  "Content-Encoding": "aes128gcm",
197
321
  "Content-Type": "application/octet-stream",
198
322
  TTL: String(24 * 3600),
@@ -24,7 +24,7 @@ import { authEvents, ensureSetupToken, sessionUser } from "./auth.js";
24
24
  import { canSeeKey, sessionVisibleTo } from "./access.js";
25
25
  import { cookies } from "./http.js";
26
26
  import { COOKIE } from "./api.js";
27
- import { HttpError, sameOrigin, SECURITY_HEADERS, sendJson } from "./http.js";
27
+ import { HttpError, pageHeaders, sameOrigin, SECURITY_HEADERS, sendJson } from "./http.js";
28
28
  import { hasSubscriptions, pushToAll } from "./push.js";
29
29
  import { closeListener, listen, listening, rebind } from "./listen.js";
30
30
  import { closeTerminalClients, pingTerminalClients, recheckTerminalClients, upgradeTerminal } from "./terminal.js";
@@ -86,11 +86,12 @@ function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: st
86
86
  const lastModified = new Date(Math.floor(stat.mtimeMs / 1000) * 1000);
87
87
  const since = Date.parse(req.headers["if-modified-since"] ?? "");
88
88
  const headers = {
89
- ...SECURITY_HEADERS,
89
+ ...pageHeaders(),
90
90
  "Cache-Control": "no-cache",
91
91
  "Last-Modified": lastModified.toUTCString(),
92
92
  };
93
- if (!Number.isNaN(since) && lastModified.getTime() <= since) {
93
+ // 页面本身不回 304:它的 CSP(允许谁嵌、能嵌谁)跟着设置变,304 带回的新头浏览器不一定换上
94
+ if (!Number.isNaN(since) && lastModified.getTime() <= since && path.extname(file) !== ".html") {
94
95
  res.writeHead(304, headers);
95
96
  res.end();
96
97
  return;
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import crypto from "node:crypto";
8
8
  import { configPath, ensureDirs, readJson, writeJsonAtomic } from "../home.js";
9
9
  import { cleanCustomCommands, type CommandPrefs } from "./command-catalog.js";
10
+ import { normalizeOrigin, validServerId } from "./servers.js";
10
11
 
11
12
 
12
13
  export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
@@ -96,6 +97,16 @@ export type AppConfig = {
96
97
  watchdogMs: number;
97
98
  bots: FeishuBotConfig[];
98
99
  };
100
+ /** 多服务器:网页左上角切换到别的 agent-loft(见 core/servers.ts) */
101
+ servers: {
102
+ /** 切换列表里这台叫什么(空着用主机名)、用什么图标(emoji) */
103
+ selfName: string;
104
+ selfIcon: string;
105
+ /** 左上角能切到的其他服务器,按这个顺序。url 是 origin */
106
+ list: { id: string; name: string; icon: string; url: string }[];
107
+ /** 允许把这台的页面嵌进去的地址(origin):别的 agent-loft 要切到这台,得先在这里 */
108
+ embedders: string[];
109
+ };
99
110
  };
100
111
 
101
112
  export const AGENT_IDS = ["claude", "codex"] as const;
@@ -131,6 +142,7 @@ export function defaultConfig(): AppConfig {
131
142
  vncPassword: "",
132
143
  },
133
144
  feishu: { watchdogMs: 10 * 60 * 1000, bots: [] },
145
+ servers: { selfName: "", selfIcon: "", list: [], embedders: [] },
134
146
  };
135
147
  }
136
148
 
@@ -164,6 +176,27 @@ function normalizeBot(raw: Partial<FeishuBotConfig>): FeishuBotConfig {
164
176
  };
165
177
  }
166
178
 
179
+ /** 多服务器的地址可能是手改的:规范成 origin,坏的、重复的丢掉 */
180
+ function normalizeServers(cfg: AppConfig): void {
181
+ const origin = (v: unknown) => {
182
+ try {
183
+ return normalizeOrigin(v);
184
+ } catch {
185
+ return null;
186
+ }
187
+ };
188
+ const seen = new Set<string>();
189
+ const ids = new Set<string>();
190
+ cfg.servers.list = cfg.servers.list.flatMap((s) => {
191
+ const url = origin(s?.url);
192
+ if (!url || seen.has(url) || !validServerId(s.id) || ids.has(s.id)) return [];
193
+ seen.add(url);
194
+ ids.add(s.id);
195
+ return [{ id: s.id, name: String(s.name ?? ""), icon: String(s.icon ?? ""), url }];
196
+ });
197
+ cfg.servers.embedders = [...new Set(cfg.servers.embedders.map(origin).filter((o): o is string => !!o))];
198
+ }
199
+
167
200
  /** 自定义命令可能是手改进配置文件的:不合规的丢掉,别让一条坏数据把命令列表搞崩 */
168
201
  function normalizeCommands(cfg: AppConfig): void {
169
202
  for (const id of AGENT_IDS) cfg.commands[id].custom = cleanCustomCommands(cfg.commands[id].custom);
@@ -180,6 +213,7 @@ export function loadConfig(): AppConfig {
180
213
  merged.workspaceRoot = path.resolve(merged.workspaceRoot);
181
214
  merged.feishu.bots = merged.feishu.bots.map(normalizeBot);
182
215
  normalizeCommands(merged);
216
+ normalizeServers(merged);
183
217
  current = merged;
184
218
  if (!raw) writeJsonAtomic(configPath, merged);
185
219
  watchExternalEdits();
@@ -206,6 +240,7 @@ function watchExternalEdits(): void {
206
240
  next.workspaceRoot = path.resolve(next.workspaceRoot);
207
241
  next.feishu.bots = next.feishu.bots.map(normalizeBot);
208
242
  normalizeCommands(next);
243
+ normalizeServers(next);
209
244
  if (JSON.stringify(next) === JSON.stringify(current)) return;
210
245
  const prev = current;
211
246
  current = next;
@@ -234,6 +269,7 @@ export function saveConfig(next: AppConfig): AppConfig {
234
269
  const normalized = mergeDefaults(defaultConfig(), next);
235
270
  normalized.workspaceRoot = path.resolve(normalized.workspaceRoot);
236
271
  normalized.feishu.bots = normalized.feishu.bots.map(normalizeBot);
272
+ normalizeServers(normalized);
237
273
  writeJsonAtomic(configPath, normalized);
238
274
  current = normalized;
239
275
  for (const listener of listeners) {
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 [];