agent-loft 0.2.44 → 0.2.46
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 +4 -3
- package/package.json +1 -1
- package/src/channels/web/api.ts +42 -5
- package/src/channels/web/http.ts +12 -0
- package/src/channels/web/push.ts +130 -6
- package/src/channels/web/server.ts +4 -3
- package/src/core/config.ts +36 -0
- package/src/core/memory.ts +22 -3
- package/src/core/servers.ts +134 -0
- package/src/main.ts +3 -0
- package/web/css/servers.css +265 -0
- package/web/index.html +1 -0
- package/web/lib/api.js +1 -0
- package/web/lib/overlay.js +1 -1
- package/web/lib/push.js +8 -1
- package/web/lib/shell.js +691 -0
- package/web/lib/ws.js +7 -1
- package/web/settings/common.js +3 -0
- package/web/settings/index.js +2 -0
- package/web/settings/notify.js +7 -2
- package/web/settings/security.js +8 -3
- package/web/settings/servers.js +207 -0
- package/web/state.js +2 -0
- package/web/views/auth.js +3 -1
- package/web/views/composer.js +1 -1
- package/web/views/layout.js +43 -5
- package/web/views/messages.js +2 -2
- package/web/views/remote.js +2 -2
- package/web/views/sidebar.js +6 -4
- package/web/views/tasks.js +1 -1
package/README.md
CHANGED
|
@@ -57,13 +57,14 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
57
57
|
- 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
|
|
58
58
|
- 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
|
|
59
59
|
- 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
|
|
60
|
+
- **网页多服务器切换**:在 设置 → 服务器 添加其他 agent-loft,再点「授权」到对方页面确认,侧栏左上角就能切换;各台分别登录,切走后保持连接,列表显示待处理数和运行状态,刷新后保留选择。几台需使用同一主域名下的 HTTPS 地址(例如 `mac.example.com`、`nas.example.com`)。在外层页面开启系统通知后,各台的提醒都能推到同一个主屏幕 App,点通知自动切到对应服务器和对话。见[使用指南](docs/产品介绍.md#在网页和手机上切换多台服务器)。
|
|
60
61
|
- **系统通知**:Web 会话回复完成、出错、需要授权或提问时推送到手机 / 电脑(设置 → 通知 → 「在此设备开启通知」,可以发测试通知)。飞书会话由飞书提醒,正在前台看着的会话不推。需要 HTTPS 访问,iPhone 需 iOS 16.4+ 且从主屏幕图标打开。
|
|
61
62
|
- **跨渠道同步**:飞书里的会话在 Web 上也能打开接着聊。同一个授权请求同时出现在飞书卡片和网页上,哪边先点算哪边,另一边自动变成「已处理」。
|
|
62
63
|
- **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
|
|
63
|
-
- **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude
|
|
64
|
+
- **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
|
|
64
65
|
- **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
|
|
65
66
|
- **聊天模式 / 工作模式**:右上角「更多」里的「聊天模式」,或者发 `/chat`、`/work`,同一条对话随时切换、上下文接着。聊天模式换成精简的系统提示,只留联网搜索,不加载技能、MCP、插件,不执行命令、不读写本机文件(文本附件的内容直接放进消息),每轮的固定开销小得多:实测一句话 Claude 约 1.6 万 → 2 千 token,Codex 约 2 万 → 1.2 万(Codex 的基础指令改不了)。适合日常聊天、查资料;要动手干活时切回工作模式。切换后第一轮要重建提示缓存,会贵一些;在工作模式里读过的大段内容还留在历史里。
|
|
66
|
-
- **记忆**:像 ChatGPT 的记忆,设置 →
|
|
67
|
+
- **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关)。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理聊天模式的/只整理工作模式的;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话;第一次用时会把已有对话收录进来)。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
|
|
67
68
|
- **定时任务**:像 ChatGPT 的 Tasks,侧栏「最近」上面的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选聊天 / 工作模式和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
|
|
68
69
|
- **技能(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 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
|
|
69
70
|
- **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
|
|
@@ -102,7 +103,7 @@ agent-loft service install # 注册为开机自启服务(systemd / laun
|
|
|
102
103
|
- 菜单栏图标:悬停看各服务器的 Claude / Codex 额度、待处理和运行中的会话;双击打开主窗口。同一个账号的额度只查一次。(Windows 上点托盘图标弹出;Linux 上在托盘菜单里点「额度和待处理」。)
|
|
103
104
|
- 菜单栏图标可以换成额度条:Claude、Codex 各是一只像素小宠物,看样子就知道是谁,身子是 5 小时额度,下面一条是周额度。桌面端设置 → 额度显示 →「菜单栏显示额度」,选所有服务器合起来(取最高),或者按服务器分别选 Claude / Codex(图标上不写服务器名);都不选就只显示图标。「额度条显示」选实心表示剩余额度(默认,像电池)还是已用额度。只有 macOS 有,Windows / Linux 的托盘图标太小放不下。
|
|
104
105
|
- 支持前面挡着 Cloudflare Access 的服务器:验证页直接在窗口里完成,过期会提醒;也可以配 Service Token 免验证。
|
|
105
|
-
- 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew
|
|
106
|
+
- 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew 装)并开机自启,装好自动连上;设置里可以改成「只在桌面端运行时运行」(不开机自启,打开桌面端时启动、退出时停止)。Linux 上一样(需要先装好 Node.js 22+,开机自启用 systemd 用户服务);Windows 上服务端还没有开机自启,可以在 WSL 里装,桌面端会自动检测到 `127.0.0.1` 上的它。防休眠:本机有会话在跑时不休眠;另有永不休眠、定时休眠(设休眠时段,时段外不休眠,时段内本机没有会话在跑、屏幕锁上后让 Mac 睡下去)和合盖不休眠(macOS,第一次开关要输管理员密码,之后不用;开着时闲置也不睡,定时休眠到点会临时关掉它让 Mac 睡下去,醒来再打开)。
|
|
106
107
|
- 顶栏「更多」→「总量汇总」:把所有已添加服务器的用量加在一起看,按日 / 月 / 年统计 token 和金额,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按服务器。不在线、没登录或服务端太旧的服务器不计入,页面上会注明。
|
|
107
108
|
- 设置(`⌘,`)的服务器列表里展开某台服务器,能看它的 Agent 环境和版本,有新版本时点「升级服务端」;桌面端自己的更新在同一页的「更新」里点「更新并重启」。
|
|
108
109
|
|
package/package.json
CHANGED
package/src/channels/web/api.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { addScheduled, clearScheduled, removeScheduled } from "../../core/schedu
|
|
|
13
13
|
import { resolveUploadFile, saveBuffer, sniff, uploadKeyOf } from "../../core/uploads.js";
|
|
14
14
|
import { mentions, replyFileType, resolveReplyFile } from "../../core/reply-files.js";
|
|
15
15
|
import { HTML_CSP, HTML_MAX, htmlDocument } from "../../core/visualize.js";
|
|
16
|
+
import { cleanServers, ownFrameAncestors, shellInfo } from "../../core/servers.js";
|
|
16
17
|
import {
|
|
17
18
|
createUser,
|
|
18
19
|
getUser,
|
|
@@ -72,7 +73,16 @@ import { handleTasksApi } from "./tasks-api.js";
|
|
|
72
73
|
import { handleSkillsApi } from "./skills-api.js";
|
|
73
74
|
import { handleTerminalApi } from "./terminal.js";
|
|
74
75
|
import { handleDesktopApi, remoteStatus } from "./desktop.js";
|
|
75
|
-
import {
|
|
76
|
+
import {
|
|
77
|
+
addRelaySubscription,
|
|
78
|
+
addSubscription,
|
|
79
|
+
listSubscriptions,
|
|
80
|
+
pushToAll,
|
|
81
|
+
removeSubscription,
|
|
82
|
+
removeSubscriptionsOf,
|
|
83
|
+
vapidKeyPair,
|
|
84
|
+
vapidPublicKey,
|
|
85
|
+
} from "./push.js";
|
|
76
86
|
|
|
77
87
|
export const COOKIE = "aim_session";
|
|
78
88
|
const startedAt = Date.now();
|
|
@@ -188,7 +198,7 @@ function serveReplyFile(req: IncomingMessage, res: ServerResponse, file: string,
|
|
|
188
198
|
// (所有接口的响应事先都带上了 SECURITY_HEADERS,见 server.ts,这里得把那个也去掉)
|
|
189
199
|
delete headers["X-Frame-Options"];
|
|
190
200
|
res.removeHeader("X-Frame-Options");
|
|
191
|
-
headers["Content-Security-Policy"] =
|
|
201
|
+
headers["Content-Security-Policy"] = `default-src 'none'; frame-ancestors ${ownFrameAncestors(config().servers)}`;
|
|
192
202
|
} else {
|
|
193
203
|
headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox";
|
|
194
204
|
}
|
|
@@ -280,9 +290,17 @@ function publicConfig(): unknown {
|
|
|
280
290
|
};
|
|
281
291
|
}
|
|
282
292
|
|
|
283
|
-
|
|
293
|
+
/** selfOrigin:发起保存的页面的地址(多服务器列表里不能加自己) */
|
|
294
|
+
function applyConfig(input: Partial<AppConfig>, selfOrigin?: string): void {
|
|
284
295
|
const current = config();
|
|
285
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
|
+
}
|
|
286
304
|
if (typeof input.workspaceRoot === "string" && input.workspaceRoot.trim()) next.workspaceRoot = input.workspaceRoot.trim();
|
|
287
305
|
if (typeof input.approvalTimeoutMs === "number") next.approvalTimeoutMs = Math.max(60_000, input.approvalTimeoutMs);
|
|
288
306
|
if (typeof input.sessionTtlMs === "number") next.sessionTtlMs = Math.max(0, input.sessionTtlMs);
|
|
@@ -643,6 +661,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
643
661
|
pending,
|
|
644
662
|
user: publicMe(user),
|
|
645
663
|
remote: remoteStatus(user),
|
|
664
|
+
// 左上角切换服务器:没加别的服务器是 null
|
|
665
|
+
servers: shellInfo(config().servers),
|
|
646
666
|
serverTime: Date.now(),
|
|
647
667
|
});
|
|
648
668
|
return;
|
|
@@ -671,6 +691,23 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
671
691
|
}
|
|
672
692
|
return;
|
|
673
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
|
+
}
|
|
674
711
|
if (p === "/api/push/unsubscribe" && method === "POST") {
|
|
675
712
|
const body = await readJsonBody<{ endpoint?: string }>(req);
|
|
676
713
|
sendJson(res, 200, { ok: removeSubscription(String(body.endpoint ?? ""), pushOwnedBy(user.id)) });
|
|
@@ -859,7 +896,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
859
896
|
res.writeHead(200, {
|
|
860
897
|
"X-Content-Type-Options": "nosniff",
|
|
861
898
|
"Referrer-Policy": "no-referrer",
|
|
862
|
-
"Content-Security-Policy": HTML_CSP,
|
|
899
|
+
"Content-Security-Policy": HTML_CSP.replace("frame-ancestors 'self'", `frame-ancestors ${ownFrameAncestors(config().servers)}`),
|
|
863
900
|
"Content-Type": "text/html; charset=utf-8",
|
|
864
901
|
"Content-Length": doc.length,
|
|
865
902
|
"Cache-Control": "private, no-cache",
|
|
@@ -974,7 +1011,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
974
1011
|
if (p === "/api/config" && method === "PUT") {
|
|
975
1012
|
const input = await readJsonBody<Partial<AppConfig>>(req);
|
|
976
1013
|
await applyListen(req, input.web);
|
|
977
|
-
applyConfig(input);
|
|
1014
|
+
applyConfig(input, typeof req.headers.origin === "string" ? req.headers.origin : undefined);
|
|
978
1015
|
sendJson(res, 200, { ...(publicConfig() as object), network: networkInfo(req) });
|
|
979
1016
|
return;
|
|
980
1017
|
}
|
package/src/channels/web/http.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/channels/web/push.ts
CHANGED
|
@@ -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?:
|
|
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
|
-
|
|
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
|
-
|
|
95
|
-
|
|
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
|
-
...
|
|
89
|
+
...pageHeaders(),
|
|
90
90
|
"Cache-Control": "no-cache",
|
|
91
91
|
"Last-Modified": lastModified.toUTCString(),
|
|
92
92
|
};
|
|
93
|
-
|
|
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;
|
package/src/core/config.ts
CHANGED
|
@@ -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/memory.ts
CHANGED
|
@@ -58,7 +58,7 @@ export type CurateSettings = {
|
|
|
58
58
|
model: string;
|
|
59
59
|
};
|
|
60
60
|
|
|
61
|
-
export const DEFAULT_CURATE: CurateSettings = { when: "daily", scope: "all", idleMinutes: 30, dailyHour:
|
|
61
|
+
export const DEFAULT_CURATE: CurateSettings = { when: "daily", scope: "all", idleMinutes: 30, dailyHour: 2, agent: "auto", model: "" };
|
|
62
62
|
|
|
63
63
|
function cleanCurate(raw: Partial<CurateSettings> | undefined, base: CurateSettings): CurateSettings {
|
|
64
64
|
const r = raw ?? {};
|
|
@@ -96,7 +96,25 @@ function fileOf(userId: string): string {
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
function empty(): UserMemory {
|
|
99
|
-
return { enabled:
|
|
99
|
+
return { enabled: false, about: "", items: [], curate: { ...DEFAULT_CURATE }, chatHistory: true };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 记忆从默认开改成默认关(0.2.46):升级前就有、但还没写过记忆文件的用户,补一份开着的,
|
|
104
|
+
* 让老实例里的人保持原样。只跑一次,跑过留个标记;新装的第一次启动时还没有用户,什么都不补。
|
|
105
|
+
*/
|
|
106
|
+
export function migrateMemoryDefault(userIds: string[]): void {
|
|
107
|
+
const marker = path.join(memoryDir, ".default-off-migrated");
|
|
108
|
+
if (fs.existsSync(marker)) return;
|
|
109
|
+
fs.mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
|
|
110
|
+
let n = 0;
|
|
111
|
+
for (const id of userIds) {
|
|
112
|
+
if (fs.existsSync(fileOf(id))) continue;
|
|
113
|
+
write(id, { ...empty(), enabled: true });
|
|
114
|
+
n++;
|
|
115
|
+
}
|
|
116
|
+
fs.writeFileSync(marker, String(Date.now()), { mode: 0o600 });
|
|
117
|
+
if (n) console.log(`[记忆] 默认改成关闭:升级前的 ${n} 个用户保持开启`);
|
|
100
118
|
}
|
|
101
119
|
|
|
102
120
|
export function readMemory(userId: string): UserMemory {
|
|
@@ -105,7 +123,8 @@ export function readMemory(userId: string): UserMemory {
|
|
|
105
123
|
? raw.items.filter((i): i is MemoryItem => !!i && typeof i.id === "string" && typeof i.text === "string")
|
|
106
124
|
: [];
|
|
107
125
|
return {
|
|
108
|
-
|
|
126
|
+
// 默认关:后台整理会占订阅额度,夜里还会单独开一个 5 小时窗口。写过的文件都存着 enabled,老用户不受影响
|
|
127
|
+
enabled: raw.enabled === true,
|
|
109
128
|
// 早先的版本只有一个「自动整理」开关:关着的就是不整理
|
|
110
129
|
curate: cleanCurate(raw.curate, raw.autoExtract === false ? { ...DEFAULT_CURATE, when: "off" } : DEFAULT_CURATE),
|
|
111
130
|
chatHistory: raw.chatHistory !== false,
|