@yanzc/claude-pro 0.8.0 → 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
@@ -146,16 +146,18 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
146
146
  - 需要真正退出再启动的只有两种情况:改了 `bin/claude-pro.js` 或 `src/supervisor.js`(运行中的监督进程是旧代码);以及新代码启动不起来而你想强行重启。`-p`、管道、`config` 子命令不经过监督进程;`CLAUDE_PRO_NO_SUPERVISOR=1` 也可以关掉它(环境变量,不是配置项)。
147
147
  - `claude-pro --self-check` 可以单独运行那个启动检查。
148
148
 
149
- ## 远程会话:浏览器只读查看
149
+ ## 远程会话:在浏览器里查看和操作
150
150
 
151
- 本地手动启动的交互式 claude-pro 会话登录网关后自动注册。远程连接只由终端向 `CLAUDE_PRO_GATEWAY_URL` 发出站请求,终端不监听端口;网页只通过网关查看本地终端会话。
151
+ 本地手动启动的交互式 claude-pro 会话登录网关后自动注册。远程连接只由终端向 `CLAUDE_PRO_GATEWAY_URL` 发出站请求,终端不监听端口;网页经网关查看并操作已经在运行的本地终端会话(不能新建会话)。
152
152
 
153
153
  - **自动上线**:`/login` 成功后当前会话立即注册;之后每个交互会话启动时自动注册,断线自动重连;`/logout` 后停止远程连接。`CLAUDE_PRO_ONLINE=0` 可以关闭远程发布。
154
154
  - **网页能看到**:会话列表、在线/离线/结束状态、模型、目录、机器名、viewer 数、transcript、流式文本和 thinking、工具调用与输出、todos、后台任务、排队消息、问题文本和连接状态。
155
- - **网页不能做**:网页没有输入框和控制写请求,不能发送消息、停止任务、回答问题、切换 model/effort、浏览目录、恢复/删除历史、打开终端、更新程序或管理电脑;这些操作只能在本地终端完成。
156
- - **页面请求**:远程入口是 `/user#remote`;页面只使用 `GET /user/remote/sessions` 和 `GET /user/remote/sessions/:id/events`(SSE)。终端使用 `POST /v1/remote/sessions` 注册,`GET .../commands` 接收 viewer/snapshot/peer 帧,`POST .../events` 发布 snapshot/batch/status/bye。
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。
157
159
  - **快照与保留**:网关状态在内存中保存;网关重启后终端重新注册并补发 snapshot。每个账户最多 60 个会话,优先淘汰最久未活动的离线会话;事件缓冲最多 3000 个事件或 8 MB;结束会话保留 6 小时,未结束但离线保留 24 小时。
158
- - **权限边界**:网页只能看到同一网关账户的会话;会话内容会经网关中转并暂存在内存。撤销建立终端流的 API key 后,终端连接会被断开。
160
+ - **权限边界**:网页只能看到和操作同一网关账户的会话(能操作就等于能在这台电脑上运行命令:不需要时用只读开关);会话内容会经网关中转并暂存在内存。撤销建立终端流的 API key 后,终端连接会被断开。
159
161
 
160
162
  ## 会话之间互发任务(本机和其他电脑)
161
163
 
@@ -178,7 +180,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
178
180
 
179
181
  - **没有权限系统**:没有确认弹窗,没有 allow/deny 规则,也没有 `/permissions`。旧参数 `--dangerously-skip-permissions`、`--permission-mode`、`--allowedTools`、`--disallowedTools` 仍被接受但会被忽略,`--plan` 也是;settings 里残留的 `permissions` 字段也会被忽略。
180
182
  - **没有计划模式**:想先看方案再动手,直接在消息里说(例如"先给方案,我确认前不要改代码")。
181
- - **检查点与 `/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 命令造成的改动不会被记录**,所以模型被要求优先用文件工具改文件。
182
184
  - **想要护栏时用 hooks**:`PreToolUse` 钩子仍然可以拦截任何工具调用,由你自己定规则(见下)。
183
185
 
184
186
  **已经放开的限制**(都可以用环境变量改回去):
@@ -200,7 +202,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
200
202
 
201
203
  ## 功能
202
204
 
203
- **工具**:`Bash`(持久 cwd、超时、后台运行、可喂 stdin)、`BashOutput`、`KillShell`、`Read`(行号、图片、ipynb)、`Write`、`Edit`(必须先读后改、检测外部修改、保留 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 工具。
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 工具。
204
206
 
205
207
  **交互**
206
208
  - 流式 Markdown 渲染(代码高亮、表格、中文宽度对齐),思考过程折叠显示(`ctrl+o` 展开)
@@ -303,7 +305,7 @@ src/prompts.js 系统提示词、压缩提示词、自动记忆提示
303
305
  src/tools/* 各工具实现(含 Skill、NotebookEdit)
304
306
  src/mcp.js MCP 客户端(stdio / HTTP)
305
307
  src/ui/* 终端 UI:屏幕管理、输入框、对话框、Markdown 渲染
306
- src/remote.js 只读远程会话发布、对话事件模型和终端 peer messaging(applyEvent,网关页面里有同一份)
308
+ src/remote.js 远程会话:发布、网页指令、对话事件模型和终端 peer messaging(applyEvent,网关页面里有同一份)
307
309
  src/commands.js 斜杠命令
308
310
  ```
309
311
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.8.0",
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
@@ -65,7 +65,7 @@ export function persistLargeOutput(root, id, text) {
65
65
  // user's answers and the like stay whatever their age.
66
66
  export const IDLE_CLEARING = { idleMs: 65 * 60_000, keep: 5, atLeast: 20_000 };
67
67
  export const CLEARED = '[Old tool result content cleared]';
68
- 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']);
69
69
  const MIN_CLEAR_TOKENS = 100; // a smaller result is left as it is: clearing it gains next to nothing
70
70
 
71
71
  const isThinking = (b) => b.type === 'thinking' || b.type === 'redacted_thinking';
package/src/config.js CHANGED
@@ -33,7 +33,8 @@ export const KNOWN_KEYS = {
33
33
  CLAUDE_PRO_GATEWAY_URL: `codex-gateway address (default https://gw.predix.icu)`,
34
34
  CLAUDE_PRO_GATEWAY_API_KEY: 'Gateway API key (normally saved by /login in gateway.json)',
35
35
  CLAUDE_PRO_GATEWAY_MODEL: 'Model with the gateway provider (default: opus; also sonnet, haiku, gpt-6.1-sol)',
36
- CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway. Otherwise a session publishes a read-only view whenever this computer is logged in; sessions on your other computers can still send it tasks (@computer/name)',
36
+ CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway. Otherwise a session is online on the gateway\'s web page whenever this computer is logged in, and sessions on your other computers can send it tasks (@computer/name)',
37
+ CLAUDE_PRO_REMOTE_COMMANDS: 'Set to 0 to make this computer\'s sessions read-only on the gateway\'s web page: it can watch them, but not send them messages, answer their questions, stop them, switch model or effort, or change their directory (default: on; read when a session goes online)',
37
38
  CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
38
39
  CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside) or default (classic: it scrolls in the terminal); /tui switches',
39
40
  CLAUDE_PRO_AUTO_RESTART: 'Restart by itself when a turn ends and claude-pro\'s own source files changed (default 1; 0 = only on /restart or the Restart tool)',
package/src/filestate.js CHANGED
@@ -12,7 +12,7 @@
12
12
  import fs from 'node:fs';
13
13
  import { resolvePath } from './utils/paths.js';
14
14
 
15
- const TRACKED = new Set(['Read', 'Write', 'Edit', 'NotebookEdit']);
15
+ const TRACKED = new Set(['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
16
16
  const SLACK_MS = 2000; // file timestamps can be coarser than the clock that stamped the message
17
17
 
18
18
  const resultText = (content) => (typeof content === 'string' ? content : '');
package/src/prompts.js CHANGED
@@ -78,7 +78,7 @@ You run on the user's own test machine with full access: tool calls run without
78
78
  - Before deleting or overwriting something, look at what is there: it may be the user's work in progress.
79
79
  - Follow security best practices: never expose, log or commit secrets, and never write code that does.
80
80
  - Do not commit unless the user asks or the project's instructions say when to.
81
- - Edits made with Write, Edit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
81
+ - Edits made with Write, Edit, MultiEdit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
82
82
 
83
83
  # Tools
84
84
  - Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
@@ -114,7 +114,7 @@ ${readOnly ? '' : `
114
114
  - Do not do anything that cannot be undone unless your task asks for it (force-pushing, publishing a package, deleting data outside the project, sending messages or spending money through external services): say in your report what should be done and why, and leave it to the main agent.
115
115
  - Never expose, log or commit secrets, and never write code that does.
116
116
  - Do not commit, push or publish unless your task asks for it: the main agent decides that.
117
- - Edits made with Write, Edit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
117
+ - Edits made with Write, Edit, MultiEdit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
118
118
  `}
119
119
  ${environmentBlock(cwd, { model, shellName, snapshot })}${files ? `\n\n# Project instructions\nThe instructions that apply in this project: its environment, commands and conventions. Follow them for how you work here; committing, pushing and publishing stay the main agent's to decide, whatever they say.\n\n${files}` : ''}${mcpInstructions ? `\n\n${mcpInstructions}` : ''}`;
120
120
  }
package/src/remote.js CHANGED
@@ -1,6 +1,9 @@
1
- // Publish a local interactive session to the gateway so the account's browser can watch it. The session never
2
- // listens on the network: it connects out to the codex-gateway with the gateway API key from /login. The browser
3
- // side is intentionally read-only; the same connection may still carry messages between terminal sessions.
1
+ // Publish a local interactive session to the gateway, so that the account's browser can watch it and steer it: send
2
+ // it messages (as if typed in its input box: /commands, !shell, #memory, pasted images), answer its questions, stop
3
+ // it, switch model and effort, complete input, browse directories for /cd and read a tool call's whole output. The
4
+ // session never listens on the network: it connects out to the codex-gateway with the gateway API key from /login,
5
+ // declares the commands it takes when it registers, and gets them on its command stream. With
6
+ // CLAUDE_PRO_REMOTE_COMMANDS=0 it declares none and is read-only on the page.
4
7
  // The same connection carries the messages of the account's sessions on other computers (`@公司 ...`, see peers.js).
5
8
  //
6
9
  // The page is told what happens as a list of transcript items (user messages, assistant text, thinking, tool
@@ -188,9 +191,19 @@ export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
188
191
  // which only the self-check and the tests set).
189
192
  export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
190
193
 
194
+ // Whether the page may steer the session, not only watch it (CLAUDE_PRO_REMOTE_COMMANDS=0: read-only).
195
+ export const remoteCommandsEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(String(env.CLAUDE_PRO_REMOTE_COMMANDS ?? '').trim());
196
+
197
+ // The commands of the page, and the handler of each (see App.connectRemote; each gets the command's body and
198
+ // returns the result's fields, or a promise of them, or throws what to tell the page). A session declares the ones
199
+ // it has handlers for when it registers (`commands`); the gateway forwards only those and answers the others itself.
200
+ // A session that declares none (0.8.x, CLAUDE_PRO_REMOTE_COMMANDS=0) is read-only on the page.
201
+ const COMMANDS = { send: 'send', interrupt: 'interrupt', dialog: 'answer', options: 'options', suggest: 'suggest', list: 'list', output: 'output' };
202
+
191
203
  export class RemoteControl {
192
204
  // gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
193
- // peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed).
205
+ // peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed), and
206
+ // the page's commands: send, interrupt, answer (dialog), options, suggest, list, output (see COMMANDS).
194
207
  constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
195
208
  this.base = String(gateway.url).replace(/\/+$/, '');
196
209
  this.apiKey = gateway.apiKey;
@@ -216,8 +229,12 @@ export class RemoteControl {
216
229
  this.registered = false;
217
230
  this.refused = null; // the status (401/403) of the gateway refusing the key after the start: the connection ended
218
231
  this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
232
+ this.replying = new Set(); // answers to the page's commands on their way (close() waits for them)
219
233
  }
220
234
 
235
+ // The commands this session takes, as declared to the gateway.
236
+ get commands() { return Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function'); }
237
+
221
238
  get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
222
239
 
223
240
  // `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
@@ -257,7 +274,8 @@ export class RemoteControl {
257
274
 
258
275
  async register() {
259
276
  const info = this.handlers.info?.() || {};
260
- const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info });
277
+ const commands = this.commands;
278
+ const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info, ...(commands.length ? { commands } : {}) });
261
279
  if (data.id) this.id = data.id;
262
280
  this.url = data.url || this.url || `${this.base}/user`;
263
281
  this.registered = true;
@@ -360,8 +378,32 @@ export class RemoteControl {
360
378
  if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
361
379
  if (!cmd.cid) return;
362
380
  if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
363
- // Browser-originated control commands are not part of the read-only portal. Ignore any stale command
364
- // frames from an older gateway instead of executing them locally.
381
+ // A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
382
+ // gateway waits 15 s for it, and takes it until 3 s after the stream closed). close() waits for the answers on
383
+ // their way: a /cd or /exit from the page ends the session from inside its command.
384
+ const reply = (result) => {
385
+ const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
386
+ this.replying.add(sent);
387
+ sent.finally(() => this.replying.delete(sent));
388
+ this.scheduleFlush(30); // what the command changed, on the page soon
389
+ };
390
+ const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
391
+ const handler = Object.hasOwn(COMMANDS, cmd.type) ? this.handlers[COMMANDS[cmd.type]] : null;
392
+ if (typeof handler !== 'function') {
393
+ // an older gateway forwards every command, declared or not
394
+ failed(new Error(this.commands.length ? `Unknown command: ${cmd.type}` : 'This session is read-only on the web page (CLAUDE_PRO_REMOTE_COMMANDS=0 on its computer).'));
395
+ return;
396
+ }
397
+ let r;
398
+ try {
399
+ r = handler(cmd.body && typeof cmd.body === 'object' && !Array.isArray(cmd.body) ? cmd.body : {});
400
+ } catch (e) {
401
+ failed(e);
402
+ return;
403
+ }
404
+ // an answer that takes a while (the gateway's list of models, a directory) is sent when it is there
405
+ if (typeof r?.then === 'function') r.then((v) => reply({ ...(v || {}), cid: cmd.cid, ok: true }), failed);
406
+ else reply({ ...(r || {}), cid: cmd.cid, ok: true });
365
407
  }
366
408
 
367
409
  // ------------------------------------------------------------ messages of the account's other sessions
@@ -526,8 +568,12 @@ export class RemoteControl {
526
568
  }
527
569
 
528
570
  async shutdown(restarting) {
529
- // Flush the final read-only transcript/status update while the command stream is still open.
571
+ // First the answers on their way, while the command stream is still open (the gateway takes them until 3 s
572
+ // after it closes). Among them the answer to the command that ends the session: a /cd, /restart or /exit from
573
+ // the page closes it from inside that command, and its answer is sent when the command returns, hence the
574
+ // wait for the current call to finish first.
530
575
  await null;
576
+ if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
531
577
  this.closing = true; // what flush() collects now goes out with the last message, not on its own
532
578
  this.flush();
533
579
  this.closed = true;
package/src/tools/bash.js CHANGED
@@ -169,7 +169,7 @@ When you commit (the system prompt says when): run git status, git diff and git
169
169
  output += text;
170
170
  for (let i = text.indexOf('\n'); i >= 0; i = text.indexOf('\n', i + 1)) lines++;
171
171
  if (output.length > 10_000_000) { output = output.slice(-5_000_000); droppedHead = true; }
172
- ctx.onProgress?.(stripAnsi(output.slice(-PROGRESS_CHARS)), { lines });
172
+ ctx.onProgress?.(stripAnsi(output.slice(-PROGRESS_CHARS)), { lines, all: () => stripAnsi(output) });
173
173
  },
174
174
  done: finish,
175
175
  });
@@ -3,6 +3,7 @@
3
3
 
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
+ import crypto from 'node:crypto';
6
7
  import { resolvePath, displayPath } from '../utils/paths.js';
7
8
  import { diffLines, makeHunks, countChanges, splitLines } from '../utils/diff.js';
8
9
  import { fitImage } from '../utils/images.js';
@@ -70,10 +71,13 @@ function unwritable(file, text, meta) {
70
71
  return error ? `${file} is ${encodingName(meta.encoding)}-encoded (kept so when it is edited), and the new text has ${error}. Use other characters, or convert the file to UTF-8 first if the user wants that.` : null;
71
72
  }
72
73
 
74
+ // Each line as its number, a tab and the line. Not padded as cat -n pads it: the padding cost 2 tokens a line on
75
+ // GPT and 1 on Claude (measured 2026-10-26: 12% of a code Read on gpt-6.1-sol, 4% on Opus 5.5), in every Read
76
+ // result, which stays in the conversation and is sent again with every later request.
73
77
  export function numberLines(lines, start, maxLineChars = MAX_LINE_CHARS) {
74
78
  return lines.map((l, i) => {
75
79
  const line = l.length > maxLineChars ? l.slice(0, maxLineChars) + '… [line truncated]' : l;
76
- return `${String(start + i).padStart(6)}\t${line}`;
80
+ return `${start + i}\t${line}`;
77
81
  }).join('\n');
78
82
  }
79
83
 
@@ -102,10 +106,10 @@ Usage:
102
106
  - Read a file whole when you need to understand it; when only a part of a long file matters, give offset and limit (find the place with Grep first if needed)
103
107
  - Any lines longer than ${MAX_LINE_CHARS} characters will be truncated
104
108
  - A file whose numbered text is longer than ${MAX_OUTPUT_CHARS} characters or about ${MAX_OUTPUT_TOKENS / 1000}k tokens (Chinese text gets there sooner) is refused (or cut there with offset/limit). When you need a large file whole, in one call, pass allow_large: true: then there is no line, character or line length limit, only the room left in the context, and a read that does not fit is refused.
105
- - Results are returned using cat -n format, with line numbers starting at 1
109
+ - Results are returned as each line's number, a tab, then the line (numbers start at 1)
106
110
  - This tool can read images (PNG, JPG, GIF, WEBP) and Jupyter notebooks (.ipynb)
107
111
  - This tool can only read files, not directories. To list a directory, use ls via the Bash tool.
108
- - Do not read a file again just to check an edit you made to it: Edit and Write report an error when they fail.
112
+ - Do not read a file again just to check an edit you made to it: Edit, MultiEdit and Write report an error when they fail.
109
113
  - If you read a file that exists but has empty contents you will receive a warning in place of file contents.`,
110
114
  input_schema: {
111
115
  type: 'object',
@@ -150,23 +154,26 @@ Usage:
150
154
  }
151
155
  if (ext === '.ipynb') {
152
156
  try {
153
- const nb = JSON.parse(fs.readFileSync(file, 'utf8'));
157
+ const raw = fs.readFileSync(file);
158
+ const nb = JSON.parse(raw.toString('utf8'));
154
159
  const rendered = renderNotebook(nb);
155
160
  if (rendered.length > MAX_OUTPUT_CHARS || tooManyTokens(rendered)) {
156
161
  return { isError: true, content: `Notebook content (${Math.round(rendered.length / 1024)}KB, about ${tokensOf(rendered).toLocaleString('en-US')} tokens) exceeds the maximum allowed size. Look at parts of it with the Bash tool (python or jq on its JSON), or use Grep to search it.` };
157
162
  }
158
- ctx.fileState.set(file, { mtimeMs: stat.mtimeMs });
163
+ ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, hash: hashOf(raw) });
159
164
  return { content: rendered, display: { summary: `Read ${(nb.cells || []).length} cells` } };
160
165
  } catch (e) {
161
166
  return { isError: true, content: `Could not parse notebook: ${e.message}` };
162
167
  }
163
168
  }
164
- const decoded = readText(file, fs.readFileSync(file));
169
+ const buf = fs.readFileSync(file);
170
+ const decoded = readText(file, buf);
165
171
  if (!decoded) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
166
172
  const note = encodingNote(decoded);
167
173
  const lines = splitLines(decoded.text);
168
- // `partial` records that part of the file was not shown, so Write can refuse to overwrite it.
169
- const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial });
174
+ // `partial` records that part of the file was not shown, so Write can refuse to overwrite it; `hash` tells a
175
+ // later change of its time without a change of its bytes from a real one (see fileStanding).
176
+ const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial, hash: hashOf(buf) });
170
177
  if (lines.length === 0) {
171
178
  seen(false);
172
179
  return { content: '<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>', display: { summary: 'Read 0 lines (empty file)' } };
@@ -208,28 +215,47 @@ Usage:
208
215
  },
209
216
  };
210
217
 
218
+ const hashOf = (buf) => crypto.createHash('sha1').update(buf).digest('hex');
219
+
220
+ // How a file stands against what the model has seen of it: null (read or written by it, unchanged since),
221
+ // 'unread', or 'modified' (changed on disk since). A time that moved while the bytes stayed the same (git, a
222
+ // formatter that changed nothing, an antivirus scan or a cloud sync on Windows) is no change: the content is
223
+ // compared as well, as Claude Code does.
224
+ export function fileStanding(file, ctx) {
225
+ const state = ctx.fileState.get(file);
226
+ if (!state) return 'unread';
227
+ const now = mtime(file);
228
+ if (now === null || state.mtimeMs === undefined || Math.abs(now - state.mtimeMs) <= 1) return null;
229
+ let same = false;
230
+ try { same = Boolean(state.hash) && hashOf(fs.readFileSync(file)) === state.hash; } catch { /* gone: changed */ }
231
+ if (!same) return 'modified';
232
+ state.mtimeMs = now;
233
+ return null;
234
+ }
235
+
211
236
  // Validate that a file may be written: it must have been read and be unchanged since. With
212
237
  // `full`, which Write needs because it replaces the whole file, the read must also have covered
213
- // all of it; Edit only replaces text it matched exactly, so a partial read is enough there.
238
+ // all of it. (Edit has its own rule, see EditTool.plan.)
214
239
  export function checkFreshness(file, ctx, { full = false } = {}) {
215
- const state = ctx.fileState.get(file);
216
- if (!state) return 'File has not been read yet. Read it first before writing to it.';
217
- if (full && state.partial) {
218
- return 'File was only partly read (offset/limit), so Write would overwrite content you have not seen. Read the whole file first, or use Edit for targeted changes.';
240
+ const standing = fileStanding(file, ctx);
241
+ if (standing === 'unread') return 'File has not been read yet. Read it first before writing to it.';
242
+ if (full && ctx.fileState.get(file).partial) {
243
+ return 'Only part of this file has been seen (a Read with offset/limit, or edits without a whole Read), so Write would overwrite content you have not seen. Read the whole file first, or use Edit for targeted changes.';
219
244
  }
220
- const now = mtime(file);
221
- if (now !== null && state.mtimeMs !== undefined && Math.abs(now - state.mtimeMs) > 1) {
245
+ if (standing === 'modified') {
222
246
  return 'File has been modified since it was last read, either by the user or by a linter. Read it again before attempting to write it.';
223
247
  }
224
248
  return null;
225
249
  }
226
250
 
227
251
  // In the encoding, BOM and line endings the file had (`meta`, from readText); checked with unwritable() first.
252
+ // Returns the hash of what was written, for the file state.
228
253
  function writeText(file, text, { crlf, bom, encoding = 'utf8' }) {
229
254
  const { buffer, error } = encodeText(crlf ? text.replace(/\r?\n/g, '\r\n') : text, { encoding, bom });
230
255
  if (error) throw new Error(`${file}: ${error}`);
231
256
  fs.mkdirSync(path.dirname(file), { recursive: true });
232
257
  fs.writeFileSync(file, buffer);
258
+ return hashOf(buffer);
233
259
  }
234
260
 
235
261
  // Where the new text of an edit is, for its result: "lines 12-18", "line 12", or "text removed at line 12".
@@ -290,8 +316,8 @@ Usage:
290
316
  // The encoding, BOM and line endings of what was there stay (a binary file it replaces: plain UTF-8).
291
317
  const prev = (exists && readText(file)) || { text: '', crlf: false, bom: false, encoding: 'utf8' };
292
318
  const preview = this.preview(input, ctx);
293
- writeText(file, input.content, prev);
294
- ctx.fileState.set(file, { mtimeMs: mtime(file) });
319
+ const hash = writeText(file, input.content, prev);
320
+ ctx.fileState.set(file, { mtimeMs: mtime(file), hash });
295
321
  const n = splitLines(input.content).length;
296
322
  if (!exists) {
297
323
  return {
@@ -313,7 +339,8 @@ function changeSummary({ added, removed }) {
313
339
  return parts.length ? `Updated with ${parts.join(' and ')}` : 'No changes';
314
340
  }
315
341
 
316
- // Apply old->new replacement to text. Returns {result, count, index} or {error}.
342
+ // Apply old->new replacement to text. Returns {result, count, index} or {error, notFound}. The errors do not repeat
343
+ // old_string (the model has it in its own call): a miss shows where the most similar text is instead (see missed).
317
344
  export function applyEdit(text, oldStr, newStr, replaceAll) {
318
345
  if (oldStr === newStr) return { error: 'No changes to make: old_string and new_string are exactly the same.' };
319
346
  if (oldStr === '') {
@@ -326,7 +353,7 @@ export function applyEdit(text, oldStr, newStr, replaceAll) {
326
353
  // Tolerate trailing whitespace differences at line ends.
327
354
  const norm = (s) => s.replace(/[ \t]+\n/g, '\n');
328
355
  if (norm(text).includes(norm(oldStr)) && norm(text) !== text) {
329
- return { error: 'String to replace not found exactly (whitespace differs at line ends). Read the file again and copy the text exactly, including whitespace.' };
356
+ return { error: 'String to replace not found exactly (whitespace differs at line ends): copy the text exactly, including the whitespace at the ends of its lines.', notFound: true };
330
357
  }
331
358
  // Curly quote normalisation.
332
359
  const straight = (s) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"');
@@ -337,25 +364,130 @@ export function applyEdit(text, oldStr, newStr, replaceAll) {
337
364
  count = text.split(actualOld).length - 1;
338
365
  }
339
366
  }
340
- if (count === 0) return { error: `String to replace not found in file.\nString: ${oldStr}` };
367
+ if (count === 0) return { error: 'String to replace not found in file.', notFound: true };
341
368
  if (count > 1 && !replaceAll) {
342
- return { error: `Found ${count} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: ${oldStr}` };
369
+ return { error: `Found ${count} matches of the string to replace (${matchLines(text, actualOld)}), but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one, add the lines around it to old_string so that it matches that one only.` };
343
370
  }
344
371
  const index = text.indexOf(actualOld);
345
372
  const result = replaceAll ? text.split(actualOld).join(newStr) : text.slice(0, index) + newStr + text.slice(index + actualOld.length);
346
373
  return { result, count, index };
347
374
  }
348
375
 
376
+ // "at lines 12, 40 and 77": where `needle` starts in `text` (the first 10).
377
+ function matchLines(text, needle) {
378
+ const lines = [];
379
+ for (let i = text.indexOf(needle); i >= 0 && lines.length < 11; i = text.indexOf(needle, i + needle.length)) {
380
+ lines.push(text.slice(0, i).split('\n').length);
381
+ }
382
+ const shown = lines.slice(0, 10);
383
+ const list = shown.length > 1 ? `${shown.slice(0, -1).join(', ')} and ${shown.at(-1)}` : String(shown[0]);
384
+ return `at line${shown.length > 1 ? 's' : ''} ${list}${lines.length > 10 ? ' and more' : ''}`;
385
+ }
386
+
387
+ // Character bigrams of a string, for a similarity of two lines (Dice coefficient).
388
+ function bigrams(s) {
389
+ const m = new Map();
390
+ for (let i = 0; i < s.length - 1; i++) { const g = s.slice(i, i + 2); m.set(g, (m.get(g) || 0) + 1); }
391
+ return m;
392
+ }
393
+ function dice(a, b) {
394
+ let n = 0, total = 0;
395
+ for (const [g, c] of a) { total += c; n += Math.min(c, b.get(g) || 0); }
396
+ for (const c of b.values()) total += c;
397
+ return total ? (2 * n) / total : 0;
398
+ }
399
+
400
+ // The part of `text` most like `oldStr`, for an edit that missed: {from, to, text} (1-based lines, numbered as Read
401
+ // numbers them) or null when nothing is alike. Lines of old_string found whole (whitespace aside) vote for where
402
+ // it would start; without any, its longest line is looked for by similarity. Most misses are an old_string from
403
+ // memory or with other indentation: the right text in the error saves a Read and gets the retry right.
404
+ function similarRegion(text, oldStr, maxLines = 14) {
405
+ const lines = text.split('\n');
406
+ const want = oldStr.replace(/\n+$/, '').split('\n');
407
+ if (lines.length > 50_000 || lines.length * want.length > 5_000_000) return null;
408
+ const key = (s) => s.trim();
409
+ const at = new Map();
410
+ lines.forEach((l, i) => { const k = key(l); if (k.length >= 3) { const list = at.get(k); if (list) list.push(i); else at.set(k, [i]); } });
411
+ const votes = new Map();
412
+ want.forEach((l, k) => {
413
+ const hits = at.get(key(l));
414
+ if (hits && hits.length <= 20) for (const i of hits) votes.set(i - k, (votes.get(i - k) || 0) + 1);
415
+ });
416
+ let start = null;
417
+ let best = 0;
418
+ for (const [s, v] of votes) if (v > best || (v === best && s < start)) { best = v; start = s; }
419
+ const meaningful = want.filter((l) => key(l).length >= 3).length;
420
+ if (start === null || best < Math.max(1, Math.ceil(meaningful * 0.3))) {
421
+ const probe = want.map(key).reduce((a, b) => (b.length > a.length ? b : a), '');
422
+ if (probe.length < 6) return null;
423
+ const k = want.findIndex((l) => key(l) === probe);
424
+ const pb = bigrams(probe);
425
+ let score = 0;
426
+ start = null;
427
+ lines.forEach((l, i) => {
428
+ const t = key(l);
429
+ if (!t || t.length > probe.length * 3 || probe.length > t.length * 3) return;
430
+ const s = dice(pb, bigrams(t));
431
+ if (s > score) { score = s; start = i - k; }
432
+ });
433
+ if (start === null || score < 0.5) return null;
434
+ }
435
+ const from = Math.max(0, start - 1);
436
+ const to = Math.min(lines.length - 1, Math.max(from, start + want.length), from + maxLines - 1);
437
+ return { from: from + 1, to: to + 1, text: numberLines(lines.slice(from, to + 1), from + 1, 300) };
438
+ }
439
+
440
+ // The error of an edit whose old_string was not used: where the most similar text is, when it missed, and what to
441
+ // do about a file it had not read or that changed since. `step`: "Edit 2 of 3: " in MultiEdit.
442
+ function missed(r, text, oldStr, unseen, step = '') {
443
+ let msg = step + r.error;
444
+ if (r.notFound) {
445
+ const near = similarRegion(text, oldStr);
446
+ if (near) {
447
+ msg += ` The most similar text${step && !step.startsWith('Edit 1 ') ? ', in the file as the edits before this one left it,' : ''} is at lines ${near.from}-${near.to}:\n${near.text}\nIf that is the place, copy old_string from these lines exactly (without the line numbers); if not, Read the file.`;
448
+ if (unseen === 'modified') msg += ' (The file has changed since you last read it.)';
449
+ return msg;
450
+ }
451
+ return `${msg} ${unseen ? UNSEEN_HINT[unseen] : 'Read the file to get its exact text.'}`;
452
+ }
453
+ return unseen ? `${msg} ${UNSEEN_HINT[unseen]}` : msg;
454
+ }
455
+
456
+ // The lines an edit left changed in the new text, for its result: "lines 12-18, 40 and 77-80" (from the diff).
457
+ function changedRanges(ops, max = 8) {
458
+ const ranges = [];
459
+ let line = 0;
460
+ let removedAt = null;
461
+ for (const op of ops) {
462
+ if (op.op === '-') { removedAt ??= line + 1; continue; }
463
+ line++;
464
+ if (op.op === '+') {
465
+ const last = ranges.at(-1);
466
+ if (last && !last.removed && last.to === line - 1) last.to = line;
467
+ else ranges.push({ from: line, to: line });
468
+ removedAt = null;
469
+ } else if (removedAt !== null) {
470
+ ranges.push({ from: removedAt, to: removedAt, removed: true });
471
+ removedAt = null;
472
+ }
473
+ }
474
+ if (removedAt !== null) ranges.push({ from: removedAt, to: removedAt, removed: true });
475
+ const text = ranges.slice(0, max).map((r) => (r.removed ? `text removed at line ${r.from}` : r.from === r.to ? `line ${r.from}` : `lines ${r.from}-${r.to}`));
476
+ if (ranges.length > max) text.push(`${ranges.length - max} more places`);
477
+ return text.length > 1 ? `${text.slice(0, -1).join(', ')} and ${text.at(-1)}` : text[0] || 'no lines changed';
478
+ }
479
+
349
480
  export const EditTool = {
350
481
  name: 'Edit',
351
482
  editsFiles: true,
352
483
  description: `Performs exact string replacements in files.
353
484
 
354
485
  Usage:
355
- - You must use your \`Read\` tool at least once in the conversation before editing (a Grep result does not count). This tool will error if you attempt an edit without reading the file.
356
- - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
357
- - The edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
486
+ - old_string must be the file's exact current text, so Read the file first unless that text is already in this conversation (a Read, Bash or Grep output, an edit of yours). An edit whose old_string occurs exactly once is made even when the file was not read or has changed since (the result says so); replace_all needs a Read of the file as it is now.
487
+ - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
488
+ - The edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. When it is not found, the error shows the most similar lines of the file.
358
489
  - Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
490
+ - More than one change to a file: make them all in one MultiEdit call, not one Edit per response. Changes to several files: put their Edit or MultiEdit calls in the same response (they are made in the order given). Every response is a round trip that sends the whole conversation again and takes tens of seconds.
359
491
  - To create a new file, pass an empty old_string with the full content as new_string (the file must not exist).`,
360
492
  input_schema: {
361
493
  type: 'object',
@@ -379,19 +511,27 @@ Usage:
379
511
  return { file, created: true, before: '', after: newStr, meta: { crlf: false, bom: false } };
380
512
  }
381
513
  if (fs.statSync(file).isDirectory()) return { error: `${file} is a directory` };
382
- const fresh = checkFreshness(file, ctx);
383
- if (fresh) return { error: fresh };
514
+ // A Read is what shows the model the text it replaces, but an old_string that occurs exactly once in the file
515
+ // as it is now shows it too: text from a Bash or Grep output, its own earlier edit, a Read whose result was
516
+ // cleared, a file one of its commands changed. Such an edit is made, with a note; refusing it cost a Read and a
517
+ // retry (in 70 sessions to 2026-10-26, 117 of 2,781 edits). replace_all has no such proof: it needs the read.
518
+ const unseen = fileStanding(file, ctx);
519
+ if (unseen && input.replace_all) {
520
+ return { error: unseen === 'unread'
521
+ ? 'File has not been read yet. Read it first before replacing every occurrence in it.'
522
+ : 'File has been modified since it was last read, either by the user or by a command. Read it again before replacing every occurrence in it.' };
523
+ }
384
524
  const current = readText(file);
385
525
  if (!current) return { error: notText(file) };
386
526
  if (current.lossy) return { error: notRewritable(file, current) };
387
527
  const { text, crlf, bom, encoding } = current;
388
528
  const before = text.replace(/\r\n/g, '\n');
389
529
  const r = applyEdit(before, oldStr, newStr, !!input.replace_all);
390
- if (r.error) return { error: r.error };
530
+ if (r.error) return { error: missed(r, before, oldStr, unseen) };
391
531
  const meta = { crlf, bom, encoding };
392
532
  const cannot = unwritable(file, r.result, meta);
393
533
  if (cannot) return { error: cannot };
394
- return { file, before, after: r.result, index: r.index, count: r.count, meta, newStr };
534
+ return { file, before, after: r.result, index: r.index, count: r.count, meta, newStr, unseen };
395
535
  },
396
536
  validate(input, ctx) { return this.plan(input, ctx).error || null; },
397
537
  // `p` is an already computed plan, so call() does not read the file and redo the edit a second time.
@@ -406,9 +546,10 @@ Usage:
406
546
  if (p.error) return { isError: true, content: p.error };
407
547
  const preview = this.preview(input, ctx, p);
408
548
  const prior = ctx.fileState.get(p.file);
409
- writeText(p.file, p.after, p.meta);
410
- // An edit does not show the rest of the file, so a partial read stays partial (a created file is all ours).
411
- ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && !!prior?.partial });
549
+ const hash = writeText(p.file, p.after, p.meta);
550
+ // An edit does not show the rest of the file, so a partial read stays partial (a created file is all ours), and
551
+ // a file edited unread, or changed since it was read, counts as partly seen: Write wants a whole Read of it.
552
+ ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && (!prior || Boolean(prior.partial) || p.unseen === 'modified'), hash });
412
553
  if (p.created) {
413
554
  return { content: `File created successfully at: ${p.file}`, display: { summary: `Created ${displayPath(p.file, ctx.cwd)}`, preview } };
414
555
  }
@@ -416,6 +557,115 @@ Usage:
416
557
  const text = input.replace_all
417
558
  ? `The file ${p.file} has been updated successfully. All ${p.count} occurrences were replaced.`
418
559
  : `The file ${p.file} has been updated successfully (${changedLines(line, p.newStr)}).`;
419
- return { content: text, display: { summary: changeSummary(preview), preview } };
560
+ return { content: p.unseen ? `${text} ${UNSEEN_NOTE[p.unseen]}` : text, display: { summary: changeSummary(preview), preview } };
420
561
  },
421
562
  };
563
+
564
+ // Several replacements in one file in one call. GPT models make one Edit per response even when they know several
565
+ // changes (2026-10-12..26: 2% of gpt-6.1-sol's responses with an edit had more than one, against 54% of Opus 5.5's;
566
+ // 561 times an edit response was followed by another one on the same file), and every response is a round trip of
567
+ // some 18 s on GPT that sends the whole conversation again. With all the changes in one call they are one response.
568
+ // The edits are applied in order to the text as the previous one left it, and all or none are made.
569
+ export const MultiEditTool = {
570
+ name: 'MultiEdit',
571
+ editsFiles: true,
572
+ description: `Makes several exact string replacements in one file in one call. The edits are applied in the order given, each to the text as the previous one left it, and either all of them are made or none (the error says which one failed and why).
573
+
574
+ Usage:
575
+ - Use it whenever you know more than one change to a file, instead of an Edit per change: every response is a round trip that sends the whole conversation again and takes tens of seconds.
576
+ - Each edit has old_string, new_string and optionally replace_all, with the rules of Edit: old_string is the exact text to replace (as the edits before it leave the file) and must occur once unless replace_all is set; never include the line number prefix of Read output.
577
+ - Order the edits so that an earlier one does not change the text a later one looks for.
578
+ - To create a file, use Write (or a first edit with an empty old_string, for a file that does not exist).
579
+ - Changes to several files: one MultiEdit or Edit call per file, all in the same response.`,
580
+ input_schema: {
581
+ type: 'object',
582
+ properties: {
583
+ file_path: { type: 'string', description: 'The absolute path to the file to modify' },
584
+ edits: {
585
+ type: 'array',
586
+ minItems: 1,
587
+ description: 'The replacements, made in this order',
588
+ items: {
589
+ type: 'object',
590
+ properties: {
591
+ old_string: { type: 'string', description: 'The text to replace' },
592
+ new_string: { type: 'string', description: 'The text to replace it with' },
593
+ replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string (default false)' },
594
+ },
595
+ required: ['old_string', 'new_string'],
596
+ },
597
+ },
598
+ },
599
+ required: ['file_path', 'edits'],
600
+ },
601
+ summarize(input, ctx) {
602
+ const n = Array.isArray(input.edits) ? input.edits.length : 0;
603
+ return `${displayPath(resolvePath(input.file_path, ctx.cwd), ctx.cwd)}${n ? `, ${n} edit${n === 1 ? '' : 's'}` : ''}`;
604
+ },
605
+ filePath(input, ctx) { return resolvePath(input.file_path, ctx.cwd); },
606
+ plan(input, ctx) {
607
+ const file = resolvePath(input.file_path, ctx.cwd);
608
+ const edits = Array.isArray(input.edits) ? input.edits : [];
609
+ if (!edits.length) return { error: 'edits must be a non-empty list of {old_string, new_string}.' };
610
+ const steps = edits.map((e) => ({
611
+ oldStr: String(e?.old_string ?? '').replace(/\r\n/g, '\n'),
612
+ newStr: String(e?.new_string ?? '').replace(/\r\n/g, '\n'),
613
+ all: Boolean(e?.replace_all),
614
+ }));
615
+ const exists = fs.existsSync(file);
616
+ let unseen = null;
617
+ let meta = { crlf: false, bom: false, encoding: 'utf8' };
618
+ let before = '';
619
+ if (exists) {
620
+ if (fs.statSync(file).isDirectory()) return { error: `${file} is a directory` };
621
+ unseen = fileStanding(file, ctx); // as in Edit: a unique old_string shows the model has the text it replaces
622
+ if (unseen && steps.some((s) => s.all)) {
623
+ return { error: unseen === 'unread'
624
+ ? 'File has not been read yet. Read it first before replacing every occurrence in it (replace_all).'
625
+ : 'File has been modified since it was last read, either by the user or by a command. Read it again before replacing every occurrence in it (replace_all).' };
626
+ }
627
+ const current = readText(file);
628
+ if (!current) return { error: notText(file) };
629
+ if (current.lossy) return { error: notRewritable(file, current) };
630
+ meta = { crlf: current.crlf, bom: current.bom, encoding: current.encoding };
631
+ before = current.text.replace(/\r\n/g, '\n');
632
+ } else if (steps[0].oldStr !== '') {
633
+ return { error: `File does not exist: ${file}. Create it with Write, or with a first edit whose old_string is empty.` };
634
+ }
635
+ let text = before;
636
+ for (let i = 0; i < steps.length; i++) {
637
+ const { oldStr, newStr, all } = steps[i];
638
+ const r = applyEdit(text, oldStr, newStr, all);
639
+ const step = steps.length > 1 ? `Edit ${i + 1} of ${steps.length}: ` : '';
640
+ if (r.error) return { error: `${missed(r, text, oldStr, unseen, step)}${steps.length > 1 ? ' No edit was made.' : ''}` };
641
+ text = r.result;
642
+ }
643
+ const cannot = unwritable(file, text, meta);
644
+ if (cannot) return { error: cannot };
645
+ return { file, before, after: text, meta, count: steps.length, unseen, created: !exists };
646
+ },
647
+ validate(input, ctx) { return this.plan(input, ctx).error || null; },
648
+ preview(input, ctx, p = this.plan(input, ctx)) { return EditTool.preview(input, ctx, p); },
649
+ async call(input, ctx) {
650
+ const p = this.plan(input, ctx);
651
+ if (p.error) return { isError: true, content: p.error };
652
+ const ops = p.created ? null : diffLines(splitLines(p.before), splitLines(p.after));
653
+ const preview = p.created ? { kind: 'create', path: p.file, lines: splitLines(p.after) } : { kind: 'diff', path: p.file, hunks: makeHunks(ops), ...countChanges(ops) };
654
+ const prior = ctx.fileState.get(p.file);
655
+ const hash = writeText(p.file, p.after, p.meta);
656
+ ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && (!prior || Boolean(prior.partial) || p.unseen === 'modified'), hash });
657
+ if (p.created) return { content: `File created successfully at: ${p.file}`, display: { summary: `Created ${displayPath(p.file, ctx.cwd)}`, preview } };
658
+ const text = `The file ${p.file} has been updated successfully: ${p.count} edit${p.count === 1 ? '' : 's'} (${changedRanges(ops)}).`;
659
+ return { content: p.unseen ? `${text} ${UNSEEN_NOTE[p.unseen]}` : text, display: { summary: changeSummary(preview), preview } };
660
+ },
661
+ };
662
+
663
+ // What an edit of a file the model had not read, or that changed since it read it, adds to its result or error.
664
+ const UNSEEN_NOTE = {
665
+ unread: '(The file had not been read in this conversation; old_string matched its current text once.)',
666
+ modified: '(The file had changed since you last read it, by a command or someone else; the edit was made on its current text. Read it again if those changes matter.)',
667
+ };
668
+ const UNSEEN_HINT = {
669
+ unread: 'The file has not been read in this conversation: Read it to get its exact text.',
670
+ modified: 'The file has changed since you last read it: Read it again.',
671
+ };
@@ -1,4 +1,4 @@
1
- import { ReadTool, WriteTool, EditTool } from './files.js';
1
+ import { ReadTool, WriteTool, EditTool, MultiEditTool } from './files.js';
2
2
  import { makeBashTool, BashOutputTool, KillShellTool } from './bash.js';
3
3
  import { GlobTool, GrepTool } from './search.js';
4
4
  import { makeWebFetchTool, WebSearchTool } from './web.js';
@@ -24,6 +24,7 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
24
24
  GrepTool,
25
25
  ReadTool,
26
26
  EditTool,
27
+ MultiEditTool,
27
28
  WriteTool,
28
29
  NotebookEditTool,
29
30
  makeWebFetchTool(config),
@@ -47,5 +48,6 @@ export function toolsForSubagent(allTools, def, { allowTask = false } = {}) {
47
48
  const base = allTools.filter((t) => !NEVER_FOR_SUBAGENTS.has(t.name) && (allowTask || t.name !== 'Task'));
48
49
  if (def.tools === '*' || !def.tools) return base;
49
50
  const wanted = new Set(def.tools);
51
+ if (wanted.has('Edit')) wanted.add('MultiEdit'); // the same permission, several changes in one call
50
52
  return base.filter((t) => wanted.has(t.name) || [...wanted].some((w) => w.startsWith('mcp__') && t.name.startsWith(w)));
51
53
  }
package/src/ui/repl.js CHANGED
@@ -20,9 +20,10 @@ import { defaultEffort, effortSupported, effortToSend, quickQuery } from '../api
20
20
  import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
21
21
  import { gatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
22
22
  import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
23
- import { buildCommands } from '../commands.js';
23
+ import { buildCommands, modelChoices, effortChoices } from '../commands.js';
24
24
  import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
25
25
  import { resolvePath, displayPath } from '../utils/paths.js';
26
+ import { listDirectory, recentDirectories } from '../utils/dirs.js';
26
27
  import { ripgrepPath } from '../utils/shell.js';
27
28
  import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce } from '../ratelimit.js';
28
29
  import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
@@ -31,7 +32,7 @@ import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText }
31
32
  import { fitImagesIn, imageSize } from '../utils/images.js';
32
33
  import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer } from '../updater.js';
33
34
  import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
34
- import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
35
+ import { RemoteControl, transcriptItems, onlineEnabled, remoteCommandsEnabled, REMOTE_WIDTH } from '../remote.js';
35
36
 
36
37
  // A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
37
38
  export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '').replace(/-\d{8}$/, '');
@@ -645,6 +646,16 @@ export class App {
645
646
  async connectRemote({ id }) {
646
647
  const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
647
648
  if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login logs in)`), { code: 'NO_GATEWAY_LOGIN' });
649
+ // What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
650
+ const commands = remoteCommandsEnabled(this.config.env) ? {
651
+ send: (body) => this.remoteSend(body.text, body.images),
652
+ interrupt: () => this.remoteInterrupt(),
653
+ answer: (body) => this.answerDialog(body),
654
+ options: () => this.remoteOptions(),
655
+ suggest: (body) => this.remoteSuggest(body),
656
+ list: (body) => this.remoteList(body),
657
+ output: (body) => this.remoteOutput(body),
658
+ } : {};
648
659
  const remote = new RemoteControl({
649
660
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
650
661
  id,
@@ -659,6 +670,7 @@ export class App {
659
670
  ...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
660
671
  ],
661
672
  status: () => this.remoteStatus(),
673
+ ...commands,
662
674
  peerMessage: (msg) => this.onPeerMessage(msg),
663
675
  changed: () => {
664
676
  this.screen.schedule();
@@ -701,7 +713,8 @@ export class App {
701
713
  if (r) {
702
714
  const who = r.account ? ` as ${r.account}` : '';
703
715
  const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
704
- const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
716
+ const readOnly = r.commands.length ? '' : c.dim(' · read-only on the page (CLAUDE_PRO_REMOTE_COMMANDS=0)');
717
+ const text = r.online ? `${c.green('online')}${who}${pages}${readOnly}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
705
718
  return { text };
706
719
  }
707
720
  if (this.remoteStarting) return { text: 'connecting…' };
@@ -784,6 +797,145 @@ export class App {
784
797
  return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
785
798
  }
786
799
 
800
+ // ---------------------------------------------------------------- the page's commands (see remote.js)
801
+
802
+ // The answer to the dialog the status showed the page (remoteDialog): {id, index}, {id, indices}, {id, text,
803
+ // indices?} (its "other" option), {id, text} (a text box) or {id, cancel: true}.
804
+ answerDialog({ id, index, indices, text, cancel } = {}) {
805
+ const d = this.dialogs[0];
806
+ if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
807
+ if (cancel) { d.resolve(d.cancelValue); return {}; }
808
+ if (d.input) {
809
+ if (typeof text !== 'string') throw new Error('Type an answer first.');
810
+ d.resolve(text);
811
+ this.screen.schedule();
812
+ return {};
813
+ }
814
+ if (!Array.isArray(d.options)) throw new Error('This dialog cannot be answered from the page.');
815
+ const valueAt = (i) => {
816
+ const o = d.options[i];
817
+ if (!Number.isInteger(i) || !o || o.value === '__other__') throw new Error('No such option.');
818
+ return o.value;
819
+ };
820
+ if (typeof text === 'string') {
821
+ if (!text.trim()) throw new Error('Type an answer first.');
822
+ d.resolve(d.multi ? [...(indices || []).map(valueAt), text.trim()] : text.trim());
823
+ } else if (d.multi) {
824
+ if (!indices?.length) throw new Error('Choose at least one option.');
825
+ d.resolve(indices.map(valueAt));
826
+ } else {
827
+ d.resolve(valueAt(index));
828
+ }
829
+ this.screen.schedule();
830
+ return {};
831
+ }
832
+
833
+ // A message from the page: as if typed in the input box and sent (a turn, queued while one runs; /commands, !,
834
+ // #, @session), its images as if pasted there. Images alone go as their placeholders, which is what the input box
835
+ // sends for them.
836
+ remoteSend(text, images) {
837
+ const pictures = remoteImages(images);
838
+ let value = String(text ?? '').replace(/\r\n/g, '\n');
839
+ if (!value.trim() && pictures.length) value = pictures.map((_, i) => `[Image #${i + 1}]`).join(' ');
840
+ if (!value.trim()) throw new Error('The message is empty.');
841
+ if (this.exiting) throw new Error('The session is ending.');
842
+ if (this.isTurnRunning() && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
843
+ if (this.dialogs.length && !this.isTurnRunning()) throw new Error('A question is open: answer it first.');
844
+ const queued = this.isTurnRunning();
845
+ this.onSubmit(value, value, pictures);
846
+ this.screen.schedule();
847
+ return { queued };
848
+ }
849
+
850
+ // Esc: the turn stops, and the questions waiting for an answer are cancelled.
851
+ remoteInterrupt() {
852
+ for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
853
+ this.interrupt();
854
+ this.screen.schedule();
855
+ return {};
856
+ }
857
+
858
+ // For the page's model and effort menus: what /model and /effort offer (in plain text; the page sends /model
859
+ // <value> or /effort <value>), what is chosen (`current`), and the model and effort in use, as the status says.
860
+ async remoteOptions() {
861
+ const cfg = this.config;
862
+ const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
863
+ const chosen = cfg.modelOverride || 'default';
864
+ const current = models.find((o) => o.value === chosen) || models.find((o) => o.value !== 'default' && cfg.resolveModel(o.value).id === cfg.model.id);
865
+ const effortChosen = cfg.effortOverride || 'default';
866
+ const { effort } = modelInfo(cfg);
867
+ return {
868
+ model: cfg.model.id,
869
+ models: models.map((o) => ({ ...o, ...(o === current ? { current: true } : {}) })),
870
+ effort: effort || defaultEffort(cfg.model.id, cfg),
871
+ efforts: efforts.options.map((o) => ({ ...o, ...(o.value === effortChosen ? { current: true } : {}) })),
872
+ };
873
+ }
874
+
875
+ // For the page's input box: what the input box here would suggest (/commands, @files and @sessions), in plain
876
+ // text, without anything happening here. Sessions on the other computers are asked for first when the list is old.
877
+ async remoteSuggest(body = {}) {
878
+ const text = String(body.text ?? '');
879
+ const cursor = Number.isInteger(body.cursor) ? Math.max(0, Math.min(text.length, body.cursor)) : text.length;
880
+ if (/(^|\s)@[^\s@"]*$/u.test(text.slice(0, cursor)) && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
881
+ await Promise.race([this.refreshRemotePeers(), new Promise((r) => setTimeout(r, 3000))]);
882
+ }
883
+ const found = this.suggest(text, cursor, { quiet: true });
884
+ if (!found?.items?.length) return { items: [] };
885
+ const plain = (s) => (s == null ? '' : stripAnsi(String(s)));
886
+ return {
887
+ items: found.items.slice(0, 50).map((it) => ({ value: it.value, label: plain(it.label ?? it.value), description: plain(it.description), submitOnEnter: Boolean(it.submitOnEnter), noSpace: Boolean(it.noSpace) })),
888
+ from: found.from,
889
+ to: found.to,
890
+ };
891
+ }
892
+
893
+ // For the page's directory browser (/cd): the directories in `path` ("": this session's working directory), with
894
+ // the drives, the home directory and where sessions ran lately.
895
+ remoteList(body = {}) {
896
+ const wanted = typeof body.path === 'string' && body.path.trim() ? body.path : (this.agent.cwd || this.cwd);
897
+ return listDirectory(wanted, {
898
+ recent: () => {
899
+ if (!this.recentDirs || Date.now() - this.recentDirs.at > 30_000) this.recentDirs = { at: Date.now(), list: recentDirectories({ projects: path.join(CONFIG_DIR, 'projects') }) };
900
+ return this.recentDirs.list;
901
+ },
902
+ });
903
+ }
904
+
905
+ // For the page's "the whole output": the full result of the tool call `id` ({text, truncated, running?}, at most
906
+ // 1 MB of UTF-8): the file it was saved to when it was too long for the conversation or cleared from it later,
907
+ // and what it printed so far while it runs.
908
+ remoteOutput({ id } = {}) {
909
+ if (typeof id !== 'string' || !id) throw new Error('Which tool call?');
910
+ const MAX = 1024 * 1024;
911
+ const cut = (text, running = false) => {
912
+ const buf = Buffer.from(text, 'utf8');
913
+ const truncated = buf.length > MAX;
914
+ // (a character cut at the end decodes as U+FFFD, which is then dropped)
915
+ const shown = truncated ? buf.subarray(0, MAX).toString('utf8').replace(/\ufffd$/, '') : text;
916
+ return { text: shown, truncated, ...(running ? { running } : {}) };
917
+ };
918
+ let result = null;
919
+ for (const m of this.agent.messages) {
920
+ if (m.role !== 'user' || !Array.isArray(m.content)) continue;
921
+ for (const b of m.content) if (b.type === 'tool_result' && b.tool_use_id === id) result = b;
922
+ }
923
+ if (!result) {
924
+ const live = this.active.find((e) => e.tu?.id === id);
925
+ if (live) return cut(live.progressAll?.() ?? String(live.progress || ''), true);
926
+ throw new Error('There is no such tool call in this conversation.');
927
+ }
928
+ let text = typeof result.content === 'string' ? result.content
929
+ : (Array.isArray(result.content) ? result.content : []).map((b) => (b.type === 'text' ? b.text : b.type === 'image' ? '[image]' : '')).join('\n');
930
+ // saved whole in the project's tool-results (a large result, a Bash output, a result cleared after a pause)
931
+ const saved = /(?:saved to:?|saved at)\s+(\S+?\.txt)\b/.exec(text)?.[1];
932
+ const results = path.join(CONFIG_DIR, 'projects');
933
+ if (saved && path.resolve(saved).startsWith(results + path.sep) && path.resolve(saved).includes(`${path.sep}tool-results${path.sep}`)) {
934
+ try { text = fs.readFileSync(saved, 'utf8'); } catch { /* the reference is what there is */ }
935
+ }
936
+ return cut(text);
937
+ }
938
+
787
939
  // ---------------------------------------------------------------- restarting (see restart.js)
788
940
 
789
941
  // What a restart would kill: agents and shells that are still running in the background.
@@ -1998,7 +2150,8 @@ export class App {
1998
2150
  this.screen.schedule();
1999
2151
  return {
2000
2152
  progress: (p, meta) => {
2001
- if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; this.remote?.toolProgress(tu.id, entry); }
2153
+ // `all`: the whole output so far (the progress is its end), for the page's "the whole output"
2154
+ if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.remote?.toolProgress(tu.id, entry); }
2002
2155
  else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.remote?.emit({ t: 'sub', id: tu.id, head: p.header }); }
2003
2156
  this.screen.schedule();
2004
2157
  },
@@ -0,0 +1,136 @@
1
+ // Directories of this computer for the gateway's web page: what it shows to choose a working directory from
2
+ // (/cd from the page, see App.remoteList). Moved here from the computer service (host.js, removed in 0.8.0), whose
3
+ // listing the page was built for: the fields and the messages (Chinese, as the page is) are the same.
4
+
5
+ import fs from 'node:fs';
6
+ import fsp from 'node:fs/promises';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { normalizeDir } from './paths.js';
10
+
11
+ const MAX_ENTRIES = 1000;
12
+ const MAX_RECENT = 15;
13
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
14
+
15
+ const describeFsError = (e, dir) => (e.code === 'ENOENT' || e.code === 'ENOTDIR' ? `目录不存在:${dir}`
16
+ : e.code === 'EACCES' || e.code === 'EPERM' ? `没有权限读取:${dir}`
17
+ : `读取 ${dir} 失败:${e.message}`);
18
+
19
+ let rootsCache = { at: 0, roots: [] };
20
+ async function roots(platform = process.platform) {
21
+ if (platform !== 'win32') return ['/'];
22
+ if (Date.now() - rootsCache.at < 30_000) return rootsCache.roots;
23
+ // a disconnected network drive can take long to answer: 1.5 seconds each, all at once
24
+ const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
25
+ const found = await Promise.all(letters.map((l) => Promise.race([
26
+ fsp.access(`${l}:\\`).then(() => `${l}:\\`, () => null),
27
+ sleep(1500).then(() => null),
28
+ ])));
29
+ rootsCache = { at: Date.now(), roots: found.filter(Boolean) };
30
+ return rootsCache.roots;
31
+ }
32
+
33
+ // The directories in `input` (only directories, links to them included), for the page to choose from:
34
+ // {path, parent, sep, entries: [{name, path}], truncated, home, roots, recent}.
35
+ export async function listDirectory(input, { home = os.homedir(), recent = () => [] } = {}) {
36
+ const dir = normalizeDir(input, { home });
37
+ if (!dir) throw new Error(`不是绝对路径:${input}`);
38
+ let st;
39
+ try { st = await fsp.stat(dir); } catch (e) { throw new Error(describeFsError(e, dir)); }
40
+ if (!st.isDirectory()) throw new Error(`不是目录:${dir}`);
41
+ let dirents;
42
+ try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e) { throw new Error(describeFsError(e, dir)); }
43
+ const entries = [];
44
+ for (const d of dirents) {
45
+ const full = path.join(dir, d.name);
46
+ let isDir = d.isDirectory();
47
+ if (!isDir && d.isSymbolicLink()) {
48
+ // a link to a directory counts, unless it cannot be opened (Windows' old junctions in the profile:
49
+ // "My Documents", "Application Data" ... refuse to be listed)
50
+ try { isDir = (await fsp.stat(full)).isDirectory(); } catch { isDir = false; }
51
+ if (isDir) {
52
+ let handle = null;
53
+ try {
54
+ handle = await fsp.opendir(full);
55
+ await handle.read(); // Windows checks the access at the first read, not at the opening
56
+ } catch {
57
+ isDir = false;
58
+ } finally {
59
+ await handle?.close().catch(() => {});
60
+ }
61
+ }
62
+ // ... and the profile's other compatibility junctions ("Application Data", "Recent", the Start Menu in the
63
+ // system's language ...), which Explorer hides: all lead into AppData
64
+ if (isDir && process.platform === 'win32' && dir.toLowerCase() === path.resolve(home).toLowerCase()) {
65
+ try {
66
+ if ((await fsp.realpath(full)).toLowerCase().startsWith(`${path.join(home, 'AppData').toLowerCase()}\\`)) isDir = false;
67
+ } catch { isDir = false; }
68
+ }
69
+ }
70
+ if (isDir) entries.push({ name: d.name, path: full });
71
+ }
72
+ const hidden = (name) => (name.startsWith('.') ? 1 : 0);
73
+ entries.sort((a, b) => hidden(a.name) - hidden(b.name) || a.name.localeCompare(b.name, undefined, { sensitivity: 'accent', numeric: true }));
74
+ const parent = path.dirname(dir);
75
+ return {
76
+ path: dir,
77
+ parent: parent === dir ? null : parent,
78
+ sep: path.sep,
79
+ entries: entries.slice(0, MAX_ENTRIES),
80
+ truncated: entries.length > MAX_ENTRIES,
81
+ home,
82
+ roots: await roots(),
83
+ recent: recent(),
84
+ };
85
+ }
86
+
87
+ // The first line of a session file is {type: 'meta', cwd, ...} (see SessionStore.append).
88
+ function sessionCwd(file) {
89
+ let fd = null;
90
+ try {
91
+ fd = fs.openSync(file, 'r');
92
+ const buf = Buffer.alloc(16 * 1024);
93
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
94
+ const meta = JSON.parse(buf.subarray(0, n).toString('utf8').split('\n')[0]);
95
+ return meta?.type === 'meta' && typeof meta.cwd === 'string' ? meta.cwd : null;
96
+ } catch {
97
+ return null;
98
+ } finally {
99
+ if (fd !== null) fs.closeSync(fd);
100
+ }
101
+ }
102
+
103
+ // Where claude-pro sessions ran lately on this computer, newest first: [{path, at}] of the directories that are
104
+ // still there. `projects`: the config directory's projects folder. One line read per project (its newest session's
105
+ // first line).
106
+ export function recentDirectories({ projects, max = MAX_RECENT }) {
107
+ let dirs = [];
108
+ try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { return []; }
109
+ const found = [];
110
+ for (const d of dirs) {
111
+ const sub = path.join(projects, d.name);
112
+ let newest = null;
113
+ try {
114
+ for (const f of fs.readdirSync(sub)) {
115
+ if (!f.endsWith('.jsonl')) continue;
116
+ const m = fs.statSync(path.join(sub, f)).mtimeMs;
117
+ if (!newest || m > newest.m) newest = { f, m };
118
+ }
119
+ } catch { continue; }
120
+ if (!newest) continue;
121
+ const cwd = sessionCwd(path.join(sub, newest.f));
122
+ if (cwd) found.push({ path: path.resolve(cwd), at: newest.m });
123
+ }
124
+ found.sort((a, b) => b.at - a.at);
125
+ const seen = new Set();
126
+ const out = [];
127
+ for (const r of found) {
128
+ const key = process.platform === 'win32' ? r.path.toLowerCase() : r.path;
129
+ if (seen.has(key)) continue;
130
+ seen.add(key);
131
+ try { if (!fs.statSync(r.path).isDirectory()) continue; } catch { continue; }
132
+ out.push({ path: r.path, at: new Date(r.at).toISOString() });
133
+ if (out.length >= max) break;
134
+ }
135
+ return out;
136
+ }
@@ -10,6 +10,27 @@ const strictUtf8 = new TextDecoder('utf-8', { fatal: true });
10
10
  const lenientUtf8 = new TextDecoder('utf-8');
11
11
  const strictGbk = new TextDecoder('gbk', { fatal: true }); // the WHATWG gbk decoder, which is the gb18030 one
12
12
 
13
+ // Whether bytes that are not valid UTF-8 as a whole are still UTF-8 text with a few bad bytes (a character cut at
14
+ // the end of a line by `cut -c` or `head -c`, a stray Latin-1 byte), rather than text in another encoding. Chinese
15
+ // UTF-8 is often valid GBK by chance (E4 B8 AD E6 96 87, "中文", reads as "涓枃"), so trying GBK first turned such
16
+ // a line or file into mojibake; GBK text read as UTF-8, the other way round, is mostly invalid sequences, with a
17
+ // valid two-byte character here and there by chance. An incomplete sequence counts once, however long.
18
+ export function mostlyUtf8(buf) {
19
+ let good = 0;
20
+ let bad = 0;
21
+ for (let i = 0; i < buf.length;) {
22
+ const b = buf[i];
23
+ if (b < 0x80) { i++; continue; }
24
+ const n = b >= 0xc2 && b <= 0xdf ? 2 : b >= 0xe0 && b <= 0xef ? 3 : b >= 0xf0 && b <= 0xf4 ? 4 : 0;
25
+ let k = 1;
26
+ while (n && k < n && i + k < buf.length && (buf[i + k] & 0xc0) === 0x80) k++;
27
+ if (n && k === n) good++;
28
+ else bad++;
29
+ i += n ? k : 1;
30
+ }
31
+ return bad === 0 || good >= 4 * bad;
32
+ }
33
+
13
34
  // {text, encoding: 'utf8'|'utf16le'|'utf16be'|'gbk', bom, lossy}, or null for binary data. `lossy`: writing the
14
35
  // text back would not give these bytes (undecodable bytes became U+FFFD, or GB18030 forms GBK cannot write).
15
36
  // `writable: false` skips that check for a GBK file, for a caller that only reads (Grep).
@@ -20,7 +41,7 @@ export function decodeText(buf, { writable = true } = {}) {
20
41
  const body = bom ? buf.subarray(3) : buf;
21
42
  if (body.subarray(0, 8000).includes(0)) return null;
22
43
  try { return { text: strictUtf8.decode(body), encoding: 'utf8', bom, lossy: false }; } catch { /* not UTF-8 */ }
23
- if (!bom) {
44
+ if (!bom && !mostlyUtf8(body)) {
24
45
  let text = null;
25
46
  try { text = strictGbk.decode(body); } catch { /* not GBK either */ }
26
47
  // Writable only when the text turns back into exactly these bytes (GB18030's four-byte forms do not).
@@ -124,7 +145,7 @@ export function decodeOutput(buf) {
124
145
  const line = buf.subarray(start, end);
125
146
  let text = null;
126
147
  try { text = strictUtf8.decode(line); } catch {
127
- const legacy = consoleDecoder();
148
+ const legacy = mostlyUtf8(line) ? null : consoleDecoder();
128
149
  if (legacy) { try { text = legacy.decode(line); } catch { /* neither */ } }
129
150
  }
130
151
  out += text ?? lenientUtf8.decode(line);