agent-loft 0.2.87 → 0.2.89
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 +7 -5
- package/package.json +1 -1
- package/src/agents/claude/session.ts +1 -1
- package/src/channels/web/api.ts +158 -6
- package/src/core/backup.ts +228 -0
- package/src/core/chat-history.ts +224 -56
- package/src/core/db.ts +72 -1
- package/src/core/fts.ts +53 -0
- package/src/core/hub.ts +20 -5
- package/src/core/memory-curator.ts +418 -76
- package/src/core/memory-dates.ts +16 -0
- package/src/core/memory-mcp.ts +1 -1
- package/src/core/memory-summaries.ts +225 -0
- package/src/core/memory.ts +698 -73
- package/src/core/personal.ts +33 -2
- package/src/core/tasks.ts +8 -7
- package/src/main.ts +27 -1
- package/src/mcp/memory-server.ts +237 -21
- package/web/css/settings.css +27 -0
- package/web/settings/memory.js +291 -13
- package/web/views/layout.js +2 -2
- package/web/views/messages.js +2 -2
- package/web/views/sidebar.js +1 -1
- package/web/views/todos.js +3 -3
package/README.md
CHANGED
|
@@ -90,7 +90,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
90
90
|
|
|
91
91
|
只勾联网搜索、读网页的 Claude 专家就是以前聊天模式的效果。专家改了,用它的对话下一条消息起生效;专家删了,用它的对话还能看、不能再发消息,用它的定时任务暂停。以前的聊天模式取消了:升级后聊天模式的旧对话不再保留,聊天模式的定时任务暂停,选个专家再启用。
|
|
92
92
|
- **MCP**:设置 → MCP,每人管自己的:本机进程(命令 + 参数 + 环境变量)或 HTTP 地址(+ 请求头),值可以标成密钥(网页上不回显,只交给 MCP 进程或请求头,不进提示词)。可以设「调用前询问」,不设就直接用。自定义专家加载各自勾选的服务;内置专家在「设置 → Agent → 对应 Agent 卡片 → 默认加载」里选择,支持个人 MCP、管理员可选的机器 MCP,也可全部取消;不指定时管理员沿用机器配置。
|
|
93
|
-
- **记忆**:像 ChatGPT 的记忆,设置 →
|
|
93
|
+
- **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关),按用很多年设计。「关于我」加上一条条记住的事;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),事情变了用 `update_memory`,记错了用 `forget`。**分三层**:长期(身份、家人、长期偏好,一直放进系统提示,不会被后来的挤掉,也可以自己置顶)、活跃(近期的事,按最近动过的时间放进系统提示,放不下的 agent 能用 `search_memory` 搜到)、归档(过时了、到期了、满了被挤出来的,不进系统提示,不删,能搜到能恢复)。**谁能动**:你加的、你在聊天里明确要求记的、你置顶的都受保护,自动整理不能改、不能删、满了也不会被挤,agent 要改得是你在当前对话里明确要求。明显的密钥(API key、`密码是……`)agent 和整理都记不进去。**不怕改错**:删除进回收站保留 30 天;每次改动都有记录(谁、什么时候、改之前是什么),在设置里能查能撤销,改之前的旧内容也搜得到;清空和彻底删除才是真删。**自动整理**:把上次整理之后新说的话连同日期交给模型(不留会话记录的一次性调用),补充、更新、归档过时的记忆。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理选中专家的对话;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。很长的对话切成几份整理,一句不漏;整理失败的对话不会丢,留着下次再试,连着全失败就退避(最长 6 小时),同一段一直失败的先搁置,点「现在整理」时再试。**摘要**:整理时顺带给每段对话写摘要(不多一次调用),月份过去后合成一份月度摘要(一个月一次调用),agent 回答「那段时间做了什么」「那件事的经过」时用 `memory_timeline` 看,还能按项目目录筛。只有整理范围内的对话才有摘要。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,能按日期筛,只有你自己的、没被删掉的对话),要看前后文用 `read_past_chat`。搜索走 SQLite FTS5 全文索引(中文按字索引,两个字的词也能搜),几十万句也在一秒内;设置页会显示近 30 天 agent 搜了多少次、多少次没搜到。聊天记录索引不开记忆也会记(侧栏的「搜索」也用它),升级后会把已有对话收录进来一次;没开记忆时记进来的不拿去整理。删对话时它的聊天记录索引和摘要一起删,提炼出来的记忆条目留着(记着来源)。**导出和备份**:记忆能导出成 JSON、导入到别的账号或服务器,聊天记录能导出成 JSONL;整个数据库每天自动备份到 `backups/db/`(校验后压缩,留最近 7 天、4 周、12 个月,`AGENT_LOFT_BACKUP_DIR` 可以换到别的盘)。每个用户一份,Claude 和 Codex、Web 和飞书共用;改了记忆(设置里改的、后台整理的、别的对话里记的),正在跑的会话空闲下来就换上新的。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
|
|
94
94
|
- **定时任务**:像 ChatGPT 的 Tasks,侧栏的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录;可以设成不携带上下文,每次运行都换新会话,之前的结果还留在对话里,只是 agent 看不到),在专用对话右上角的「更多」里可以直接编辑任务、立即运行,或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
|
|
95
95
|
- **技能(skills)**:设置 → 技能。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。**共享**:新建、编辑时选择「仅自己可见」「指定用户」或「所有人可见」,也可在自己技能的「更多 → 共享」里调整;默认仅自己可见。其他用户在「共享技能」中查看正文和附带文件、安装;安装后出现在「我的技能」,可停用、卸载或重新安装。安装的是作者的同一份技能,更新自动跟随;作者撤回共享后,范围外用户不再可用。只有作者能编辑,管理员可下架自己看得到的共享技能。共享不包含作者填写的变量和密钥,每人使用自己的配置。**使用**:内置专家默认使用你启用的全部技能,也可以在「设置 → Agent」中分别指定 Claude Code / Codex 加载哪些技能;自定义专家只用它选中的;agent 遇到对得上的事自己用。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
|
|
96
96
|
- **资料库**:像 ChatGPT 的资料库,侧栏的「资料库」。对话里发过的附件、agent 回复里给出的、这一轮新写出来的图片 / 文档 / 音视频(复制一份收进来,之后原文件改了删了不影响)都汇总在这里:按图片 / 文档 / 音视频筛、按文件名搜,点开看大图或下载,「在新对话里用」,单个或批量删除(文件从磁盘上删掉)。从资料库拿到对话里的文件硬链接进那条对话的上传目录,不占双份空间,agent 照常能读。按人隔离,规则同对话:自己的;没主人的对话(飞书群聊等)的归管理员。上传了一直没发出去的一天后清掉;删除会话时立即清理该会话的上传文件和资料库记录,删除原件也会清理复用到其他会话的副本。agent 侧的会话记录仍保留,恢复会话不会恢复已删除的文件。
|
|
@@ -193,7 +193,7 @@ agent-loft service install
|
|
|
193
193
|
- 审批超时一律按拒绝处理。Codex 默认沙箱为 `workspace-write`,不会因为 `~/.codex/config.toml` 里配了 `never` 或 `danger-full-access` 就绕过审批。
|
|
194
194
|
- agent 子进程拿不到本服务自己的凭据(`FEISHU_*`、`AGENT_LOFT_*` 等环境变量会被剔除)。
|
|
195
195
|
- 技能存在 `data/skills/`:技能本体在 `files/<技能 id>/`,每个人装了哪些、变量的值在 `users/<用户 id>.json`(0600)。普通变量注入到会话环境里,agent 能读到;受保护的密钥 agent 看不到值,但和多用户一样不是安全边界——能读文件的专家(包括内置的 Claude Code / Codex)能直接读这些文件。别人分享的技能会在你的会话里照着执行,装之前在技能页点开看一眼它要做什么、要哪些变量。
|
|
196
|
-
- 记忆和聊天记录索引都存在 `data/agent-loft.db`(SQLite
|
|
196
|
+
- 记忆和聊天记录索引都存在 `data/agent-loft.db`(SQLite,会话、脚注、用量也在里面)。**恢复备份**:停掉服务 → `gunzip` 备份文件 → 覆盖 `data/agent-loft.db` → 删掉同目录的 `agent-loft.db-wal` 和 `agent-loft.db-shm` → 启动。备份只含数据库,配置、专家这些 JSON 文件不在里面。记给谁由 agent-loft 在拉起记忆工具时定死(工具参数里没有用户),模型想写别人的记忆也写不了;但和多用户一样不是安全边界:能读文件的专家能读到这个数据库文件。只能联网的专家没有读写本机文件的工具,网页里的提示注入也骗不走本机文件。
|
|
197
197
|
- 专家存在 `data/experts.json`,MCP 存在 `data/mcp.json`(0600,含 MCP 的密钥值),内置 Agent 的个人默认选择存在 `data/builtin-agents.json`。和技能一样不是安全边界:能读文件的专家读得到。
|
|
198
198
|
|
|
199
199
|
## 结构
|
|
@@ -206,9 +206,11 @@ src/
|
|
|
206
206
|
store.ts 会话持久化(每个 agent 的会话 id 各自保存)
|
|
207
207
|
config.ts 配置(Web 可改,改完热加载)
|
|
208
208
|
users.ts Web 登录用户和归属规则(谁能看到哪条会话)
|
|
209
|
-
memory.ts
|
|
209
|
+
memory.ts 记忆的存储、分层、改动记录和注入系统提示的那段文字;personal.ts 定记忆用谁的
|
|
210
|
+
memory-summaries.ts 对话摘要和月度摘要;fts.ts 全文索引的切词和查询
|
|
211
|
+
backup.ts 数据库的每日自动备份
|
|
210
212
|
chat-history.ts 聊天记录索引(数据库的 history 表)和关键词搜索
|
|
211
|
-
memory-curator.ts
|
|
213
|
+
memory-curator.ts 录入聊天、回填已有对话、自动整理记忆、写摘要、定期维护
|
|
212
214
|
feishu-links.ts 飞书账号 ↔ 用户的绑定和绑定码
|
|
213
215
|
experts.ts 专家的存储、校验,开会话时解析成交给 agent 的配置(MCP、技能、子智能体)
|
|
214
216
|
expert-prompt.ts 专家告诉 agent 的话(Claude 换系统提示或追加,Codex 附在消息后面)
|
|
@@ -227,7 +229,7 @@ src/
|
|
|
227
229
|
vnc-transcode.ts 远程桌面转码:服务端当 VNC 客户端收全分辨率画面,缩小、只把变了的格子压成 JPEG 按 Tight 发给页面
|
|
228
230
|
pairing.ts uploads.ts commands.ts …
|
|
229
231
|
mcp/
|
|
230
|
-
memory-server.ts 记忆工具(remember / forget / search_past_chats)的 stdio MCP 服务,两个 agent 共用
|
|
232
|
+
memory-server.ts 记忆工具(remember / forget / update_memory / search_memory / search_past_chats / read_past_chat / memory_timeline)的 stdio MCP 服务,两个 agent 共用
|
|
231
233
|
tasks-server.ts 定时任务工具的 stdio MCP 服务:只传话,经 unix socket 转给主进程;AGENT_LOFT_TOOLSET=skills 时是技能工具
|
|
232
234
|
agents/
|
|
233
235
|
claude/ Claude Agent SDK 驱动
|
package/package.json
CHANGED
|
@@ -137,7 +137,7 @@ function buildContent(input: UserInput, inlineText: boolean): string | ContentBl
|
|
|
137
137
|
}
|
|
138
138
|
|
|
139
139
|
/** 记忆工具在 Claude 里的全名 */
|
|
140
|
-
const MEMORY_TOOLS = new Set(["remember", "forget", "search_past_chats"].map((t) => `mcp__${MEMORY_MCP_NAME}__${t}`));
|
|
140
|
+
const MEMORY_TOOLS = new Set(["remember", "forget", "update_memory", "search_memory", "search_past_chats", "read_past_chat", "memory_timeline"].map((t) => `mcp__${MEMORY_MCP_NAME}__${t}`));
|
|
141
141
|
/** 定时任务工具:要用户确认的那几个由 agent-loft 自己弹卡(tasks-bridge.ts),这里不再问一遍 */
|
|
142
142
|
const TASK_TOOLS = new Set(["list_tasks", "create_task", "update_task", "delete_task"].map((t) => `mcp__${TASKS_MCP_NAME}__${t}`));
|
|
143
143
|
/** 技能工具:建、改技能前由 agent-loft 自己弹卡(skills-bridge.ts) */
|
package/src/channels/web/api.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { cleanCustomCommands } from "../../core/command-catalog.js";
|
|
|
8
8
|
import { hub } from "../../core/hub.js";
|
|
9
9
|
import { interactions } from "../../core/interactions.js";
|
|
10
10
|
import { approve, listApproved, listPending, revoke } from "../../core/pairing.js";
|
|
11
|
-
import { agentBinding, getConversation, listConversations, touchConversation, updateConversation } from "../../core/store.js";
|
|
11
|
+
import { agentBinding, conversationLabels, getConversation, listConversations, touchConversation, 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
14
|
import { mentions, replyFileType, resolveReplyFile } from "../../core/reply-files.js";
|
|
@@ -34,17 +34,30 @@ import { appendDirOrder, getDirOrder, getSidebarNav, setDirOrder, setSidebarNav
|
|
|
34
34
|
import {
|
|
35
35
|
addMemoryItem,
|
|
36
36
|
clearMemory,
|
|
37
|
+
countMemoryItems,
|
|
38
|
+
exportMemory,
|
|
39
|
+
getMemoryItem,
|
|
40
|
+
importMemory,
|
|
41
|
+
listMemoryItems,
|
|
42
|
+
localDate,
|
|
37
43
|
MEMORY_LIMITS,
|
|
44
|
+
purgeMemoryItem,
|
|
38
45
|
readMemory,
|
|
46
|
+
readMemoryLog,
|
|
39
47
|
removeMemoryItem,
|
|
48
|
+
restoreMemoryItem,
|
|
40
49
|
setMemoryOptions,
|
|
50
|
+
setMemoryTier,
|
|
51
|
+
undoMemoryChange,
|
|
41
52
|
updateMemoryItem,
|
|
42
53
|
type CurateSettings,
|
|
43
54
|
} from "../../core/memory.js";
|
|
44
55
|
import { createLinkCode, listLinks, unlink, unlinkUser } from "../../core/feishu-links.js";
|
|
45
56
|
import { getWeixinAccount, removeWeixinAccount, weixinKey } from "../../core/weixin-accounts.js";
|
|
46
|
-
import { purgeUserData } from "../../core/personal.js";
|
|
47
|
-
import { countRecords, purgeHistory, readMeta, searchHistory, writeMeta } from "../../core/chat-history.js";
|
|
57
|
+
import { purgeConversationData, purgeUserData } from "../../core/personal.js";
|
|
58
|
+
import { countRecords, iterateRecords, purgeHistory, readMeta, searchHistory, searchStats, writeMeta } from "../../core/chat-history.js";
|
|
59
|
+
import { backupNow, backupStatus } from "../../core/backup.js";
|
|
60
|
+
import { countSummaries, deleteSummary, exportSummaries, listSummaries, purgeSummaries, readSummary, upsertSummary, type MemorySummary } from "../../core/memory-summaries.js";
|
|
48
61
|
import { curateNow, pendingCount } from "../../core/memory-curator.js";
|
|
49
62
|
import { listAllowlist, setAllowlist } from "../../agents/claude/permissions.js";
|
|
50
63
|
import { isPermissionLevel, type PermissionLevel } from "../../core/permission.js";
|
|
@@ -106,7 +119,16 @@ const uploads = new Map<string, { key: string; attachment: SavedAttachment; at:
|
|
|
106
119
|
|
|
107
120
|
/** 单条删除和项目批量删除共用清理规则,保留 agent 自己的文字记录。 */
|
|
108
121
|
function hideConversation(key: string): void {
|
|
122
|
+
const conv = getConversation(key);
|
|
109
123
|
updateConversation(key, { hidden: true });
|
|
124
|
+
// 删对话:聊天记录索引和摘要真的删掉,不只是搜不到(agent 自己的文字记录还留着,它们不归这里管)
|
|
125
|
+
if (conv) {
|
|
126
|
+
try {
|
|
127
|
+
purgeConversationData(conv);
|
|
128
|
+
} catch (err) {
|
|
129
|
+
console.warn(`[记忆] 清理 ${key} 的聊天记录失败:`, err);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
110
132
|
deleteConversationFiles(key);
|
|
111
133
|
for (const [id, entry] of uploads) if (entry.key === key) uploads.delete(id);
|
|
112
134
|
clearScheduled(key);
|
|
@@ -1409,12 +1431,124 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1409
1431
|
sendJson(res, 200, {
|
|
1410
1432
|
...readMemory(user.id),
|
|
1411
1433
|
limits: MEMORY_LIMITS,
|
|
1434
|
+
counts: countMemoryItems(user.id),
|
|
1435
|
+
summaries: countSummaries(user.id),
|
|
1412
1436
|
// 等着整理的对话有几段、上次整理的结果(设置页显示)
|
|
1413
1437
|
pending: pendingCount(user.id),
|
|
1414
1438
|
...(meta.lastCuration ? { lastCuration: meta.lastCuration } : {}),
|
|
1439
|
+
...(meta.curateRetry ? { curateRetry: meta.curateRetry } : {}),
|
|
1440
|
+
// 近 30 天 agent 搜聊天记录的次数和没搜到的次数:判断关键词搜索够不够用
|
|
1441
|
+
searchStats: searchStats(user.id, localDate(Date.now() - 30 * 86400_000)),
|
|
1442
|
+
// 备份是整个数据库的,只给管理员看
|
|
1443
|
+
...(isAdmin(user) ? { backup: backupStatus() } : {}),
|
|
1444
|
+
});
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
if (p === "/api/account/memory/backup" && method === "POST") {
|
|
1448
|
+
if (!isAdmin(user)) throw new HttpError(403, "只有管理员能备份");
|
|
1449
|
+
try {
|
|
1450
|
+
await backupNow();
|
|
1451
|
+
} catch (err) {
|
|
1452
|
+
throw new HttpError(500, err instanceof Error ? err.message : String(err));
|
|
1453
|
+
}
|
|
1454
|
+
sendJson(res, 200, backupStatus());
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
if (p === "/api/account/memory/items" && method === "GET") {
|
|
1458
|
+
const view = url.searchParams.get("view");
|
|
1459
|
+
if (view !== "archive" && view !== "trash") throw new HttpError(400, "view 只能是 archive 或 trash");
|
|
1460
|
+
sendJson(res, 200, { items: listMemoryItems(user.id, view) });
|
|
1461
|
+
return;
|
|
1462
|
+
}
|
|
1463
|
+
if (p === "/api/account/memory/log" && method === "GET") {
|
|
1464
|
+
const before = Number(url.searchParams.get("before"));
|
|
1465
|
+
sendJson(res, 200, { log: readMemoryLog(user.id, { limit: 30, ...(before > 0 ? { before } : {}) }) });
|
|
1466
|
+
return;
|
|
1467
|
+
}
|
|
1468
|
+
{
|
|
1469
|
+
const m = /^\/api\/account\/memory\/log\/(\d+)\/undo$/.exec(p);
|
|
1470
|
+
if (m && method === "POST") {
|
|
1471
|
+
sendJson(res, 200, memoryOp(user.id, () => undoMemoryChange(user.id, Number(m[1]))));
|
|
1472
|
+
return;
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
if (p === "/api/account/memory/summaries" && method === "GET") {
|
|
1476
|
+
const kind = url.searchParams.get("kind");
|
|
1477
|
+
const offset = Number(url.searchParams.get("offset")) || 0;
|
|
1478
|
+
const rows = listSummaries(user.id, { ...(kind === "conv" || kind === "month" ? { kind } : {}), limit: 30, offset });
|
|
1479
|
+
const labels = conversationLabels();
|
|
1480
|
+
sendJson(res, 200, {
|
|
1481
|
+
summaries: rows
|
|
1482
|
+
.filter((s) => s.kind === "month" || !labels.get(s.scope)?.hidden)
|
|
1483
|
+
.map((s) => ({ ...s, ...(s.kind === "conv" ? { convTitle: labels.get(s.scope)?.title ?? "" } : {}) })),
|
|
1415
1484
|
});
|
|
1416
1485
|
return;
|
|
1417
1486
|
}
|
|
1487
|
+
{
|
|
1488
|
+
const m = /^\/api\/account\/memory\/summaries\/(\d+)$/.exec(p);
|
|
1489
|
+
if (m && method === "DELETE") {
|
|
1490
|
+
sendJson(res, 200, { ok: deleteSummary(user.id, Number(m[1])) });
|
|
1491
|
+
return;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
if (p === "/api/account/memory/export" && method === "GET") {
|
|
1495
|
+
const body = JSON.stringify({ ...exportMemory(user.id), summaries: exportSummaries(user.id) }, null, 2);
|
|
1496
|
+
res.writeHead(200, {
|
|
1497
|
+
...SECURITY_HEADERS,
|
|
1498
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
1499
|
+
"Content-Disposition": `attachment; filename="agent-loft-memory-${localDate(Date.now())}.json"`,
|
|
1500
|
+
"Cache-Control": "no-store",
|
|
1501
|
+
});
|
|
1502
|
+
res.end(body);
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
if (p === "/api/account/history/export" && method === "GET") {
|
|
1506
|
+
// 一行一句的 JSONL:聊天记录可能很多,边读边发,不一次读进内存
|
|
1507
|
+
res.writeHead(200, {
|
|
1508
|
+
...SECURITY_HEADERS,
|
|
1509
|
+
"Content-Type": "application/x-ndjson; charset=utf-8",
|
|
1510
|
+
"Content-Disposition": `attachment; filename="agent-loft-chats-${localDate(Date.now())}.jsonl"`,
|
|
1511
|
+
"Cache-Control": "no-store",
|
|
1512
|
+
});
|
|
1513
|
+
try {
|
|
1514
|
+
for (const rows of iterateRecords(user.id)) {
|
|
1515
|
+
if (res.destroyed) return;
|
|
1516
|
+
const chunk = rows.map((r) => JSON.stringify({ conversation: r.k, agent: r.a, role: r.r === "u" ? "user" : "assistant", text: r.t, at: r.ts })).join("\n");
|
|
1517
|
+
if (!res.write(`${chunk}\n`)) await new Promise<void>((resolve) => {
|
|
1518
|
+
res.once("drain", resolve);
|
|
1519
|
+
res.once("close", resolve);
|
|
1520
|
+
});
|
|
1521
|
+
}
|
|
1522
|
+
res.end();
|
|
1523
|
+
} catch (err) {
|
|
1524
|
+
// 响应头已经发了,只能断开:对方看到的是下载失败,不是一个缺了后半截的「成功」文件
|
|
1525
|
+
console.warn("[记忆] 导出聊天记录失败:", err);
|
|
1526
|
+
res.destroy();
|
|
1527
|
+
}
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
if (p === "/api/account/memory/import" && method === "POST") {
|
|
1531
|
+
const body = await readJsonBody<{ summaries?: unknown }>(req, 50 * 1024 * 1024);
|
|
1532
|
+
const result = memoryOp(user.id, () => importMemory(user.id, body));
|
|
1533
|
+
let summaries = 0;
|
|
1534
|
+
for (const s of Array.isArray(body.summaries) ? (body.summaries as Partial<MemorySummary>[]) : []) {
|
|
1535
|
+
if ((s?.kind !== "conv" && s?.kind !== "month") || typeof s.scope !== "string" || typeof s.text !== "string" || !s.text.trim()) continue;
|
|
1536
|
+
// 只补没有的:这里已经有的摘要比导入的新
|
|
1537
|
+
if (readSummary(user.id, s.kind, s.scope)) continue;
|
|
1538
|
+
upsertSummary(user.id, {
|
|
1539
|
+
kind: s.kind,
|
|
1540
|
+
scope: s.scope,
|
|
1541
|
+
title: typeof s.title === "string" ? s.title : "",
|
|
1542
|
+
text: s.text,
|
|
1543
|
+
...(typeof s.project === "string" ? { project: s.project } : {}),
|
|
1544
|
+
fromTs: Number(s.fromTs) || 0,
|
|
1545
|
+
toTs: Number(s.toTs) || 0,
|
|
1546
|
+
});
|
|
1547
|
+
summaries++;
|
|
1548
|
+
}
|
|
1549
|
+
sendJson(res, 200, { ...result, summaries });
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1418
1552
|
if (p === "/api/account/memory/curate" && method === "POST") {
|
|
1419
1553
|
// 「现在整理」:聊完了的对话合起来整理一次。要等模型回来,可能要几十秒
|
|
1420
1554
|
const log = await curateNow(user.id);
|
|
@@ -1446,6 +1580,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1446
1580
|
if (p === "/api/account/history" && method === "DELETE") {
|
|
1447
1581
|
// 清掉聊天记录索引。不再回填:清了就是不想让以前的聊天被搜到,只记以后的
|
|
1448
1582
|
purgeHistory(user.id);
|
|
1583
|
+
// 摘要是从聊天记录写出来的,一起清
|
|
1584
|
+
purgeSummaries(user.id);
|
|
1449
1585
|
writeMeta(user.id, { backfilled: true, extracted: {} });
|
|
1450
1586
|
sendJson(res, 200, { ok: true });
|
|
1451
1587
|
return;
|
|
@@ -1463,12 +1599,28 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1463
1599
|
{
|
|
1464
1600
|
const m = /^\/api\/account\/memory\/items\/(m_[a-f0-9]+)$/.exec(p);
|
|
1465
1601
|
if (m && method === "PATCH") {
|
|
1466
|
-
const body = await readJsonBody<{ text?: string }>(req);
|
|
1467
|
-
|
|
1602
|
+
const body = await readJsonBody<{ text?: string; tier?: string }>(req);
|
|
1603
|
+
const tier = body.tier === "core" || body.tier === "active" || body.tier === "archive" ? body.tier : undefined;
|
|
1604
|
+
if (body.tier !== undefined && !tier) throw new HttpError(400, "tier 只能是 core、active 或 archive");
|
|
1605
|
+
sendJson(
|
|
1606
|
+
res,
|
|
1607
|
+
200,
|
|
1608
|
+
memoryOp(user.id, () => {
|
|
1609
|
+
if (tier) setMemoryTier(user.id, m[1]!, tier);
|
|
1610
|
+
return typeof body.text === "string" ? updateMemoryItem(user.id, m[1]!, body.text) : getMemoryItem(user.id, m[1]!);
|
|
1611
|
+
}),
|
|
1612
|
+
);
|
|
1468
1613
|
return;
|
|
1469
1614
|
}
|
|
1470
1615
|
if (m && method === "DELETE") {
|
|
1471
|
-
|
|
1616
|
+
// ?purge=1:回收站里的彻底删除,连改动记录一起;否则进回收站
|
|
1617
|
+
const purge = url.searchParams.get("purge") === "1";
|
|
1618
|
+
sendJson(res, 200, { ok: !!memoryOp(user.id, () => (purge ? purgeMemoryItem(user.id, m[1]!) : removeMemoryItem(user.id, m[1]!))) });
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
const restore = /^\/api\/account\/memory\/items\/(m_[a-f0-9]+)\/restore$/.exec(p);
|
|
1622
|
+
if (restore && method === "POST") {
|
|
1623
|
+
sendJson(res, 200, memoryOp(user.id, () => restoreMemoryItem(user.id, restore[1]!)));
|
|
1472
1624
|
return;
|
|
1473
1625
|
}
|
|
1474
1626
|
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// 数据库的自动备份:记忆和聊天记录要存很多年,单靠这一个文件不够。
|
|
2
|
+
//
|
|
3
|
+
// 每天一份,放在 <家目录>/backups/db/(AGENT_LOFT_BACKUP_DIR 可以改到别的盘,比如外接硬盘或别的共享目录)。
|
|
4
|
+
// 用 VACUUM INTO 取一份一致的快照(WAL 模式下也安全,不挡别的读写),校验过再压缩,压缩完才算备份成功。
|
|
5
|
+
// 放在 worker 线程里做:库大了要好几秒,不能卡住服务。
|
|
6
|
+
//
|
|
7
|
+
// 保留:最近 7 天每天一份、最近 4 周每周一份、最近 12 个月每月一份,升级前留的那份不自动删。
|
|
8
|
+
//
|
|
9
|
+
// 恢复:停掉服务 → gunzip 备份文件 → 覆盖 data/agent-loft.db → 删掉 agent-loft.db-wal 和 -shm → 启动。
|
|
10
|
+
// 只备份数据库。配置和专家这些是 JSON 文件,不在这里面。
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { Worker } from "node:worker_threads";
|
|
14
|
+
import { home } from "../home.js";
|
|
15
|
+
import { database, dbPath, LEGACY_MEMORY_ITEMS } from "./db.js";
|
|
16
|
+
|
|
17
|
+
const DAY = 86400_000;
|
|
18
|
+
const CHECK_MS = 3600_000;
|
|
19
|
+
const PREFIX = "agent-loft-";
|
|
20
|
+
const SUFFIX = ".db.gz";
|
|
21
|
+
|
|
22
|
+
export function backupDir(): string {
|
|
23
|
+
return process.env.AGENT_LOFT_BACKUP_DIR?.trim() || path.join(home, "backups", "db");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
27
|
+
const dayName = (ts: number) => {
|
|
28
|
+
const d = new Date(ts);
|
|
29
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** 在 worker 里跑:快照 → 校验 → 压缩 → 改名。任何一步失败都不留半截文件 */
|
|
33
|
+
const WORKER = `
|
|
34
|
+
const { workerData, parentPort } = require("node:worker_threads");
|
|
35
|
+
const fs = require("node:fs");
|
|
36
|
+
const zlib = require("node:zlib");
|
|
37
|
+
const { pipeline } = require("node:stream/promises");
|
|
38
|
+
const emit = process.emitWarning;
|
|
39
|
+
process.emitWarning = function (w, ...rest) {
|
|
40
|
+
if (/SQLite/i.test(typeof w === "string" ? w : (w && w.message) || "")) return;
|
|
41
|
+
return emit.call(process, w, ...rest);
|
|
42
|
+
};
|
|
43
|
+
const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
|
|
44
|
+
(async () => {
|
|
45
|
+
const { source, target } = workerData;
|
|
46
|
+
const raw = target + ".tmp-db";
|
|
47
|
+
const gz = target + ".tmp";
|
|
48
|
+
let result = { ok: true };
|
|
49
|
+
try {
|
|
50
|
+
// 上次备份到一半进程被杀留下的:VACUUM INTO 遇到已有的文件会报错,不清掉就再也备份不了
|
|
51
|
+
fs.rmSync(raw, { force: true });
|
|
52
|
+
fs.rmSync(gz, { force: true });
|
|
53
|
+
const db = new DatabaseSync(source);
|
|
54
|
+
db.exec("PRAGMA busy_timeout = 30000");
|
|
55
|
+
db.prepare("VACUUM INTO ?").run(raw);
|
|
56
|
+
db.close();
|
|
57
|
+
const check = new DatabaseSync(raw, { readOnly: true });
|
|
58
|
+
const ok = check.prepare("PRAGMA quick_check").get();
|
|
59
|
+
check.close();
|
|
60
|
+
if (Object.values(ok)[0] !== "ok") throw new Error("备份校验没通过:" + JSON.stringify(ok));
|
|
61
|
+
await pipeline(fs.createReadStream(raw), zlib.createGzip({ level: 6 }), fs.createWriteStream(gz, { mode: 0o600 }));
|
|
62
|
+
fs.renameSync(gz, target);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
fs.rmSync(gz, { force: true });
|
|
65
|
+
result = { ok: false, error: err && err.message ? err.message : String(err) };
|
|
66
|
+
} finally {
|
|
67
|
+
fs.rmSync(raw, { force: true });
|
|
68
|
+
}
|
|
69
|
+
// 临时文件都清完才算结束:主线程收到消息后可能马上又备份一次
|
|
70
|
+
parentPort.postMessage(result);
|
|
71
|
+
})();
|
|
72
|
+
`;
|
|
73
|
+
|
|
74
|
+
function snapshot(target: string): Promise<void> {
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const worker = new Worker(WORKER, { eval: true, workerData: { source: dbPath, target }, execArgv: [] });
|
|
77
|
+
let settled = false;
|
|
78
|
+
worker.once("message", (m: { ok: boolean; error?: string }) => {
|
|
79
|
+
settled = true;
|
|
80
|
+
if (m.ok) resolve();
|
|
81
|
+
else reject(new Error(m.error ?? "备份失败"));
|
|
82
|
+
});
|
|
83
|
+
worker.once("error", (err) => {
|
|
84
|
+
settled = true;
|
|
85
|
+
reject(err);
|
|
86
|
+
});
|
|
87
|
+
worker.once("exit", () => {
|
|
88
|
+
if (!settled) reject(new Error("备份线程意外退出"));
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export type BackupInfo = { name: string; at: number; size: number };
|
|
94
|
+
|
|
95
|
+
/** 现有的每日备份,新的在前 */
|
|
96
|
+
export function listBackups(): BackupInfo[] {
|
|
97
|
+
const dir = backupDir();
|
|
98
|
+
let names: string[];
|
|
99
|
+
try {
|
|
100
|
+
names = fs.readdirSync(dir);
|
|
101
|
+
} catch {
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
const out: BackupInfo[] = [];
|
|
105
|
+
for (const name of names) {
|
|
106
|
+
if (!name.startsWith(PREFIX) || !name.endsWith(SUFFIX)) continue;
|
|
107
|
+
try {
|
|
108
|
+
const st = fs.statSync(path.join(dir, name));
|
|
109
|
+
out.push({ name, at: st.mtimeMs, size: st.size });
|
|
110
|
+
} catch {
|
|
111
|
+
// 刚被删掉
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return out.sort((a, b) => b.at - a.at);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 该留哪些:最近 7 天每天一份,最近 4 周每周最新的一份,最近 12 个月每月最新的一份。
|
|
119
|
+
* 文件名里的日期说了算,不看文件时间(拷过来的文件时间不准)。
|
|
120
|
+
*/
|
|
121
|
+
export function backupsToKeep(names: string[], now = Date.now()): Set<string> {
|
|
122
|
+
const dated = names
|
|
123
|
+
.map((name) => ({ name, m: /(\d{4})-(\d{2})-(\d{2})/.exec(name) }))
|
|
124
|
+
.filter((x): x is { name: string; m: RegExpExecArray } => !!x.m)
|
|
125
|
+
.map((x) => ({ name: x.name, at: new Date(Number(x.m[1]), Number(x.m[2]) - 1, Number(x.m[3])).getTime() }))
|
|
126
|
+
.sort((a, b) => b.at - a.at);
|
|
127
|
+
const keep = new Set<string>();
|
|
128
|
+
const weeks = new Set<number>();
|
|
129
|
+
const months = new Set<string>();
|
|
130
|
+
for (const { name, at } of dated) {
|
|
131
|
+
const age = (now - at) / DAY;
|
|
132
|
+
if (age < 7) keep.add(name);
|
|
133
|
+
const week = Math.floor(at / (7 * DAY));
|
|
134
|
+
if (age < 28 && !weeks.has(week)) {
|
|
135
|
+
weeks.add(week);
|
|
136
|
+
keep.add(name);
|
|
137
|
+
}
|
|
138
|
+
const d = new Date(at);
|
|
139
|
+
const month = `${d.getFullYear()}-${d.getMonth()}`;
|
|
140
|
+
if (age < 366 && !months.has(month)) {
|
|
141
|
+
months.add(month);
|
|
142
|
+
keep.add(name);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return keep;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function prune(now: number): void {
|
|
149
|
+
const dir = backupDir();
|
|
150
|
+
const names = listBackups().map((b) => b.name);
|
|
151
|
+
const keep = backupsToKeep(names, now);
|
|
152
|
+
for (const name of names) if (!keep.has(name)) fs.rmSync(path.join(dir, name), { force: true });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 同一时间只做一份 */
|
|
156
|
+
let running: Promise<BackupInfo> | undefined;
|
|
157
|
+
let lastError: { at: number; message: string } | undefined;
|
|
158
|
+
|
|
159
|
+
/** 现在备份一份。同一天再备份就覆盖那天的 */
|
|
160
|
+
export function backupNow(now = Date.now()): Promise<BackupInfo> {
|
|
161
|
+
if (running) return running;
|
|
162
|
+
running = (async () => {
|
|
163
|
+
const dir = backupDir();
|
|
164
|
+
const name = `${PREFIX}${dayName(now)}${SUFFIX}`;
|
|
165
|
+
const target = path.join(dir, name);
|
|
166
|
+
try {
|
|
167
|
+
// 目录建不了(外接盘没挂上、没权限)也算备份失败,要记下来让设置页显示
|
|
168
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
169
|
+
database();
|
|
170
|
+
await snapshot(target);
|
|
171
|
+
prune(now);
|
|
172
|
+
lastError = undefined;
|
|
173
|
+
const size = fs.statSync(target).size;
|
|
174
|
+
console.log(`[备份] 数据库已备份到 ${target}(${(size / 1048576).toFixed(1)} MB)`);
|
|
175
|
+
return { name, at: Date.now(), size };
|
|
176
|
+
} catch (err) {
|
|
177
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
178
|
+
lastError = { at: Date.now(), message };
|
|
179
|
+
console.error("[备份] 备份失败:", message);
|
|
180
|
+
throw err;
|
|
181
|
+
}
|
|
182
|
+
})().finally(() => {
|
|
183
|
+
running = undefined;
|
|
184
|
+
});
|
|
185
|
+
return running;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function backupStatus(): { dir: string; last?: BackupInfo; count: number; error?: { at: number; message: string } } {
|
|
189
|
+
const all = listBackups();
|
|
190
|
+
return { dir: backupDir(), ...(all[0] ? { last: all[0] } : {}), count: all.length, ...(lastError ? { error: lastError } : {}) };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 最新的备份距今超过一天就备份 */
|
|
194
|
+
async function backupIfDue(now = Date.now()): Promise<void> {
|
|
195
|
+
const last = listBackups()[0];
|
|
196
|
+
if (last && now - last.at < DAY) return;
|
|
197
|
+
await backupNow(now).catch(() => {});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
let timer: NodeJS.Timeout | undefined;
|
|
201
|
+
|
|
202
|
+
export function startBackups(): void {
|
|
203
|
+
if (timer) return;
|
|
204
|
+
// 启动时的事多,缓一缓
|
|
205
|
+
setTimeout(() => void backupIfDue(), 120_000).unref();
|
|
206
|
+
timer = setInterval(() => void backupIfDue(), CHECK_MS);
|
|
207
|
+
timer.unref();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 还有条目存在老格式里要搬表、或者要补删已删除对话的记录:同步留一份升级前的备份(不压缩,这时候也不能等)。
|
|
212
|
+
* 这份不参与自动清理,要手动删。
|
|
213
|
+
*/
|
|
214
|
+
export function backupBeforeMigration(): string | undefined {
|
|
215
|
+
const d = database();
|
|
216
|
+
const pending =
|
|
217
|
+
d.prepare(`SELECT 1 FROM memory WHERE ${LEGACY_MEMORY_ITEMS} LIMIT 1`).get() ||
|
|
218
|
+
// 从老版本升上来、还没清过已删除对话的:这一步也会删数据(memory-items 搬完后才可能只剩这一步)
|
|
219
|
+
(d.prepare("SELECT 1 FROM history LIMIT 1").get() && !d.prepare("SELECT 1 FROM migrations WHERE name = 'memory-hidden-conversations-purged'").get());
|
|
220
|
+
if (!pending) return undefined;
|
|
221
|
+
const dir = backupDir();
|
|
222
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
223
|
+
const target = path.join(dir, `before-memory-upgrade-${Date.now()}.db`);
|
|
224
|
+
d.prepare("VACUUM INTO ?").run(target);
|
|
225
|
+
fs.chmodSync(target, 0o600);
|
|
226
|
+
console.log(`[备份] 升级记忆前留了一份备份:${target}`);
|
|
227
|
+
return target;
|
|
228
|
+
}
|