agent-loft 0.2.49 → 0.2.51

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
@@ -29,7 +29,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
29
29
  | 🧑‍🏫 | **专家** | 自己配专家:选引擎、写提示词,定它能做什么(只能联网 / 读文件 / 改文件 / 跑命令),挂哪些技能和 MCP,能把活派给哪些子智能体。新对话、定时任务都能选 |
30
30
  | 🔀 | **飞书机器人灵活绑定 agent** | 机器人数量不限,每个机器人可以只对应一个 agent,也可以对应多个(在会话里切换)。网页上扫码就能创建,改完立即生效;由服务端主动连向飞书,家里没有公网 IP 也能在外面用 |
31
31
  | 🔗 | **飞书续接 Web 任务** | 飞书里发 `/web` 接上一条 Web 会话,或者在网页侧栏右键会话选「在飞书继续…」。之后回复、授权、提问都发到飞书,发 `/detach` 回来 |
32
- | 🖥️ | **完整的 Web 工作台** | 流式回复、附件、语音输入、模型和思考程度切换、上下文占用、从任意回复分叉、按项目分组的侧栏、全部设置,电脑和手机(PWA)都能用 |
32
+ | 🖥️ | **完整的 Web 工作台** | 流式回复、附件、语音输入、模型和思考程度切换、上下文占用、从任意回复分叉、按项目分组的侧栏、搜索会话、全部设置,电脑和手机(PWA)都能用 |
33
33
  | 🔔 | **飞书 + 苹果系统推送** | 除了飞书消息,Web 会话还能推送到 iPhone、iPad 锁屏和 Mac 通知中心(标准 Web Push,不需要开发者账号),图标上显示未读数 |
34
34
  | 🗂️ | **桌面端同时接入多台设备** | 桌面端(macOS / Windows / Linux)同时连多台服务器,菜单栏 / 托盘一眼看完各台的额度、待处理和运行中的会话 |
35
35
 
@@ -47,14 +47,19 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
47
47
  - 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,开新会话或切换目录时清理。
48
48
  - 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
49
49
  - 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
50
- - 新对话页:点大标题里的目录名,在目录树里逐层选工作目录;输入框上方选专家,右下角选模型和思考程度。对话从头到尾一个专家,要换专家就新建对话;模型和思考程度随时可换。
50
+ - 新对话页:点大标题里的目录名,在固定高度的目录弹窗里逐层选工作目录,也能新建文件夹;输入框上方选专家,鼠标停在专家上看简介,右下角选模型和思考程度。对话从头到尾一个专家,要换专家就新建对话;模型和思考程度随时可换。
51
51
  - 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
52
52
  - 滚动和 ChatGPT 一样:发出的问题顶到最上面、下面留白,回复长到屏幕底部才跟着往下滚;回复过程中自己滚动了就不再自动滚,下次发消息再恢复。
53
53
  - 定时发送:右上角「更多」→「定时发送」,默认排在 5 小时额度重置后 5 分钟(弹窗里提示 5 小时 / 7 天额度的重置时间),由服务端到点发出,关掉页面也会发。适合额度用完、要等刷新才能接着干活的时候。
54
- - 侧栏分「最近」和「项目」两组:Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书机器人各占一行(右键看历史会话);分叉出来的会话用虚线挂在原会话下面;会话标题由 agent 自动生成,双击重命名。
55
- - 回复过程中接着发的消息排队,标着「排队中」,上一条回复完自动接着处理;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
56
- - 太长的消息先收起,点「展开显示」看全文;对话里有 3 条以上消息时,右边有一列快速定位,鼠标移上去列出每条消息的开头,点一下跳过去。
57
- - 侧栏按页加载:「最近」先显示 10 条、每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
54
+ - 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书机器人各占一行(右键看历史会话);项目名、有分叉的会话后面有个小三角,点一下折叠 / 展开(折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;会话标题由 agent 自动生成,双击重命名;鼠标移到会话上,标题后显示对应的专家图标。
55
+ - **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;电脑和手机上弹窗都固定高度,结果在内部滚动;↑↓ 选、回车打开。
56
+ - 会话页顶部标题前是专家的头像,鼠标停上去或点一下,看专家的说明、模型、能力和当前工作目录。
57
+ - 附件可以直接拖到聊天区任意位置上传。
58
+ - 回复过程中接着发的消息排队,标着「排队中」,上一条回复完自动接着处理;点「撤销并编辑」图标把排队消息放回输入框;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
59
+ - 用户消息的复制按钮后有「回退到此处」图标:把这条消息及附件放回输入框,并删除它及之后的聊天内容,重新发送时从之前的上下文继续。
60
+ - 太长的消息先收起,点「展开显示」看全文;对话里有至少 3 条用户消息时,右侧显示快速定位尺,电脑上鼠标移入查看消息开头、点击跳转;手机上滚动时显示,停下约 1.2 秒后隐藏,点刻度跳转。
61
+ - 回复底部的 token 数自动按大小显示为 K、M 等单位。
62
+ - 侧栏按页加载:每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
58
63
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
59
64
  - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
60
65
  - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
@@ -66,18 +71,18 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
66
71
  - **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
67
72
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
68
73
  - **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex` 换专家会开新会话)。**内置专家**:Claude Code、Codex,就是 agent 原装的样子(原装提示词、机器上的技能和 MCP、所有工具)。**自定义专家**每人管自己的,可以配:
69
- - 引擎(Claude / Codex,建好后不能换)、默认模型和思考程度;
74
+ - 头像(自己上传,没传就用引擎的图标)、引擎(Claude / Codex,建好后不能换)、默认模型和思考程度(从模型列表里选);
70
75
  - 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
71
- - 权限,一级包含一级:**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
72
- - 联网搜索、读网页的开关,带不带个人记忆,默认工作目录,新对话页上的欢迎语和快捷提问;
76
+ - 权限,勾选:联网搜索、读网页,以及文件权限(一级包含一级):都不勾就是**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
77
+ - 带不带个人记忆,默认工作目录,新对话页上的欢迎语和快捷提问;
73
78
  - 技能:只给选中的(Claude 用技能白名单,没选的调不了;没选技能就不挂 Skill 工具,省 token);
74
79
  - MCP:从「设置 → MCP」里勾(管理员还能勾机器上配的);
75
80
  - 子智能体(只有 Claude):别的 Claude 专家,主专家用 Agent 工具把子任务派给它。子智能体的权限不能超过主专家(运行时也封顶在主专家的权限)。
76
81
 
77
- 「新建 → 从模板:聊天助手」就是以前聊天模式的效果。专家改了,用它的对话下一条消息起生效;专家删了,用它的对话还能看、不能再发消息,用它的定时任务暂停。以前的聊天模式取消了:升级后聊天模式的旧对话不再保留,聊天模式的定时任务暂停,选个专家再启用。
82
+ 只勾联网搜索、读网页的 Claude 专家就是以前聊天模式的效果。专家改了,用它的对话下一条消息起生效;专家删了,用它的对话还能看、不能再发消息,用它的定时任务暂停。以前的聊天模式取消了:升级后聊天模式的旧对话不再保留,聊天模式的定时任务暂停,选个专家再启用。
78
83
  - **MCP**:设置 → MCP,每人管自己的:本机进程(命令 + 参数 + 环境变量)或 HTTP 地址(+ 请求头),值可以标成密钥(网页上不回显,只交给 MCP 进程或请求头,不进提示词)。可以设「调用前询问」,不设就直接用。只给自定义专家用,内置专家照旧用机器上配的。
79
- - **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关)。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理选中专家的对话;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话;第一次用时会把已有对话收录进来)。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
80
- - **定时任务**:像 ChatGPT 的 Tasks,侧栏「最近」上面的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
84
+ - **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关)。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理选中专家的对话;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话)。聊天记录索引不开记忆也会记(侧栏的「搜索」也用它),升级后会把已有对话收录进来一次;没开记忆时记进来的不拿去整理。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
85
+ - **定时任务**:像 ChatGPT 的 Tasks,侧栏的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
81
86
  - **技能(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 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
82
87
  - **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
83
88
  - 桌面:走 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 的用户名和登录密码(苹果认证,由服务端登录)。
@@ -116,7 +121,7 @@ agent-loft service install # 注册为开机自启服务(systemd / laun
116
121
  - 菜单栏图标可以换成额度条:Claude、Codex 各是一只像素小宠物,看样子就知道是谁,身子是 5 小时额度,下面一条是周额度。桌面端设置 → 额度显示 →「菜单栏显示额度」,选所有服务器合起来(取最高),或者按服务器分别选 Claude / Codex(图标上不写服务器名);都不选就只显示图标。「额度条显示」选实心表示剩余额度(默认,像电池)还是已用额度。只有 macOS 有,Windows / Linux 的托盘图标太小放不下。
117
122
  - 支持前面挡着 Cloudflare Access 的服务器:验证页直接在窗口里完成,过期会提醒;也可以配 Service Token 免验证。
118
123
  - 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew 装)并开机自启,装好自动连上;设置里可以改成「只在桌面端运行时运行」(不开机自启,打开桌面端时启动、退出时停止)。Linux 上一样(需要先装好 Node.js 22+,开机自启用 systemd 用户服务);Windows 上服务端还没有开机自启,可以在 WSL 里装,桌面端会自动检测到 `127.0.0.1` 上的它。防休眠:本机有会话在跑时不休眠;另有永不休眠、定时休眠(设休眠时段,时段外不休眠,时段内本机没有会话在跑、屏幕锁上后让 Mac 睡下去)和合盖不休眠(macOS,第一次开关要输管理员密码,之后不用;开着时闲置也不睡,定时休眠到点会临时关掉它让 Mac 睡下去,醒来再打开)。
119
- - 顶栏「更多」→「总量汇总」:把所有已添加服务器的用量加在一起看,按日 / 月 / 年统计 token 和金额,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按服务器。不在线、没登录或服务端太旧的服务器不计入,页面上会注明。
124
+ - 顶栏「更多」→「用量汇总」:把所有已添加服务器的用量,加上这台电脑上直接用的 Claude Code、Codex(桌面端和 CLI,读它们自己的会话记录),合在一起看。按日 / 月 / 年统计 token 和金额,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按来源。本机直接用的金额按模型单价估算;Agent Loft 自己跑的会话只算在服务器里,不重复算。不在线、没登录或服务端太旧的服务器不计入,页面上会注明。
120
125
  - 设置(`⌘,`)的服务器列表里展开某台服务器,能看它的 Agent 环境和版本,有新版本时点「升级服务端」;桌面端自己的更新在同一页的「更新」里点「更新并重启」。
121
126
 
122
127
  桌面端只是个壳(代码在 `desktop/`),服务端照常用 npm 安装和升级。
@@ -155,7 +160,7 @@ agent-loft service install
155
160
 
156
161
  `aloft` 是 `agent-loft` 的简写。
157
162
 
158
- 聊天里的命令(飞书和 Web 通用;Web 输入框打 `/` 会弹出命令补全,飞书里打 `/` 会弹出机器人的指令面板(agent-loft 自动注册,约 5~8 分钟生效;只发一个 `/` 也会回一张可点击的命令卡片),顺序和显示项在 设置 → 命令 里调整):`/new` `/fork` `/sessions [all]` `/resume <id>` `/model [名称]` `/effort <程度>` `/stop` `/cd <目录>` `/pwd` `/status` `/autoedit [on|off]` `/approve <id> allow-once|allow-always|allow-session|deny` `/help`;只在飞书里有的:`/expert [名称]`(或者直接发 `/claude`、`/codex`,换专家会开新会话)`/web` `/detach` `/bind <绑定码>`
163
+ 聊天里的命令(飞书和 Web 通用;Web 打开页面时会预加载当前专家和目录的命令,输入框打 `/` 会弹出命令补全,飞书里打 `/` 会弹出机器人的指令面板(agent-loft 自动注册,约 5~8 分钟生效;只发一个 `/` 也会回一张可点击的命令卡片),顺序和显示项在 设置 → 命令 里调整):`/new` `/fork` `/sessions [all]` `/resume <id>` `/model [名称]` `/effort <程度>` `/stop` `/cd <目录>` `/pwd` `/status` `/autoedit [on|off]` `/approve <id> allow-once|allow-always|allow-session|deny` `/help`;只在飞书里有的:`/expert [名称]`(或者直接发 `/claude`、`/codex`,换专家会开新会话)`/web` `/detach` `/bind <绑定码>`
159
164
 
160
165
  自定义命令:设置 → 命令 → 「添加命令」,填命令名、说明和一段提示词,之后发 `/命令名 参数` 就会把这段提示词发给 agent(提示词里的 `$ARGUMENTS` 换成参数,没写就把参数接在后面)。按 agent 分开存,可以编辑、删除,也会同步到飞书指令面板。
161
166
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.49",
3
+ "version": "0.2.51",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -234,6 +234,7 @@ export class ClaudeDriver implements AgentDriver {
234
234
  flush();
235
235
  out.push({
236
236
  role: "user",
237
+ anchor: msg.uuid,
237
238
  text,
238
239
  ...(attachments.length ? { attachments } : {}),
239
240
  ...(Number.isFinite(ts) ? { ts } : {}),
@@ -288,6 +289,16 @@ export class ClaudeDriver implements AgentDriver {
288
289
  return res.sessionId;
289
290
  }
290
291
 
292
+ async rewindTo(id: string, cwd: string, anchor: string): Promise<string | undefined> {
293
+ if (!SESSION_ID.test(id)) throw new Error("会话 id 不对");
294
+ const raw = await getSessionMessages(id, { dir: cwd });
295
+ const index = raw.findIndex((m) => m.uuid === anchor && m.type === "user");
296
+ if (index < 0) throw new Error("在会话记录里找不到这条消息,请刷新后重试");
297
+ const previous = raw[index - 1];
298
+ if (!previous) return undefined;
299
+ return (await forkSession(id, { dir: cwd, upToMessageId: previous.uuid })).sessionId;
300
+ }
301
+
291
302
  async listModels(session: AgentSession): Promise<ModelInfo[]> {
292
303
  return (session as ClaudeSession).listModels();
293
304
  }
@@ -608,6 +608,13 @@ export class ClaudeSession implements AgentSession {
608
608
  this.deliver(input);
609
609
  }
610
610
 
611
+ cancelQueued(input: UserInput): boolean {
612
+ const index = this.pending.indexOf(input);
613
+ if (index < 0) return false;
614
+ this.pending.splice(index, 1);
615
+ return true;
616
+ }
617
+
611
618
  /** 一轮结束(出结果、出错或 CLI 退出):交出下一条排队的消息 */
612
619
  private onTurnEnd(): void {
613
620
  this.turnBusy = false;
@@ -632,11 +639,13 @@ export class ClaudeSession implements AgentSession {
632
639
  this.start();
633
640
  this.queue.push({
634
641
  type: "user",
642
+ ...(input.id ? { uuid: input.id } : {}),
635
643
  message: { role: "user", content },
636
644
  parent_tool_use_id: null,
637
645
  // 人敲的字必须显式标记来源;缺省会在严格的信任门上 fail closed
638
646
  origin: { kind: "human" },
639
647
  } as SDKUserMessage);
648
+ if (input.id) this.events.onUserAnchor?.(input, input.id);
640
649
  }
641
650
 
642
651
  async listModels(): Promise<ModelInfo[]> {
@@ -132,6 +132,7 @@ export class CodexDriver implements AgentDriver {
132
132
  const bareImages = attachments.length ? 0 : (item.content ?? []).filter((c) => c.type === "localImage").length;
133
133
  out.push({
134
134
  role: "user",
135
+ ...(turn.id ? { anchor: turn.id } : {}),
135
136
  text: bareImages ? [text, ...Array(bareImages).fill("📎 图片")].filter(Boolean).join("\n") : text,
136
137
  ...(attachments.length ? { attachments } : {}),
137
138
  ...(ts ? { ts } : {}),
@@ -175,6 +176,14 @@ export class CodexDriver implements AgentDriver {
175
176
  return res.thread.id;
176
177
  }
177
178
 
179
+ async rewindTo(id: string, cwd: string, anchor: string): Promise<string | undefined> {
180
+ const res = await appServer.call<{ thread: { turns?: { id: string }[] } }>("thread/read", { threadId: id, includeTurns: true });
181
+ const turns = res.thread.turns ?? [];
182
+ const index = turns.findIndex((turn) => turn.id === anchor);
183
+ if (index < 0) throw new Error("在会话记录里找不到这条消息,请刷新后重试");
184
+ return index === 0 ? undefined : this.forkAt(id, cwd, turns[index - 1]!.id);
185
+ }
186
+
178
187
  async listModels(): Promise<ModelInfo[]> {
179
188
  const res = await appServer.call<ModelListResponse>("model/list", {});
180
189
  return (res.data ?? [])
@@ -272,6 +272,7 @@ export class CodexSession implements AgentSession {
272
272
  /** 每开一轮加一:迟到的回调据此判断自己是不是已经过时 */
273
273
  private turnSeq = 0;
274
274
  private queue: UserInput[] = [];
275
+ private currentInput: UserInput | undefined;
275
276
  /** 启动途中就被叫停(停止或丢弃)的轮次代次:turn/start 迟到返回时,拿它的 id 补一个中断 */
276
277
  private abandoned = new Set<number>();
277
278
  /** 已经收尾过的轮次:error 通知之后还可能再来一个 turn/completed,不能收两次尾 */
@@ -543,7 +544,15 @@ export class CodexSession implements AgentSession {
543
544
  this.startTurn(input);
544
545
  }
545
546
 
547
+ cancelQueued(input: UserInput): boolean {
548
+ const index = this.queue.indexOf(input);
549
+ if (index < 0) return false;
550
+ this.queue.splice(index, 1);
551
+ return true;
552
+ }
553
+
546
554
  private startTurn(input: UserInput): void {
555
+ this.currentInput = input;
547
556
  this.replyText = "";
548
557
  this.phase = "starting";
549
558
  this.turnId = undefined;
@@ -609,6 +618,7 @@ export class CodexSession implements AgentSession {
609
618
  }
610
619
 
611
620
  private onTurnId(id: string): void {
621
+ if (id !== this.turnId && this.currentInput) this.events.onUserAnchor?.(this.currentInput, id);
612
622
  this.turnId = id;
613
623
  this.phase = "running";
614
624
  if (this.stopRequested) {
@@ -27,7 +27,7 @@ import {
27
27
  type Role,
28
28
  type User,
29
29
  } from "../../core/users.js";
30
- import type { SavedAttachment } from "../../core/types.js";
30
+ import type { AttachmentInfo, SavedAttachment } from "../../core/types.js";
31
31
  import { dailyUsage } from "../../core/usage.js";
32
32
  import { appendDirOrder, getDirOrder, setDirOrder } from "../../core/ui-prefs.js";
33
33
  import {
@@ -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, writeMeta } from "../../core/chat-history.js";
45
+ import { purgeHistory, readMeta, readRecords, 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";
@@ -67,7 +67,7 @@ import {
67
67
  takeAttempt,
68
68
  } from "./auth.js";
69
69
  import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
70
- import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor } from "./conv-pages.js";
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
73
  import { handleSkillsApi } from "./skills-api.js";
@@ -109,6 +109,33 @@ export function takeUploads(key: string, ids: unknown): SavedAttachment[] {
109
109
  return entries.map((e) => e!.attachment);
110
110
  }
111
111
 
112
+ /** 已发送的附件重新领一个上传编号,让撤回的消息能带着原附件再次发送 */
113
+ function editableDraft(key: string, user: User, message: { text: string; attachments: AttachmentInfo[] }) {
114
+ let missing = 0;
115
+ const restored = message.attachments.flatMap((file) => {
116
+ const resolved = resolveUploadFile(file.path);
117
+ const sourceKey = resolved && uploadKeyOf(resolved);
118
+ const source = sourceKey && getConversation(sourceKey);
119
+ if (!resolved || !source || !canSeeConv(user, source)) {
120
+ missing++;
121
+ return [];
122
+ }
123
+ try {
124
+ const head = Buffer.alloc(12);
125
+ const fd = fs.openSync(resolved, "r");
126
+ try { fs.readSync(fd, head, 0, head.length, 0); } finally { fs.closeSync(fd); }
127
+ const attachment: SavedAttachment = { ...file, path: resolved, size: fs.statSync(resolved).size, mediaType: sniff(head)?.mediaType };
128
+ const id = crypto.randomBytes(12).toString("hex");
129
+ uploads.set(id, { key, attachment, at: Date.now() });
130
+ return [{ id, name: file.name, kind: file.kind, ...(file.kind === "image" ? { url: `/api/file?path=${encodeURIComponent(resolved)}` } : {}) }];
131
+ } catch {
132
+ missing++;
133
+ return [];
134
+ }
135
+ });
136
+ return { text: message.text, uploads: restored, missing };
137
+ }
138
+
112
139
  setInterval(() => {
113
140
  const now = Date.now();
114
141
  for (const [id, entry] of uploads) if (now - entry.at > 60 * 60 * 1000) uploads.delete(id);
@@ -735,13 +762,34 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
735
762
  if (p.startsWith("/api/terminals") && (await handleTerminalApi(req, res, p, user))) return;
736
763
  if ((p === "/api/remote" || p.startsWith("/api/desktop/")) && (await handleDesktopApi(req, res, p, user))) return;
737
764
 
738
- // ----- 目录选择器:列工作区内的子目录 -----
765
+ // ----- 目录选择器:列出或新建工作区内的子目录 -----
739
766
  if (p === "/api/dirs" && method === "GET") {
740
767
  const listing = listWorkspaceDirs(url.searchParams.get("path") ?? "");
741
768
  if (!listing) throw new HttpError(404, `目录不存在,或不在 ${config().workspaceRoot} 之内`);
742
769
  sendJson(res, 200, listing);
743
770
  return;
744
771
  }
772
+ if (p === "/api/dirs" && method === "POST") {
773
+ const body = await readJsonBody<{ path?: unknown; name?: unknown }>(req);
774
+ const name = typeof body.name === "string" ? body.name.trim() : "";
775
+ if (!name || name === "." || name === ".." || /[\\/\x00-\x1f\x7f]/.test(name) || Buffer.byteLength(name) > 255) {
776
+ throw new HttpError(400, "请输入有效的文件夹名称,不能包含斜杠或控制字符");
777
+ }
778
+ if (body.path !== undefined && typeof body.path !== "string") throw new HttpError(400, "目录路径必须是文字");
779
+ const parent = resolveWorkspacePath(typeof body.path === "string" && body.path ? body.path : ".");
780
+ if (!parent) throw new HttpError(404, `目录不存在,或不在 ${config().workspaceRoot} 之内`);
781
+ const target = path.join(parent, name);
782
+ try {
783
+ fs.mkdirSync(target);
784
+ } catch (err) {
785
+ const code = (err as NodeJS.ErrnoException).code;
786
+ if (code === "EEXIST") throw new HttpError(409, "同名文件或文件夹已存在");
787
+ if (code === "EACCES" || code === "EPERM") throw new HttpError(403, "没有权限在此目录新建文件夹");
788
+ throw new HttpError(400, "无法新建文件夹,请检查名称和所在目录");
789
+ }
790
+ sendJson(res, 201, { path: target });
791
+ return;
792
+ }
745
793
 
746
794
  // ----- 会话 -----
747
795
  // 侧栏按页拉:scope=recent(最近)/ dir(某个项目目录)按树分页;bot(某个飞书机器人的全部聊天)平铺
@@ -759,6 +807,29 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
759
807
  sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 10)));
760
808
  return;
761
809
  }
810
+ // 搜索会话(侧栏「搜索」弹窗):标题、目录名,再搜聊天内容(聊天记录索引,见 chat-history.ts)。
811
+ // expert:只看这个专家的对话(内置的就是 claude / codex)
812
+ if (p === "/api/conversations/search" && method === "GET") {
813
+ const q = (url.searchParams.get("q") ?? "").slice(0, 200);
814
+ const expert = url.searchParams.get("expert");
815
+ const all = hub.list(visible).filter((c) => !c.hidden && (!expert || c.expert.id === expert));
816
+ const keys = new Set(all.map((c) => c.key));
817
+ let content: { key: string; text: string }[] = [];
818
+ if (q.trim()) {
819
+ try {
820
+ // 一条对话可能命中很多句,多要一些,保证别的对话也排得上
821
+ content = searchHistory(user.id, q, { limit: 300, skip: (k) => !keys.has(k) }).map((hit) => {
822
+ const lower = q.trim().toLowerCase();
823
+ const text = [hit.user, hit.assistant].find((t) => t?.toLowerCase().includes(lower)) ?? hit.user ?? hit.assistant ?? "";
824
+ return { key: hit.key, text };
825
+ });
826
+ } catch {
827
+ // 没有索引、读不了:只按标题搜
828
+ }
829
+ }
830
+ sendJson(res, 200, { results: searchConvs(all, q, content) });
831
+ return;
832
+ }
762
833
  if (p === "/api/conversations" && method === "GET") {
763
834
  sendJson(res, 200, hub.list(visible));
764
835
  return;
@@ -795,6 +866,21 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
795
866
  // 别人的会话:当它不存在
796
867
  if (!visible(conv)) throw new HttpError(404, "会话不存在");
797
868
 
869
+ if ((sub === "cancel-queued" || sub === "rewind") && method === "POST") {
870
+ const body = await readJsonBody<{ id?: unknown; anchor?: unknown; sessionId?: unknown }>(req);
871
+ const id = typeof body.id === "string" ? body.id : undefined;
872
+ const anchor = typeof body.anchor === "string" ? body.anchor : undefined;
873
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId : undefined;
874
+ if (!(sub === "cancel-queued" ? id : id || anchor)) throw new HttpError(400, "缺少消息位置");
875
+ try {
876
+ const message = sub === "cancel-queued" ? hub.cancelQueued(key, id!) : await hub.rewind(key, { id, anchor, sessionId });
877
+ sendJson(res, 200, { draft: editableDraft(key, user, message), queued: "queued" in message && message.queued, info: hub.info(key) });
878
+ } catch (err) {
879
+ throw new HttpError(409, err instanceof Error ? err.message : String(err));
880
+ }
881
+ return;
882
+ }
883
+
798
884
  if (!sub && method === "PATCH") {
799
885
  const body = await readJsonBody<{ title?: string; hidden?: boolean }>(req);
800
886
  updateConversation(key, {
@@ -1110,11 +1196,14 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1110
1196
  }
1111
1197
  const found = getConversation(url.searchParams.get("key") ?? "");
1112
1198
  const conv = found && visible(found) ? found : undefined;
1199
+ const draftCwd = !conv && url.searchParams.get("cwd");
1200
+ const cwd = conv?.cwd ?? (draftCwd ? resolveWorkspacePath(draftCwd) : undefined);
1201
+ if (draftCwd && !cwd) throw new HttpError(404, "工作目录不存在,或不在工作区之内");
1113
1202
  const commands = await hub.commandCatalog(m[1]!, {
1114
- ...(conv ? { cwd: conv.cwd } : {}),
1203
+ ...(cwd ? { cwd } : {}),
1115
1204
  allowedAgents: hub.enabledAgents().map((d) => d.id),
1116
- // 带 key 是输入框补全:只列 Web 能用的;不带是设置页排序,全列
1117
- ...(conv ? { channel: "web" } : {}),
1205
+ // 输入框(包括尚未创建的新对话)只列 Web 能用的;设置页仍列全部
1206
+ ...(conv || url.searchParams.get("channel") === "web" ? { channel: "web" } : {}),
1118
1207
  // 成员看不到机器上装的技能
1119
1208
  ...(admin ? {} : { member: true }),
1120
1209
  });
@@ -66,3 +66,40 @@ export const clampLimit = (v: unknown, def: number): number => {
66
66
  const n = Math.floor(Number(v));
67
67
  return Number.isFinite(n) && n > 0 ? Math.min(n, 200) : def;
68
68
  };
69
+
70
+ export type SearchResult = { conv: ConversationInfo; snippet?: string };
71
+
72
+ /**
73
+ * 搜索会话:标题(和工作目录名)里每个词都出现的排前面,整句出现的更靠前,同样的按活跃时间;
74
+ * 再接上聊天内容里搜到的(contentHits,按相关程度排好的,同一条对话只取第一句)。
75
+ * 没输入查询:给最近活跃的。
76
+ */
77
+ export function searchConvs(
78
+ list: ConversationInfo[],
79
+ query: string,
80
+ contentHits: { key: string; text: string }[] = [],
81
+ limit = 50,
82
+ ): SearchResult[] {
83
+ const q = query.trim().toLowerCase();
84
+ if (!q) return [...list].sort((a, b) => b.activeAt - a.activeAt).slice(0, limit).map((conv) => ({ conv }));
85
+ const words = q.split(/\s+/);
86
+ const byTitle = list
87
+ .map((c) => {
88
+ const title = (c.title ?? "").toLowerCase();
89
+ const hay = `${title} ${c.cwd.split(/[\\/]/).filter(Boolean).pop() ?? ""}`.toLowerCase();
90
+ if (!words.every((w) => hay.includes(w))) return null;
91
+ return { c, rank: title.includes(q) ? 2 : 1 };
92
+ })
93
+ .filter((x) => x !== null)
94
+ .sort((a, b) => b.rank - a.rank || b.c.activeAt - a.c.activeAt);
95
+ const out: SearchResult[] = byTitle.map((x) => ({ conv: x.c }));
96
+ const seen = new Set(out.map((r) => r.conv.key));
97
+ const byKey = new Map(list.map((c) => [c.key, c]));
98
+ for (const hit of contentHits) {
99
+ const conv = byKey.get(hit.key);
100
+ if (!conv || seen.has(hit.key)) continue;
101
+ seen.add(hit.key);
102
+ out.push({ conv, snippet: hit.text });
103
+ }
104
+ return out.slice(0, limit);
105
+ }
@@ -4,6 +4,8 @@ import { userMcpServers } from "../../agents/codex/session.js";
4
4
  import {
5
5
  ACCESS_LABEL,
6
6
  ACCESS_LEVELS,
7
+ avatarImage,
8
+ avatarUrl,
7
9
  createExpert,
8
10
  deleteExpert,
9
11
  EXPERT_LIMITS,
@@ -28,6 +30,7 @@ function expertView(e: Expert) {
28
30
  name: e.name,
29
31
  description: e.description,
30
32
  icon: e.icon,
33
+ avatar: avatarUrl(e),
31
34
  color: e.color,
32
35
  welcome: e.welcome,
33
36
  quickPrompts: e.quickPrompts,
@@ -55,9 +58,13 @@ export function expertBrief(e: Expert) {
55
58
  name: e.name,
56
59
  description: e.description,
57
60
  icon: e.icon,
61
+ avatar: avatarUrl(e),
58
62
  color: e.color,
59
63
  engine: e.engine,
60
64
  access: e.access,
65
+ webSearch: e.webSearch,
66
+ webFetch: e.webFetch,
67
+ memory: e.memory,
61
68
  cwd: e.cwd ?? "",
62
69
  model: e.model ?? "",
63
70
  effort: e.effort ?? "",
@@ -100,7 +107,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
100
107
  }
101
108
 
102
109
  if (p === "/api/experts" && method === "POST") {
103
- const body = await readJsonBody<ExpertInput>(req, 256 * 1024);
110
+ const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
104
111
  try {
105
112
  sendJson(res, 200, expertView(createExpert(user.id, body)));
106
113
  } catch (err) {
@@ -109,6 +116,17 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
109
116
  return true;
110
117
  }
111
118
 
119
+ // 头像:登录了就能看(管理员看别人的对话时也要显示)。地址带版本号,可以长期缓存
120
+ const am = /^\/api\/experts\/(e_[a-f0-9]+)\/avatar$/.exec(p);
121
+ if (am && method === "GET") {
122
+ const expert = getExpert(am[1]!);
123
+ const img = expert && avatarImage(expert);
124
+ if (!img) throw new HttpError(404, "没有头像");
125
+ res.writeHead(200, { "Content-Type": img.type, "Content-Length": img.data.length, "Cache-Control": "private, max-age=31536000, immutable" });
126
+ res.end(img.data);
127
+ return true;
128
+ }
129
+
112
130
  const em = /^\/api\/experts\/(e_[a-f0-9]+)$/.exec(p);
113
131
  if (em) {
114
132
  const expert = getExpert(em[1]!);
@@ -118,7 +136,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
118
136
  return true;
119
137
  }
120
138
  if (method === "PATCH") {
121
- const body = await readJsonBody<ExpertInput>(req, 256 * 1024);
139
+ const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
122
140
  try {
123
141
  sendJson(res, 200, expertView(updateExpert(user.id, expert.id, body)));
124
142
  } catch (err) {
@@ -13,6 +13,8 @@ import path from "node:path";
13
13
  import { dataDir, readJson, writeJsonAtomic } from "../home.js";
14
14
 
15
15
  export type HistoryRecord = {
16
+ /** 实时用户消息的编号,撤销排队消息时用于精确移除 */
17
+ id?: string;
16
18
  /** 对话 key */
17
19
  k: string;
18
20
  /** agent */
@@ -82,6 +84,23 @@ export function readRecords(userId: string): HistoryRecord[] {
82
84
  return out;
83
85
  }
84
86
 
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);
93
+ }
94
+
95
+ export function removeHistoryRecord(userId: string, key: string, id: string): void {
96
+ rewriteRecords(userId, readRecords(userId).filter((r) => r.k !== key || r.id !== id));
97
+ }
98
+
99
+ /** 回退后只保留当前对话剩下的内容,避免搜索再搜出已经移除的消息 */
100
+ export function replaceConversationRecords(userId: string, key: string, records: HistoryRecord[]): void {
101
+ rewriteRecords(userId, [...readRecords(userId).filter((r) => r.k !== key), ...records]);
102
+ }
103
+
85
104
  export function readMeta(userId: string): Meta {
86
105
  const m = readJson<Partial<Meta>>(`${base(userId)}.meta.json`, {});
87
106
  return { ...m, extracted: m.extracted && typeof m.extracted === "object" ? m.extracted : {} };
@@ -35,8 +35,10 @@ export type Expert = {
35
35
  owner: string;
36
36
  name: string;
37
37
  description: string;
38
- /** emoji */
38
+ /** emoji(以前的图标;有头像时用头像) */
39
39
  icon: string;
40
+ /** 头像:用户上传的图片,前端缩成小图后的 data URL(data:image/...;base64,...)。空 = 没有 */
41
+ avatar?: string;
40
42
  color: string;
41
43
  welcome: string;
42
44
  quickPrompts: QuickPrompt[];
@@ -80,8 +82,19 @@ export const EXPERT_LIMITS = {
80
82
  quickPrompts: 8,
81
83
  quickTitle: 40,
82
84
  quickPrompt: 2000,
85
+ /** 头像 data URL 的长度(前端缩到 128px,正常几 KB 到几十 KB) */
86
+ avatar: 300_000,
83
87
  };
84
88
 
89
+ /** 头像的地址(给前端用;带版本号,换了头像就是新地址) */
90
+ export const avatarUrl = (e: Pick<Expert, "id" | "rev" | "avatar">): string => (e.avatar ? `/api/experts/${e.id}/avatar?v=${e.rev}` : "");
91
+
92
+ /** 头像 data URL 拆成类型和内容 */
93
+ export function avatarImage(e: Pick<Expert, "avatar">): { type: string; data: Buffer } | undefined {
94
+ const m = e.avatar ? /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/=]+)$/.exec(e.avatar) : null;
95
+ return m ? { type: m[1]!, data: Buffer.from(m[2]!, "base64") } : undefined;
96
+ }
97
+
85
98
  const storePath = path.join(dataDir, "experts.json");
86
99
 
87
100
  /** 专家改了 / 删了。owner:谁的。用着它的会话空闲下来要换上新的 */
@@ -191,12 +204,21 @@ function validate(owner: string, input: ExpertInput, prev?: Expert, selfId?: str
191
204
  subagents.push(id);
192
205
  }
193
206
 
207
+ // 头像:没传就沿用;传空字符串就是去掉
208
+ const avatarRaw = pick("avatar");
209
+ const avatar = typeof avatarRaw === "string" ? avatarRaw.trim() : "";
210
+ if (avatar) {
211
+ if (avatar.length > EXPERT_LIMITS.avatar) throw new Error("头像图片太大");
212
+ if (!avatarImage({ avatar })) throw new Error("头像只能是 PNG、JPEG、WebP 或 GIF 图片");
213
+ }
214
+
194
215
  const model = text(pick("model"), 100, "模型");
195
216
  const effort = text(pick("effort"), 20, "思考程度");
196
217
  return {
197
218
  name,
198
219
  description: text(pick("description"), EXPERT_LIMITS.description, "说明"),
199
220
  icon: text(pick("icon"), 16, "图标"),
221
+ ...(avatar ? { avatar } : {}),
200
222
  color,
201
223
  welcome: text(pick("welcome"), EXPERT_LIMITS.welcome, "欢迎语"),
202
224
  quickPrompts,