agent-loft 0.2.58 → 0.2.60

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
@@ -44,7 +44,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
44
44
  - 回复逐字显示,markdown 和代码高亮,思考过程和工具调用可以折叠;每条回复下方显示用时、费用和完成时间,可以复制,也可以「从这里分叉」成一条新会话(原会话不动);自己发的消息也能一键复制。
45
45
  - agent 做多步骤的活时列的任务清单显示在输入框上方,看得到做到第几项、正在做哪一项。
46
46
  - 授权卡、提问卡直接在页面上点。
47
- - 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,开新会话或切换目录时清理。
47
+ - 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,发出去的都收进资料库,开新会话、切换目录也不删。
48
48
  - 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。
49
49
  - **回复里的图**:专家和 agent 在回复里写 ```` ```chart ````(一段 JSON:折线、面积、柱状、饼图、散点)就画成可悬停的图,可以切到表格看具体数字;写 ```` ```mermaid ```` 画流程图、时序图等。跟着系统深浅色走,图库用到时才加载;飞书上 chart 换成表格。写法自动附在每个专家(包括内置的 Claude Code、Codex)的提示词里。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
50
50
  - 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
@@ -62,7 +62,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
62
62
  - 回复底部的 token 数自动按大小显示为 K、M 等单位。
63
63
  - 侧栏按页加载:每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
64
64
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
65
- - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
65
+ - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。
66
66
  - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
67
67
  - 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
68
68
  - **网页多服务器切换**:在 设置 → 服务器 添加其他 agent-loft,再点「授权」到对方页面确认,侧栏左上角就能切换;各台分别登录,切走后保持连接,列表显示待处理数和运行状态,刷新后保留选择。几台需使用同一主域名下的 HTTPS 地址(例如 `mac.example.com`、`nas.example.com`)。在外层页面开启系统通知后,各台的提醒都能推到同一个主屏幕 App,点通知自动切到对应服务器和对话。见[使用指南](docs/产品介绍.md#在网页和手机上切换多台服务器)。
@@ -85,6 +85,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
85
85
  - **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关)。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理选中专家的对话;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话)。聊天记录索引不开记忆也会记(侧栏的「搜索」也用它),升级后会把已有对话收录进来一次;没开记忆时记进来的不拿去整理。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
86
86
  - **定时任务**:像 ChatGPT 的 Tasks,侧栏的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
87
87
  - **技能(skills)**:设置 → 技能。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。每人管自己的,不做分享和技能广场(以前从别人那装过的照常能用,可以卸载)。**使用**:内置专家能用你启用的全部技能,自定义专家只用它选中的;agent 遇到对得上的事自己用。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
88
+ - **资料库**:像 ChatGPT 的资料库,侧栏的「资料库」。对话里发过的附件、agent 回复里给出的、这一轮新写出来的图片 / 文档 / 音视频(复制一份收进来,之后原文件改了删了不影响)都汇总在这里:按图片 / 文档 / 音视频筛、按文件名搜,点开看大图或下载,「在新对话里用」,单个或批量删除(文件从磁盘上删掉)。输入框的「+」也能「从资料库选」。从资料库拿到对话里的文件硬链接进那条对话的上传目录,不占双份空间,agent 照常能读。按人隔离,规则同对话:自己的;没主人的对话(飞书群聊等)的归管理员。上传了一直没发出去的一天后清掉,对话被删的连同文件一起删。
88
89
  - **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
89
90
  - 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,工具栏上选画质:流畅 / 标准(默认)/ 高清由服务端把画面缩小到长边 1280 / 1920 / 2560、只把变了的地方压成 JPEG 发过来(macOS 屏幕共享只给无损的 ZRLE,5K 屏一整屏 30MB,原样转发隔着公网几秒一帧),原画是原样转发、只适合局域网;远程那边接了几块屏时可以只看其中一块(按系统里的显示器名称选,服务端只截那块再缩,比几块屏拼在一起缩小清楚得多;macOS 的各块屏位置要从屏幕共享发来的画面里学,第一次连上要几秒,原画下不能选);可以缩放到窗口或按原始大小看、全屏(手机上也能,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 的用户名和登录密码(苹果认证,由服务端登录)。
90
91
  - 终端:新终端开在当前对话的工作目录里,可以开多个标签;`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 上软键盘弹出来时这排键会垫到键盘上面。
@@ -93,7 +94,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
93
94
 
94
95
  ## 安装
95
96
 
96
- 需要 Linux 或 macOS,Node.js 22 及以上。
97
+ 需要 Linux 或 macOS,Node.js 22.13 及以上。
97
98
 
98
99
  ```bash
99
100
  npm install -g agent-loft # 或者在仓库里 npm install 后用 node bin/cli.js
@@ -121,8 +122,8 @@ agent-loft service install # 注册为开机自启服务(systemd / laun
121
122
  - 菜单栏图标:悬停看各服务器的 Claude / Codex 额度、待处理和运行中的会话;双击打开主窗口。同一个账号的额度只查一次。(Windows 上点托盘图标弹出;Linux 上在托盘菜单里点「额度和待处理」。)
122
123
  - 菜单栏图标可以换成额度条:Claude、Codex 各是一只像素小宠物,看样子就知道是谁,身子是 5 小时额度,下面一条是周额度。桌面端设置 → 额度显示 →「菜单栏显示额度」,选所有服务器合起来(取最高),或者按服务器分别选 Claude / Codex(图标上不写服务器名);都不选就只显示图标。「额度条显示」选实心表示剩余额度(默认,像电池)还是已用额度。只有 macOS 有,Windows / Linux 的托盘图标太小放不下。
123
124
  - 支持前面挡着 Cloudflare Access 的服务器:验证页直接在窗口里完成,过期会提醒;也可以配 Service Token 免验证。
124
- - 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew 装)并开机自启,装好自动连上;设置里可以改成「只在桌面端运行时运行」(不开机自启,打开桌面端时启动、退出时停止)。Linux 上一样(需要先装好 Node.js 22+,开机自启用 systemd 用户服务);Windows 上服务端还没有开机自启,可以在 WSL 里装,桌面端会自动检测到 `127.0.0.1` 上的它。防休眠:本机有会话在跑时不休眠;另有永不休眠、定时休眠(设休眠时段,时段外不休眠,时段内本机没有会话在跑、屏幕锁上后让 Mac 睡下去)和合盖不休眠(macOS,第一次开关要输管理员密码,之后不用;开着时闲置也不睡,定时休眠到点会临时关掉它让 Mac 睡下去,醒来再打开)。
125
- - 顶栏「更多」→「用量汇总」:把所有已添加服务器的用量,加上这台电脑上直接用的 Claude Code、Codex(桌面端和 CLI,读它们自己的会话记录),合在一起看。按日 / 月 / 年统计 token 和金额,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按来源。本机直接用的金额按模型单价估算;Agent Loft 自己跑的会话只算在服务器里,不重复算。不在线、没登录或服务端太旧的服务器不计入,页面上会注明。
125
+ - 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew 装)并开机自启,装好自动连上;设置里可以改成「只在桌面端运行时运行」(不开机自启,打开桌面端时启动、退出时停止)。Linux 上一样(需要先装好 Node.js 22.13+,开机自启用 systemd 用户服务);Windows 上服务端还没有开机自启,可以在 WSL 里装,桌面端会自动检测到 `127.0.0.1` 上的它。防休眠:本机有会话在跑时不休眠;另有永不休眠、定时休眠(设休眠时段,时段外不休眠,时段内本机没有会话在跑、屏幕锁上后让 Mac 睡下去)和合盖不休眠(macOS,第一次开关要输管理员密码,之后不用;开着时闲置也不睡,定时休眠到点会临时关掉它让 Mac 睡下去,醒来再打开)。
126
+ - 顶栏服务器标签后面的用量按钮(柱状图图标)打开「用量汇总」:把所有已添加服务器的用量,加上这台电脑上直接用的 Claude Code、Codex(桌面端和 CLI,读它们自己的会话记录),合在一起看。按日 / 月 / 年统计 token 和金额,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按来源。本机直接用的金额按模型单价估算;Agent Loft 自己跑的会话只算在服务器里,不重复算。不在线、没登录或服务端太旧的服务器不计入,页面上会注明。
126
127
  - 设置(`⌘,`)的服务器列表里展开某台服务器,能看它的 Agent 环境和版本,有新版本时点「升级服务端」;桌面端自己的更新在同一页的「更新」里点「更新并重启」。
127
128
 
128
129
  桌面端只是个壳(代码在 `desktop/`),服务端照常用 npm 安装和升级。
@@ -134,7 +135,7 @@ npm install -g --prefix "$HOME/.local" agent-loft
134
135
  PATH="$HOME/.local/bin:$PATH" "$HOME/.local/bin/agent-loft" service install
135
136
  ```
136
137
 
137
- 第一条成功后再执行第二条,然后重新打开桌面端,选择连接本机服务端即可。需要 Node.js 22 以上。
138
+ 第一条成功后再执行第二条,然后重新打开桌面端,选择连接本机服务端即可。需要 Node.js 22.13 以上。
138
139
 
139
140
  ### 从旧桥接器迁移
140
141
 
@@ -178,7 +179,7 @@ agent-loft service install
178
179
  - 审批超时一律按拒绝处理。Codex 默认沙箱为 `workspace-write`,不会因为 `~/.codex/config.toml` 里配了 `never` 或 `danger-full-access` 就绕过审批。
179
180
  - agent 子进程拿不到本服务自己的凭据(`FEISHU_*`、`AGENT_LOFT_*` 等环境变量会被剔除)。
180
181
  - 技能存在 `data/skills/`:技能本体在 `files/<技能 id>/`,每个人装了哪些、变量的值在 `users/<用户 id>.json`(0600)。普通变量注入到会话环境里,agent 能读到;受保护的密钥 agent 看不到值,但和多用户一样不是安全边界——能读文件的专家(包括内置的 Claude Code / Codex)能直接读这些文件。别人分享的技能会在你的会话里照着执行,装之前在技能页点开看一眼它要做什么、要哪些变量。
181
- - 记忆存在 `data/memory/<用户 id>.json`,聊天记录索引在 `data/history/<用户 id>.jsonl`。记给谁由 agent-loft 在拉起记忆工具时定死(工具参数里没有用户),模型想写别人的记忆也写不了;但和多用户一样不是安全边界:能读文件的专家能读到这些文件。只能联网的专家没有读写本机文件的工具,网页里的提示注入也骗不走本机文件。
182
+ - 记忆和聊天记录索引都存在 `data/agent-loft.db`(SQLite,会话、脚注、用量也在里面)。记给谁由 agent-loft 在拉起记忆工具时定死(工具参数里没有用户),模型想写别人的记忆也写不了;但和多用户一样不是安全边界:能读文件的专家能读到这个数据库文件。只能联网的专家没有读写本机文件的工具,网页里的提示注入也骗不走本机文件。
182
183
  - 专家存在 `data/experts.json`,MCP 存在 `data/mcp.json`(0600,含 MCP 的密钥值)。和技能一样不是安全边界:能读文件的专家读得到。
183
184
 
184
185
  ## 结构
@@ -192,12 +193,14 @@ src/
192
193
  config.ts 配置(Web 可改,改完热加载)
193
194
  users.ts Web 登录用户和归属规则(谁能看到哪条会话)
194
195
  memory.ts 记忆的存储和注入系统提示的那段文字;personal.ts 定记忆用谁的
195
- chat-history.ts 聊天记录索引(每人一个 JSONL)和关键词搜索
196
+ chat-history.ts 聊天记录索引(数据库的 history 表)和关键词搜索
196
197
  memory-curator.ts 录入聊天、回填已有对话、聊完后自动整理记忆
197
198
  feishu-links.ts 飞书账号 ↔ 用户的绑定和绑定码
198
199
  experts.ts 专家的存储、校验,开会话时解析成交给 agent 的配置(MCP、技能、子智能体)
199
200
  expert-prompt.ts 专家告诉 agent 的话(Claude 换系统提示或追加,Codex 附在消息后面)
200
201
  mcp.ts MCP 的存储(按人)、机器上原有的 MCP
202
+ library.ts 资料库:文件索引(数据库的 files 表)、收录用户发的附件和 agent 生成的文件、启动时收拾上传目录
203
+ db.ts 数据库(data/agent-loft.db):建表、导入升级前的 JSON
201
204
  tasks.ts 定时任务的存储(按人隔离);task-schedule.ts 频率和 cron;task-prompt.ts 每次运行附给 agent 的说明和静默暗号
202
205
  task-runner.ts 定时任务的调度:到点核对主人和对话、送进对话、记下结果
203
206
  tasks-bridge.ts 定时任务工具在主进程这头:核对签名、弹授权卡、增删改(tasks-mcp.ts 定怎么拉起);技能工具也走这条通道
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.58",
3
+ "version": "0.2.60",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -23,7 +23,7 @@
23
23
  "url": "git+https://github.com/qijieinnet/agent-loft.git"
24
24
  },
25
25
  "engines": {
26
- "node": ">=22"
26
+ "node": ">=22.13"
27
27
  },
28
28
  "bin": {
29
29
  "agent-loft": "bin/cli.js",
@@ -42,7 +42,7 @@ import {
42
42
  } from "../../core/memory.js";
43
43
  import { createLinkCode, listLinks, unlink, unlinkUser } from "../../core/feishu-links.js";
44
44
  import { purgeUserData } from "../../core/personal.js";
45
- import { purgeHistory, readMeta, readRecords, searchHistory, writeMeta } from "../../core/chat-history.js";
45
+ import { countRecords, purgeHistory, readMeta, searchHistory, writeMeta } from "../../core/chat-history.js";
46
46
  import { curateNow, pendingCount } from "../../core/memory-curator.js";
47
47
  import { listAllowlist, setAllowlist } from "../../agents/claude/permissions.js";
48
48
  import { agentAvailability, agentHealth, invalidateHealth } from "../../agents/health.js";
@@ -70,6 +70,8 @@ import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
70
70
  import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor, searchConvs } from "./conv-pages.js";
71
71
  import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
72
72
  import { handleTasksApi } from "./tasks-api.js";
73
+ import { handleLibraryApi } from "./library-api.js";
74
+ import { attachToConversation, canSeeFile, getLibraryFile } from "../../core/library.js";
73
75
  import { handleSkillsApi } from "./skills-api.js";
74
76
  import { handleExpertsApi } from "./experts-api.js";
75
77
  import { canUseExpert, getExpert, isBuiltin, listExperts } from "../../core/experts.js";
@@ -757,6 +759,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
757
759
 
758
760
  // ----- 定时任务 -----
759
761
  if (p.startsWith("/api/tasks") && (await handleTasksApi(req, res, p, user))) return;
762
+ if (p.startsWith("/api/library") && (await handleLibraryApi(req, res, p, user))) return;
760
763
  if (p.startsWith("/api/skills") && (await handleSkillsApi(req, res, url, user))) return;
761
764
  if ((p.startsWith("/api/experts") || p.startsWith("/api/mcp")) && (await handleExpertsApi(req, res, p, user))) return;
762
765
  if (p.startsWith("/api/terminals") && (await handleTerminalApi(req, res, p, user))) return;
@@ -1018,6 +1021,27 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1018
1021
  sendJson(res, 200, { id, name: attachment.name, kind: attachment.kind, size: attachment.size });
1019
1022
  return;
1020
1023
  }
1024
+ // 从资料库拿来用:{ ids: [...] },放进这条对话的上传目录,和刚上传的一样领个编号,发消息时认领
1025
+ if (sub === "attach" && method === "POST") {
1026
+ const body = await readJsonBody<{ ids?: unknown }>(req);
1027
+ if (!Array.isArray(body.ids) || body.ids.length === 0) throw new HttpError(400, "要给出用哪些文件");
1028
+ const out = body.ids.slice(0, 20).map((fid) => {
1029
+ const file = typeof fid === "string" ? getLibraryFile(fid) : undefined;
1030
+ if (!file || file.source === "copy" || !canSeeFile(user, file) || !fs.existsSync(file.path)) throw new HttpError(404, "资料库里没有这个文件(可能已经删了)");
1031
+ const attachment = attachToConversation(file, key);
1032
+ const id = crypto.randomBytes(8).toString("hex");
1033
+ uploads.set(id, { key, attachment, at: Date.now() });
1034
+ return {
1035
+ id,
1036
+ name: attachment.name,
1037
+ kind: attachment.kind,
1038
+ size: attachment.size,
1039
+ ...(attachment.kind === "image" ? { url: `/api/file?path=${encodeURIComponent(attachment.path)}` } : {}),
1040
+ };
1041
+ });
1042
+ sendJson(res, 200, { uploads: out });
1043
+ return;
1044
+ }
1021
1045
  if (sub === "fork" && method === "POST") {
1022
1046
  const body = await readJsonBody<{ anchor?: string }>(req);
1023
1047
  const anchor = typeof body.anchor === "string" && body.anchor ? body.anchor : undefined;
@@ -1273,8 +1297,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1273
1297
  }
1274
1298
  if (p === "/api/account/history" && method === "GET") {
1275
1299
  // 只给数量:索引里有多少句、来自多少段对话
1276
- const records = readRecords(user.id);
1277
- sendJson(res, 200, { count: records.length, conversations: new Set(records.map((r) => r.k)).size });
1300
+ sendJson(res, 200, countRecords(user.id));
1278
1301
  return;
1279
1302
  }
1280
1303
  if (p === "/api/account/history" && method === "DELETE") {
@@ -0,0 +1,59 @@
1
+ // 资料库页面的接口:/api/library。每个人只看得到、删得了自己的文件(别人的一律当不存在),规则见 core/library.ts。
2
+ // 放进对话里用的接口在 api.ts(/api/conversations/<key>/attach),要和上传的附件一起认领。
3
+ import type { IncomingMessage, ServerResponse } from "node:http";
4
+ import { canSeeFile, deleteLibraryFile, getLibraryFile, librarySummary, listLibrary, type LibraryFile, type LibraryKind } from "../../core/library.js";
5
+ import { getConversation } from "../../core/store.js";
6
+ import type { User } from "../../core/users.js";
7
+ import { HttpError, readJsonBody, sendJson } from "./http.js";
8
+
9
+ export function fileView(f: LibraryFile) {
10
+ const conv = getConversation(f.convKey);
11
+ return {
12
+ id: f.id,
13
+ name: f.name,
14
+ kind: f.kind,
15
+ size: f.size,
16
+ source: f.source,
17
+ createdAt: f.createdAt,
18
+ url: `/api/file?path=${encodeURIComponent(f.path)}`,
19
+ conv: { key: f.convKey, title: conv?.title ?? "", ...(conv?.hidden ? { hidden: true } : {}) },
20
+ };
21
+ }
22
+
23
+ const KINDS = new Set<LibraryKind>(["image", "file", "media"]);
24
+
25
+ export async function handleLibraryApi(req: IncomingMessage, res: ServerResponse, p: string, user: User): Promise<boolean> {
26
+ const method = req.method ?? "GET";
27
+ const url = new URL(req.url ?? "/", "http://x");
28
+
29
+ if (p === "/api/library" && method === "GET") {
30
+ const kind = url.searchParams.get("kind") as LibraryKind | null;
31
+ const beforeAt = Number(url.searchParams.get("beforeAt"));
32
+ const beforeId = url.searchParams.get("beforeId");
33
+ const { files, more } = listLibrary(user, {
34
+ ...(kind && KINDS.has(kind) ? { kind } : {}),
35
+ q: url.searchParams.get("q") ?? "",
36
+ ...(beforeId && Number.isFinite(beforeAt) ? { before: { at: beforeAt, id: beforeId } } : {}),
37
+ limit: Number(url.searchParams.get("limit")) || 60,
38
+ });
39
+ sendJson(res, 200, { files: files.map(fileView), more, summary: librarySummary(user) });
40
+ return true;
41
+ }
42
+
43
+ // 删掉几个(批量):{ ids: [...] }。别人的、不存在的跳过,返回实际删了几个
44
+ if (p === "/api/library/delete" && method === "POST") {
45
+ const body = await readJsonBody<{ ids?: unknown }>(req);
46
+ if (!Array.isArray(body.ids) || body.ids.length === 0) throw new HttpError(400, "要给出删哪些文件");
47
+ let deleted = 0;
48
+ for (const id of body.ids.slice(0, 500)) {
49
+ const file = typeof id === "string" ? getLibraryFile(id) : undefined;
50
+ if (!file || file.source === "copy" || !canSeeFile(user, file)) continue;
51
+ deleteLibraryFile(file);
52
+ deleted++;
53
+ }
54
+ sendJson(res, 200, { deleted, summary: librarySummary(user) });
55
+ return true;
56
+ }
57
+
58
+ return false;
59
+ }
@@ -1,16 +1,14 @@
1
1
  // 聊天记录索引:给「参考以前的聊天」(search_past_chats)和「聊完自动整理记忆」用。
2
2
  //
3
- // 每个用户一份,data/history/<用户 id>.jsonl,一行一句(用户说的 / agent 的最终回复)。
3
+ // 存在数据库的 history 表里(见 db.ts),一行一句(用户说的 / agent 的最终回复),按用户分开。
4
4
  // 只收有主人的对话(见 personal.ts 的 memoryOwnerOf),按主人分开存 —— 搜索只在自己的里面搜。
5
5
  // 来源两个:
6
6
  // - 实时:hub 的事件流(见 startHistoryCapture),从现在起说的话;
7
7
  // - 回填:第一次用时把已有对话从 agent 的记录里读一遍(见 memory-curator.ts),只做一次。
8
8
  //
9
- // 为什么不用 SQLite 全文索引:FTS5 的 trigram 分词搜不到两个字的中文词(「豆豆」),
10
- // 个人的聊天量直接扫文件就够快(几万句也是毫秒级),也省得 MCP 子进程每次打实验性 API 的警告。
11
- import fs from "node:fs";
12
- import path from "node:path";
13
- import { dataDir, readJson, writeJsonAtomic } from "../home.js";
9
+ // 搜索不用 SQLite 的 FTS5:trigram 分词搜不到两个字的中文词(「豆豆」)。先用 instr 在库里筛出
10
+ // 含有某个词的句子,再在这里按命中情况打分,不用把整个人的记录都读出来。
11
+ import { sql, transaction } from "./db.js";
14
12
 
15
13
  export type HistoryRecord = {
16
14
  /** 实时用户消息的编号,撤销排队消息时用于精确移除 */
@@ -48,61 +46,69 @@ export type Meta = {
48
46
  lastCuration?: CurationLog;
49
47
  };
50
48
 
51
- const historyDir = path.join(dataDir, "history");
52
49
  /** 一句话最多存这么多字:长篇代码、整页网页没必要全存 */
53
50
  const TEXT_MAX = 4000;
54
51
 
55
- function base(userId: string): string {
52
+ function checkUser(userId: string): string {
56
53
  if (!/^[A-Za-z0-9_]{1,64}$/.test(userId)) throw new Error("用户 id 不合法");
57
- return path.join(historyDir, userId);
54
+ return userId;
55
+ }
56
+
57
+ type Row = { id: number; conv_key: string; agent: string; role: "u" | "a"; text: string; ts: number; msg_id: string | null };
58
+
59
+ const COLUMNS = "id, conv_key, agent, role, text, ts, msg_id";
60
+
61
+ function toRecord(row: Row): HistoryRecord {
62
+ return { ...(row.msg_id ? { id: row.msg_id } : {}), k: row.conv_key, a: row.agent, r: row.role, t: row.text, ts: row.ts };
63
+ }
64
+
65
+ function insertRecords(userId: string, records: HistoryRecord[]): void {
66
+ const insert = sql("INSERT INTO history (user_id, conv_key, agent, role, text, ts, msg_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
67
+ for (const r of records) insert.run(userId, r.k, r.a, r.r, r.t.slice(0, TEXT_MAX), r.ts, r.id ?? null);
58
68
  }
59
69
 
60
70
  export function appendRecords(userId: string, records: HistoryRecord[]): void {
71
+ checkUser(userId);
61
72
  if (records.length === 0) return;
62
- fs.mkdirSync(historyDir, { recursive: true, mode: 0o700 });
63
- const lines = records.map((r) => JSON.stringify({ ...r, t: r.t.slice(0, TEXT_MAX) })).join("\n");
64
- fs.appendFileSync(`${base(userId)}.jsonl`, `${lines}\n`, { mode: 0o600 });
73
+ transaction(() => insertRecords(userId, records));
65
74
  }
66
75
 
76
+ /** 这个用户的全部记录,按记下的先后 */
67
77
  export function readRecords(userId: string): HistoryRecord[] {
68
- let raw: string;
69
- try {
70
- raw = fs.readFileSync(`${base(userId)}.jsonl`, "utf8");
71
- } catch {
72
- return [];
73
- }
74
- const out: HistoryRecord[] = [];
75
- for (const line of raw.split("\n")) {
76
- if (!line) continue;
77
- try {
78
- const r = JSON.parse(line) as HistoryRecord;
79
- if (typeof r.k === "string" && typeof r.t === "string" && (r.r === "u" || r.r === "a")) out.push(r);
80
- } catch {
81
- // 写到一半被打断的行:跳过
82
- }
83
- }
84
- return out;
78
+ checkUser(userId);
79
+ return (sql(`SELECT ${COLUMNS} FROM history WHERE user_id = ? ORDER BY id`).all(userId) as Row[]).map(toRecord);
85
80
  }
86
81
 
87
- function rewriteRecords(userId: string, records: HistoryRecord[]): void {
88
- fs.mkdirSync(historyDir, { recursive: true, mode: 0o700 });
89
- const target = `${base(userId)}.jsonl`;
90
- const temporary = `${target}.tmp`;
91
- fs.writeFileSync(temporary, records.map((r) => JSON.stringify({ ...r, t: r.t.slice(0, TEXT_MAX) })).join("\n") + (records.length ? "\n" : ""), { mode: 0o600 });
92
- fs.renameSync(temporary, target);
82
+ /** 有多少句、来自多少段对话 */
83
+ export function countRecords(userId: string): { count: number; conversations: number } {
84
+ checkUser(userId);
85
+ const row = sql("SELECT count(*) AS n, count(DISTINCT conv_key) AS c FROM history WHERE user_id = ?").get(userId) as { n: number; c: number };
86
+ return { count: row.n, conversations: row.c };
93
87
  }
94
88
 
95
89
  export function removeHistoryRecord(userId: string, key: string, id: string): void {
96
- rewriteRecords(userId, readRecords(userId).filter((r) => r.k !== key || r.id !== id));
90
+ checkUser(userId);
91
+ sql("DELETE FROM history WHERE user_id = ? AND conv_key = ? AND msg_id = ?").run(userId, key, id);
97
92
  }
98
93
 
99
94
  /** 回退后只保留当前对话剩下的内容,避免搜索再搜出已经移除的消息 */
100
95
  export function replaceConversationRecords(userId: string, key: string, records: HistoryRecord[]): void {
101
- rewriteRecords(userId, [...readRecords(userId).filter((r) => r.k !== key), ...records]);
96
+ checkUser(userId);
97
+ transaction(() => {
98
+ sql("DELETE FROM history WHERE user_id = ? AND conv_key = ?").run(userId, key);
99
+ insertRecords(userId, records);
100
+ });
102
101
  }
103
102
 
104
103
  export function readMeta(userId: string): Meta {
105
- const m = readJson<Partial<Meta>>(`${base(userId)}.meta.json`, {});
104
+ checkUser(userId);
105
+ const row = sql("SELECT data FROM history_meta WHERE user_id = ?").get(userId) as { data: string } | undefined;
106
+ let m: Partial<Meta> = {};
107
+ try {
108
+ m = row ? (JSON.parse(row.data) as Partial<Meta>) : {};
109
+ } catch {
110
+ // 坏了就当没有
111
+ }
106
112
  return { ...m, extracted: m.extracted && typeof m.extracted === "object" ? m.extracted : {} };
107
113
  }
108
114
 
@@ -111,20 +117,25 @@ export function patchMeta(userId: string, patch: Partial<Meta>): void {
111
117
  }
112
118
 
113
119
  export function writeMeta(userId: string, meta: Meta): void {
114
- fs.mkdirSync(historyDir, { recursive: true, mode: 0o700 });
115
- writeJsonAtomic(`${base(userId)}.meta.json`, meta);
120
+ checkUser(userId);
121
+ sql("INSERT OR REPLACE INTO history_meta (user_id, data) VALUES (?, ?)").run(userId, JSON.stringify(meta));
116
122
  }
117
123
 
118
124
  export function markExtracted(userId: string, key: string, upTo: number): void {
119
- const meta = readMeta(userId);
120
- meta.extracted[key] = Math.max(meta.extracted[key] ?? 0, upTo);
121
- writeMeta(userId, meta);
125
+ transaction(() => {
126
+ const meta = readMeta(userId);
127
+ meta.extracted[key] = Math.max(meta.extracted[key] ?? 0, upTo);
128
+ writeMeta(userId, meta);
129
+ });
122
130
  }
123
131
 
124
132
  /** 删用户时:整个删掉 */
125
133
  export function purgeHistory(userId: string): void {
126
- fs.rmSync(`${base(userId)}.jsonl`, { force: true });
127
- fs.rmSync(`${base(userId)}.meta.json`, { force: true });
134
+ checkUser(userId);
135
+ transaction(() => {
136
+ sql("DELETE FROM history WHERE user_id = ?").run(userId);
137
+ sql("DELETE FROM history_meta WHERE user_id = ?").run(userId);
138
+ });
128
139
  }
129
140
 
130
141
  /**
@@ -137,9 +148,13 @@ export function pendingConversations(
137
148
  now = Date.now(),
138
149
  ): { key: string; records: HistoryRecord[]; last: number }[] {
139
150
  const meta = readMeta(userId);
151
+ // 每条对话整理到的时刻在 meta 里,交给 json_each 在库里比,只取还没整理过的
152
+ const rows = sql(
153
+ `SELECT h.id, h.conv_key, h.agent, h.role, h.text, h.ts, h.msg_id FROM history h LEFT JOIN json_each(?) e ON e.key = h.conv_key
154
+ WHERE h.user_id = ? AND h.ts > coalesce(e.value, 0) ORDER BY h.id`,
155
+ ).all(JSON.stringify(meta.extracted), userId) as Row[];
140
156
  const byKey = new Map<string, HistoryRecord[]>();
141
- for (const r of readRecords(userId)) {
142
- if (r.ts <= (meta.extracted[r.k] ?? 0)) continue;
157
+ for (const r of rows.map(toRecord)) {
143
158
  let list = byKey.get(r.k);
144
159
  if (!list) byKey.set(r.k, (list = []));
145
160
  list.push(r);
@@ -230,38 +245,44 @@ export function searchHistory(
230
245
  query: string,
231
246
  opts: { limit?: number; skip?: (key: string) => boolean; now?: number } = {},
232
247
  ): SearchHit[] {
233
- const records = readRecords(userId);
248
+ checkUser(userId);
249
+ // 能得分的句子至少含有一个词(长的中文词是至少含有它的一个两字组合),先在库里筛出来
250
+ const needles = [...new Set(terms(query).flatMap((t) => (isCjk(t) && t.length >= 4 ? [t, ...bigrams(t)] : [t])))].slice(0, 200);
251
+ if (needles.length === 0) return [];
252
+ const rows = sql(
253
+ `SELECT ${COLUMNS} FROM history WHERE user_id = ? AND (${needles.map(() => "instr(lower(text), ?) > 0").join(" OR ")})`,
254
+ ).all(userId, ...needles) as Row[];
234
255
  const now = opts.now ?? Date.now();
235
- const scored: { i: number; score: number }[] = [];
236
- records.forEach((r, i) => {
237
- if (opts.skip?.(r.k)) return;
238
- const s = scoreText(r.t, query);
239
- if (s === 0) return;
256
+ const scored: { row: Row; score: number }[] = [];
257
+ for (const row of rows) {
258
+ if (opts.skip?.(row.conv_key)) continue;
259
+ const s = scoreText(row.text, query);
260
+ if (s === 0) continue;
240
261
  // 新的稍微靠前:一个月内的最多加 30%
241
- const age = Math.max(0, now - r.ts) / (30 * 86400_000);
242
- scored.push({ i, score: s * (1 + 0.3 * Math.exp(-age)) });
243
- });
244
- scored.sort((a, b) => b.score - a.score || records[b.i]!.ts - records[a.i]!.ts);
262
+ const age = Math.max(0, now - row.ts) / (30 * 86400_000);
263
+ scored.push({ row, score: s * (1 + 0.3 * Math.exp(-age)) });
264
+ }
265
+ scored.sort((a, b) => b.score - a.score || b.row.ts - a.row.ts || a.row.id - b.row.id);
245
266
  const out: SearchHit[] = [];
246
267
  const used = new Set<number>();
247
268
  const limit = opts.limit ?? 6;
248
- for (const { i, score } of scored) {
269
+ const next = sql(`SELECT ${COLUMNS} FROM history WHERE user_id = ? AND id > ? ORDER BY id LIMIT 1`);
270
+ const prev = sql(`SELECT ${COLUMNS} FROM history WHERE user_id = ? AND id < ? ORDER BY id DESC LIMIT 1`);
271
+ for (const { row, score } of scored) {
249
272
  if (out.length >= limit) break;
250
- if (used.has(i)) continue;
251
- const r = records[i]!;
273
+ if (used.has(row.id)) continue;
252
274
  // 配上同一条对话里紧挨着的另一半:问配答,答配问
253
- const pairIndex = r.r === "u" ? i + 1 : i - 1;
254
- const pair = records[pairIndex];
255
- const partner = pair && pair.k === r.k && pair.r !== r.r ? pair : undefined;
256
- used.add(i);
257
- if (partner) used.add(pairIndex);
258
- const user = r.r === "u" ? r : partner;
259
- const assistant = r.r === "a" ? r : partner;
275
+ const pair = (row.role === "u" ? next : prev).get(userId, row.id) as Row | undefined;
276
+ const partner = pair && pair.conv_key === row.conv_key && pair.role !== row.role ? pair : undefined;
277
+ used.add(row.id);
278
+ if (partner) used.add(partner.id);
279
+ const user = row.role === "u" ? row : partner;
280
+ const assistant = row.role === "a" ? row : partner;
260
281
  out.push({
261
- key: r.k,
262
- ts: r.ts,
263
- ...(user ? { user: snippet(user.t, query, 300) } : {}),
264
- ...(assistant ? { assistant: snippet(assistant.t, query, 600) } : {}),
282
+ key: row.conv_key,
283
+ ts: row.ts,
284
+ ...(user ? { user: snippet(user.text, query, 300) } : {}),
285
+ ...(assistant ? { assistant: snippet(assistant.text, query, 600) } : {}),
265
286
  score,
266
287
  });
267
288
  }