@yanzc/claude-pro 0.7.0 → 0.7.1

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
@@ -67,7 +67,7 @@ claude-pro config set CLAUDE_PRO_PROVIDER claude-code
67
67
 
68
68
  `~/.claude.json` 保存设备 ID 和 OAuth 账号信息,实际访问令牌保存在 `~/.claude/.credentials.json` 的 `claudeAiOauth.accessToken` 中。Windows 对应 `%USERPROFILE%\.claude.json` 和 `%USERPROFILE%\.claude\.credentials.json`。可用 `CLAUDE_PRO_CLAUDE_CONFIG_FILE` 和 `CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE` 指向现有文件;`CLAUDE_CONFIG_DIR` 可以指定凭据目录。凭据位置参考[官方认证文档](https://code.claude.com/docs/en/authentication#credential-management)。
69
69
 
70
- 调用方式是:本项目 → `https://api.anthropic.com/v1/messages?beta=true`。请求复用 `Authorization: Bearer <accessToken>`,带上 Claude Code 的 OAuth beta、`x-app: cli`、User-Agent、系统标识,以及来自 `.claude.json` 的设备和账号 metadata。流式响应、原生 `tool_use` / `tool_result`、工具执行、hooks、检查点、计划模式及会话功能都由本项目原有逻辑处理。
70
+ 调用方式是:本项目 → `https://api.anthropic.com/v1/messages?beta=true`。请求复用 `Authorization: Bearer <accessToken>`,带上 Claude Code 的 OAuth beta、`x-app: cli`、User-Agent、系统标识,以及来自 `.claude.json` 的设备和账号 metadata。流式响应、原生 `tool_use` / `tool_result`、工具执行、hooks、检查点及会话功能都由本项目原有逻辑处理。
71
71
 
72
72
  此模式默认 `sonnet` → `claude-sonnet-5-5`,`opus` → `claude-opus-5-5`,`haiku` → `claude-haiku-5-5`(与 Claude Code 2.1.293 起一样;话题标题、WebFetch 摘要等小请求用它);子 agent 默认用 `sonnet`(`CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL` 可改)。使用 `--model`、`/model` 或 `CLAUDE_PRO_CLAUDE_CODE_MODEL` 指定模型。**`/model`、`/effort` 的选择会一直保留**:按后端记在 `~/.claude-pro/settings.json` 的 `remembered` 里,之后每次启动(交互式和 `-p`)都沿用,优先于 `.env`/settings/环境变量里的配置;命令行 `--model`/`--effort` 只覆盖当次启动;`/model default`、`/effort default` 删掉记住的选择,回到配置的值。`claude-pro config list` 会显示当前记住的选择。已有的 DeepSeek API URL、API key 和 API 模型别名不会参与订阅请求。OAuth 令牌始终只发往 Anthropic,原 API 配置可以通过 `--provider api` 继续使用。
73
73
 
@@ -169,7 +169,7 @@ claude-pro config set ANTHROPIC_MODEL deepseek-pro --project
169
169
 
170
170
  交互式会话运行在一个很薄的**监督进程**(`src/supervisor.js`,只用 Node 内置模块)之下,所以程序可以自己重启、加载自己刚改过的代码,不需要你退出再启动:
171
171
 
172
- - **模型自己重启**:改完 `src/`、`bin/` 里的代码后,模型调用 `Restart` 工具。它先在一个临时进程里把新代码完整启动一遍(所有模块能加载、界面能画出来、工具定义和系统提示词合法)——**启动不起来就不重启**,把错误还给模型去修,修好再调用;通过后在**本回合结束时**重启,对话、待办列表、`/model`、`/effort`、计划模式、排队的消息、输入框里没发出去的草稿、`/rewind` 检查点都带过去,新进程里模型收到一条"已重启"的提示后接着做(可用 `then` 指定重启后先验证什么)。只在**源码仓库**(有 `.git` 的克隆,包括 `npm link` 到它)里这样做:从 npm 装的副本没有版本控制、下次更新会被覆盖,那里不给模型 `Restart` 工具,系统提示词改成"不要改自己的文件,绕过问题并在最后说明缺陷,方便用户反馈"。
172
+ - **模型自己重启**:改完 `src/`、`bin/` 里的代码后,模型调用 `Restart` 工具。它先在一个临时进程里把新代码完整启动一遍(所有模块能加载、界面能画出来、工具定义和系统提示词合法)——**启动不起来就不重启**,把错误还给模型去修,修好再调用;通过后在**本回合结束时**重启,对话、待办列表、`/model`、`/effort`、排队的消息、输入框里没发出去的草稿、`/rewind` 检查点都带过去,新进程里模型收到一条"已重启"的提示后接着做(可用 `then` 指定重启后先验证什么)。只在**源码仓库**(有 `.git` 的克隆,包括 `npm link` 到它)里这样做:从 npm 装的副本没有版本控制、下次更新会被覆盖,那里不给模型 `Restart` 工具,系统提示词改成"不要改自己的文件,绕过问题并在最后说明缺陷,方便用户反馈"。
173
173
  - **改了源码自动重启**:一个回合结束(或空闲)时,如果 `src/`、`bin/` 下的文件变过,就自动做同样的检查并重启。检查不通过只提示错误、不重启。按 Esc 打断的那一回合不会触发。`CLAUDE_PRO_AUTO_RESTART=0` 关闭。
174
174
  - **手动**:`/restart`(别名 `/reload`),`/restart force` 跳过检查并无视后台任务。
175
175
  - 后台 agent / 后台 shell 会被重启杀掉,所以有它们在跑时拒绝重启(可 `force`)。5 分钟内重启超过 5 次视为死循环,拒绝。
@@ -182,9 +182,9 @@ claude-pro config set ANTHROPIC_MODEL deepseek-pro --project
182
182
  和 Claude Code 的 `/remote-control` 一样,可以在手机或另一台电脑上看着会话干活,并给它发指令;这里**不用任何命令或设置**。官方版经 Anthropic 中转,这里经**网关**(gw.predix.icu,即 `CLAUDE_PRO_GATEWAY_URL`)中转:claude-pro 只向网关发出站请求,**不监听任何端口,不走局域网**;在网关用户端登录后,左侧菜单"**远程控制**"里按电脑分组列出自己的会话,可以查看、操作,也可以在某台电脑上新建、结束、重启会话,恢复历史对话(见下面"网页管理电脑和后台会话")。模型请求走哪个提供方都可以,远程控制只用网关的登录。
183
183
 
184
184
  - **默认在线**:这台电脑登录了网关(`/login` 选网关)以后,每个交互会话启动时自动连上网关(不阻塞启动,断开后自动重连),网页上能看到这台电脑上所有开着的会话,别的电脑也能给它们发任务(见下一节)。`/login` 登录成功后当前会话**马上上线**(不用重启),并打印它的链接;`/logout` 后马上下线;在别的窗口登录或退出,这个窗口几秒内跟上。想让模型请求走 Claude 订阅:先 `/login` 选网关登录,再 `/login` 选 Claude 订阅,网关登录保留,会话照样在线。
185
- - **链接和二维码**:`/status` 显示这个会话的远程状态(在线、连接中、没登录、key 被拒…)、它在网关上的链接(`https://gw.predix.icu/user#remote/<id>`)和二维码,手机扫码即可打开(没登录时先登录,登录后直接进入这个会话)。所有会话的列表在 `/user#remote`。在线时输入框右上角显示 `⇄ &名字`,有网页在看时页脚显示 `⇄ N watching`。
185
+ - **在网页上找到会话**:网关用户端的"远程控制"(`/user#remote`)按电脑列出所有会话,点开即可。`/status` 显示这个会话的远程状态(在线、连接中、没登录、key 被拒…)。在线时输入框右上角显示 `⇄ &名字`,有网页在看时页脚显示 `⇄ N watching`。
186
186
  - **网页上能看到**:完整对话(用户消息、流式输出的回答、可展开的思考、工具调用和结果,包括 diff 和正在运行的命令的最新几行输出)、斜杠命令和提示的输出、当前状态(正在想/运行多久/多少 token、限流暂停的倒计时)、待办列表、排队中的消息。
187
- - **网页上能做**:发消息(和在终端里输入完全一样:忙的时候排队插入,`/命令`、`!shell` 都可以)、**Stop**(等于 Esc)、回答模型的提问(`AskUserQuestion`,含多选和"其他")、批准/拒绝计划、以及 `/model`、`/rewind` 之类命令弹出的选择框。网页顶部可以直接改会话的名字、工作目录(`/cd`,带目录浏览)、模型、effort 和 plan 模式(都是替你发对应的斜杠命令,终端里显示同样的结果;任务进行中不能改)。网页输入框里输入 `/`、`@`、`&` 有和终端一样的补全,也能粘贴或拖入图片(每次最多 6 张、每张不超过 5 MB,PNG/JPEG/GIF/WebP)。终端和网页可以交替使用,两边同步。
187
+ - **网页上能做**:发消息(和在终端里输入完全一样:忙的时候排队插入,`/命令`、`!shell` 都可以)、**Stop**(等于 Esc)、回答模型的提问(`AskUserQuestion`,含多选和"其他")、以及 `/model`、`/rewind` 之类命令弹出的选择框。网页顶部可以直接改会话的名字、工作目录(`/cd`,带目录浏览)、模型和 effort(都是替你发对应的斜杠命令,终端里显示同样的结果;任务进行中不能改)。网页输入框里输入 `/`、`@`、`&` 有和终端一样的补全,也能粘贴或拖入图片(每次最多 6 张、每张不超过 5 MB,PNG/JPEG/GIF/WebP)。终端和网页可以交替使用,两边同步。
188
188
  - **安全**:只有同一个网关账户登录后才能看到和操作这个会话;**能登录这个网关账户的人,就能通过它在这台电脑上以完全权限执行命令**。会话内容经网关中转并暂存在网关上。
189
189
  - **省流量**:没人打开网页时只上报状态(列表里的标题、忙/闲),不上传对话;有人打开时先发一份完整快照,再实时推送。
190
190
  - **重启不断线**:自动重启(改了源码、自动更新)沿用同一个会话 id,网页显示"重启中"后接着看;网关重启丢了状态时,claude-pro 自动重新注册并补发完整对话。
@@ -225,8 +225,8 @@ claude-pro config set ANTHROPIC_MODEL deepseek-pro --project
225
225
 
226
226
  ## 完全访问与安全网
227
227
 
228
- - **没有权限系统**:没有确认弹窗,没有 allow/deny 规则,也没有 `/permissions`。旧参数 `--dangerously-skip-permissions`、`--permission-mode`、`--allowedTools`、`--disallowedTools` 仍被接受但会被忽略(`--permission-mode plan` 等同于 `--plan`);settings 里残留的 `permissions` 字段也会被忽略。
229
- - **计划模式(唯一的开关)**:`shift+tab`、`/plan` 或 `--plan` 进入。此时只能读和调研,改文件、跑会改东西的命令都会被挡住;模型调研完用 `ExitPlanMode` 提交计划,你批准后回到完全访问。
228
+ - **没有权限系统**:没有确认弹窗,没有 allow/deny 规则,也没有 `/permissions`。旧参数 `--dangerously-skip-permissions`、`--permission-mode`、`--allowedTools`、`--disallowedTools` 仍被接受但会被忽略,`--plan` 也是;settings 里残留的 `permissions` 字段也会被忽略。
229
+ - **没有计划模式**:想先看方案再动手,直接在消息里说(例如"先给方案,我确认前不要改代码")。
230
230
  - **检查点与 `/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 命令造成的改动不会被记录**,所以模型被要求优先用文件工具改文件。
231
231
  - **想要护栏时用 hooks**:`PreToolUse` 钩子仍然可以拦截任何工具调用,由你自己定规则(见下)。
232
232
  - 模型自己的使用规则不受影响,系统提示里的安全条款与官方 Claude Code 现在的措辞一致:允许授权的安全测试、防御、CTF、教学,拒绝恶意用途。这一条是模型的使用规范,不是能力限制,没有去掉。
@@ -246,11 +246,11 @@ claude-pro config set ANTHROPIC_MODEL deepseek-pro --project
246
246
  | `Bash` 的标准输入 | 一律关闭 | 可以用 `stdin` 参数喂入文本(回答提示、给脚本传数据) |
247
247
  | 提示词里的限制 | “尽量少输出”“除非必要不要建文件”“不要强推/改 git 配置/amend” | 回答长度按任务需要;需要就建文件(测试、脚本、配置);用户要求时可以做上述 git 操作 |
248
248
 
249
- **刻意保留的**:`Edit`/`Write` 必须先 `Read`(防止覆盖没看过的改动,这是正确性保护,不是能力限制;`Write` 覆盖已有文件要求读过完整内容,只读了一部分时用 `Edit`;`--resume` 恢复会话时会按记录重建读取状态,读过之后被改动的文件需要重读)、计划模式(需要时才开)、"没被要求就不提交"、做不可撤销且没被要求的外部操作(强推、发布包、给外部服务发消息或花钱)之前先说一声。
249
+ **刻意保留的**:`Edit`/`Write` 必须先 `Read`(防止覆盖没看过的改动,这是正确性保护,不是能力限制;`Write` 覆盖已有文件要求读过完整内容,只读了一部分时用 `Edit`;`--resume` 恢复会话时会按记录重建读取状态,读过之后被改动的文件需要重读)、"没被要求就不提交"、做不可撤销且没被要求的外部操作(强推、发布包、给外部服务发消息或花钱)之前先说一声。
250
250
 
251
251
  ## 功能
252
252
 
253
- **工具**(与 Claude Code 同名同语义):`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`、`ExitPlanMode`、`AskUserQuestion`,以及 MCP 工具。
253
+ **工具**(与 Claude Code 同名同语义):`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 工具。
254
254
 
255
255
  **交互**
256
256
  - 流式 Markdown 渲染(代码高亮、表格、中文宽度对齐),思考过程折叠显示(`ctrl+o` 展开)
@@ -265,7 +265,7 @@ claude-pro config set ANTHROPIC_MODEL deepseek-pro --project
265
265
 
266
266
  **`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
267
267
 
268
- **斜杠命令**:`/help` `/tui` `/cd` `/rename` `/peers` `/sendfile` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/plan` `/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` ``)。
268
+ **斜杠命令**:`/help` `/tui` `/cd` `/rename` `/peers` `/sendfile` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/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` ``)。
269
269
 
270
270
  **记忆**:自动读取 `~/.claude-pro/CLAUDE.md`、项目各级目录的 `CLAUDE.md` / `.claude/CLAUDE.md` / `CLAUDE.local.md`;某一级目录没有 `CLAUDE.md` 时读它的 `AGENTS.md` 代替(与 Claude Code 相同,两者都有时通常是同一份说明,不重复发送)。
271
271
 
@@ -306,7 +306,7 @@ claude-pro -p "解释一下 src/agent.js" # 只输出最终回
306
306
  cat error.log | claude-pro -p "这个报错是什么原因"
307
307
  claude-pro -p --output-format json "..." # JSON 结果(含 token 用量)
308
308
  claude-pro -p --verify "npm test" "修复失败的测试" # 改完自动跑测试,失败继续修
309
- claude-pro -p --plan "给出重构方案" # 只调研、只出方案,不动文件
309
+ claude-pro -p "只调研,给出重构方案,不要改文件" # 只出方案:在消息里说就行
310
310
  ```
311
311
 
312
312
  ## 快捷键
@@ -317,7 +317,6 @@ claude-pro -p --plan "给出重构方案" # 只调研、只
317
317
  | `\` + `Enter` / `ctrl+j` / `alt+enter` | 换行 |
318
318
  | `Esc` | 中断当前任务;连按两次:有文字时清空输入,输入框为空时打开回退菜单(同 `/rewind`) |
319
319
  | `ctrl+c` | 中断 / 清空输入 / 连按两次退出 |
320
- | `shift+tab` | 开关计划模式(只读) |
321
320
  | `ctrl+o` | 切换详细输出(思考过程、完整工具输出) |
322
321
  | `ctrl+t` | 显示/隐藏 todo 列表 |
323
322
  | `ctrl+l` | 清屏重绘 |
@@ -350,7 +349,6 @@ src/ratelimit.js 限流:解析重置时间响应头、决定等多久、
350
349
  src/claude-code.js 读取现有 Claude Code OAuth 登录态,生成认证头和账号 metadata
351
350
  src/oauth.js 访问令牌过期时用刷新令牌续期,加锁、原子写回凭据文件
352
351
  src/agent.js Agent 循环:工具调度、并行只读工具、中断、自动压缩、验证循环
353
- src/modes.js 会话模式:完全访问 / 计划模式(没有权限规则)
354
352
  src/checkpoints.js 检查点与 /rewind
355
353
  src/filestate.js 恢复会话时从记录重建"已读文件"状态(文件自读取后没变过才信任)
356
354
  src/hooks.js Hooks 运行器
@@ -360,7 +358,6 @@ src/tools/* 各工具实现(含 Skill、NotebookEdit)
360
358
  src/mcp.js MCP 客户端(stdio / HTTP)
361
359
  src/ui/* 终端 UI:屏幕管理、输入框、对话框、Markdown 渲染
362
360
  src/remote.js 远程控制:经网关中转的客户端、对话事件模型(applyEvent,网关页面里有同一份)
363
- src/qr.js 终端二维码(字节模式、纠错 L、版本 1–6)
364
361
  src/commands.js 斜杠命令
365
362
  ```
366
363
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "claude-pro: a self-implemented coding agent for Anthropic-compatible APIs or local Claude Code subscription login. 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
@@ -4,7 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { streamMessage, contextTokens, isAbort } from './api.js';
7
- import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuationMessage, PLAN_MODE_REMINDER, SUMMARY_SYSTEM } from './prompts.js';
7
+ import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuationMessage, SUMMARY_SYSTEM } from './prompts.js';
8
8
  import { toolResultsDir } from './session.js';
9
9
  import { rebuildFileState } from './filestate.js';
10
10
  import { CacheStats, TTL_MS } from './cache.js';
@@ -169,7 +169,7 @@ function validateInput(schema, input) {
169
169
  }
170
170
 
171
171
  export class Agent {
172
- constructor({ config, modes, tools, systemPrompt, io, model, isSubagent = false, cwd, name = 'main', spawnSubagent, hooks, tasks, checkpoints, depth = 0, refreshSystemPrompt, beforeTurn, effort, compactWindow = 0 }) {
172
+ constructor({ config, tools, systemPrompt, io, model, isSubagent = false, cwd, name = 'main', spawnSubagent, hooks, tasks, checkpoints, depth = 0, refreshSystemPrompt, beforeTurn, effort, compactWindow = 0 }) {
173
173
  this.config = config;
174
174
  this.effort = effort || undefined; // a sub-agent's own effort level; undefined: the session's (config.effort)
175
175
  this.compactWindow = compactWindow; // a sub-agent's own auto-compact window (tokens); 0: the session's
@@ -178,7 +178,6 @@ export class Agent {
178
178
  this.tasks = tasks; // background tasks (sub-agents started with run_in_background)
179
179
  this.notifications = []; // {taskId, text} waiting to be shown to the model
180
180
  this.editsThisRun = 0; // successful file edits since the last verification
181
- this.modes = modes; // session mode: full access, or read-only plan mode
182
181
  this.checkpoints = checkpoints; // snapshots of files before they are edited, per user prompt
183
182
  this.tools = tools;
184
183
  this.systemPrompt = systemPrompt; // string or () => string
@@ -189,6 +188,8 @@ export class Agent {
189
188
  this.spawnSubagent = spawnSubagent;
190
189
  this.messages = [];
191
190
  this.todos = [];
191
+ this.userTurns = 0; // turns the user started (see noteUserTurn)
192
+ this.todosTurn = 0; // ... and the one in which the todo list was last written
192
193
  this.fileState = new Map();
193
194
  this.projectRoot = cwd;
194
195
  this.cwd = cwd;
@@ -385,14 +386,25 @@ export class Agent {
385
386
  }
386
387
 
387
388
  // Run one user turn to completion. Returns {text, interrupted}.
389
+ // A turn the user started (a message of theirs, or a task from another session; not only a report of a background
390
+ // agent). The todo list belongs to a request: one that the whole turn before this one left as it was is done or
391
+ // dropped (its last items never ticked off, or one waiting for the user left in it), so it is put away instead of
392
+ // showing under the next task. The model writes a new one when it needs one.
393
+ noteUserTurn(content) {
394
+ const fromUser = toBlocks(content).some((b) => b.type === 'image' || (b.type === 'text' && !/^<(task-notification|system-reminder)>/.test(b.text)));
395
+ if (!fromUser) return;
396
+ this.userTurns++;
397
+ if (this.todos.length && this.todosTurn < this.userTurns - 1) this.todos = [];
398
+ }
399
+
388
400
  async run(userContent, { signal } = {}) {
389
401
  if (!this.isSubagent) {
390
402
  this.beforeTurn?.();
391
403
  this.endEffortBoost();
404
+ this.noteUserTurn(userContent);
392
405
  }
393
406
  this.clearAfterIdle();
394
407
  let content = toBlocks(userContent);
395
- if (this.modes.mode === 'plan' && !this.isSubagent) content = [...content, { type: 'text', text: PLAN_MODE_REMINDER }];
396
408
  if (this.hooks?.has('UserPromptSubmit') && !this.isSubagent) {
397
409
  const prompt = content.filter((b) => b.type === 'text').map((b) => b.text).join('\n');
398
410
  const h = await this.hooks.run('UserPromptSubmit', { prompt }, { cwd: this.cwd, signal });
@@ -599,7 +611,6 @@ export class Agent {
599
611
  config: this.config,
600
612
  signal,
601
613
  fileState: this.fileState,
602
- modes: this.modes,
603
614
  checkpoints: this.checkpoints,
604
615
  agent: this,
605
616
  io: this.io,
@@ -618,7 +629,7 @@ export class Agent {
618
629
  const batches = [];
619
630
  for (const tu of toolUses) {
620
631
  const tool = map.get(tu.name);
621
- const safe = !!tool?.readOnly && tool.name !== 'ExitPlanMode' && tool.name !== 'AskUserQuestion';
632
+ const safe = !!tool?.readOnly && tool.name !== 'AskUserQuestion';
622
633
  const last = batches[batches.length - 1];
623
634
  if (safe && last?.parallel) last.items.push(tu);
624
635
  else batches.push({ parallel: safe, items: [tu] });
@@ -669,13 +680,7 @@ export class Agent {
669
680
  return fail(invalid);
670
681
  }
671
682
 
672
- // Nothing is ever asked: tools run right away. The only gate is plan mode (read-only research).
673
- const decision = this.modes.check(tool, input);
674
- if (decision.behavior === 'deny') {
675
- this.io.toolRejected?.(tu, tool, decision.message, this);
676
- return fail(decision.message);
677
- }
678
-
683
+ // Nothing is ever asked: tools run right away (a PreToolUse hook can still block one).
679
684
  if (this.hooks?.has('PreToolUse')) {
680
685
  const h = await this.hooks.run('PreToolUse', { tool_name: tool.name, tool_input: input }, { cwd: this.cwd, signal });
681
686
  for (const w of h.warnings) this.io.notice?.(w, 'warn');
package/src/commands.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { c, padEnd, truncate, colorEnabled } from './ui/ansi.js';
5
+ import { c, padEnd, truncate } from './ui/ansi.js';
6
6
  import { SelectDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
8
  import { loadConfig, settingsFiles, updateSettingsFile, rememberChoice, applyRememberedChoices, KNOWN_KEYS, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
@@ -22,7 +22,6 @@ import { cleanName, machineName } from './peers.js';
22
22
  import { rewind, promptAt } from './checkpoints.js';
23
23
  import { canRestart, runSelfCheck } from './restart.js';
24
24
  import { describeHost, normalizeDir } from './host.js';
25
- import { qrLines } from './qr.js';
26
25
 
27
26
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
28
27
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
@@ -375,8 +374,8 @@ export function buildCommands(app) {
375
374
  const remote = await app.syncRemote();
376
375
  app.ensureHost({ login: true });
377
376
  if (!remote) return;
378
- out(remote.url
379
- ? `${c.green('⇄')} This session is online at the gateway: ${c.blue(remote.url)} ${c.dim('(/status shows it, with a QR code for a phone)')}`
377
+ out(remote.registered
378
+ ? `${c.green('⇄')} This session is online at the gateway: the web page (远程控制) shows it.`
380
379
  : c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
381
380
  };
382
381
 
@@ -479,7 +478,6 @@ export function buildCommands(app) {
479
478
  description: 'Show version, model, API endpoint and session info',
480
479
  run() {
481
480
  const cfg = app.runtime.config;
482
- const modes = app.runtime.modes;
483
481
  const mem = memoryFiles(app.cwd);
484
482
  const mcp = app.runtime.mcp.status();
485
483
  const row = (k, v) => `${c.dim(padEnd(k, 18))} ${v}`;
@@ -501,7 +499,7 @@ export function buildCommands(app) {
501
499
  row('Max output', formatTokens(cfg.maxOutputTokens)),
502
500
  row('Prompt cache', cfg.promptCachingDisabled(cfg.mainModel.id) ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.mainModel.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.mainModel.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
503
501
  row('Auto-compact', cfg.autoCompactEnabled ? `at ${formatTokens(cfg.autoCompactThreshold())} tokens (window ${formatTokens(cfg.compactWindow())})` : 'disabled'),
504
- row('Mode', modes.mode === 'plan' ? 'plan (read-only; shift+tab to leave)' : 'full access (no permission prompts)'),
502
+ row('Access', 'full (no permission prompts)'),
505
503
  row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
506
504
  row('Shell', `${app.runtime.shell.name} ${c.dim(app.runtime.shell.path)}`),
507
505
  row('ripgrep', hasRipgrep(cfg) ? 'yes' : 'no (using JS fallback)'),
@@ -513,7 +511,7 @@ export function buildCommands(app) {
513
511
  },
514
512
  });
515
513
 
516
- // /status about the gateway: this session there (its page, and a QR code of it for a phone), its name for the
514
+ // /status about the gateway: whether this session is online there, its name for the
517
515
  // sessions on the other computers, and the computer service.
518
516
  function remoteLines(row) {
519
517
  const cfg = app.runtime.config;
@@ -521,15 +519,9 @@ export function buildCommands(app) {
521
519
  const me = app.peerLabel();
522
520
  const lines = [
523
521
  row('Remote control', remote.text),
524
- ...(remote.url ? [row('', c.blue(remote.url))] : []),
525
522
  row('Name', `&${me} ${c.dim(`(on your other computers: &${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
526
523
  row('Computer service', describeHost(cfg.env)),
527
524
  ];
528
- const qr = remote.url && app.remote?.online ? qrLines(remote.url, { color: colorEnabled }) : null;
529
- if (qr) {
530
- lines.push('', c.dim(' Scan with a phone to open this session (log in to the gateway there):'), ...qr.map((l) => ` ${l}`));
531
- lines.push(c.dim(` Whoever can log in to this gateway account, or holds one of its API keys, can run anything on this computer through it.`));
532
- }
533
525
  return lines;
534
526
  }
535
527
 
@@ -723,17 +715,6 @@ export function buildCommands(app) {
723
715
  },
724
716
  });
725
717
 
726
- add({
727
- name: 'plan',
728
- description: 'Toggle read-only plan mode (same as shift+tab)',
729
- run() {
730
- const mode = app.runtime.modes.toggle();
731
- out(mode === 'plan'
732
- ? [`${c.plan('Plan mode on')}: the agent can only read and research, then proposes a plan with ExitPlanMode.`, c.dim('Run /plan or press shift+tab to leave it.')]
733
- : `Plan mode off: ${c.bold('full access')}, tools run immediately.`);
734
- },
735
- });
736
-
737
718
  add({
738
719
  name: 'rewind',
739
720
  aliases: ['checkpoint'],
package/src/host.js CHANGED
@@ -1119,7 +1119,7 @@ function statusCommand() {
1119
1119
  const auto = installedAutostart();
1120
1120
  const boot = bootAutostartInstalled();
1121
1121
  const lines = [
1122
- `claude-pro host (lets the gateway's web page open sessions on this computer): ${running ? `running, pid ${state.pid}, since ${state.startedAt || '?'}` : state.disabled ? 'stopped (claude-pro host start)' : 'not running (claude-pro host start)'}`,
1122
+ `claude-pro host (the web page runs and manages sessions on this computer through it): ${running ? `running, pid ${state.pid}, since ${state.startedAt || '?'}` : state.disabled ? 'stopped (claude-pro host start)' : 'not running (claude-pro host start)'}`,
1123
1123
  ];
1124
1124
  if (running) lines.push(` gateway: ${state.gateway ? `${state.gateway}${state.account ? ` as ${state.account}` : ''} · ${state.online ? 'online' : 'not connected now'}` : 'not logged in (it waits for /login)'}`);
1125
1125
  if (state.id) lines.push(` id: ${state.id}${state.machine ? ` · computer: ${state.machine}` : ''}${state.terminal ? ` · opens: ${state.terminal}` : ''}${state.version ? ` · version ${state.version}` : ''}`);
package/src/main.js CHANGED
@@ -15,7 +15,6 @@ Options:
15
15
  --provider <backend> api (default) | claude-code (direct HTTP with existing local login)
16
16
  --model <model> Model for this session (name or alias: opus, sonnet, haiku)
17
17
  --effort <level> Reasoning effort: none|minimal|low|medium|high|xhigh|max
18
- --plan Start in read-only plan mode (research first, then ExitPlanMode)
19
18
  --output-format <format> text | json | stream-json (with --print)
20
19
  --verify <command> After the agent edits files, run this (e.g. "npm test") and send failures back to fix
21
20
  --append-system-prompt <text> Append text to the system prompt
@@ -33,7 +32,7 @@ Options:
33
32
  There are no permission prompts: every tool runs immediately (full access). File edits are
34
33
  checkpointed per prompt, and /rewind in a session undoes them. The old flags
35
34
  --dangerously-skip-permissions, --permission-mode, --allowedTools and --disallowedTools
36
- are accepted and ignored (--permission-mode plan is the same as --plan), and so is
35
+ are accepted and ignored, and so are --plan (there is no plan mode: ask for a plan in the message) and
37
36
  --remote-control (--rc): a session is online at the gateway whenever this computer is logged in to it.
38
37
 
39
38
  Commands:
@@ -71,8 +70,8 @@ function parseArgs(argv) {
71
70
  case '--model': flags.model = next(); break;
72
71
  case '--provider': flags.provider = next(); break;
73
72
  case '--effort': flags.effort = next(); break;
74
- case '--plan': flags.plan = true; break;
75
- case '--permission-mode': if (next() === 'plan') flags.plan = true; break;
73
+ case '--plan': break; // no plan mode any more: asking for a plan in the message does it
74
+ case '--permission-mode': next(); break;
76
75
  case '--dangerously-skip-permissions': break; // nothing to skip: there are no prompts
77
76
  case '--allowedTools': case '--allowed-tools': case '--disallowedTools': case '--disallowed-tools': skipRules(); break;
78
77
  case '--output-format': flags.outputFormat = next(); break;
package/src/print.js CHANGED
@@ -27,7 +27,6 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
27
27
  };
28
28
  const mainRateLimit = rateLimitReporter();
29
29
  const io = {
30
- approvePlan: async () => 'reject', // non-interactive: a plan is only presented, never executed
31
30
  askQuestion: async () => null,
32
31
  notice: (text) => err(c.yellow(text)),
33
32
  toolStart: (tu, tool, input, agent) => {
package/src/prompts.js CHANGED
@@ -64,7 +64,7 @@ Do not make up URLs. Give a URL only when it came from the user, a file or a too
64
64
  - If you cannot or will not help with something, say so briefly without lecturing, and offer alternatives if possible.
65
65
 
66
66
  # How you work
67
- You run on the user's own test machine with full access: tool calls run without asking the user for confirmation, except where a control of the program (plan mode, a hook) steps in. Use that freedom to get the job done. Do not ask for permission to read, write, install, run or delete what the task needs, and decide how to go about it (how much to plan, whether to use sub-agents, how to verify) by what the task needs rather than by a fixed procedure.
67
+ You run on the user's own test machine with full access: tool calls run without asking the user for confirmation, except where a control of the program (a hook) steps in. Use that freedom to get the job done. Do not ask for permission to read, write, install, run or delete what the task needs, and decide how to go about it (how much to plan, whether to use sub-agents, how to verify) by what the task needs rather than by a fixed procedure.
68
68
  - Aim at the user's goal rather than the letter of the steps they described: when you see a clearly better way to reach it, take it and say why, unless they asked for their way specifically. Do not change the goal itself or a constraint they set.
69
69
  - When you have enough information to act, act. Do not re-derive facts already established in the conversation, re-argue a decision the user has made, or lay out options you will not pursue; when you weigh a choice, give a recommendation, not a survey.
70
70
  - Work end to end: understand, implement, run and verify before reporting back. Do not stop at a plan unless asked for one.
@@ -86,7 +86,7 @@ You run on the user's own test machine with full access: tool calls run without
86
86
  # Tools
87
87
  - Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
88
88
  - Delegate to sub-agents (Task) when that makes the work better, faster or keeps your context small: broad searches, independent subtasks, a second look at risky work. Weigh what it costs first: each agent builds its own context and spends its own tokens (from the user's usage limit too), it does not see what you or other agents know, and agents that edit related files at the same time get in each other's way. Closely coupled work that needs shared state is usually better done yourself. Use run_in_background for long jobs.
89
- - If a tool call is blocked (by plan mode, a hook or another control of the program), do not retry it or get around it another way: adjust your approach within what is allowed, or tell the user what is in the way.
89
+ - If a tool call is blocked (by a hook or another control of the program), do not retry it or get around it another way: adjust your approach within what is allowed, or tell the user what is in the way.
90
90
  - Tool results and user messages may include <system-reminder> tags: information added by the harness, not part of the user's request.
91
91
 
92
92
  ${selfRestart ? `# Your own source code
@@ -137,11 +137,6 @@ ${message}
137
137
  ${current ? 'Does this message start a new topic (a different task or question), or does it continue the current one (a follow-up, "continue", an answer, a correction)? ' : ''}Reply with only a JSON object: {"isNewTopic": ${current ? 'true or false' : 'true'}, "title": ...}. For a new topic, "title" names it in 2 to 6 words (at most about 16 characters in Chinese or Japanese), in the language of the user's message, with no quotes, no emoji and no punctuation at the end. Otherwise "title" is null.`;
138
138
  }
139
139
 
140
- export const PLAN_MODE_REMINDER = `<system-reminder>
141
- Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
142
- Research the codebase with read-only tools, then present a concise implementation plan by calling the ExitPlanMode tool. Do not ask for approval in plain text; use ExitPlanMode.
143
- </system-reminder>`;
144
-
145
140
  // The system prompt of the plain summary request (see Agent.requestSummary).
146
141
  export const SUMMARY_SYSTEM = 'You are a helpful AI assistant tasked with summarizing conversations.';
147
142
 
package/src/runtime.js CHANGED
@@ -3,7 +3,6 @@
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
5
  import { loadConfig, applyRememberedChoices, SOURCE_CHECKOUT } from './config.js';
6
- import { ModeManager } from './modes.js';
7
6
  import { CheckpointStore } from './checkpoints.js';
8
7
  import { loadAgents, loadSkills } from './agents.js';
9
8
  import { buildTools, toolsForSubagent } from './tools/index.js';
@@ -25,8 +24,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
25
24
  pruneToolResults(cwd);
26
25
  pruneCheckpoints(cwd);
27
26
  pruneStaleShellFiles();
28
- // Full access: nothing is ever asked. The only mode switch is the read-only plan mode (--plan).
29
- const modes = new ModeManager(flags.plan ? 'plan' : 'full');
27
+ // Full access: nothing is ever asked.
30
28
  const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
31
29
 
32
30
  const agents = loadAgents(cwd);
@@ -37,7 +35,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
37
35
  const hooks = new HookRunner(config);
38
36
  const tasks = new BackgroundTasks();
39
37
  const memoryDir = autoMemoryDir(cwd);
40
- const runtime = { config, modes, checkpoints, agents, mcp, shell, io, cwd, hooks, tasks, memoryDir };
38
+ const runtime = { config, checkpoints, agents, mcp, shell, io, cwd, hooks, tasks, memoryDir };
41
39
  runtime.skills = loadSkills(cwd);
42
40
  // The self-check builds the Restart tool too, so that a mistake in it is found before a restart relies on it.
43
41
  const restartable = canRestart() || process.env.CLAUDE_PRO_SELF_CHECK === '1';
@@ -116,7 +114,6 @@ export async function createRuntime({ cwd, flags = {}, io }) {
116
114
  const depth = (ctx.depth ?? ctx.agent?.depth ?? 0) + 1;
117
115
  const sub = new Agent({
118
116
  config,
119
- modes,
120
117
  checkpoints,
121
118
  depth,
122
119
  spawnSubagent: runtime.spawnSubagent,
@@ -148,7 +145,6 @@ export async function createRuntime({ cwd, flags = {}, io }) {
148
145
 
149
146
  runtime.agent = new Agent({
150
147
  config,
151
- modes,
152
148
  checkpoints,
153
149
  tools: runtime.tools,
154
150
  systemPrompt: runtime.systemPrompt,
@@ -2,7 +2,7 @@ import { ReadTool, WriteTool, EditTool } 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';
5
- import { TodoWriteTool, ExitPlanModeTool, AskUserQuestionTool } from './interaction.js';
5
+ import { TodoWriteTool, AskUserQuestionTool } from './interaction.js';
6
6
  import { makeTaskTool, TaskOutputTool, TaskStopTool } from './task.js';
7
7
  import { NotebookEditTool } from './notebook.js';
8
8
  import { makeSkillTool } from './skill.js';
@@ -31,7 +31,6 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
31
31
  TodoWriteTool,
32
32
  BashOutputTool,
33
33
  KillShellTool,
34
- ExitPlanModeTool,
35
34
  AskUserQuestionTool,
36
35
  makeEffortTool(config),
37
36
  ...(restart ? [RestartTool] : []),
@@ -41,7 +40,7 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
41
40
  }
42
41
 
43
42
  // Effort: a sub-agent shares the main agent's settings, so it must not change them.
44
- const NEVER_FOR_SUBAGENTS = new Set(['TaskOutput', 'TaskStop', 'TodoWrite', 'ExitPlanMode', 'AskUserQuestion', 'Restart', 'Effort', 'ListPeers', 'MessagePeer']);
43
+ const NEVER_FOR_SUBAGENTS = new Set(['TaskOutput', 'TaskStop', 'TodoWrite', 'AskUserQuestion', 'Restart', 'Effort', 'ListPeers', 'MessagePeer']);
45
44
 
46
45
  // Tools for a sub-agent. `allowTask`: it is below the nesting limit, so it may start sub-agents of its own.
47
46
  export function toolsForSubagent(allTools, def, { allowTask = false } = {}) {
@@ -1,5 +1,4 @@
1
- // Tools that interact with the session rather than the machine: TodoWrite,
2
- // ExitPlanMode and AskUserQuestion.
1
+ // Tools that interact with the session rather than the machine: TodoWrite and AskUserQuestion.
3
2
 
4
3
  export const TodoWriteTool = {
5
4
  name: 'TodoWrite',
@@ -36,6 +35,7 @@ How:
36
35
  async call(input, ctx) {
37
36
  const todos = Array.isArray(input.todos) ? input.todos.filter((t) => t && t.content) : [];
38
37
  ctx.agent.todos = todos.every((t) => t.status === 'completed') ? [] : todos;
38
+ ctx.agent.todosTurn = ctx.agent.userTurns; // see Agent.noteUserTurn
39
39
  return {
40
40
  content: 'The todo list is updated.',
41
41
  display: { todos },
@@ -43,34 +43,6 @@ How:
43
43
  },
44
44
  };
45
45
 
46
- export const ExitPlanModeTool = {
47
- name: 'ExitPlanMode',
48
- readOnly: true,
49
- description: `Use this tool when you are in plan mode and have finished planning the implementation steps of a task that requires writing code, and are ready to code. This will prompt the user to approve your plan.
50
- Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.`,
51
- input_schema: {
52
- type: 'object',
53
- properties: {
54
- plan: { type: 'string', description: 'The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise.' },
55
- },
56
- required: ['plan'],
57
- },
58
- summarize() { return ''; },
59
- async call(input, ctx) {
60
- if (ctx.modes.mode !== 'plan') return { isError: true, content: 'You are not in plan mode. Proceed with the task.' };
61
- const choice = await ctx.io.approvePlan(input.plan);
62
- if (choice === 'full') {
63
- ctx.modes.setMode('full');
64
- return { content: 'User has approved your plan. You can now start coding. Start with updating your todo list if applicable.', display: { plan: input.plan, approved: true } };
65
- }
66
- return {
67
- content: 'The user wants to keep planning. Do not start implementation. Wait for the user to explain what should change in the plan.',
68
- display: { plan: input.plan, approved: false },
69
- stopTurn: true,
70
- };
71
- },
72
- };
73
-
74
46
  export const AskUserQuestionTool = {
75
47
  name: 'AskUserQuestion',
76
48
  readOnly: true,
package/src/tools/task.js CHANGED
@@ -96,7 +96,7 @@ Usage notes:
96
96
  if (input.run_in_background) {
97
97
  if (!ctx.tasks) return { isError: true, content: 'Background agents are not available here; run the task in the foreground.' };
98
98
  // The task outlives this turn, so it gets its own signal and no live progress display.
99
- const base = { cwd: ctx.cwd, projectRoot: ctx.projectRoot, config: ctx.config, modes: ctx.modes, checkpoints: ctx.checkpoints, io: ctx.io, depth: ctx.agent?.depth ?? 0 };
99
+ const base = { cwd: ctx.cwd, projectRoot: ctx.projectRoot, config: ctx.config, checkpoints: ctx.checkpoints, io: ctx.io, depth: ctx.agent?.depth ?? 0 };
100
100
  const task = ctx.tasks.start({
101
101
  description: input.description || def.name,
102
102
  subagentType: def.name,
package/src/ui/ansi.js CHANGED
@@ -48,7 +48,6 @@ export const c = {
48
48
  white: hex('#ffffff'),
49
49
  claude: hex('#d77757'), // the orange brand accent
50
50
  permission: hex('#b1b9f9'),
51
- plan: hex('#48968c'),
52
51
  edits: hex('#af87ff'),
53
52
  code: hex('#b1b9f9'),
54
53
  userBg: hex('#373737', true), // the band behind the user's messages (see renderUserMessage)
package/src/ui/render.js CHANGED
@@ -99,10 +99,6 @@ export function renderToolResult(entry, { verbose = false, width = 100, cwd }) {
99
99
  return resultLines([...partial.map((l) => c.dim(truncate(l, w))), c.red('Interrupted by user')]);
100
100
  }
101
101
  if (d.todos) return renderTodos(d.todos);
102
- if (d.plan !== undefined) {
103
- const md = renderMarkdown(d.plan, { width: w });
104
- return resultLines([d.approved ? c.green('User approved the plan') : c.yellow('User asked to keep planning'), ...(verbose ? md : [])]);
105
- }
106
102
  if (d.preview && !r.isError) {
107
103
  const lines = [d.summary ? `${d.summary}` : ''];
108
104
  if (d.preview.kind === 'create' && !verbose) return resultLines([d.summary || `Created ${displayPath(d.preview.path, cwd)}`]);
package/src/ui/repl.js CHANGED
@@ -306,7 +306,6 @@ export class App {
306
306
  try { this.onKey(str, key || {}); } catch (e) { this.logError(e); }
307
307
  });
308
308
  stdin.resume();
309
- this.runtime.modes.listeners.add(() => this.screen.schedule());
310
309
  // Started by a restart of this session: the output of the process before it is still on screen, so no
311
310
  // welcome box and no transcript, just a line saying so.
312
311
  const restart = this.flags.restart || null;
@@ -950,21 +949,21 @@ export class App {
950
949
  this.screen.schedule();
951
950
  }
952
951
 
953
- // This session at the gateway, for /status: {text, url} (url: its page, once registered).
952
+ // This session at the gateway, for /status: {text}. (Its page is in the web page's list, 远程控制: no link here.)
954
953
  remoteState() {
955
954
  const r = this.remote;
956
955
  if (r) {
957
956
  const who = r.account ? ` as ${r.account}` : '';
958
957
  const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
959
958
  const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
960
- return { text, url: r.url };
959
+ return { text };
961
960
  }
962
- if (this.remoteStarting) return { text: 'connecting…', url: null };
961
+ if (this.remoteStarting) return { text: 'connecting…' };
963
962
  const login = readGatewayLogin(this.config.gatewayUrl);
964
- if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`), url: null };
965
- if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)'), url: null };
966
- if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)'), url: null };
967
- return { text: c.dim('offline'), url: null };
963
+ if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
964
+ if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
965
+ if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
966
+ return { text: c.dim('offline') };
968
967
  }
969
968
 
970
969
  // The state the page shows below the transcript; sent whenever it changes.
@@ -990,7 +989,6 @@ export class App {
990
989
  todos: (this.agent.todos || []).map((t) => ({ content: t.content, status: t.status })),
991
990
  queue: this.queue.map((q) => q.display ?? q.text),
992
991
  dialog: this.remoteDialog(),
993
- mode: this.runtime.modes.mode,
994
992
  model,
995
993
  effort: effort || defaultEffort(cfg.mainModel.id, cfg),
996
994
  title: this.sessionLabel() || path.basename(this.cwd),
@@ -1091,7 +1089,7 @@ export class App {
1091
1089
  const cfg = this.config;
1092
1090
  const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
1093
1091
  const { effort } = modelInfo(cfg);
1094
- return { model: cfg.mainModel.id, models, effort: effort || defaultEffort(cfg.mainModel.id, cfg), efforts: efforts.options, mode: this.runtime.modes.mode };
1092
+ return { model: cfg.mainModel.id, models, effort: effort || defaultEffort(cfg.mainModel.id, cfg), efforts: efforts.options };
1095
1093
  }
1096
1094
 
1097
1095
  // For the page's input box: what the input box here would suggest (/commands, @files, &sessions), in plain text,
@@ -1218,7 +1216,6 @@ export class App {
1218
1216
  modelOverride: cfg.modelOverride,
1219
1217
  effortOverride: cfg.effortOverride,
1220
1218
  effortBoost: cfg.effortBoost,
1221
- mode: this.runtime.modes.mode,
1222
1219
  todos: this.agent.todos,
1223
1220
  draft: this.editor.text,
1224
1221
  screenHistory: this.screen.history.slice(-3000),
@@ -1263,7 +1260,6 @@ export class App {
1263
1260
  if ('effortOverride' in state) cfg.effortOverride = state.effortOverride || null;
1264
1261
  // The Effort tool's level holds for the request the restart continues, not for the user's next one.
1265
1262
  if (state.effortBoost) { cfg.effortBoost = state.effortBoost; cfg.effortBoostKeepNext = Boolean(state.continueWith); }
1266
- if (state.mode === 'plan') this.runtime.modes.setMode('plan');
1267
1263
  this.restarts = (Array.isArray(state.restarts) ? state.restarts : []).filter((t) => Number.isFinite(t));
1268
1264
  if (resumable) {
1269
1265
  this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
@@ -1541,7 +1537,6 @@ export class App {
1541
1537
  }
1542
1538
  if (key.ctrl && key.name === 'f') { this.openFind(); return; }
1543
1539
  if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
1544
- if (key.name === 'tab' && key.shift) { this.runtime.modes.toggle(); this.screen.schedule(); return; }
1545
1540
  // alt+v like Claude Code on Windows (ctrl+v is the terminal's own text paste there).
1546
1541
  if ((key.meta || key.ctrl) && key.name === 'v') { this.pasteImage(); return; }
1547
1542
  if (key.ctrl && key.name === 'o') {
@@ -1700,12 +1695,12 @@ export class App {
1700
1695
  shortcutsHelp() {
1701
1696
  const rows = [
1702
1697
  ['! for bash mode', 'double tap esc to clear input'],
1703
- ['/ for commands', 'shift + tab to cycle permission modes'],
1704
- ['@ for file paths, & for other sessions', 'ctrl + o to toggle verbose output'],
1698
+ ['/ for commands', 'ctrl + o to toggle verbose output'],
1699
+ ['@ for file paths, & for other sessions', 'ctrl + f to find in the conversation'],
1705
1700
  ['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
1706
1701
  ['# to memorize', 'ctrl + t to toggle todos'],
1707
1702
  ['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
1708
- ['alt + v to paste an image', 'ctrl + f to find in the conversation'],
1703
+ ['alt + v to paste an image', ''],
1709
1704
  ];
1710
1705
  return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
1711
1706
  }
@@ -2157,27 +2152,6 @@ export class App {
2157
2152
  });
2158
2153
  }
2159
2154
 
2160
- async approvePlan(plan) {
2161
- this.flushStreaming();
2162
- const md = renderMarkdown(plan, { width: this.width - 8 });
2163
- const max = Math.max(8, this.screen.height - 14);
2164
- const body = md.length > max ? [...md.slice(0, max), c.dim(`… +${md.length - max} lines (the full plan is printed above)`)] : md;
2165
- if (md.length > max) this.logLocal(c.plan(`${DOT} Plan:`), ...md.map((l) => ' ' + l), '');
2166
- const dialog = new SelectDialog({
2167
- title: 'Ready to code?',
2168
- body: ["Here is the plan:", '', ...body],
2169
- question: 'Would you like to proceed?',
2170
- color: c.plan,
2171
- cancelValue: 'reject',
2172
- options: [
2173
- { label: 'Yes, start coding', value: 'full' },
2174
- { label: 'No, keep planning', value: 'reject' },
2175
- ],
2176
- });
2177
- dialog.markdown = plan; // the remote page shows the whole plan
2178
- return await this.showDialog(dialog);
2179
- }
2180
-
2181
2155
  async askQuestion(q) {
2182
2156
  const answer = await this.showDialog(new SelectDialog({
2183
2157
  title: q.header || 'Question',
@@ -2384,7 +2358,6 @@ export class App {
2384
2358
  }
2385
2359
  };
2386
2360
  return {
2387
- approvePlan: async () => 'reject',
2388
2361
  askQuestion: async () => null,
2389
2362
  notice: (text, kind) => app.notice(`[${def.name}] ${text}`, kind),
2390
2363
  toolStart(tu, tool, input, agent) {
@@ -2582,13 +2555,11 @@ export class App {
2582
2555
  }
2583
2556
 
2584
2557
  footer(w) {
2585
- const mode = this.runtime.modes.mode;
2586
2558
  let left;
2587
2559
  const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
2588
2560
  if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
2589
2561
  else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
2590
2562
  else if (this.restartRequest) left = c.dim(' ↻ restarting when this turn ends');
2591
- else if (mode === 'plan') left = ' ' + c.plan('⏸ plan mode on (read-only)') + c.dim(' (shift+tab to leave)');
2592
2563
  else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
2593
2564
  else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
2594
2565
  else left = c.dim(' ? for shortcuts');
package/src/modes.js DELETED
@@ -1,154 +0,0 @@
1
- // Session mode. There are no permission prompts or rules: every tool call runs right away.
2
- // The only switch is plan mode, an opt-in read-only phase for investigating and proposing a
3
- // plan before changing anything (shift+tab or --plan turns it on; ExitPlanMode turns it off).
4
-
5
- export const MODES = ['full', 'plan'];
6
-
7
- // Split a shell command into simple commands on && || ; | and newlines (quote aware).
8
- export function splitCommand(cmd) {
9
- const parts = [];
10
- let cur = '', quote = null;
11
- for (let i = 0; i < cmd.length; i++) {
12
- const ch = cmd[i];
13
- if (quote) {
14
- cur += ch;
15
- if (ch === '\\' && quote === '"' && i + 1 < cmd.length) { cur += cmd[++i]; continue; }
16
- if (ch === quote) quote = null;
17
- continue;
18
- }
19
- if (ch === '"' || ch === "'") { quote = ch; cur += ch; continue; }
20
- if (ch === '\\' && i + 1 < cmd.length) { cur += ch + cmd[++i]; continue; }
21
- const two = cmd.slice(i, i + 2);
22
- if (two === '&&' || two === '||') { parts.push(cur); cur = ''; i++; continue; }
23
- if (ch === ';' || ch === '|' || ch === '\n') { parts.push(cur); cur = ''; continue; }
24
- if (ch === '&' && cmd[i + 1] !== '>' && cmd[i - 1] !== '>') { parts.push(cur); cur = ''; continue; }
25
- cur += ch;
26
- }
27
- parts.push(cur);
28
- return parts.map((p) => p.trim()).filter(Boolean);
29
- }
30
-
31
- function stripQuotedStrings(s) {
32
- return s.replace(/'[^']*'/g, "''").replace(/"(?:\\.|[^"\\])*"/g, '""');
33
- }
34
-
35
- // Syntax we can't classify: command substitution, redirection to files, etc.
36
- function hasUnclassifiableSyntax(cmd) {
37
- const s = stripQuotedStrings(cmd);
38
- if (/\$\(|`|<\(|>\(/.test(s)) return true;
39
- // Redirections other than to /dev/null or fd duplication.
40
- const redir = s.replace(/\d?>&\d/g, '').replace(/&?>>?\s*\/dev\/null/g, '').replace(/\d?>>?\s*\/dev\/null/g, '');
41
- return /[<>]/.test(redir);
42
- }
43
-
44
- // Commands that read only, whatever their arguments (the ones whose arguments can make them write or run
45
- // something have their own check in COMMAND_CHECKS below). No pagers: `less +!cmd` runs a command.
46
- const READ_ONLY_SIMPLE = new Set([
47
- 'ls', 'pwd', 'echo', 'cat', 'head', 'tail', 'wc', 'which', 'whoami', 'stat', 'du', 'df',
48
- 'uname', 'printenv', 'type', 'realpath', 'basename', 'dirname', 'cut', 'tr', 'diff',
49
- 'grep', 'egrep', 'fgrep', 'true', 'false', 'test', 'nproc', 'id', 'cd', 'column', 'jq', 'md5sum', 'sha256sum',
50
- ]);
51
- const READ_ONLY_PREFIXES = [
52
- 'git status', 'git rev-parse', 'git ls-files', 'git blame', 'git describe', 'git stash list',
53
- 'git config --get', 'git config -l', 'git config --list',
54
- 'node --version', 'node -v', 'npm --version', 'npm -v', 'npm ls', 'npm list', 'npm view', 'npm outdated', 'pnpm --version',
55
- 'yarn --version', 'python --version', 'python3 --version', 'pip list', 'pip show', 'pip --version', 'go version',
56
- 'cargo --version', 'rustc --version', 'java -version', 'dotnet --version', 'docker ps', 'docker images', 'where',
57
- ];
58
-
59
- // `git branch` only lists with these flags; a name, -d/-D, -m/-M, -c/-C, -u ... would create, delete or rename.
60
- const GIT_BRANCH_FLAGS = new Set(['-a', '--all', '-r', '--remotes', '-v', '-vv', '--verbose', '-l', '--list', '--show-current', '--no-color', '--color', '--no-column', '--column']);
61
- const GIT_BRANCH_VALUE_FLAGS = /^--(?:contains|no-contains|merged|no-merged|points-at|sort|format|abbrev)(?:=.*)?$/;
62
- function gitBranchReads(args) {
63
- let listing = false;
64
- for (let i = 0; i < args.length; i++) {
65
- const a = args[i];
66
- if (GIT_BRANCH_FLAGS.has(a)) { if (a === '-l' || a === '--list') listing = true; continue; }
67
- if (GIT_BRANCH_VALUE_FLAGS.test(a)) { if (!a.includes('=') && !/^--abbrev$/.test(a)) i++; continue; }
68
- if (listing && !a.startsWith('-')) continue; // a pattern to list
69
- return false;
70
- }
71
- return true;
72
- }
73
-
74
- // `git tag` likewise: listing is fine, anything that makes or removes a tag is not.
75
- function gitTagReads(args) {
76
- if (!args.some((a) => a === '-l' || a === '--list')) return false;
77
- return args.every((a) => !a.startsWith('-') || /^(?:-l|--list|-n\d*|--sort=.*|--column|--no-column|--contains|--no-contains|--merged|--no-merged|--points-at|--format=.*|--color|--no-color)$/.test(a));
78
- }
79
-
80
- const positional = (args) => args.filter((a) => !a.startsWith('-') && !a.startsWith('+'));
81
-
82
- // Commands that are read-only only with certain arguments: args => true when this call reads only.
83
- const COMMAND_CHECKS = {
84
- // -exec and -delete run or remove things, -fprint* and -fls write files
85
- find: (args) => !args.some((a) => /^-(?:exec|execdir|ok|okdir|delete|fprint0?|fprintf|fls)$/.test(a)),
86
- // -o FILE and --output FILE (GNU getopt accepts any unambiguous prefix of it)
87
- sort: (args) => !args.some((a) => /^-[a-zA-Z]*o/.test(a) || /^--o/.test(a)),
88
- // `uniq INPUT OUTPUT` writes OUTPUT
89
- uniq: (args) => positional(args).length <= 1,
90
- tree: (args) => !args.some((a) => /^-[a-zA-Z]*o/.test(a) || /^--output/.test(a)),
91
- // setting the clock or the host name changes the machine
92
- date: (args) => !args.some((a) => /^-[a-zA-Z]*s/.test(a) || /^--set/.test(a)) && positional(args).length === 0,
93
- hostname: (args) => args.length === 0 || args.every((a) => /^(?:-[fsiIdAy]|--(?:fqdn|short|ip-address|domain|all-ip-addresses))$/.test(a)),
94
- // --pre runs a command on every file
95
- rg: (args) => !args.some((a) => /^--(?:pre|hostname-bin)(?:=|$)/.test(a)),
96
- file: (args) => !args.some((a) => /^-[a-zA-Z]*C/.test(a) || a === '--compile'),
97
- // `git log --output=FILE` and friends write the result to a file
98
- git: (args, part) => {
99
- const sub = args.find((a) => !a.startsWith('-'));
100
- const rest = args.slice(args.indexOf(sub) + 1);
101
- if (args[0] !== sub) return null; // options before the subcommand (-C dir, -c key=value): not classified
102
- if (sub === 'diff' || sub === 'log' || sub === 'show') return !rest.some((a) => /^--output(?:=|$)/.test(a));
103
- if (sub === 'branch') return gitBranchReads(rest);
104
- if (sub === 'tag') return gitTagReads(rest);
105
- if (sub === 'remote') return part === 'git remote' || part === 'git remote -v';
106
- return null;
107
- },
108
- // `go env -w` and `-u` change the Go settings
109
- go: (args) => (args[0] === 'env' ? !args.some((a) => a === '-w' || a === '-u') : args[0] === 'version'),
110
- };
111
-
112
- // True when every part of the command only reads (used to let research commands run in plan mode).
113
- export function isReadOnlyCommand(cmd) {
114
- if (hasUnclassifiableSyntax(cmd)) return false;
115
- return splitCommand(cmd).every((part) => {
116
- const words = part.split(/\s+/);
117
- const first = words[0];
118
- if (/^\w+=/.test(first)) return false; // env assignment prefix
119
- // hasOwn: a command called `constructor` or `toString` must not find a function on the prototype.
120
- if (Object.hasOwn(COMMAND_CHECKS, first)) {
121
- const verdict = COMMAND_CHECKS[first](words.slice(1), part);
122
- if (verdict !== null) return verdict;
123
- }
124
- if (READ_ONLY_SIMPLE.has(first)) return true;
125
- // A command that has an argument check is only ever read-only through that check, except where it
126
- // is also in the simple list (above); the rest is matched by prefix.
127
- return READ_ONLY_PREFIXES.some((p) => part === p || part.startsWith(`${p} `));
128
- });
129
- }
130
-
131
- export class ModeManager {
132
- constructor(mode = 'full') {
133
- this.mode = MODES.includes(mode) ? mode : 'full';
134
- this.listeners = new Set();
135
- }
136
-
137
- setMode(mode) {
138
- if (!MODES.includes(mode)) return;
139
- this.mode = mode;
140
- for (const l of this.listeners) l(mode);
141
- }
142
-
143
- toggle() {
144
- this.setMode(this.mode === 'plan' ? 'full' : 'plan');
145
- return this.mode;
146
- }
147
-
148
- // {behavior: 'allow'} or, in plan mode for anything that changes state, {behavior: 'deny', message}.
149
- check(tool, input = {}) {
150
- if (this.mode !== 'plan' || tool.readOnly) return { behavior: 'allow' };
151
- if (tool.name === 'Bash' && isReadOnlyCommand(String(input.command || ''))) return { behavior: 'allow' };
152
- return { behavior: 'deny', message: 'Plan mode is active: do not make changes or run commands that modify anything yet. Keep researching with read-only tools, then present your plan with ExitPlanMode.' };
153
- }
154
- }
package/src/qr.js DELETED
@@ -1,206 +0,0 @@
1
- // QR codes in the terminal: /status prints one of the session's page, so that a phone opens it by pointing its camera
2
- // at the screen. Byte mode, error correction level L, versions 1-6 (up to 134 bytes, which a URL with a token
3
- // fits in easily); the mask is chosen with the standard penalty rules.
4
-
5
- // [EC codewords per block, blocks, data codewords per block] at level L, by version.
6
- const EC_L = [null, [7, 1, 19], [10, 1, 34], [15, 1, 55], [20, 1, 80], [26, 1, 108], [18, 2, 68]];
7
- const MAX_VERSION = 6;
8
-
9
- // GF(256) with the polynomial 0x11d.
10
- const EXP = new Uint8Array(512);
11
- const LOG = new Uint8Array(256);
12
- for (let i = 0, x = 1; i < 255; i++) {
13
- EXP[i] = x;
14
- LOG[x] = i;
15
- x <<= 1;
16
- if (x & 0x100) x ^= 0x11d;
17
- }
18
- for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
19
- const mul = (a, b) => (a && b ? EXP[LOG[a] + LOG[b]] : 0);
20
-
21
- function rsRemainder(data, n) {
22
- let gen = [1]; // (x - a^0)(x - a^1)...(x - a^(n-1)), highest degree first
23
- for (let i = 0; i < n; i++) {
24
- const next = new Array(gen.length + 1).fill(0);
25
- for (let j = 0; j < gen.length; j++) { next[j] ^= gen[j]; next[j + 1] ^= mul(gen[j], EXP[i]); }
26
- gen = next;
27
- }
28
- const rem = new Array(n).fill(0);
29
- for (const byte of data) {
30
- const factor = byte ^ rem.shift();
31
- rem.push(0);
32
- for (let i = 0; i < n; i++) rem[i] ^= mul(gen[i + 1], factor);
33
- }
34
- return rem;
35
- }
36
-
37
- function codewords(bytes, version) {
38
- const [ecLen, blocks, dataLen] = EC_L[version];
39
- const capacity = blocks * dataLen;
40
- const bits = [];
41
- const put = (value, len) => { for (let i = len - 1; i >= 0; i--) bits.push((value >>> i) & 1); };
42
- put(0b0100, 4);
43
- put(bytes.length, 8);
44
- for (const b of bytes) put(b, 8);
45
- put(0, Math.min(4, capacity * 8 - bits.length));
46
- while (bits.length % 8) bits.push(0);
47
- const data = [];
48
- for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((v, b) => (v << 1) | b, 0));
49
- for (let pad = 0xec; data.length < capacity; pad ^= 0xec ^ 0x11) data.push(pad);
50
- const dataBlocks = [];
51
- const ecBlocks = [];
52
- for (let b = 0; b < blocks; b++) {
53
- const d = data.slice(b * dataLen, (b + 1) * dataLen);
54
- dataBlocks.push(d);
55
- ecBlocks.push(rsRemainder(d, ecLen));
56
- }
57
- const out = [];
58
- for (let i = 0; i < dataLen; i++) for (const d of dataBlocks) out.push(d[i]);
59
- for (let i = 0; i < ecLen; i++) for (const e of ecBlocks) out.push(e[i]);
60
- return out;
61
- }
62
-
63
- const MASKS = [
64
- (x, y) => (x + y) % 2 === 0,
65
- (x, y) => y % 2 === 0,
66
- (x) => x % 3 === 0,
67
- (x, y) => (x + y) % 3 === 0,
68
- (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
69
- (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0,
70
- (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
71
- (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
72
- ];
73
-
74
- function penalty(m) {
75
- const n = m.length;
76
- let score = 0;
77
- let dark = 0;
78
- const lines = [];
79
- for (let i = 0; i < n; i++) {
80
- lines.push(m[i]);
81
- lines.push(m.map((row) => row[i]));
82
- }
83
- for (const line of lines) {
84
- for (let i = 0; i < n;) {
85
- let j = i;
86
- while (j < n && line[j] === line[i]) j++;
87
- if (j - i >= 5) score += 3 + (j - i - 5);
88
- i = j;
89
- }
90
- const s = line.map((v) => (v ? 1 : 0)).join('');
91
- for (const p of ['10111010000', '00001011101']) for (let k = s.indexOf(p); k >= 0; k = s.indexOf(p, k + 1)) score += 40;
92
- }
93
- for (let y = 0; y < n; y++) {
94
- for (let x = 0; x < n; x++) {
95
- if (m[y][x]) dark++;
96
- if (x < n - 1 && y < n - 1 && m[y][x] === m[y][x + 1] && m[y][x] === m[y + 1][x] && m[y][x] === m[y + 1][x + 1]) score += 3;
97
- }
98
- }
99
- return score + 10 * Math.floor(Math.abs((dark * 100) / (n * n) - 50) / 5);
100
- }
101
-
102
- // The modules of the QR code for `text` (rows of booleans, true = dark), or null when it is too long.
103
- // `mask`: use this mask (0-7) instead of the best one.
104
- export function qrMatrix(text, { mask: forcedMask } = {}) {
105
- const bytes = [...Buffer.from(String(text), 'utf8')];
106
- let version = 1;
107
- while (version <= MAX_VERSION && EC_L[version][1] * EC_L[version][2] * 8 < 12 + 8 * bytes.length) version++;
108
- if (version > MAX_VERSION) return null;
109
- const size = 17 + 4 * version;
110
- const base = Array.from({ length: size }, () => new Array(size).fill(false));
111
- const fn = Array.from({ length: size }, () => new Array(size).fill(false));
112
- const set = (m, x, y, dark) => { m[y][x] = dark; fn[y][x] = true; };
113
-
114
- for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
115
- for (let dy = -4; dy <= 4; dy++) {
116
- for (let dx = -4; dx <= 4; dx++) {
117
- const x = cx + dx;
118
- const y = cy + dy;
119
- if (x < 0 || y < 0 || x >= size || y >= size) continue;
120
- const d = Math.max(Math.abs(dx), Math.abs(dy));
121
- set(base, x, y, d !== 2 && d !== 4);
122
- }
123
- }
124
- }
125
- for (let i = 0; i < size; i++) {
126
- if (!fn[6][i]) set(base, i, 6, i % 2 === 0);
127
- if (!fn[i][6]) set(base, 6, i, i % 2 === 0);
128
- }
129
- if (version >= 2) {
130
- const c = size - 7;
131
- for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(base, c + dx, c + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
132
- }
133
- const drawFormat = (m, mask) => {
134
- const data = (1 << 3) | mask; // level L = 01
135
- let rem = data;
136
- for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
137
- const bits = ((data << 10) | rem) ^ 0x5412;
138
- const bit = (i) => ((bits >>> i) & 1) === 1;
139
- for (let i = 0; i <= 5; i++) set(m, 8, i, bit(i));
140
- set(m, 8, 7, bit(6));
141
- set(m, 8, 8, bit(7));
142
- set(m, 7, 8, bit(8));
143
- for (let i = 9; i < 15; i++) set(m, 14 - i, 8, bit(i));
144
- for (let i = 0; i < 8; i++) set(m, size - 1 - i, 8, bit(i));
145
- for (let i = 8; i < 15; i++) set(m, 8, size - 15 + i, bit(i));
146
- set(m, 8, size - 8, true);
147
- };
148
- drawFormat(base, 0); // reserves the format areas before the data goes in
149
-
150
- const data = codewords(bytes, version);
151
- let bitIndex = 0;
152
- for (let right = size - 1; right >= 1; right -= 2) {
153
- if (right === 6) right = 5;
154
- for (let vert = 0; vert < size; vert++) {
155
- for (let j = 0; j < 2; j++) {
156
- const x = right - j;
157
- const upward = ((right + 1) & 2) === 0;
158
- const y = upward ? size - 1 - vert : vert;
159
- if (fn[y][x]) continue;
160
- if (bitIndex < data.length * 8) base[y][x] = ((data[bitIndex >>> 3] >>> (7 - (bitIndex & 7))) & 1) === 1;
161
- bitIndex++;
162
- }
163
- }
164
- }
165
-
166
- let best = null;
167
- for (let mask = 0; mask < 8; mask++) {
168
- if (forcedMask !== undefined && mask !== forcedMask) continue;
169
- const m = base.map((row, y) => row.map((v, x) => (fn[y][x] ? v : v !== MASKS[mask](x, y))));
170
- drawFormat(m, mask);
171
- const score = forcedMask !== undefined ? 0 : penalty(m);
172
- if (!best || score < best.score) best = { m, score };
173
- }
174
- return best.m;
175
- }
176
-
177
- // The QR code as terminal lines, two rows of modules per line. With colors it is drawn black on white whatever the
178
- // terminal's theme; without, it assumes a dark background (light modules are the drawn ones). Null when too long.
179
- export function qrLines(text, { color = true, quiet = 2 } = {}) {
180
- const m = qrMatrix(text);
181
- if (!m) return null;
182
- const n = m.length + quiet * 2;
183
- const dark = (x, y) => {
184
- const mx = x - quiet;
185
- const my = y - quiet;
186
- return mx >= 0 && my >= 0 && mx < m.length && my < m.length && m[my][mx];
187
- };
188
- const lines = [];
189
- for (let y = 0; y < n; y += 2) {
190
- let line = '';
191
- let last = null;
192
- for (let x = 0; x < n; x++) {
193
- const top = dark(x, y);
194
- const bottom = y + 1 < n && dark(x, y + 1);
195
- if (color) {
196
- const sgr = `\x1b[${top ? 30 : 97};${bottom ? 40 : 107}m`;
197
- if (sgr !== last) { line += sgr; last = sgr; }
198
- line += '▀';
199
- } else {
200
- line += !top && !bottom ? '█' : !top ? '▀' : !bottom ? '▄' : ' ';
201
- }
202
- }
203
- lines.push(color ? `${line}\x1b[0m` : line);
204
- }
205
- return lines;
206
- }