agent-loft 0.2.50 → 0.2.52

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
@@ -47,17 +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 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书机器人各占一行(右键看历史会话);项目名、有分叉的会话后面有个小三角,点一下折叠 / 展开(折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;会话标题由 agent 自动生成,双击重命名。
55
- - **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;↑↓ 选、回车打开。
54
+ - 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书机器人各占一行(右键看历史会话);项目名、有分叉的会话后面有个小三角,点一下折叠 / 展开(折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;会话标题由 agent 自动生成,双击重命名;鼠标移到会话上,行尾显示对应的专家图标;定时任务的时钟图标始终放在最右侧。
55
+ - **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;电脑和手机上弹窗都固定高度,结果在内部滚动,手机上从底部展开;↑↓ 选、回车打开。
56
56
  - 会话页顶部标题前是专家的头像,鼠标停上去或点一下,看专家的说明、模型、能力和当前工作目录。
57
57
  - 附件可以直接拖到聊天区任意位置上传。
58
- - 回复过程中接着发的消息排队,标着「排队中」,上一条回复完自动接着处理;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
59
- - 太长的消息先收起,点「展开显示」看全文;对话里有 3 条以上消息时,右边有一列快速定位,鼠标移上去列出每条消息的开头,点一下跳过去。
60
- - 侧栏按页加载:「最近」先显示 10 条、每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
58
+ - 回复过程中接着发的消息排队,标着「排队中」,隐藏底部的复制和回退按钮,上一条回复完自动接着处理;点「撤销并编辑」图标把排队消息放回输入框;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
59
+ - 用户消息的复制按钮后有「回退到此处」图标:把这条消息及附件放回输入框,并删除它及之后的聊天内容,重新发送时从之前的上下文继续。
60
+ - 太长的消息先收起,点「展开显示」看全文;对话里有至少 3 条用户消息时,右侧显示快速定位尺,电脑上鼠标移入查看消息开头、点击跳转;手机上手动滚动时显示短轨道,按住拖动可预览问题和位置,松手跳转,停止操作约 1.6 秒后隐藏。
61
+ - 回复底部的 token 数自动按大小显示为 K、M 等单位。
62
+ - 侧栏按页加载:每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
61
63
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
62
64
  - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
63
65
  - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
@@ -69,7 +71,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
69
71
  - **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
70
72
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
71
73
  - **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex` 换专家会开新会话)。**内置专家**:Claude Code、Codex,就是 agent 原装的样子(原装提示词、机器上的技能和 MCP、所有工具)。**自定义专家**每人管自己的,可以配:
72
- - 头像(自己上传,没传就用引擎的图标)、引擎(Claude / Codex,建好后不能换)、默认模型和思考程度(从模型列表里选);
74
+ - 头像(点头像区域的加号上传;未上传时,会话中用引擎的图标)、引擎(Claude / Codex,建好后不能换)、默认模型和思考程度(从模型列表里选);
73
75
  - 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
74
76
  - 权限,勾选:联网搜索、读网页,以及文件权限(一级包含一级):都不勾就是**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
75
77
  - 带不带个人记忆,默认工作目录,新对话页上的欢迎语和快捷提问;
@@ -80,7 +82,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
80
82
  只勾联网搜索、读网页的 Claude 专家就是以前聊天模式的效果。专家改了,用它的对话下一条消息起生效;专家删了,用它的对话还能看、不能再发消息,用它的定时任务暂停。以前的聊天模式取消了:升级后聊天模式的旧对话不再保留,聊天模式的定时任务暂停,选个专家再启用。
81
83
  - **MCP**:设置 → MCP,每人管自己的:本机进程(命令 + 参数 + 环境变量)或 HTTP 地址(+ 请求头),值可以标成密钥(网页上不回显,只交给 MCP 进程或请求头,不进提示词)。可以设「调用前询问」,不设就直接用。只给自定义专家用,内置专家照旧用机器上配的。
82
84
  - **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关)。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理选中专家的对话;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话)。聊天记录索引不开记忆也会记(侧栏的「搜索」也用它),升级后会把已有对话收录进来一次;没开记忆时记进来的不拿去整理。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
83
- - **定时任务**:像 ChatGPT 的 Tasks,侧栏「最近」上面的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
85
+ - **定时任务**:像 ChatGPT 的 Tasks,侧栏的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
84
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 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
85
87
  - **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
86
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 的用户名和登录密码(苹果认证,由服务端登录)。
@@ -158,7 +160,7 @@ agent-loft service install
158
160
 
159
161
  `aloft` 是 `agent-loft` 的简写。
160
162
 
161
- 聊天里的命令(飞书和 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 <绑定码>`
162
164
 
163
165
  自定义命令:设置 → 命令 → 「添加命令」,填命令名、说明和一段提示词,之后发 `/命令名 参数` 就会把这段提示词发给 agent(提示词里的 `$ARGUMENTS` 换成参数,没写就把参数接在后面)。按 agent 分开存,可以编辑、删除,也会同步到飞书指令面板。
164
166
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.50",
3
+ "version": "0.2.52",
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 {
@@ -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(某个飞书机器人的全部聊天)平铺
@@ -818,6 +866,21 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
818
866
  // 别人的会话:当它不存在
819
867
  if (!visible(conv)) throw new HttpError(404, "会话不存在");
820
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
+
821
884
  if (!sub && method === "PATCH") {
822
885
  const body = await readJsonBody<{ title?: string; hidden?: boolean }>(req);
823
886
  updateConversation(key, {
@@ -887,12 +950,14 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
887
950
  const seq = hub.currentSeq();
888
951
  // 进行中的这一轮,agent 的记录里可能已经写进去了一部分,和 live 重复:
889
952
  // 记录里最后一条用户消息就是这一轮的那条时,从它起砍掉,交给 live 来画
890
- const liveUser = live.find((e) => e.ev.type === "user")?.ev as { text?: string } | undefined;
891
- if (liveUser) {
953
+ const liveUser = live.find((e) => e.ev.type === "user" && !e.ev.queued)?.ev;
954
+ if (liveUser?.type === "user") {
955
+ const anchor = live.findLast((e) => e.ev.type === "user_anchor" && e.ev.id === liveUser.id)?.ev;
892
956
  const lastUser = messages.map((m) => m.role).lastIndexOf("user");
893
957
  const norm = (t: string) => t.replace(/\s+/g, " ").trim();
894
958
  const want = norm(liveUser.text ?? "");
895
- if (lastUser >= 0 && want && norm(messages[lastUser]!.text).startsWith(want.slice(0, 200))) {
959
+ const sameAnchor = anchor?.type === "user_anchor" && messages[lastUser]?.anchor === anchor.anchor;
960
+ if (lastUser >= 0 && (sameAnchor || (want && norm(messages[lastUser]!.text).startsWith(want.slice(0, 200))))) {
896
961
  messages = messages.slice(0, lastUser);
897
962
  }
898
963
  }
@@ -1133,11 +1198,14 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1133
1198
  }
1134
1199
  const found = getConversation(url.searchParams.get("key") ?? "");
1135
1200
  const conv = found && visible(found) ? found : undefined;
1201
+ const draftCwd = !conv && url.searchParams.get("cwd");
1202
+ const cwd = conv?.cwd ?? (draftCwd ? resolveWorkspacePath(draftCwd) : undefined);
1203
+ if (draftCwd && !cwd) throw new HttpError(404, "工作目录不存在,或不在工作区之内");
1136
1204
  const commands = await hub.commandCatalog(m[1]!, {
1137
- ...(conv ? { cwd: conv.cwd } : {}),
1205
+ ...(cwd ? { cwd } : {}),
1138
1206
  allowedAgents: hub.enabledAgents().map((d) => d.id),
1139
- // 带 key 是输入框补全:只列 Web 能用的;不带是设置页排序,全列
1140
- ...(conv ? { channel: "web" } : {}),
1207
+ // 输入框(包括尚未创建的新对话)只列 Web 能用的;设置页仍列全部
1208
+ ...(conv || url.searchParams.get("channel") === "web" ? { channel: "web" } : {}),
1141
1209
  // 成员看不到机器上装的技能
1142
1210
  ...(admin ? {} : { member: true }),
1143
1211
  });
@@ -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 : {} };
package/src/core/hub.ts CHANGED
@@ -11,6 +11,7 @@ import crypto from "node:crypto";
11
11
  import { EventEmitter } from "node:events";
12
12
  import { config, onConfigChange, resolveWorkspacePath } from "./config.js";
13
13
  import { attachFooters, copyFooters, formatDuration, recordFooter } from "./footers.js";
14
+ import { removeHistoryRecord, replaceConversationRecords } from "./chat-history.js";
14
15
  import { flushUsage, recordUsage, usageOf, type UsageTotals } from "./usage.js";
15
16
  import { interactions, SETTLEMENT_LABEL } from "./interactions.js";
16
17
  import {
@@ -72,7 +73,9 @@ export type ConvEvent =
72
73
  /** id:这条消息的编号,后面的 queue 事件按它对上;queued:收到时前面还有在跑 / 在等的,要排队 */
73
74
  | { type: "user"; text: string; attachments: string[]; files?: AttachmentInfo[]; origin: Origin; id?: string; queued?: boolean }
74
75
  /** 排队的消息:轮到它了(started,或者被当成提问的回答用掉了),或者没发出去(dropped:停止、会话切换…) */
75
- | { type: "queue"; id: string; state: "started" | "dropped" }
76
+ | { type: "queue"; id: string; state: "started" | "dropped" | "removed" }
77
+ | { type: "user_anchor"; id: string; anchor: string }
78
+ | { type: "history_reset" }
76
79
  /**
77
80
  * 这里弹出过一张授权 / 提问卡(内容和状态在 interactions 里按 id 查)。只是给卡片在对话里占个位置:
78
81
  * 刷新页面时进行中的这一轮靠重放事件画出来,没有它卡片就丢了
@@ -229,9 +232,10 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
229
232
  * 用来告诉页面哪条消息轮到了 / 被丢了,以及「打断并发送」时把哪条挪到前面
230
233
  */
231
234
  private turnFifo = new Map<string, { id: string; input: UserInput; queued: boolean }[]>();
235
+ private pendingInputs = new Map<string, Map<string, { input: UserInput; cancelled: boolean }>>();
236
+ private rewinding = new Set<string>();
232
237
  /** 收到了、还在串行队列里没交给 agent 的消息数:这时再来的消息也算排队 */
233
238
  private waitingSends = new Map<string, number>();
234
- private msgSeq = 0;
235
239
  private announced = new Set<string>();
236
240
  /** 每条会话因缓冲区溢出被丢掉的最后一个 seq */
237
241
  private truncated = new Map<string, number>();
@@ -496,24 +500,21 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
496
500
  return [...parts, streaming].join("\n");
497
501
  }
498
502
 
499
- /** 正在进行的这一轮(从最后一条用户消息起),给刚打开页面的客户端补画用。 */
503
+ /** 正在进行的这一轮及尚未处理的输入,给刚打开页面的客户端补画用。 */
500
504
  liveTurn(key: string): EventEnvelope[] {
501
505
  if (!this.isBusy(key)) return [];
502
506
  const buf = this.buffers.get(key) ?? [];
503
- let start = buf.length;
504
- for (let i = buf.length - 1; i >= 0; i--) {
505
- const t = buf[i]!.ev.type;
506
- if (t === "user") {
507
- start = i;
508
- break;
509
- }
510
- if (t === "result" || t === "error") {
511
- start = i + 1;
512
- break;
513
- }
514
- if (i === 0) start = 0;
515
- }
516
- return buf.slice(start);
507
+ const start = buf.findLastIndex(({ ev }) => ev.type === "result" || ev.type === "error") + 1;
508
+ const fifo = this.turnFifo.get(key) ?? [];
509
+ const active = fifo[0]?.id;
510
+ const inputs = new Set(fifo.map((entry) => entry.id));
511
+ for (const [id, waiting] of this.pendingInputs.get(key) ?? []) if (!waiting.cancelled) inputs.add(id);
512
+ return buf.filter(({ ev }, i) => i >= start || (
513
+ (ev.type === "user" || ev.type === "queue" || ev.type === "user_anchor") && inputs.has(ev.id!)
514
+ )).map((env) => (
515
+ // 下一轮的输入可能早在上一轮结束之前就收到了,重放时它已经不再排队。
516
+ env.ev.type === "user" && env.ev.id === active ? { ...env, ev: { ...env.ev, queued: false } } : env
517
+ ));
517
518
  }
518
519
 
519
520
  isBusy(key: string): boolean {
@@ -665,6 +666,10 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
665
666
  ...(skills ? { skills } : {}),
666
667
  },
667
668
  {
669
+ onUserAnchor: (input, anchor) => {
670
+ if (!alive() || !input.id) return;
671
+ this.emitEvent(key, { type: "user_anchor", id: input.id, anchor });
672
+ },
668
673
  onTurnStart: () => {
669
674
  if (!alive()) return;
670
675
  this.emitEvent(key, { type: "turn_start" });
@@ -923,6 +928,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
923
928
  * 才调到这里时必须传:下载期间点了停止,这条消息就不该再发出去。
924
929
  */
925
930
  send(key: string, input: UserInput, origin: Origin, gen?: InputGen, opts: { task?: TaskTurn } = {}): void {
931
+ if (this.rewinding.has(key)) throw new Error("会话正在回退,请稍后发送");
926
932
  const conv = getConversation(key);
927
933
  if (!conv) throw new Error(`会话不存在:${key}`);
928
934
  const task = opts.task;
@@ -959,9 +965,10 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
959
965
  attachments: input.attachments.map((a) => `${KIND_LABEL[a.kind]} ${a.name}`),
960
966
  files: input.attachments.map(attachmentInfo),
961
967
  origin,
962
- id: `m${++this.msgSeq}`,
968
+ id: crypto.randomUUID(),
963
969
  queued: false,
964
970
  };
971
+ input = { ...input, id: shown.id };
965
972
  const by = `${origin.name ?? "用户"}以消息作答`;
966
973
 
967
974
  /**
@@ -998,6 +1005,10 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
998
1005
  // 前面有在跑的、或者还在串行队列里等着的:这条要排队
999
1006
  shown.queued = this.isBusy(key) || (this.waitingSends.get(key) ?? 0) > 0;
1000
1007
  this.emitEvent(key, shown);
1008
+ const waiting = { input, cancelled: false };
1009
+ let pendingInputs = this.pendingInputs.get(key);
1010
+ if (!pendingInputs) this.pendingInputs.set(key, (pendingInputs = new Map()));
1011
+ pendingInputs.set(shown.id, waiting);
1001
1012
  const dropped = () => this.emitEvent(key, { type: "queue", id: shown.id, state: "dropped" });
1002
1013
  const gone = (text: string) => {
1003
1014
  dropped();
@@ -1006,6 +1017,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1006
1017
  this.waitingSends.set(key, (this.waitingSends.get(key) ?? 0) + 1);
1007
1018
  void this.serial(key, async () => {
1008
1019
  try {
1020
+ if (waiting.cancelled) return;
1009
1021
  if (cancelled()) return gone("没有发出(停止了或者会话被切换了)");
1010
1022
  if (questionAtEntry && tryAnswer(questionAtEntry)) {
1011
1023
  // 被当成提问的回答用掉了:不再排队
@@ -1019,16 +1031,20 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1019
1031
  const expired = !task && !switchedAfterEntry && ttl > 0 && Date.now() - lastActive > ttl;
1020
1032
  if (expired) {
1021
1033
  await this.expireNow(key);
1034
+ if (waiting.cancelled) return;
1022
1035
  // 清理要等旧会话 dispose,期间可能又点了停止
1023
1036
  if (cancelled()) return dropped();
1024
1037
  }
1025
1038
  const blocked = await this.blockedSlash(key, input.text);
1039
+ if (waiting.cancelled) return;
1026
1040
  if (blocked) {
1027
1041
  this.emitEvent(key, { type: "notice", text: blocked });
1028
1042
  return gone(blocked);
1029
1043
  }
1030
1044
  this.sendNow(key, input, task ?? null, { id: shown.id, queued: shown.queued });
1031
1045
  } finally {
1046
+ pendingInputs.delete(shown.id);
1047
+ if (!pendingInputs.size) this.pendingInputs.delete(key);
1032
1048
  this.waitingSends.set(key, Math.max(0, (this.waitingSends.get(key) ?? 1) - 1));
1033
1049
  }
1034
1050
  });
@@ -1361,6 +1377,97 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1361
1377
  return `已换成专家「${hit.label}」,开了新会话。`;
1362
1378
  }
1363
1379
 
1380
+ /** 撤销一条还没开始的输入;当前回复和其他排队消息继续 */
1381
+ cancelQueued(key: string, id: string): { text: string; attachments: AttachmentInfo[] } {
1382
+ if (this.rewinding.has(key)) throw new Error("会话正在回退,请稍后重试");
1383
+ const fifo = this.turnFifo.get(key) ?? [];
1384
+ const index = fifo.findIndex((entry) => entry.id === id);
1385
+ let input: UserInput;
1386
+ if (index >= 0) {
1387
+ if (index === 0 || !this.live.get(key)?.session.cancelQueued?.(fifo[index]!.input)) {
1388
+ throw new Error("这条消息已经开始处理了,请使用「回退到此处」");
1389
+ }
1390
+ input = fifo.splice(index, 1)[0]!.input;
1391
+ const tag = this.turnTags.get(key)?.splice(index, 1)[0];
1392
+ if (tag) this.emit("task", { ...tag, key, status: "interrupted", text: "排队消息已撤销" });
1393
+ this.setInflight(key, (this.inflight.get(key) ?? 1) - 1);
1394
+ } else {
1395
+ const waiting = this.pendingInputs.get(key)?.get(id);
1396
+ const shown = (this.buffers.get(key) ?? []).find((e) => e.ev.type === "user" && e.ev.id === id);
1397
+ if (!waiting || waiting.cancelled || shown?.ev.type !== "user" || !shown.ev.queued) {
1398
+ throw new Error("这条消息已经不在排队了");
1399
+ }
1400
+ waiting.cancelled = true;
1401
+ input = waiting.input;
1402
+ }
1403
+ this.buffers.set(key, (this.buffers.get(key) ?? []).filter(({ ev }) => !("id" in ev && ev.id === id && ["user", "queue", "user_anchor"].includes(ev.type))));
1404
+ const conv = getConversation(key);
1405
+ const owner = conv && memoryOwnerOf(conv);
1406
+ if (owner) removeHistoryRecord(owner, key, id);
1407
+ this.emitEvent(key, { type: "queue", id, state: "removed" });
1408
+ return { text: stripContext(input.text), attachments: input.attachments.map(attachmentInfo) };
1409
+ }
1410
+
1411
+ /** 回退的是对话上下文,已经执行过的文件修改不在此操作里回滚 */
1412
+ async rewind(key: string, target: { id?: string; anchor?: string; sessionId?: string }): Promise<{ text: string; attachments: AttachmentInfo[]; queued?: boolean }> {
1413
+ if (this.rewinding.has(key)) throw new Error("会话正在回退,请稍后重试");
1414
+ const fifo = this.turnFifo.get(key) ?? [];
1415
+ const queued = target.id && (fifo.findIndex((entry) => entry.id === target.id) > 0 || this.pendingInputs.get(key)?.has(target.id));
1416
+ if (queued) {
1417
+ const users = (this.buffers.get(key) ?? []).flatMap(({ ev }) => ev.type === "user" && ev.id ? [ev.id] : []);
1418
+ const index = users.indexOf(target.id!);
1419
+ if (index < 0) throw new Error("找不到这条排队消息,请刷新后重试");
1420
+ const draft = this.cancelQueued(key, target.id!);
1421
+ for (const id of users.slice(index + 1)) {
1422
+ if (fifo.findIndex((entry) => entry.id === id) > 0 || this.pendingInputs.get(key)?.has(id)) this.cancelQueued(key, id);
1423
+ }
1424
+ return { ...draft, queued: true };
1425
+ }
1426
+ this.rewinding.add(key);
1427
+ try {
1428
+ return await this.switchOp(key, async (op) => {
1429
+ const conv = getConversation(key);
1430
+ if (!conv) throw new Error("会话不存在");
1431
+ const driver = this.requireDriver(conv.agent);
1432
+ if (!driver.rewindTo) throw new Error(`${driver.label} 暂不支持回退`);
1433
+ const source = agentBinding(conv).sessionId;
1434
+ if (target.sessionId && target.sessionId !== source) throw new Error("会话已经变化,请刷新后重试");
1435
+ const buf = this.buffers.get(key) ?? [];
1436
+ const anchorEvent = buf.findLast(({ ev }) => ev.type === "user_anchor" && ev.id === target.id)?.ev;
1437
+ const anchor = target.anchor ?? (anchorEvent?.type === "user_anchor" ? anchorEvent.anchor : undefined);
1438
+ const history = source ? attachFooters(source, await withTimeout(driver.readHistory(source, conv.cwd), "读取回退位置")) : [];
1439
+ const index = anchor ? history.findIndex((m) => m.role === "user" && m.anchor === anchor) : -1;
1440
+ const live = buf.find(({ ev }) => ev.type === "user" && ev.id === target.id)?.ev;
1441
+ // 第一条尚未写入 agent 记录:清空当前会话即可,不丢失更早的上下文
1442
+ const firstUnwritten = history.length === 0 && live?.type === "user";
1443
+ if (index < 0 && !firstUnwritten) throw new Error("在会话记录里找不到这条消息,请稍后刷新重试");
1444
+ const message = index >= 0 ? history[index]! : { text: live!.type === "user" ? live!.text : "", attachments: live!.type === "user" ? live!.files : [] };
1445
+ const kept = index >= 0 ? history.slice(0, index) : [];
1446
+ await this.drop(key, "对话已回退");
1447
+ const sessionId = index > 0 && source && anchor ? await withTimeout(driver.rewindTo(source, conv.cwd, anchor), "回退会话") : undefined;
1448
+ this.markSwitched(key, op.seq);
1449
+ updateAgentBinding(key, conv.agent, { sessionId, forkFrom: undefined });
1450
+ if (sessionId) {
1451
+ recordSessionOwner(sessionId, conv.owner);
1452
+ for (const m of kept) if (m.footer) recordFooter(sessionId, m.text, m.footer);
1453
+ }
1454
+ const owner = memoryOwnerOf(conv);
1455
+ if (owner) replaceConversationRecords(owner, key, kept.flatMap((m) => {
1456
+ if (m.role === "question") return [];
1457
+ const text = [m.text, m.attachments?.length ? `(附件:${m.attachments.map((a) => a.name).join("、")})` : ""].filter(Boolean).join("\n");
1458
+ return text.trim() ? [{ k: key, a: conv.agent, r: m.role === "user" ? "u" as const : "a" as const, t: text, ts: m.ts ?? conv.createdAt }] : [];
1459
+ }));
1460
+ this.buffers.delete(key);
1461
+ this.truncated.set(key, this.currentSeq());
1462
+ this.emitEvent(key, { type: "history_reset" });
1463
+ this.emitEvent(key, { type: "meta" });
1464
+ return { text: message.text, attachments: message.attachments ?? [] };
1465
+ });
1466
+ } finally {
1467
+ this.rewinding.delete(key);
1468
+ }
1469
+ }
1470
+
1364
1471
  async stop(key: string): Promise<string> {
1365
1472
  // 不进串行队列:停止要立刻生效。排队中还没送出的消息靠代次作废
1366
1473
  this.stopGen.set(key, (this.stopGen.get(key) ?? 0) + 1);
@@ -68,7 +68,7 @@ export function startHistoryCapture(): void {
68
68
  ? [ev.text, ev.attachments.length ? `(附件:${ev.attachments.join("、")})` : ""].filter(Boolean).join("\n")
69
69
  : ev.text;
70
70
  if (!text.trim()) return;
71
- appendRecords(owner, [{ k: env.key, a: conv.agent, r: ev.type === "user" ? "u" : "a", t: text, ts: env.ts }]);
71
+ appendRecords(owner, [{ k: env.key, a: conv.agent, r: ev.type === "user" ? "u" : "a", t: text, ts: env.ts, ...(ev.type === "user" && ev.id ? { id: ev.id } : {}) }]);
72
72
  } catch (err) {
73
73
  console.warn("[记忆] 记录聊天失败:", err instanceof Error ? err.message : err);
74
74
  }