@yanzc/claude-pro 0.7.8 → 0.9.0

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
@@ -15,7 +15,7 @@
15
15
  ⎿ PASS
16
16
  ```
17
17
 
18
- > **认证**:只使用网关登录。`/login` 会在浏览器完成授权,再把本机专用 key 保存到 `~/.claude-pro/gateway.json`;模型请求和远程控制都只发往网关。
18
+ > **认证**:只使用网关登录。`/login` 会在浏览器完成授权,再把本机专用 key 保存到 `~/.claude-pro/gateway.json`;模型请求和远程会话发布都只发往网关。
19
19
 
20
20
  ## 安装与运行
21
21
 
@@ -28,12 +28,7 @@ npm install -g @yanzc/claude-pro
28
28
  claude-pro # 在任意项目目录里运行
29
29
  ```
30
30
 
31
- 自动更新:用 npm 全局安装的版本在启动时、以及运行中**每 5 分钟**查一次 npm 上的最新版(同一台电脑上的所有会话共用这个间隔,查到的新版本号也共享;查询绕过 npm 的 CDN 缓存)。
32
- - **不打断工作**:发现新版后先记下,底部显示 `update x.y.z ready · installs when idle`;**等这个会话和这台电脑上其他开着的会话都空闲**(没有在执行任务、没有等待回答的问题、没有后台 agent/命令)才安装,有会话在忙就每 30 秒再看一次,本会话一轮结束时也会再试。
33
- - **安装中有提示**:底部显示 `⇣ updating claude-pro to x.y.z…`(`npm install -g --prefer-online`),装好后提示并自动重启加载,对话保留;重启后显示 `↻ Restarted: updated to claude-pro x.y.z`。
34
- - **多个终端**:同一时间只有一个会话去安装(加锁),其他会话看到程序文件变了,会提示"x.y.z 已由另一个窗口安装",各自在空闲时重启;正在工作的会话等它的任务结束才重启。
35
- - npm 刚发布时安装包要几分钟才能下载,期间安装失败会在 1 分钟后重试。所以发布后一般 5–10 分钟内各个客户端就用上新版。
36
- - `/update` 立即检查;`CLAUDE_PRO_AUTO_UPDATE=0` 或 `DISABLE_AUTOUPDATER=1` 关闭。从源码运行(git 检出)的副本从不自动更新。
31
+ 更新是手动触发的:npm 全局安装的版本运行 `/update` 后才检查 npm,并在会话空闲时安装新版;安装由单个会话加锁,完成后通过重启加载新版本并保留对话。源码仓库副本不会被 `/update` 改写。
37
32
 
38
33
  从源码运行:
39
34
 
@@ -113,6 +108,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
113
108
  - 网关对话用 1 小时缓存(停顿一会儿回来不用整段重写);子 agent、压缩等用 5 分钟。改缓存时长、关闭缓存的设置见 `claude-pro config list`。
114
109
  - 页脚的 `◷ 12m` 是缓存还能保留多久;变红表示已过期,下一条消息会把整个对话重新写入缓存。`/cost` 显示命中率和没命中的原因。
115
110
  - 缓存还热时 `/model`、`/effort` 会先确认(切换会让缓存失效);离开一个多小时回来时,清掉较早的工具结果,少重写一些。
111
+ - 人不在时自动保温(Claude 模型):缓存到期前 5 分钟把上一个请求重发一次,只要 1 个输出 token。读缓存会让它再保留一小时,花费是整段重写的 1/40(Opus 上 15 万 token 的对话:约 $0.03,重写约 $1.20)。一次停顿最多保温 8 小时,`CLAUDE_PRO_CACHE_KEEPALIVE_HOURS` 可以改(0 关闭)。`/cost` 显示刷新次数和花费。GPT 模型不需要:网关上的 GPT 缓存停顿几个小时后通常还在。
116
112
 
117
113
  (缓存标记放在哪、端点不认时怎么退、压缩如何复用缓存等细节见 ARCHITECTURE.md 6.5。)
118
114
 
@@ -150,47 +146,32 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
150
146
  - 需要真正退出再启动的只有两种情况:改了 `bin/claude-pro.js` 或 `src/supervisor.js`(运行中的监督进程是旧代码);以及新代码启动不起来而你想强行重启。`-p`、管道、`config` 子命令不经过监督进程;`CLAUDE_PRO_NO_SUPERVISOR=1` 也可以关掉它(环境变量,不是配置项)。
151
147
  - `claude-pro --self-check` 可以单独运行那个启动检查。
152
148
 
153
- ## 远程控制:在浏览器或手机上看执行过程、下发指令
149
+ ## 远程会话:在浏览器里查看和操作
154
150
 
155
- 可以在手机或另一台电脑上看着会话干活,并给它发指令,**不用任何命令或设置**。会话经**网关**(gw.predix.icu,即 `CLAUDE_PRO_GATEWAY_URL`)中转:claude-pro 只向网关发出站请求,**不监听任何端口,不走局域网**;在网关用户端登录后,左侧菜单"**远程控制**"里按电脑分组列出自己的会话,可以查看、操作,也可以在某台电脑上新建、结束、重启会话,恢复历史对话(见下面"网页管理电脑和后台会话")。模型请求和远程控制都使用同一个网关登录。
151
+ 本地手动启动的交互式 claude-pro 会话登录网关后自动注册。远程连接只由终端向 `CLAUDE_PRO_GATEWAY_URL` 发出站请求,终端不监听端口;网页经网关查看并操作已经在运行的本地终端会话(不能新建会话)。
156
152
 
157
- - **默认在线**:这台电脑登录了网关(`/login`)以后,每个交互会话启动时自动连上网关(不阻塞启动,断开后自动重连),网页上能看到这台电脑上所有开着的会话,别的电脑也能给它们发任务(见下一节)。`/login` 登录成功后当前会话**马上上线**(不用重启),并打印它的链接;`/logout` 后马上下线;在别的窗口登录或退出,这个窗口几秒内跟上。模型请求和远程控制共用这个网关登录。
158
- - **在网页上找到会话**:网关用户端的"远程控制"(`/user#remote`)按电脑列出所有会话,点开即可。`/status` 显示这个会话的远程状态(在线、连接中、没登录、key 被拒…)。在线时输入框右上角显示 `⇄ &名字`,有网页在看时页脚显示 `⇄ N watching`。
159
- - **网页上能看到**:完整对话(用户消息、流式输出的回答、可展开的思考、工具调用和结果,包括 diff 和正在运行的命令的最新几行输出)、斜杠命令和提示的输出、当前状态(正在想/运行多久/多少 token、限流暂停的倒计时)、待办列表、排队中的消息。
160
- - **网页上能做**:发消息(和在终端里输入完全一样:忙的时候排队插入,`/命令`、`!shell` 都可以)、**Stop**(等于 Esc)、回答模型的提问(`AskUserQuestion`,含多选和"其他")、以及 `/model`、`/rewind` 之类命令弹出的选择框。网页顶部可以直接改会话的名字、工作目录(`/cd`,带目录浏览)、模型和 effort(都是替你发对应的斜杠命令,终端里显示同样的结果;任务进行中不能改)。网页输入框里输入 `/`、`@`、`&` 有和终端一样的补全,也能粘贴或拖入图片(每次最多 6 张、每张不超过 5 MB,PNG/JPEG/GIF/WebP)。终端和网页可以交替使用,两边同步。
161
- - **安全**:只有同一个网关账户登录后才能看到和操作这个会话;**能登录这个网关账户的人,就能通过它在这台电脑上以完全权限执行命令**。会话内容经网关中转并暂存在网关上。
162
- - **省流量**:没人打开网页时只上报状态(列表里的标题、忙/闲),不上传对话;有人打开时先发一份完整快照,再实时推送。
163
- - **重启不断线**:自动重启(改了源码、自动更新)沿用同一个会话 id,网页显示"重启中"后接着看;网关重启丢了状态时,claude-pro 自动重新注册并补发完整对话。
164
- - 一个会话对应网关上的一个远程会话。每个网关账户最多 20 个(超出时淘汰最久没活动的离线会话);已结束的会话在列表里保留 6 小时,断开但没结束的保留 24 小时。不支持从网页上传图片。
165
- - 不想在线:`/logout`(这台电脑的会话和电脑服务都会下线)。
166
-
167
- ### 网页管理电脑和后台会话(电脑服务 `claude-pro host`)
168
-
169
- 装了 claude-pro 的电脑就是网页的"执行者":网页是操作界面(新建、打开、结束、重启会话,恢复历史对话,看电脑状态和日志),电脑在后台执行,不弹窗口。在终端里手动开的 claude-pro 照常工作,也照常出现在网页上(同一台电脑下)。
170
-
171
- - **接入一台新电脑**:网页"远程控制"里点**添加电脑**,它给出一条命令,例如 `npm i -g @yanzc/claude-pro && claude-pro connect K7QF-M2XD`(`--url <网关>` 可选),在那台电脑上运行一次:用配对码换到这台电脑自己的密钥(存进 `~/.claude-pro/gateway.json`,和 `/login` 一样),设置登录后自动启动,并马上启动电脑服务,打印"已连接到 <账户>,可以在网页上使用这台电脑了"。已经 `/login` 过网关的电脑不用 connect:`/login` 成功后同样会设置自动启动并启动电脑服务;登录了网关的会话启动时也会做一次。
172
- - **新建会话**:选电脑、浏览目录(上面列出最近用过的目录)、可选模型,创建。默认是**后台会话**:那台电脑上没有任何窗口,会话完全在网页上使用(和终端里的 claude-pro 同一套代码,命令、工具、记忆、CLAUDE.md、自动更新都一样);勾上"同时打开终端窗口"才弹出终端窗口(Windows Terminal,没装时是普通控制台;macOS"终端";Linux 桌面上的终端,没有桌面时是 tmux)。一台电脑可以开很多个,每个都是独立进程,一个崩溃不影响别的。
173
- - **历史对话**:网页列出这台电脑上保存的对话(可搜索),点一下就在原来的目录里恢复成后台会话;已经开着的直接打开那个会话。也可以删除:这台电脑上这段对话的记录(会话文件、存成文件的工具结果、它的 /rewind 检查点、跑过它的后台会话的日志)全部删掉,之后不能再恢复;项目的记忆、CLAUDE.md、输入历史不动,网关后台的记录也不动。对话正开在后台会话里时,选"结束并删除记录"会先结束那个会话;正开在终端里的会话不会被代为关闭,要先在那台电脑上 `/exit`。
174
- - **后台会话的管理**:网页上可以结束(等于 `/exit`,忙时先中断,10 秒不退就强制结束)、重启(等于 `/restart`,对话保留)、看日志、展开某个工具调用的完整输出。会话意外退出时自动拉起(同一段对话、同一个网页链接;10 分钟内最多 3 次,之后标为失败并显示日志最后几行,可以在网页上重启)。电脑重启后,电脑服务会重新打开之前的后台会话(只恢复对话,不自动继续被中断的任务);用结束或 `/exit` 关掉的不再打开。
175
- - **把后台会话叫到前台**:网页上点"在电脑上打开窗口",那台电脑上就弹出一个终端窗口接上这个会话(正在执行任务时也可以,任务不中断:窗口里能看到到目前为止的对话和正在进行的这一轮,之后实时跟着走),可以直接在窗口里输入、排队消息、Esc 停止、回答提问,网页同时照常可用。关掉窗口(包括直接点右上角的 X)只是断开,会话回到后台继续运行,仍由电脑服务管理(重启后恢复、网页上结束和重启都照旧)。每点一次开一个新窗口;网页卡片上显示当前接着几个窗口。没有桌面的 Linux 上是开一个 tmux 会话。
176
- - **在本机终端接上后台会话**:`claude-pro attach [名字]`(不带名字时列出本机的后台会话供选择):完整的终端界面,可以输入;`Ctrl+]` 断开,会话继续在后台跑。可以同时 attach 多个终端,网页也可以同时看。会话重启时 attach 自动重新接上。后台会话里 `Ctrl+C` 两次或 `Ctrl+D` 不会结束会话(只有 `/exit` 会)。
177
- - **自动启动**:默认在用户登录后启动(Windows 在"启动"文件夹放一个不弹窗口的 .vbs;macOS 是 LaunchAgent;Linux 桌面是自动启动项,没有桌面时是 systemd 用户服务)。`claude-pro host install --at-boot`:**开机就运行,不用登录**(Windows 是"系统启动时"运行的计划任务,以当前用户身份、不管是否登录,不保存密码,所以访问不了网络共享;需要在"以管理员身份运行"的终端里执行。Linux 是 systemd 用户服务加 `loginctl enable-linger`。macOS 没有 root 做不到,只能登录后启动)。`claude-pro host uninstall` 撤销(之后会话和 `/login` 不会再自动设置);`CLAUDE_PRO_HOST=0` 完全关掉自动启动和自动拉起。
178
- - **其他命令**:`claude-pro host status`(是否在运行、在线、自动启动方式、日志位置);`claude-pro host stop`(停掉,并把这台电脑从网页列表里去掉;之后会话不再自动拉起它,`claude-pro host start` 才重新启动;后台会话继续运行,下次启动的电脑服务会接管);`claude-pro host`(在前台运行,看日志调试用)。服务日志在 `~/.claude-pro/host.log`(网页上也能看),后台会话的日志在 `~/.claude-pro/logs/sessions/<id>.log`,状态在 `~/.claude-pro/host.json`,后台会话列表在 `~/.claude-pro/host-sessions.json`。
179
- - **跟着登录走**:`/logout`、或者网页上移除了这台电脑(密钥作废)后,后台会话结束(保留在恢复列表里),服务从网页列表下线并等待;重新 `/login` 或 `claude-pro connect` 后自动恢复。claude-pro 升级或源码改动后,服务一两分钟内自己换成新版本:先确认新版本能加载,加载不了就继续用旧的,不会让网页失去这台电脑。
180
- - **安全**:能登录这个网关账户的人,可以在这台电脑上任意目录打开会话、以完全权限执行命令。
153
+ - **自动上线**:`/login` 成功后当前会话立即注册;之后每个交互会话启动时自动注册,断线自动重连;`/logout` 后停止远程连接。`CLAUDE_PRO_ONLINE=0` 可以关闭远程发布。
154
+ - **网页能看到**:会话列表、在线/离线/结束状态、模型、目录、机器名、viewer 数、transcript、流式文本和 thinking、工具调用与输出、todos、后台任务、排队消息、问题文本和连接状态。
155
+ - **网页能做**:发消息(等同在终端输入框回车:`/命令`、`!shell`、`#记忆`、`@会话`,最多 6 张图片;忙时排队)、回答对话框(选项、多选、“其他”文字、文本框、取消)、停止(等同 Esc,同时取消等待中的问题)、切换 model/effort(发 `/model`、`/effort`)、浏览目录并 `/cd`(会话在新目录重启,网页接着看)、输入补全(`/命令`、`@文件`、`@会话`)、查看某次工具调用的完整输出(最多 1 MB,运行中的也行)。
156
+ - **只读开关**:`CLAUDE_PRO_REMOTE_COMMANDS=0`(环境变量,或 `claude-pro config set CLAUDE_PRO_REMOTE_COMMANDS 0`)让这台电脑的会话在网页上只能看、不能操作;会话上线时读取,`/status` 会显示 read-only。
157
+ - **网页不能做**:新建会话、恢复/删除历史、打开终端、更新程序或管理电脑;这些只能在本地终端完成。
158
+ - **协议**:远程入口是 `/user#remote`。终端用 `POST /v1/remote/sessions` 注册,并在 `commands` 里声明它接受的指令(`send`、`interrupt`、`dialog`、`options`、`suggest`、`list`、`output`;只读时不带这个字段,网关只转发声明过的类型);`GET .../commands`(SSE)接收 viewer/snapshot/peer 帧和网页的指令 `{cid, type, body}`,用 `POST .../results` 回复 `{cid, ok, …}`;`POST .../events` 发布 snapshot/batch/status/bye。
159
+ - **快照与保留**:网关状态在内存中保存;网关重启后终端重新注册并补发 snapshot。每个账户最多 60 个会话,优先淘汰最久未活动的离线会话;事件缓冲最多 3000 个事件或 8 MB;结束会话保留 6 小时,未结束但离线保留 24 小时。
160
+ - **权限边界**:网页只能看到和操作同一网关账户的会话(能操作就等于能在这台电脑上运行命令:不需要时用只读开关);会话内容会经网关中转并暂存在内存。撤销建立终端流的 API key 后,终端连接会被断开。
181
161
 
182
162
  ## 会话之间互发任务(本机和其他电脑)
183
163
 
184
- 每个交互会话都有一个名字(默认是目录名,输入框右上角的 `&名字`),别的会话可以给它发任务,它做完后回答自动发回来。
164
+ 每个交互会话都有一个名字(默认是目录名,输入框右上角的 `@名字`),别的会话可以给它发任务,它做完后回答自动发回来。
185
165
 
186
166
  - **本机**:同一台电脑上开着的会话直接互通(经 127.0.0.1,不经过网络)。
187
- - **其他电脑**:同一个网关账户下在线的会话经网关互通。例如公司电脑上开着 claude-pro,在家里输入 `&公司 跑一下测试`,任务送到公司那台的会话,回答自动显示在家里这边。电脑名默认是主机名,用 `CLAUDE_PRO_MACHINE_NAME=公司` 改成好记的名字(支持中文)。
188
- - **输入 `&`** 弹出所有能发的会话(本机的和其他电脑在线的),选一个再写任务回车即可:
189
- - `&名字 任务`:本机的会话;
190
- - `&电脑名/名字 任务`:其他电脑上的会话;那台电脑只开着一个会话时直接 `&电脑名 任务`。
191
- - `@` 只用于引用文件。
192
- - **`&` 可以写在句子中间**:输入时在空格后面打 `&` 也会弹出会话列表;在发给当前 agent 的消息里提到 `&名字`,agent 会被告知那是哪个会话、怎么联系它。输入法打出全角 `&` 也可以。
193
- - **`/rename 新名字`**:给当前会话改名(比如 `/rename web-server`),别的会话从此用 `&web-server` 找它;这个名字也成为对话标题(终端标签页、`/resume` 列表、网页),不再自动按话题改;`/resume` 这个对话时名字一起回来。
167
+ - **其他电脑**:同一个网关账户下在线的会话经网关互通。例如公司电脑上开着 claude-pro,在家里输入 `@公司 跑一下测试`,任务送到公司那台的会话,回答自动显示在家里这边。电脑名默认是主机名,用 `CLAUDE_PRO_MACHINE_NAME=公司` 改成好记的名字(支持中文)。
168
+ - **输入 `@`** 弹出文件和会话的混合补全(本机的和其他电脑在线的会话都会列出),选文件可引用它,选会话再写任务回车即可:
169
+ - `@文件路径`:引用文件;带空格的路径使用 `@"文件路径"`;
170
+ - `@名字 任务`:向本机或远程会话发送任务;
171
+ - `@电脑名/名字 任务`:向其他电脑上的指定会话发送任务;那台电脑只开着一个会话时直接 `@电脑名 任务`。
172
+ - 文件和会话同名时,行首 `@名字 任务` 按会话处理;要强制引用文件可写 `@./名字`。
173
+ - **`@` 可以写在句子中间**:输入时在空格后面打 `@` 也会弹出文件和会话列表;在发给当前 agent 的消息里提到 `@名字`,agent 会被告知那是哪个会话、怎么联系它。文件引用仍会展开为文件内容。输入法打出全角 `&` 不再是会话语法。
174
+ - **`/rename 新名字`**:给当前会话改名(比如 `/rename web-server`),别的会话从此用 `@web-server` 找它;这个名字也成为对话标题(终端标签页、`/resume` 列表、网页),不再自动按话题改;`/resume` 这个对话时名字一起回来。
194
175
  - **`/peers`**:列出本机和其他电脑上在线的会话。模型也能用 ListPeers / MessagePeer 工具自己找别的会话分派任务。
195
176
  - 回答会在对方这一轮做完后自动发回;对方正忙时,任务排在它当前工作之后。网关替离线的会话暂存回答(24 小时;网关重启会丢失还没送达的消息)。
196
177
  - **安全**:在线的会话能被同一网关账户执行任何任务。能登录这个账户、或持有它任一 API key 的人,都能在这些电脑上以完全权限执行命令。不需要时 `/logout`。
@@ -199,7 +180,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
199
180
 
200
181
  - **没有权限系统**:没有确认弹窗,没有 allow/deny 规则,也没有 `/permissions`。旧参数 `--dangerously-skip-permissions`、`--permission-mode`、`--allowedTools`、`--disallowedTools` 仍被接受但会被忽略,`--plan` 也是;settings 里残留的 `permissions` 字段也会被忽略。
201
182
  - **没有计划模式**:想先看方案再动手,直接在消息里说(例如"先给方案,我确认前不要改代码")。
202
- - **检查点与 `/rewind`(或在空输入框连按两次 `Esc`)**:每条提问都会建一个检查点,Write / Edit / NotebookEdit 修改文件前会先保存原样。菜单按时间列出这次会话的提问(最新的在最下面、默认选中),选一条后可以:**Restore code and conversation**(代码和对话都回到这条之前)、**Restore conversation**(只回退对话,文件不动)、**Restore code**(只恢复文件,对话不动)、**Summarize from here**(这条及之后的对话压缩成摘要,腾出上下文)、**Summarize up to here**(这条之前的压缩成摘要,之后的原样保留)、**Never mind**(回到列表)。回退对话或"Summarize from here"后,那条提问的原文(完整的,不截断)回填到输入框,可以改了再发,相当于删掉不想要的那段对话重新来。`/clear` 之后,菜单最上面多一项 `/resume <id> (previous session)`,可以回到 `/clear` 之前的对话(本进程内有效)。**Bash 命令造成的改动不会被记录**,所以模型被要求优先用文件工具改文件。
183
+ - **检查点与 `/rewind`(或在空输入框连按两次 `Esc`)**:每条提问都会建一个检查点,Write / Edit / MultiEdit / NotebookEdit 修改文件前会先保存原样。菜单按时间列出这次会话的提问(最新的在最下面、默认选中),选一条后可以:**Restore code and conversation**(代码和对话都回到这条之前)、**Restore conversation**(只回退对话,文件不动)、**Restore code**(只恢复文件,对话不动)、**Summarize from here**(这条及之后的对话压缩成摘要,腾出上下文)、**Summarize up to here**(这条之前的压缩成摘要,之后的原样保留)、**Never mind**(回到列表)。回退对话或"Summarize from here"后,那条提问的原文(完整的,不截断)回填到输入框,可以改了再发,相当于删掉不想要的那段对话重新来。`/clear` 之后,菜单最上面多一项 `/resume <id> (previous session)`,可以回到 `/clear` 之前的对话(本进程内有效)。**Bash 命令造成的改动不会被记录**,所以模型被要求优先用文件工具改文件。
203
184
  - **想要护栏时用 hooks**:`PreToolUse` 钩子仍然可以拦截任何工具调用,由你自己定规则(见下)。
204
185
 
205
186
  **已经放开的限制**(都可以用环境变量改回去):
@@ -221,20 +202,19 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
221
202
 
222
203
  ## 功能
223
204
 
224
- **工具**:`Bash`(持久 cwd、超时、后台运行、可喂 stdin)、`BashOutput`、`KillShell`、`Read`(行号、图片、ipynb)、`Write`、`Edit`(必须先读后改、检测外部修改、保留 CRLF/BOM)、`NotebookEdit`、`Glob`、`Grep`(有 ripgrep 用 rg,否则用内置 JS 搜索:异步不卡界面,遵循 `.gitignore`/`.ignore`、`!` 排除 glob、`^`/`$` 行锚点、多行匹配、上下文行;找不到 rg 时可用 `CLAUDE_PRO_RIPGREP_PATH` 指定;与 rg 不同的是它始终跳过 `node_modules` 等目录,除非 glob 里点名;模型误传的 `file_path` 当作 `path`,grep 的 `-l`/`-c` 当作输出模式)、`WebFetch`、`WebSearch`(DuckDuckGo/Bing)、`TodoWrite`、`Task`(子 agent)、`TaskOutput`、`TaskStop`、`Skill`、`AskUserQuestion`,以及 MCP 工具。
205
+ **工具**:`Bash`(持久 cwd、超时、后台运行、可喂 stdin)、`BashOutput`、`KillShell`、`Read`(行号、图片、ipynb)、`Write`、`MultiEdit`(一次调用改一个文件的多处,按顺序,要么全改要么全不改)、`Edit`(old_string 必须与文件当前内容唯一匹配:没 Read 过、或读后被命令改过的文件也能直接改,结果里会注明;replace_all 和 `Write` 仍要先读、并检测外部修改;只是时间戳变了、内容没变不算修改;保留 CRLF/BOM 和文件编码:UTF-8、带 BOM 的 UTF-16、GBK)、`NotebookEdit`、`Glob`、`Grep`(有 ripgrep 用 rg,否则用内置 JS 搜索:异步不卡界面,遵循 `.gitignore`/`.ignore`、`!` 排除 glob、`^`/`$` 行锚点、多行匹配、上下文行;PATH 上没有 rg 时自动用 VS Code 自带的 rg.exe,也可用 `CLAUDE_PRO_RIPGREP_PATH` 指定;与 rg 不同的是它始终跳过 `node_modules` 等目录,除非 glob 里点名;模型误传的 `file_path` 当作 `path`,grep 的 `-l`/`-c` 当作输出模式)、`WebFetch`、`WebSearch`(DuckDuckGo/Bing)、`TodoWrite`、`Task`(子 agent)、`TaskOutput`、`TaskStop`、`Skill`、`AskUserQuestion`,以及 MCP 工具。
225
206
 
226
207
  **交互**
227
208
  - 流式 Markdown 渲染(代码高亮、表格、中文宽度对齐),思考过程折叠显示(`ctrl+o` 展开)
228
209
  - `Esc` 中断;忙碌时输入的消息会排队并插入当前任务
229
210
  - `!` Bash 模式、`#` 写入记忆(CLAUDE.md)、`\`+回车 或 `ctrl+j` 换行、粘贴大段文本折叠为 `[Pasted text #1 +42 lines]`
230
- - **全屏模式(默认)**:程序画在终端的备用屏幕上(像 vim),输入框固定在窗口最底下,不随输出或终端滚动条移动;对话在程序里滚动:鼠标滚轮(每格 3 行)、`PgUp`/`PgDn`(半屏)、`Ctrl+Home`(对话开头)、`Ctrl+End`(回到最新)。往上翻时新输出不会把画面拉回底部,底部浮着 `Jump to bottom (ctrl+End) ↓ · N new lines`,**点它**或按 `Ctrl+End` 回到底部;发消息时自动回到底部。**选中文字直接用鼠标拖**(不用按 Shift),松开就复制到剪贴板;双击选一个词,三击选一整行;拖到对话区上下边缘会跟着滚动。选中的部分反色显示,点一下别处、按 `Esc` 或任意键就消失;有选中时 `Ctrl+C` 是复制(不会中断任务)。**右键**和在终端里一样:有选中时复制,没有时把剪贴板的文字粘贴进输入框(和 `Ctrl+V` 相同)。仍可按住 Shift 拖动用终端自己的选中。退出后终端回到启动前的样子(对话不留在终端滚动记录里)。`/tui default` 切回经典模式(对话写进终端自己的滚动记录,输入框在窗口底部、靠空行顶到底),`/tui fullscreen` 切回全屏,选择会记住(`CLAUDE_PRO_TUI`)
211
+ - **全屏模式(默认)**:程序画在终端的备用屏幕上(像 vim),输入框固定在窗口最底下,不随输出或终端滚动条移动;对话在程序里滚动:鼠标滚轮(每格 3 行)、`PgUp`/`PgDn`(半屏)、`Ctrl+Home`(对话开头)、`Ctrl+End`(回到最新)。往上翻时新输出不会把画面拉回底部,底部浮着 `Jump to bottom (ctrl+End) ↓ · N new lines`,**点它**或按 `Ctrl+End` 回到底部;发消息时自动回到底部。**选中文字直接用鼠标拖**(不用按 Shift),松开只保留反色选择,不会自动复制;双击选一个词,三击选一整行;拖到对话区上下边缘会跟着滚动。选中的部分反色显示,点一下别处、按 `Esc` 或任意键就消失;有选中时只有 `Ctrl+C` 会复制。`Ctrl+V` 粘贴剪贴板文字(剪贴板里只有图片时作为图片附加),`Alt+V` 优先附加剪贴板图片;右键不执行复制或粘贴。仍可按住 Shift 拖动用终端自己的选中。退出后终端回到启动前的样子(对话不留在终端滚动记录里)。`/tui default` 切回经典模式(对话写进终端自己的滚动记录,输入框在窗口底部、靠空行顶到底),`/tui fullscreen` 切回全屏,选择会记住(`CLAUDE_PRO_TUI`)
231
212
  - `ctrl+c` 或连按两次 `Esc` 清掉的草稿不会丢:在空输入框按 `↑` 找回(连同粘贴的文本和图片),中间发过别的消息也可以
232
- - `@文件` 补全并附加内容:走的就是 `Read` 工具,等于模型自己读了这个文件。最多带前 2000 行(被截断时会明确告诉模型,并把该文件记为"只读了一部分",之后 `Write` 不会去覆盖没给它看过的行);图片作为图片附加;二进制文件和超过 512KB 的文本会被跳过并提示原因;`@目录` 列出目录内容
233
- - `alt+v` 粘贴剪贴板里的图片(截图用 `Win+Shift+S`),输入框里显示为 `[Image #1]`;超过 1568px 的图会自动缩小,超过 512 KB 的 PNG(3D 画面、照片类截图)改用 JPEG 发送,通常只有原来的 1/10(每次请求都带着整个对话,图片太重会让请求超过 32 MB 的上限)。把图片文件拖进终端(或粘贴图片路径)也会作为图片附加
213
+ - `@` 同时补全文件和本机/远程会话:文件引用走 `Read` 工具,等于模型自己读了这个文件。最多带前 2000 行(被截断时会明确告诉模型,并把该文件记为"只读了一部分",之后 `Write` 不会去覆盖没给它看过的行);图片作为图片附加;二进制文件和超过 512KB 的文本会被跳过并提示原因;`@目录` 列出目录内容;行首 `@会话 任务` 把任务发给另一会话
234
214
  - 上下文用量接近阈值时自动压缩(`CLAUDE_CODE_AUTO_COMPACT_WINDOW`),也可手动 `/compact`
235
215
  - 会话自动保存到 `~/.claude-pro/projects/`,`claude-pro -c` 继续上次,`claude-pro -r` 选择历史会话
236
216
 
237
- **`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
217
+ **`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件/会话补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
238
218
 
239
219
  **斜杠命令**:`/help` `/tui` `/cd` `/rename` `/peers` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/trace` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit`,以及 `.claude/commands/*.md`、`.claude-pro/commands/*.md`、`~/.claude-pro/commands/*.md` 中的自定义命令(支持 `$ARGUMENTS`、`$1`、`` !`cmd` ``)。
240
220
 
@@ -248,7 +228,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
248
228
 
249
229
  **后台子 agent**:模型可以用 `Task` 的 `run_in_background: true` 把子 agent 放到后台,自己继续干别的。子 agent 完成后,结果会作为 `<task-notification>` 自动送回;如果当时主 agent 空闲,会自动开启新的一轮来处理结果。`TaskOutput` 用于提前等待结果,`TaskStop` 用于取消;`/tasks` 列出所有后台 agent,`/tasks kill agent_1` 停止其中一个。`-p` 模式会等所有后台 agent 结束后再退出。
250
230
 
251
- **自动验证循环**:如果项目有明确的测试入口,claude-pro 会自动发现并使用 `package.json` 的 `test`/`check`/`verify`/`lint` 脚本,或 `pytest`、`cargo test`、`go test ./...`、`make test`。也可以显式设置验证命令(`--verify "npm test"`、会话中 `/verify npm test`,或 `CLAUDE_PRO_VERIFY_COMMAND`);显式配置优先,`/verify off` 可关闭自动发现。只要某一轮改过文件,模型结束前就会自动运行验证命令。失败的输出会发回给模型继续修复,直到通过,最多 3 轮。没有改文件的轮次不会触发验证。
231
+ **自动验证循环**:如果项目有明确的测试入口,claude-pro 会自动发现并使用 `package.json` 的 `test`/`check`/`verify`/`lint` 脚本,或 `pytest`、`cargo test`、`go test ./...`、`make test`。也可以显式设置验证命令(例如 `--verify "npm run check"`、会话中 `/verify npm run check`,或 `CLAUDE_PRO_VERIFY_COMMAND`);显式配置优先,`/verify off` 可关闭自动发现。只要某一轮改过文件,模型结束前就会自动运行验证命令。失败的输出会发回给模型继续修复,直到通过,最多 3 轮。没有改文件的轮次不会触发验证。
252
232
 
253
233
  **大输出落盘**:工具结果超过 10 万字符时,全文会保存到 `~/.claude-pro/projects/<项目>/tool-results/`,只把预览和文件路径发给模型,模型可以再用 `Read`/`Grep` 按需查看。Bash 输出被截断时同样会保存全文。超过 7 天的旧文件在启动时自动清理。
254
234
 
@@ -257,7 +237,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
257
237
  ```json
258
238
  { "hooks": {
259
239
  "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "node scripts/no-rm-rf.js" } ] } ],
260
- "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "npm test --silent" } ] } ]
240
+ "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "npm run check --silent" } ] } ]
261
241
  } }
262
242
  ```
263
243
 
@@ -276,7 +256,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
276
256
  claude-pro -p "解释一下 src/agent.js" # 只输出最终回答
277
257
  cat error.log | claude-pro -p "这个报错是什么原因"
278
258
  claude-pro -p --output-format json "..." # JSON 结果(含 token 用量)
279
- claude-pro -p --verify "npm test" "修复失败的测试" # 改完自动跑测试,失败继续修
259
+ claude-pro -p --verify "npm run check" "修复失败的检查" # 改完自动运行检查,失败继续修
280
260
  claude-pro -p "只调研,给出重构方案,不要改文件" # 只出方案:在消息里说就行
281
261
  ```
282
262
 
@@ -287,11 +267,12 @@ claude-pro -p "只调研,给出重构方案,不要改文件" # 只出方
287
267
  | `Enter` | 发送 |
288
268
  | `\` + `Enter` / `ctrl+j` / `alt+enter` | 换行 |
289
269
  | `Esc` | 中断当前任务;连按两次:有文字时清空输入,输入框为空时打开回退菜单(同 `/rewind`) |
290
- | `ctrl+c` | 中断 / 清空输入 / 连按两次退出 |
270
+ | `ctrl+c` | 全屏有选中文字时复制;否则中断 / 清空输入 / 连按两次退出 |
271
+ | `ctrl+v` | 粘贴剪贴板文字(只有图片时附加图片) |
272
+ | `alt+v` | 附加剪贴板图片(没有图片时粘贴文字) |
291
273
  | `ctrl+o` | 切换详细输出(思考过程、完整工具输出) |
292
274
  | `ctrl+t` | 显示/隐藏 todo 列表 |
293
275
  | `ctrl+l` | 清屏重绘 |
294
- | `alt+v` | 粘贴剪贴板图片 |
295
276
  | `PgUp` / `PgDn`、滚轮、`Ctrl+Home` / `Ctrl+End` | 全屏模式下滚动对话 / 到开头 / 回到最新 |
296
277
  | `ctrl+f` | 全屏模式下在对话里查找(像 VS Code):输入框的位置换成查找框,边输入边高亮所有匹配(不分大小写,当前这个橙色、其余黄色),右上角显示"第几个/共几个"(`No results` 表示没有)。先跳到视图底部往上最近的一个;`Enter` 或 `↑` 跳到更早的一个,`Shift+Enter` 或 `↓` 跳到更新的一个,到头后绕回;`PgUp`/`PgDn`、滚轮照常滚动;`Esc` 关闭,画面停在当前位置(`Ctrl+End` 回到底部)。再按 `ctrl+f` 会带上上次的关键字(已选中,直接输入就替换);先用鼠标选中文字再按,会搜选中的文字。查找时有新输出,匹配会跟着更新。经典模式(`/tui default`)的对话在终端自己的滚动缓冲里,请用终端自带的查找 |
297
278
  | `↑` / `↓` | 在多行输入(包括自动折行的长文字)里上下移动光标;光标在第一行时 `↑` 先移到开头、再按才翻到上一条历史消息,`↓` 在最后一行同理 |
@@ -299,14 +280,12 @@ claude-pro -p "只调研,给出重构方案,不要改文件" # 只出方
299
280
 
300
281
  ## 开发
301
282
 
302
- GitHub Actions(`.github/workflows/test.yml`)在 Ubuntu、macOS、Windows 上用 Node 22 和 24 跑 `npm run check` 和 `npm test`。
283
+ GitHub Actions(`.github/workflows/test.yml`)在 Ubuntu、macOS、Windows 上用 Node 22 和 24 跑 `npm run check`。这个自检会以 `--self-check` 启动程序,确认模块能够加载并且界面可以启动。
303
284
 
304
285
  ```bash
305
- npm test # 单元测试(node:test)
286
+ npm run check # 启动自检,不连接真实账户
306
287
  ```
307
288
 
308
- `test/tui-harness.js` 可以在无头 xterm 中驱动真实的交互界面(发送按键、截取屏幕),用于测试 UI。限流相关的测试把 `src/ratelimit.js` 的 `timing`(时钟和休眠)换成可控的假时钟,几小时的暂停在测试里瞬间走完;`test/e2e.test.js` 则启动真正的命令行进程对接假 API 服务器。
309
-
310
289
  ```
311
290
  bin/claude-pro.js 入口;交互式会话在这里交给监督进程
312
291
  src/supervisor.js 监督进程:子进程以退出码 75 请求重启时重新启动它,只用 Node 内置模块
@@ -326,7 +305,7 @@ src/prompts.js 系统提示词、压缩提示词、自动记忆提示
326
305
  src/tools/* 各工具实现(含 Skill、NotebookEdit)
327
306
  src/mcp.js MCP 客户端(stdio / HTTP)
328
307
  src/ui/* 终端 UI:屏幕管理、输入框、对话框、Markdown 渲染
329
- src/remote.js 远程控制:经网关中转的客户端、对话事件模型(applyEvent,网关页面里有同一份)
308
+ src/remote.js 远程会话:发布、网页指令、对话事件模型和终端 peer messaging(applyEvent,网关页面里有同一份)
330
309
  src/commands.js 斜杠命令
331
310
  ```
332
311
 
@@ -334,7 +313,7 @@ src/commands.js 斜杠命令
334
313
 
335
314
  WebSearch 通过抓取 DuckDuckGo/Bing 实现。检查点只覆盖文件工具的修改,不覆盖 Bash 命令造成的改动。
336
315
 
337
- 提示:选中文字自动复制是终端的功能。Windows Terminal 在设置里打开“选择时自动复制”(settings.json 里的 `"copyOnSelect": true`)即可。
316
+ 提示:全屏模式里的鼠标选择不会自动写入剪贴板;使用 `Ctrl+C` 复制、`Ctrl+V` 粘贴。按住 Shift 的终端原生选择行为由终端自身决定。
338
317
 
339
318
  ## 历史
340
319
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.7.8",
3
+ "version": "0.9.0",
4
4
  "description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/agent.js CHANGED
@@ -8,6 +8,7 @@ import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuatio
8
8
  import { toolResultsDir } from './session.js';
9
9
  import { rebuildFileState } from './filestate.js';
10
10
  import { CacheStats, TTL_MS } from './cache.js';
11
+ import { CacheKeepAlive } from './keepalive.js';
11
12
  import { resolvePath } from './utils/paths.js';
12
13
  import { fitImagesIn, lightenImagesIn } from './utils/images.js';
13
14
  import { latestWorkState, workStateFromText } from './work-state.js';
@@ -64,7 +65,7 @@ export function persistLargeOutput(root, id, text) {
64
65
  // user's answers and the like stay whatever their age.
65
66
  export const IDLE_CLEARING = { idleMs: 65 * 60_000, keep: 5, atLeast: 20_000 };
66
67
  export const CLEARED = '[Old tool result content cleared]';
67
- const CLEARABLE_TOOLS = new Set(['Read', 'Bash', 'BashOutput', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'Edit', 'Write']);
68
+ const CLEARABLE_TOOLS = new Set(['Read', 'Bash', 'BashOutput', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'Edit', 'MultiEdit', 'Write']);
68
69
  const MIN_CLEAR_TOKENS = 100; // a smaller result is left as it is: clearing it gains next to nothing
69
70
 
70
71
  const isThinking = (b) => b.type === 'thinking' || b.type === 'redacted_thinking';
@@ -123,6 +124,16 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
123
124
  return { messages: out, results: clear.size, tokens, forget: [...gone].filter((f) => !shown.has(f)) };
124
125
  }
125
126
 
127
+ // A summary request's messages with the older half of the turns left out: the first message (the task, or the
128
+ // summary of an earlier compaction) and the newer half stay, with a note in between. null when nothing is left
129
+ // to leave out.
130
+ function withoutOldestHalf(messages) {
131
+ if (messages.length <= 4) return null;
132
+ const cut = Math.floor((messages.length - 1) / 2);
133
+ const note = { role: 'user', content: [{ type: 'text', text: '[Part of the conversation is left out here: with it the summary request did not fit in the context window.]' }] };
134
+ return repairToolResults(normalizeMessages([messages[0], note, ...messages.slice(1 + cut)])).messages;
135
+ }
136
+
126
137
  const notificationBlocks = (notes) => notes.map((n) => ({ type: 'text', text: n.text }));
127
138
 
128
139
  // Queued input may arrive as plain strings or as ready-made content blocks (text + images).
@@ -163,11 +174,14 @@ const recoveredToolResult = (id) => ({
163
174
  // tool_use was persisted but before the user tool_result was appended; gateway adapters reject
164
175
  // that sequence as "No tool output found for function call". The repair is deterministic and
165
176
  // only adds an explicit interrupted result (or drops an orphan result), never a successful one.
177
+ // `recovered`: the ids of the tool calls that got an interrupted result. Blocks are copied only where they
178
+ // change, so the others (images, which a 400 makes the request scale in place) are the conversation's own.
166
179
  export function repairToolResults(messages) {
167
180
  const out = [];
168
181
  let pending = null;
169
182
  let changed = false;
170
183
  let recoveryIndex = 0;
184
+ const recovered = [];
171
185
  const usedIds = new Set();
172
186
  const freshId = () => {
173
187
  let id;
@@ -175,16 +189,17 @@ export function repairToolResults(messages) {
175
189
  usedIds.add(id);
176
190
  return id;
177
191
  };
192
+ const interrupted = (id) => { recovered.push(id); return recoveredToolResult(id); };
178
193
  const flushPending = () => {
179
194
  if (!pending?.length) return;
180
- out.push({ role: 'user', content: pending.map(recoveredToolResult) });
195
+ out.push({ role: 'user', content: pending.map(interrupted) });
181
196
  pending = null;
182
197
  changed = true;
183
198
  };
184
199
 
185
200
  for (const original of messages) {
186
201
  const source = Array.isArray(original.content) ? original.content : toBlocks(original.content);
187
- const m = { ...original, content: source.map((b) => ({ ...b })) };
202
+ const m = { ...original, content: source.slice() };
188
203
  const uses = m.role === 'assistant' ? m.content.filter((b) => b.type === 'tool_use') : [];
189
204
 
190
205
  if (uses.length) {
@@ -194,7 +209,7 @@ export function repairToolResults(messages) {
194
209
  let id = typeof block.id === 'string' && block.id ? block.id : null;
195
210
  if (!id || usedIds.has(id)) {
196
211
  id = freshId();
197
- block.id = id;
212
+ m.content[m.content.indexOf(block)] = { ...block, id };
198
213
  changed = true;
199
214
  } else usedIds.add(id);
200
215
  ids.push(id);
@@ -215,12 +230,13 @@ export function repairToolResults(messages) {
215
230
  if (!expected.has(id) || seen.has(id)) { changed = true; continue; }
216
231
  seen.add(id);
217
232
  if (block.content === undefined || block.content === null) {
218
- block.content = '(no output)';
233
+ results.push({ ...block, content: '(no output)' });
219
234
  changed = true;
235
+ continue;
220
236
  }
221
237
  results.push(block);
222
238
  }
223
- for (const id of pending) if (!seen.has(id)) { results.push(recoveredToolResult(id)); changed = true; }
239
+ for (const id of pending) if (!seen.has(id)) { results.push(interrupted(id)); changed = true; }
224
240
  const content = [...results, ...rest];
225
241
  if (content.length !== m.content.length || content.some((b, i) => b !== m.content[i])) changed = true;
226
242
  out.push({ ...m, content });
@@ -239,7 +255,7 @@ export function repairToolResults(messages) {
239
255
  }
240
256
  }
241
257
  flushPending();
242
- return { messages: out, changed };
258
+ return { messages: out, changed, recovered };
243
259
  }
244
260
 
245
261
  // Minimal JSON-schema check for required fields and primitive types.
@@ -280,6 +296,7 @@ export class Agent {
280
296
  this.trace = trace;
281
297
  this.traceTurnId = null;
282
298
  this.messages = [];
299
+ this.recoveredToolIds = new Set(); // tool calls already said to be recovered (see callModel)
283
300
  this.todos = [];
284
301
  this.workState = null; // last validated state emitted by compaction; the transcript remains the source on resume
285
302
  this.userTurns = 0; // turns the user started (see noteUserTurn)
@@ -292,7 +309,7 @@ export class Agent {
292
309
  this.heldTokens = 0; // room taken by tool results not yet in the conversation (see takeContext)
293
310
  // What this agent's own requests used. `requests` counts the turns' requests; the summary requests of
294
311
  // compactions are counted apart (`compactions`) and their tokens are in the totals like any others.
295
- this.usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0, requests: 0, compactions: 0 };
312
+ this.usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0, requests: 0, compactions: 0, keepalives: 0 };
296
313
  // What the sub-agents this agent started used (they bill like everything else); only the main agent has any.
297
314
  this.subUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0, requests: 0, compactions: 0, runs: 0 };
298
315
  this.cache = new CacheStats(); // how much of the input came from the prompt cache, and why a request missed
@@ -304,6 +321,8 @@ export class Agent {
304
321
  this.postCompactTokens = undefined; // undefined: never compacted; null: compacted, awaiting measurement
305
322
  this.compactFailures = 0; // automatic compactions that failed in a row
306
323
  this.lastActivityAt = 0; // when the last message was added (ms since epoch; 0: unknown), see clearAfterIdle
324
+ this.busy = 0; // turns and summaries in progress: while there are any, the cache needs no refresh
325
+ this.keepAlive = isSubagent ? null : new CacheKeepAlive(this); // the prompt cache kept warm while idle
307
326
  }
308
327
 
309
328
  get model() { return this.modelFn(); }
@@ -340,6 +359,7 @@ export class Agent {
340
359
  }
341
360
 
342
361
  replaceMessages(messages) {
362
+ this.keepAlive?.stop(); // what is cached is no longer the conversation's prefix
343
363
  this.messages = messages;
344
364
  this.cache.noteRewrite(); // the old conversation is no longer a prefix of the next request: not a cache miss
345
365
  this.io.messagesReplaced?.(messages, this);
@@ -381,16 +401,25 @@ export class Agent {
381
401
  });
382
402
  }
383
403
 
384
- async streamAgentRequest(request, { signal, kind = 'turn', cacheBucket = 'main', cacheMessages = true, cacheOverride = null, compactionId = null, onEvent = () => {} } = {}) {
404
+ async streamAgentRequest(request, { signal, kind = 'turn', cacheBucket = 'main', cacheMessages = true, cacheOverride = null, compactionId = null, onEvent = () => {}, waitForRateLimit = true } = {}) {
385
405
  const handle = this.traceRequestStart({ kind, messages: request.messages, cacheBucket, cacheMessages, compactionId });
406
+ // A bug in what shows or traces the stream must not fail the request: it had no HTTP status, so it was taken
407
+ // for a network error and the request was sent (and billed) again, up to the retry limit, failing the same way
408
+ // each time. The reply is assembled without the display; the error is said once.
409
+ let handlerError = null;
386
410
  const forward = (ev) => {
387
- this.trace?.requestEvent(handle, ev);
388
- onEvent(ev);
411
+ try {
412
+ this.trace?.requestEvent(handle, ev);
413
+ onEvent(ev);
414
+ } catch (e) {
415
+ handlerError ??= e;
416
+ }
389
417
  };
390
418
  try {
391
- const res = await streamMessage(this.config, request, { signal, onEvent: forward });
419
+ const res = await streamMessage(this.config, request, { signal, onEvent: forward, waitForRateLimit });
420
+ if (handlerError) this.io.notice?.(`Showing the reply failed (${handlerError.message}); the reply itself is complete.`, 'warn');
392
421
  const observed = cacheOverride ? { ...res, cache: { ...res.cache, ...cacheOverride } } : res;
393
- const recorded = this.recordUsage(observed, kind === 'summary' ? 'summary' : 'turn');
422
+ const recorded = this.recordUsage(observed, kind === 'summary' || kind === 'keepalive' ? kind : 'turn');
394
423
  this.trace?.requestEnd(handle, {
395
424
  usage: res.usage,
396
425
  cache: observed.cache,
@@ -419,7 +448,7 @@ export class Agent {
419
448
  const sum = (k) => a[k] + b[k];
420
449
  return {
421
450
  input: sum('input'), output: sum('output'), cacheRead: sum('cacheRead'), cacheWrite: sum('cacheWrite'), cacheWrite1h: sum('cacheWrite1h'),
422
- requests: sum('requests'), compactions: sum('compactions'),
451
+ requests: sum('requests'), compactions: sum('compactions'), keepalives: a.keepalives,
423
452
  };
424
453
  }
425
454
 
@@ -430,8 +459,9 @@ export class Agent {
430
459
  b.runs++;
431
460
  }
432
461
 
433
- // Count one finished request. `kind` is "turn" for the conversation's own requests and "summary" for the
434
- // request that compacts it; both go into the prompt cache statistics.
462
+ // Count one finished request. `kind` is "turn" for the conversation's own requests, "summary" for the
463
+ // request that compacts it and "keepalive" for a refresh of its cache while idle (keepalive.js); all go into
464
+ // the prompt cache statistics.
435
465
  recordUsage(res, kind = 'turn') {
436
466
  const u = res.usage || {};
437
467
  this.usage.input += u.input_tokens || 0;
@@ -440,7 +470,11 @@ export class Agent {
440
470
  this.usage.cacheWrite += u.cache_creation_input_tokens || 0;
441
471
  this.usage.cacheWrite1h += u.cache_creation?.ephemeral_1h_input_tokens || 0;
442
472
  if (kind === 'summary') this.usage.compactions++;
443
- else this.usage.requests++;
473
+ else if (kind === 'keepalive') this.usage.keepalives++;
474
+ else {
475
+ this.usage.requests++;
476
+ this.keepAlive?.noteRequest(res.cache?.at);
477
+ }
444
478
  const misses = this.cache.misses;
445
479
  this.cache.record({ usage: u, ...res.cache });
446
480
  const cacheMiss = this.cache.misses > misses ? this.cache.lastMiss : null;
@@ -476,6 +510,8 @@ export class Agent {
476
510
  // appended to it would make it load as empty, and it would vanish from the list of conversations
477
511
  // that can be resumed.
478
512
  resetConversation() {
513
+ this.keepAlive?.stop();
514
+ if (this.keepAlive) this.keepAlive.pauseStart = 0;
479
515
  this.messages = [];
480
516
  this.todos = [];
481
517
  this.workState = null;
@@ -502,6 +538,8 @@ export class Agent {
502
538
  if (this.isSubagent || !this.config.clearAfterIdle || !this.lastActivityAt) return null;
503
539
  const idle = now - this.lastActivityAt;
504
540
  if (idle <= IDLE_CLEARING.idleMs) return null;
541
+ // Kept warm through the pause (keepalive.js): clearing now would throw that cache away.
542
+ if (!this.cacheExpired(now)) return null;
505
543
  const last = this.messages.findLast((m) => m.role === 'assistant');
506
544
  const unfinished = Array.isArray(last?.content) && last.content.some((b) => b.type === 'tool_use');
507
545
  if (unfinished && this.config.thinkingBudget > 0) return null;
@@ -522,6 +560,31 @@ export class Agent {
522
560
  return this.lastActivityAt > 0 && now - this.lastActivityAt >= TTL_MS[this.config.cacheTtl('main')];
523
561
  }
524
562
 
563
+ // The conversation's last request again, for a refresh of its cache entry (keepalive.js): the messages before
564
+ // the last reply, the way callModel sent them then (normalizing and repairing give the same result for the same
565
+ // messages), and max_tokens 1. null when there is no reply yet.
566
+ keepAliveRequest() {
567
+ const last = this.messages.findLastIndex((m) => m.role === 'assistant');
568
+ if (last < 1) return null;
569
+ const { messages } = repairToolResults(normalizeMessages(this.messages.slice(0, last)));
570
+ if (messages[messages.length - 1]?.role !== 'user') return null;
571
+ return { model: this.model, system: this.currentSystem(), messages, tools: this.toolSchemas(), cacheBucket: 'main', maxTokens: 1 };
572
+ }
573
+
574
+ // What the session file keeps of the cache for a restarted conversation (see CacheStats.snapshot); null: cold.
575
+ cacheState() {
576
+ const s = this.cache.snapshot();
577
+ return s && { ...s, since: this.keepAlive?.pauseStart || 0 };
578
+ }
579
+
580
+ // A loaded conversation whose cache the session file says is still warm: refreshed from here on as well.
581
+ restoreCacheState(state) {
582
+ if (!this.cache.restore(state)) return false;
583
+ this.keepAlive?.noteRequest(state.since || 0);
584
+ this.keepAlive?.plan();
585
+ return true;
586
+ }
587
+
525
588
  // A new request from the user goes back to the effort the user chose, after the Effort tool changed it for
526
589
  // the one before. A request that a restart continues keeps it.
527
590
  endEffortBoost() {
@@ -546,12 +609,14 @@ export class Agent {
546
609
  }
547
610
 
548
611
  async run(userContent, { signal } = {}) {
612
+ this.keepAlive?.stop(); // the user is back: this turn's requests read the cache themselves
549
613
  const previousTraceTurn = this.traceTurnId;
550
614
  const traceTurnId = this.trace?.turnStart({ agent: this.name, depth: this.depth, content: userContent });
551
615
  this.traceTurnId = traceTurnId;
552
616
  let traceResult = null;
553
617
  let traceError = null;
554
618
  const tracedReturn = (result) => { traceResult = result; return result; };
619
+ this.busy++; // undone in the finally below
555
620
  try {
556
621
  if (!this.isSubagent) {
557
622
  this.beforeTurn?.();
@@ -694,6 +759,8 @@ export class Agent {
694
759
  error: traceError,
695
760
  });
696
761
  this.traceTurnId = previousTraceTurn;
762
+ this.busy--;
763
+ if (!this.busy) this.keepAlive?.plan(); // idle from here: keep what this turn cached warm
697
764
  }
698
765
  }
699
766
 
@@ -744,7 +811,7 @@ export class Agent {
744
811
  const input = { command, timeout: this.config.bashMaxTimeout };
745
812
  const handle = this.io.toolStart?.({ id: `verify_${Date.now()}`, name: 'Verify', input }, tool, input, this) || {};
746
813
  const ctx = { ...this.makeCtx(signal), cwd: this.projectRoot, setCwd() {} };
747
- ctx.onProgress = (p) => handle.progress?.(p);
814
+ ctx.onProgress = (p, meta) => handle.progress?.(p, meta);
748
815
  let result;
749
816
  try {
750
817
  result = await bash.call(input, ctx);
@@ -771,10 +838,13 @@ export class Agent {
771
838
  this.recordedSystem = system;
772
839
  this.io.systemPrompt?.(system, this);
773
840
  }
774
- const normalized = normalizeMessages(this.messages);
775
- const repaired = repairToolResults(normalized);
776
- if (repaired.changed) {
777
- this.replaceMessages(repaired.messages);
841
+ // The repair goes into the request only, done again (the same way) for every request: storing it in place of
842
+ // the conversation merged and inserted messages, which moved the messages the checkpoints point at, so a
843
+ // /rewind after a restart cut the conversation in the wrong place.
844
+ const repaired = repairToolResults(normalizeMessages(this.messages));
845
+ const fresh = repaired.recovered.filter((id) => !this.recoveredToolIds.has(id));
846
+ if (fresh.length) {
847
+ for (const id of fresh) this.recoveredToolIds.add(id);
778
848
  this.io.notice?.('Recovered an unfinished tool call in the conversation; continuing with an interrupted result.', 'warn');
779
849
  }
780
850
  const request = {
@@ -911,7 +981,7 @@ export class Agent {
911
981
 
912
982
  this.toolUseCount++;
913
983
  const handle = this.io.toolStart?.(tu, tool, input, this) || {};
914
- ctx.onProgress = (p) => handle.progress?.(p);
984
+ ctx.onProgress = (p, meta) => handle.progress?.(p, meta);
915
985
  let result;
916
986
  try {
917
987
  result = await tool.call(input, ctx);
@@ -995,7 +1065,19 @@ export class Agent {
995
1065
  // The messages are marked for the cache only where that can be read: no request after the summary starts with
996
1066
  // this history, so writing it (25% over the plain input price) pays only for reading what is already there.
997
1067
  // When the cache is known to have run out, and in the plain request, only the tools and system prompt are marked.
998
- async requestSummary(messages, { signal, onEvent, compactionId = null }) {
1068
+ // While a summary is being written (compaction, /rewind's summaries) the cache needs no refresh either.
1069
+ async requestSummary(messages, options) {
1070
+ this.keepAlive?.stop();
1071
+ this.busy++;
1072
+ try {
1073
+ return await this.summaryRequest(messages, options);
1074
+ } finally {
1075
+ this.busy--;
1076
+ if (!this.busy) this.keepAlive?.plan(); // a compaction that failed left the cache as it was
1077
+ }
1078
+ }
1079
+
1080
+ async summaryRequest(messages, { signal, onEvent, compactionId = null }) {
999
1081
  const cacheMessages = !this.cacheExpired();
1000
1082
  const call = (request, options = {}) => {
1001
1083
  const useMessages = request.cacheMessages === undefined ? cacheMessages : request.cacheMessages;
@@ -1015,7 +1097,27 @@ export class Agent {
1015
1097
  } catch (err) {
1016
1098
  if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
1017
1099
  }
1018
- return call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false }, { cacheOverride: { caching: false } });
1100
+ const plain = (msgs) => call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false, messages: msgs }, { cacheOverride: { caching: false } });
1101
+ let tooLong;
1102
+ try {
1103
+ return await plain(messages);
1104
+ } catch (err) {
1105
+ if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
1106
+ tooLong = err;
1107
+ }
1108
+ // The history alone is over the window (one turn of very large results can do it): the summary is made from
1109
+ // less, old tool results first (as idle clearing does), then the oldest turns. Without this every later
1110
+ // request failed too, and only /clear or /rewind got the conversation going again.
1111
+ let smaller = clearOldToolResults(messages, { keep: 3, atLeast: 0, cwd: this.cwd })?.messages || messages;
1112
+ for (let i = 0; i < 4 && smaller; i++) {
1113
+ try {
1114
+ return await plain(smaller);
1115
+ } catch (err) {
1116
+ if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
1117
+ }
1118
+ smaller = withoutOldestHalf(smaller);
1119
+ }
1120
+ throw tooLong;
1019
1121
  }
1020
1122
 
1021
1123
  // Summarise part of the conversation, as /rewind's "Summarize from here" ('after': the messages from `index` on)