@yanzc/claude-pro 0.9.8 → 0.11.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
@@ -1,6 +1,6 @@
1
1
  # claude-pro — 完全访问的命令行编程 Agent
2
2
 
3
- `claude-pro` 是一个**自己实现**的终端 AI 编程助手:模型请求只通过 **codex-gateway** 发送。网关负责上游模型和账户计费,claude-pro 本地只保存网关登录得到的机器专用 key。
3
+ `claude-pro` 是一个**自己实现**的终端 AI 编程助手,**支持多家模型厂商**:用 `/connect` 接上 Anthropic、OpenAI、DeepSeek、Kimi、智谱、通义、OpenRouter、7bit.fun 网关或你自己的接口,各用各的 Key,可以同时连接多家、随时切换模型。7bit.fun 只是其中一家,额外提供余额、远程网页控制和跨电脑会话。
4
4
 
5
5
  最大的特点:**没有任何权限确认**。Bash 命令、文件读写、联网、MCP 工具,模型要用就直接执行,不弹窗、不问、没有 allow/deny 规则。它面向你自己的测试机器,目的是让模型的能力不被打断地发挥出来。作为补偿,每次文件修改都会做检查点,`/rewind` 可以撤销。
6
6
 
@@ -15,7 +15,7 @@
15
15
  ⎿ PASS
16
16
  ```
17
17
 
18
- > **认证**:只使用网关登录。`/login` 会在浏览器完成授权,再把本机专用 key 保存到 `~/.claude-pro/gateway.json`;模型请求和远程会话发布都只发往网关。
18
+ > **认证**:`/connect` 里粘贴各家的 API Key。7bit.fun 的 Key 保存在 `~/.claude-pro/gateway.json`,其他厂商的保存在 `~/.claude-pro/providers.json`。远程会话发布只在连接了 7bit.fun 时才有。
19
19
 
20
20
  ## 安装与运行
21
21
 
@@ -42,36 +42,72 @@ npm link # 注册全局命令 claude-pro,之后在任意项
42
42
 
43
43
  > 在 Git Bash 自带的 mintty 窗口里交互模式需要 `winpty claude-pro`;推荐在 Windows Terminal / PowerShell / cmd 中运行。
44
44
 
45
- ## 网关登录
45
+ ## 登录与供应商
46
46
 
47
- claude-pro 只支持 codex-gateway。交互式启动时如果没有网关登录,会自动打开浏览器;也可以手动运行:
47
+ 交互式启动时,如果还没有连接任何厂商,会自动打开 `/connect`;也可以手动运行:
48
48
 
49
49
  ```powershell
50
- claude-pro /login
50
+ claude-pro /connect
51
51
  claude-pro
52
52
  claude-pro --model opus
53
53
  claude-pro -p "用 Read 工具读取 package.json,告诉我项目版本"
54
54
  ```
55
55
 
56
- 登录得到的 key 保存在 `~/.claude-pro/gateway.json`(Windows 对应 `%USERPROFILE%\.claude-pro\gateway.json`),不会读取 Claude CLI 或 Codex CLI 的登录文件。
56
+ 网关的 key 保存在 `~/.claude-pro/gateway.json`(Windows 对应 `%USERPROFILE%\.claude-pro\gateway.json`),不会读取 Claude CLI 或 Codex CLI 的登录文件。
57
57
 
58
- ## /login:网关账户
58
+ ## 7bit.fun 网关
59
59
 
60
- `/login` 只有一个选项:网关。第一次登录会在浏览器打开网关授权页,授权后 claude-pro 用一次性 code 换取本机专用 API key。
60
+ 先登录 https://7bit.fun/user ,在「API 密钥」点「创建新密钥」,然后在 claude-pro 里运行 `/connect`,选第一项 **7bit.fun**,粘贴 Key。输入时只显示星号和长度;Key 先用 `GET /v1/account` 验证,通过后才保存,并显示账户名和余额。被拒绝时会显示网关的原话,可以再粘贴一次。已经连接时再选 7bit.fun,回车保留原来的 Key,或者粘贴新的替换。`/disconnect 7bit.fun` 忘掉网关 Key,这台电脑的会话随之从网关下线。
61
+
62
+ 2026-11-19 起没有 `/login`、`/logout` 命令,也不再用浏览器跳转授权(网关的 `/cli/login` 已停用)。之前保存的 Key 照常可用,不需要重新连接。
63
+
64
+ ## /connect:选择供应商
65
+
66
+ 和 OpenCode 的 `/connect` 一样:从列表里选一家,粘贴它的 API Key,就能用它的模型。**可以同时连接多家**,它们的模型都列在 `/model` 里,名字一律是 `厂商/模型`(如 `7bit/claude-opus-5-5`、`deepseek/deepseek-v4-pro`、`openrouter/anthropic/claude-sonnet-4.5`),随时切换。没连接的厂商不会出现在 `/model` 里。
67
+
68
+ - **默认模型跟随已连接的厂商**:设置里没有指定 `model` 时,连了提供 Claude 的厂商(7bit.fun 或 Anthropic)就用 `opus`,否则用第一个连接的厂商在 `/connect` 时选的模型。只连了 DeepSeek 的用户,启动后直接就是 DeepSeek 的模型。
69
+ - **`opus`、`sonnet`、`haiku` 是别名**:指向已连接的 Claude 厂商,两家都连了按 `/connect` 列表顺序取 7bit.fun;`7bit/opus` 固定指 7bit.fun 的。
70
+ - **兼容旧写法**:不带前缀的名字(`claude-opus-5-5`、`gpt-6.2-sol`)按 7bit.fun 的模型处理,旧设置和记住的选择照常可用。
71
+ - **断开时自动换模型**:`/disconnect` 了正在用的厂商,会换到仍连接着的厂商的默认模型。
72
+
73
+ | 供应商 | 协议 | 地址 |
74
+ |---|---|---|
75
+ | 7bit.fun | 网关 | 余额、远程网页、跨电脑会话都靠它 |
76
+ | Anthropic (Claude) | Anthropic | api.anthropic.com |
77
+ | OpenAI | OpenAI | api.openai.com/v1 |
78
+ | DeepSeek | Anthropic | api.deepseek.com/anthropic |
79
+ | Kimi (Moonshot) | Anthropic | api.moonshot.cn/anthropic |
80
+ | 智谱 GLM | Anthropic | open.bigmodel.cn/api/anthropic |
81
+ | MiniMax | Anthropic | api.minimaxi.com/anthropic |
82
+ | 通义千问(阿里云百炼) | Anthropic | dashscope.aliyuncs.com/apps/anthropic |
83
+ | OpenRouter | OpenAI | openrouter.ai/api/v1 |
84
+ | 硅基流动 | OpenAI | api.siliconflow.cn/v1 |
85
+ | 火山方舟 | OpenAI | ark.cn-beijing.volces.com/api/v3 |
86
+ | Google Gemini | OpenAI | generativelanguage.googleapis.com/v1beta/openai |
87
+ | xAI (Grok) | OpenAI | api.x.ai/v1 |
88
+ | Ollama(本机) | OpenAI | localhost:11434/v1,不需要 Key |
89
+ | 你自己的(Anthropic 兼容 / OpenAI 兼容) | 任选 | 自己填名字和地址:中转站、LM Studio、vLLM…… |
90
+
91
+ 同时有两种接口的供应商优先走 Anthropic 协议:思考过程、工具调用、图片都是原生的。OpenAI 协议由 claude-pro 在本地转换(`src/openai-chat.js`,移植自 codex-gateway):工具调用、图片、用量、`reasoning_content` 思考过程、推理强度(`/effort` → `reasoning_effort`)都会转换;提示词缓存标记和 Anthropic 的服务端工具不会发过去(WebSearch 会退回到抓取搜索页)。
92
+
93
+ 连接时的步骤:粘贴 Key(只显示星号)→ 用 Key 请求它的模型列表(自动识别 Key 放在 `x-api-key` 还是 `Authorization: Bearer`;被拒绝可以重新粘贴)→ 从列表里选要用的模型(或“继续用当前模型”)→ 给这个模型发一个很小的请求,确认协议、Key 和模型都对,才保存。模型的上下文窗口、输出上限和价格取自 [models.dev](https://models.dev)(OpenCode 用的模型目录,缓存一天),没有收录的模型按 200k 窗口算、不计价。
94
+
95
+ Key 保存在 `~/.claude-pro/providers.json`(只有你自己能读)。`/disconnect [供应商]` 忘掉它的 Key;正在用它的模型时会回到默认模型。余额、远程网页和跨电脑会话只跟 7bit.fun 的登录有关,和当前用哪家的模型无关。一段对话中途换到另一家的模型时,上一家的思考过程不会发给下一家(它无法验证别家的签名),换回去时又会带上。
61
96
 
62
97
  ```text
63
- /login
64
- /logout
65
- /cost
98
+ /connect 供应商列表(已连接的打 ✔)
99
+ /connect deepseek 直接连接某一家
100
+ /model deepseek/deepseek-v4-pro
101
+ /disconnect deepseek
66
102
  ```
67
103
 
68
- 网关地址默认是 `https://gw.predix.icu`,也可以通过 `CLAUDE_PRO_GATEWAY_URL` 修改。账户余额和用量在网关用户页查看。
104
+ 网关地址默认是 `https://7bit.fun`,也可以通过 `CLAUDE_PRO_GATEWAY_URL` 修改。旧地址 `https://gw.predix.icu` 是同一个网关:用它保存的登录和设置会自动按 7bit.fun 读取,不需要重新登录。账户余额和用量在网关用户页查看。
69
105
 
70
106
  ## 配置
71
107
 
72
- 网关 key 只来自 `/login`:登录后保存在 `~/.claude-pro/gateway.json`,不用手动填写,也没有环境变量或 `.env` 文件可以设置它(没有浏览器的机器可以把另一台登录过的电脑的 `gateway.json` 拷过去)。
108
+ 各家的 key 只来自 `/connect`(7bit.fun 的在 `~/.claude-pro/gateway.json`,其他厂商的在 `~/.claude-pro/providers.json`),没有环境变量或 `.env` 文件可以设置它们。
73
109
 
74
- 一般只需要 `/login`、`/model`、`/effort` 和 settings。五个普通设置直接写在 `settings.json` 顶层(下面也是默认值):
110
+ 一般只需要 `/connect`、`/model`、`/effort` 和 settings。五个普通设置直接写在 `settings.json` 顶层(下面也是默认值;`model` 不写时跟随已连接的厂商,见上面的 `/connect`):
75
111
 
76
112
  ```json
77
113
  {
@@ -92,12 +128,12 @@ claude-pro config list # 普通设置,含默认值
92
128
  claude-pro config set model sonnet
93
129
  claude-pro config set promptCacheTtl 1h
94
130
  claude-pro config list --advanced # 另外显示高级配置
95
- claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
131
+ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
96
132
  ```
97
133
 
98
134
  会话中 `/config` 默认只显示这五项,`/config advanced` 查看高级项;`/config set model sonnet` 等同于 CLI 的 `config set`。普通设置写顶层,高级设置写 `env`。`/config set/unset` 保留 `--project`、`--local`,分别修改项目共享设置或本地设置。`/model`、`/effort` 仍会记住选择;`--model`、`--effort` 可覆盖本次启动。
99
135
 
100
- 设置文件从低到高:`~/.claude-pro/settings.json`、项目 `.claude-pro/settings.json`、`.claude-pro/settings.local.json`。高级项仍兼容进程环境变量(高于设置文件),包括网关地址、远程会话、输出/thinking 预算、缓存总开关、保活、网络重试、工具路径、验证、自动记忆/话题标题和 Trace 开关;普通设置不从进程环境读取。旧 `settings.json.env` 中的 `CLAUDE_PRO_GATEWAY_MODEL`、`CLAUDE_CODE_EFFORT_LEVEL`、`CLAUDE_CODE_PROMPT_CACHE_TTL`、`CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL` 只作为兼容别名读取,同文件顶层新字段优先;用 `config set` 或 `/config set` 设置旧别名,会改写顶层新字段并移除同文件旧别名。provider 固定为 `gateway`,已删除 `--provider` 和 `CLAUDE_PRO_PROVIDER` 配置入口。
136
+ 设置文件从低到高:`~/.claude-pro/settings.json`、项目 `.claude-pro/settings.json`、`.claude-pro/settings.local.json`。高级项仍兼容进程环境变量(高于设置文件),包括网关地址、远程会话、输出/thinking 预算、缓存总开关、保活、网络重试、工具路径、验证、自动记忆/话题标题和 Trace 开关;普通设置不从进程环境读取。旧 `settings.json.env` 中的 `CLAUDE_PRO_GATEWAY_MODEL`、`CLAUDE_CODE_EFFORT_LEVEL`、`CLAUDE_CODE_PROMPT_CACHE_TTL`、`CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL` 只作为兼容别名读取,同文件顶层新字段优先;用 `config set` 或 `/config set` 设置旧别名,会改写顶层新字段并移除同文件旧别名。没有 `--provider` 或 `CLAUDE_PRO_PROVIDER` 配置:用哪家由模型名决定(`/model`、`--model deepseek/deepseek-v4-pro`、设置 `model`)。
101
137
 
102
138
  ## 系统提示词
103
139
 
@@ -150,9 +186,10 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
150
186
 
151
187
  ## 远程会话:在浏览器里查看和操作
152
188
 
153
- 本地手动启动的交互式 claude-pro 会话登录网关后自动注册。远程连接只由终端向 `CLAUDE_PRO_GATEWAY_URL` 发出站请求,终端不监听端口;网页经网关查看并操作已经在运行的本地终端会话(不能新建会话)。
189
+ 本地手动启动的交互式 claude-pro 会话登录网关后自动上线,但默认只用于会话之间互发任务;在会话里输入 `/rc`(或用 `claude-pro --rc` 启动)开启远程控制后,网页才能看到并操作它,`/rc off` 关闭。远程连接只由终端向 `CLAUDE_PRO_GATEWAY_URL` 发出站请求,终端不监听端口;网页经网关查看并操作已经在运行的本地终端会话(不能新建会话)。
154
190
 
155
- - **自动上线**:`/login` 成功后当前会话立即注册;之后每个交互会话启动时自动注册,断线自动重连;`/logout` 后停止远程连接。`CLAUDE_PRO_ONLINE=0` 可以关闭远程发布。
191
+ - **自动上线**:`/connect` 连上 7bit.fun 后当前会话立即注册;之后每个交互会话启动时自动注册,断线自动重连;`/disconnect 7bit.fun` 后停止远程连接。`CLAUDE_PRO_ONLINE=0` 可以关闭远程发布。
192
+ - **远程控制开关 `/rc`**:没开时不上传对话,网关只知道会话在线、名字、模型和是否在忙,网页列表里不显示它(只提示“另有 N 个未开启远程控制”),网页的指令也会被拒绝。开启后补发完整对话;关闭时网关清掉暂存的对话并断开正在看的网页。开关在会话重启(包括 `/cd`、更新)后保持,新会话默认关闭。输入框右上角在开启时显示 `⇄`。
156
193
  - **网页能看到**:会话列表、在线/离线/结束状态、模型、目录、机器名、viewer 数、transcript、流式文本和 thinking、工具调用与输出、todos、后台任务、排队消息、问题文本和连接状态。
157
194
  - **网页能做**:发消息(等同在终端输入框回车:`/命令`、`!shell`、`#记忆`、`@会话`,最多 6 张图片;忙时排队)、回答对话框(选项、多选、“其他”文字、文本框、取消)、停止(等同 Esc,同时取消等待中的问题)、切换 model/effort(发 `/model`、`/effort`)、浏览目录并 `/cd`(会话在新目录重启,网页接着看)、输入补全(`/命令`、`@文件`、`@会话`)、查看某次工具调用的完整输出(最多 1 MB,运行中的也行)。
158
195
  - **只读开关**:`CLAUDE_PRO_REMOTE_COMMANDS=0`(环境变量,或 `claude-pro config set CLAUDE_PRO_REMOTE_COMMANDS 0`)让这台电脑的会话在网页上只能看、不能操作;会话上线时读取,`/status` 会显示 read-only。
@@ -174,9 +211,20 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
174
211
  - 文件和会话同名时,行首 `@名字 任务` 按会话处理;要强制引用文件可写 `@./名字`。
175
212
  - **`@` 可以写在句子中间**:输入时在空格后面打 `@` 也会弹出文件和会话列表;在发给当前 agent 的消息里提到 `@名字`,agent 会被告知那是哪个会话、怎么联系它。文件引用仍会展开为文件内容。输入法打出全角 `&` 不再是会话语法。
176
213
  - **`/rename 新名字`**:给当前会话改名(比如 `/rename web-server`),别的会话从此用 `@web-server` 找它;这个名字也成为对话标题(终端标签页、`/resume` 列表、网页),不再自动按话题改;`/resume` 这个对话时名字一起回来。
177
- - **`/peers`**:列出本机和其他电脑上在线的会话。模型也能用 ListPeers / MessagePeer 工具自己找别的会话分派任务。
214
+ - **`/peers`**:列出本机、其他电脑和通讯录好友在线的会话。模型也能用 ListPeers / MessagePeer 工具自己找别的会话分派任务。
178
215
  - 回答会在对方这一轮做完后自动发回;对方正忙时,任务排在它当前工作之后。网关替离线的会话暂存回答(24 小时;网关重启会丢失还没送达的消息)。
179
- - **安全**:在线的会话能被同一网关账户执行任何任务。能登录这个账户、或持有它任一 API key 的人,都能在这些电脑上以完全权限执行命令。不需要时 `/logout`。
216
+ - **安全**:在线的会话能被同一网关账户执行任何任务。能登录这个账户、或持有它任一 API key 的人,都能在这些电脑上以完全权限执行命令。不需要时 `/disconnect 7bit.fun`。
217
+
218
+ ## 通讯录:和别人的会话互发任务
219
+
220
+ 不同网关账户之间,双方同意后,各自的 claude-pro 会话也能互发任务。
221
+
222
+ - **通讯号**:每个账户有一个公开的通讯号(默认随机,如 `cp7k3qxm`),别人用它加你,看不到你的邮箱。`/contacts handle 新名字` 或网页「远程控制 → 通讯录」里修改(3-20 个小写字母、数字、`_`、`-`,以字母开头)。
223
+ - **加好友**:`/contacts add 对方通讯号` 发出请求;对方在线的会话会提示,对方用 `/contacts accept 你的通讯号` 同意(也可以 `reject`、`block`),或在网页通讯录里点同意。双方互相请求时直接成为好友。`/contacts remove` 删除,`/contacts block` 拉黑(对方不能再请求、不能发任务,也不会被告知)。`/contacts` 列出全部。
224
+ - **发任务**:好友在线的会话在 `/peers` 和 ListPeers 里显示为 `@通讯号:电脑名/会话名`;`@通讯号 任务`(对方只开着一个会话时)或 `@通讯号:电脑名/会话名 任务` 发送,回答自动发回。
225
+ - **确认**:好友发来的任务默认在终端弹窗问你「执行 / 拒绝 / 以后都执行」,拒绝时对方会收到“已拒绝”。`/contacts trust 通讯号 auto` 让这个好友的任务直接执行,`confirm` 改回每条确认。交给模型时会注明这是外人的请求、不是用户的指令,并要求它不泄露密钥和私人文件、不做破坏性操作。
226
+ - **好友能看到什么**:只有你在线会话的名字、电脑名和是否在忙;看不到目录、标题和对话,发来的消息里也不带你的目录。
227
+ - **要求**:双方都要在 claude-pro 里 `/connect` 连上 7bit.fun(模型用别家也可以,这个 key 只用于通讯)。
180
228
 
181
229
  ## 完全访问与安全网
182
230
 
@@ -218,7 +266,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
218
266
 
219
267
  **`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件/会话补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
220
268
 
221
- **斜杠命令**:`/help` `/cd` `/rename` `/peers` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/trace` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit`,以及 `.claude/commands/*.md`、`.claude-pro/commands/*.md`、`~/.claude-pro/commands/*.md` 中的自定义命令(支持 `$ARGUMENTS`、`$1`、`` !`cmd` ``)。
269
+ **斜杠命令**:`/help` `/cd` `/rename` `/peers` `/contacts` `/rc` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/trace` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit`,以及 `.claude/commands/*.md`、`.claude-pro/commands/*.md`、`~/.claude-pro/commands/*.md` 中的自定义命令(支持 `$ARGUMENTS`、`$1`、`` !`cmd` ``)。
222
270
 
223
271
  **记忆**:自动读取 `~/.claude-pro/CLAUDE.md`、项目各级目录的 `CLAUDE.md` / `.claude/CLAUDE.md` / `CLAUDE.local.md`;某一级目录没有 `CLAUDE.md` 时读它的 `AGENTS.md` 代替(两者都有时通常是同一份说明,不重复发送)。
224
272
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.9.8",
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.",
3
+ "version": "0.11.0",
4
+ "description": "claude-pro: a command line coding agent for many model providers (Anthropic, OpenAI, DeepSeek, Kimi, GLM, Qwen, OpenRouter, the 7bit.fun gateway, your own endpoint...). Full access with no permission prompts; file edits are checkpointed and can be rewound.",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -13,6 +13,9 @@
13
13
  "coding-agent",
14
14
  "cli",
15
15
  "anthropic",
16
+ "openai",
17
+ "deepseek",
18
+ "multi-provider",
16
19
  "ai"
17
20
  ],
18
21
  "bin": {
package/src/agent.js CHANGED
@@ -349,6 +349,16 @@ export function repairToolResults(messages) {
349
349
  return { messages: out, changed, recovered };
350
350
  }
351
351
 
352
+ // The recovered tool calls (repairToolResults) worth a notice: those of the last assistant message, a turn cut off by a
353
+ // crash or a restart, once in a process (`said`). A call the conversation has gone on past was said when it was found
354
+ // and is repaired silently: the set of calls said is this process's, so every restart announced the same old one again
355
+ // (2026-11-20, a Browser call cut off a day before, kept through two compactions).
356
+ export function newlyRecovered(messages, recovered, said = new Set()) {
357
+ const last = messages.findLast((m) => m.role === 'assistant');
358
+ const lastIds = new Set(Array.isArray(last?.content) ? last.content.filter((b) => b.type === 'tool_use').map((b) => b.id) : []);
359
+ return recovered.filter((id) => lastIds.has(id) && !said.has(id));
360
+ }
361
+
352
362
  // Minimal JSON-schema check for required fields and primitive types.
353
363
  function validateInput(schema, input) {
354
364
  if (!schema || typeof input !== 'object' || input === null) return 'Input must be an object';
@@ -931,7 +941,7 @@ export class Agent {
931
941
  const tool = { name: 'Verify', summarize: () => command };
932
942
  const input = { command, timeout: this.config.bashMaxTimeout };
933
943
  const handle = this.io.toolStart?.({ id: `verify_${Date.now()}`, name: 'Verify', input }, tool, input, this) || {};
934
- const ctx = { ...this.makeCtx(signal), cwd: this.projectRoot, setCwd() {} };
944
+ const ctx = { ...this.makeCtx(signal), cwd: this.projectRoot };
935
945
  ctx.onProgress = (p, meta) => handle.progress?.(p, meta);
936
946
  let result;
937
947
  try {
@@ -966,7 +976,7 @@ export class Agent {
966
976
  // the conversation merged and inserted messages, which moved the messages the checkpoints point at, so a
967
977
  // /rewind after a restart cut the conversation in the wrong place.
968
978
  const repaired = repairToolResults(normalizeMessages(this.messages));
969
- const fresh = repaired.recovered.filter((id) => !this.recoveredToolIds.has(id));
979
+ const fresh = newlyRecovered(this.messages, repaired.recovered, this.recoveredToolIds);
970
980
  if (fresh.length) {
971
981
  for (const id of fresh) this.recoveredToolIds.add(id);
972
982
  this.io.notice?.('Recovered an unfinished tool call in the conversation; continuing with an interrupted result.', 'warn');
@@ -1017,7 +1027,6 @@ export class Agent {
1017
1027
  const agent = this;
1018
1028
  return {
1019
1029
  get cwd() { return agent.cwd; },
1020
- setCwd(dir) { agent.cwd = dir; },
1021
1030
  projectRoot: this.projectRoot,
1022
1031
  config: this.config,
1023
1032
  signal,
package/src/api.js CHANGED
@@ -6,32 +6,52 @@ let Anthropic = null;
6
6
  import { parseRateLimit, parseRetryAfter, planRetry, sleepUntil, timing } from './ratelimit.js';
7
7
  import { cacheControl, cachePlanOf, fingerprint } from './cache.js';
8
8
  import { gatewayLogin, loadGatewayModels, cachedGatewayModel, gatewayEffort, gatewayDefaultEffort, nearestEffort } from './gateway.js';
9
+ import { GATEWAY_PROVIDER, providerEndpoint, priceCost } from './providers.js';
10
+ import { chatFetch } from './openai-chat.js';
9
11
  import { fitImagesIn } from './utils/images.js';
10
12
  import { costOf } from './pricing.js';
11
13
 
12
- let cached = null;
13
14
  const SIGNATURE_PREFIX = 'cgw1:';
14
15
 
15
- // The gateway provider's key, from /login. Without one the request fails the way a refused key does.
16
- function gatewayKey(config) {
17
- const key = gatewayLogin(config.gatewayUrl)?.apiKey;
18
- if (!key) throw new APIError(`Not logged in to the gateway ${config.gatewayUrl}. Run /login and choose the gateway.`, { status: 401, retryable: false });
19
- return key;
16
+ // The provider a model is served by: the gateway's for a model without one (and for a bare id).
17
+ const providerOf = (model) => (model && typeof model === 'object' && model.provider) || GATEWAY_PROVIDER;
18
+ // A model as the per-model memories below know it: the same id at two providers is two models.
19
+ const keyOf = (model) => `${providerOf(model)}|${typeof model === 'string' ? model : model?.id}`;
20
+
21
+ // Where a model's requests go and with what key: the gateway (its key from /connect, as a bearer token), or a provider
22
+ // connected with /connect (see providers.js). Without one the request fails the way a refused key does.
23
+ function endpointFor(config, model) {
24
+ const provider = providerOf(model);
25
+ if (provider === GATEWAY_PROVIDER) {
26
+ const key = gatewayLogin(config.gatewayUrl)?.apiKey;
27
+ if (!key) throw new APIError(`7bit.fun is not connected (its models: 7bit/…). Run /connect 7bit.fun, or /model for another provider's model.`, { status: 401, retryable: false });
28
+ return { provider, name: '7bit.fun', protocol: 'anthropic', baseURL: config.gatewayUrl, key, bearer: true };
29
+ }
30
+ try {
31
+ return providerEndpoint(provider);
32
+ } catch (e) {
33
+ throw new APIError(e.message, { status: 401, retryable: false });
34
+ }
20
35
  }
21
36
 
22
- export async function getClient(config) {
37
+ // One client per endpoint and key, kept while they stay the same. A Chat Completions provider gets a fetch that
38
+ // translates (see openai-chat.js); the SDK above it does not know.
39
+ const clients = new Map();
40
+ export async function getClient(config, model = config.model) {
23
41
  Anthropic ??= (await import('@anthropic-ai/sdk')).default;
24
- const authToken = gatewayKey(config);
25
- const key = `${config.gatewayUrl}|${authToken}|${config.apiTimeout}`;
26
- if (cached?.key === key && cached.fetch === globalThis.fetch) return cached.client;
42
+ const ep = endpointFor(config, model);
43
+ const key = `${ep.provider}|${ep.protocol}|${ep.baseURL}|${ep.bearer}|${ep.key}|${config.apiTimeout}`;
44
+ const kept = clients.get(ep.provider);
45
+ if (kept?.key === key && kept.fetch === globalThis.fetch) return kept.client;
46
+ // (null, not left out: the SDK would take the other one from ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN)
27
47
  const client = new Anthropic({
28
- baseURL: config.gatewayUrl,
29
- authToken,
30
- apiKey: null,
48
+ baseURL: ep.baseURL,
49
+ ...(ep.bearer ? { authToken: ep.key, apiKey: null } : { apiKey: ep.key, authToken: null }),
50
+ ...(ep.protocol === 'openai' ? { fetch: chatFetch(ep) } : {}),
31
51
  timeout: config.apiTimeout,
32
52
  maxRetries: 0,
33
53
  });
34
- cached = { key, client, fetch: globalThis.fetch };
54
+ clients.set(ep.provider, { key, client, fetch: globalThis.fetch });
35
55
  return client;
36
56
  }
37
57
 
@@ -58,7 +78,7 @@ function withCacheControl(messages, mark) {
58
78
  // errors. Claude Code carries on without the marker instead of failing the request, and so does this: the
59
79
  // marker is left off from then on, so the endpoint is not asked the same thing again.
60
80
  const cacheRefused = new Map();
61
- const cacheKey = (config, modelId) => `${config.gatewayUrl}|${modelId}`;
81
+ const cacheKey = (config, model) => `${providerOf(model) === GATEWAY_PROVIDER ? config.gatewayUrl : providerOf(model)}|${keyOf(model)}`;
62
82
 
63
83
  const PLACES = ['system', 'tools', 'messages'];
64
84
  const blocksAt = (params, place) => {
@@ -69,8 +89,8 @@ const blocksAt = (params, place) => {
69
89
  const hasMark = (params, place) => blocksAt(params, place).some((b) => b.cache_control);
70
90
 
71
91
  // What an endpoint has refused so far, for /status: the places (system, tools, messages) and "ttl".
72
- export function cacheRefusals(config, modelId) {
73
- return [...(cacheRefused.get(cacheKey(config, modelId)) || [])];
92
+ export function cacheRefusals(config, model) {
93
+ return [...(cacheRefused.get(cacheKey(config, model)) || [])];
74
94
  }
75
95
 
76
96
  // Take cache_control (or only its ttl) off a request after the endpoint refused it. Returns what was taken off
@@ -109,7 +129,7 @@ const thinkingStaysOn = new Set();
109
129
 
110
130
  // The effort a model uses when none is sent (docs.claude.com, "Effort"): medium on Opus 5.5 and Haiku 5.5, high on
111
131
  // the other models that take one; null for a model that takes none or is not known.
112
- const gatewayModelInfo = (config, id) => cachedGatewayModel(gatewayLogin(config.gatewayUrl), id);
132
+ const gatewayModelInfo = (config, id) => (config ? cachedGatewayModel(gatewayLogin(config.gatewayUrl), id) : null);
113
133
  export function defaultEffort(modelId, config = null) {
114
134
  const id = String(modelId || '');
115
135
  if (!effortSupported(id)) return null;
@@ -155,15 +175,23 @@ export function parseMaxTokensLimit(message) {
155
175
  // budget is set; such a turn's requests leave `thinking` out until the next prompt. That is no thinking on older
156
176
  // models and adaptive thinking on those that cannot turn it off (Opus 5.5, Fable, Sonnet 5.5 refuse "disabled"),
157
177
  // which takes assistant messages without thinking.
178
+ //
179
+ // The same holds between providers: a provider cannot verify another's thinking, so each thinking block keeps the
180
+ // provider it came from (`origin`, set in streamMessage; none on a block from before 2026-11-19: the gateway's), and goes
181
+ // back to that provider alone. `origin` itself is never sent.
158
182
  const isCodexThinking = (b) => b?.type === 'thinking' && typeof b.signature === 'string' && b.signature.startsWith(SIGNATURE_PREFIX);
183
+ const isThinking = (b) => b?.type === 'thinking' || b?.type === 'redacted_thinking';
159
184
  const isPrompt = (m) => m.role === 'user' && !(Array.isArray(m.content) && m.content.some((b) => b.type === 'tool_result'));
160
- function withoutCodexThinking(messages) {
185
+ const withoutOrigin = (b) => { const { origin, ...rest } = b; return rest; };
186
+ function withoutForeignThinking(messages, provider, toCodex) {
187
+ const foreign = (b) => isThinking(b) && ((b.origin || GATEWAY_PROVIDER) !== provider || (!toCodex && isCodexThinking(b)));
161
188
  const prompt = messages.findLastIndex(isPrompt);
162
189
  let inTurn = false;
163
190
  const out = messages.flatMap((m, i) => {
164
- if (m.role !== 'assistant' || !Array.isArray(m.content) || !m.content.some(isCodexThinking)) return [m];
165
- if (i > prompt) inTurn = true;
166
- const content = m.content.filter((b) => !isCodexThinking(b));
191
+ if (m.role !== 'assistant' || !Array.isArray(m.content)) return [m];
192
+ if (!m.content.some((b) => foreign(b) || (b && 'origin' in b))) return [m];
193
+ if (i > prompt && m.content.some(foreign)) inTurn = true;
194
+ const content = m.content.filter((b) => !foreign(b)).map(withoutOrigin);
167
195
  return content.length ? [{ ...m, content }] : [];
168
196
  });
169
197
  return { messages: out, inTurn };
@@ -173,19 +201,21 @@ function withoutCodexThinking(messages) {
173
201
  // for sub-agents, compaction and side queries (see Config.cacheTtl). `cacheMessages: false` leaves the messages
174
202
  // unmarked: for a request whose messages are never sent twice, writing them to the cache only costs more.
175
203
  export function buildParams(config, { model, system, messages, tools, maxTokens, effort, cacheBucket = 'main', cacheMessages = true }) {
176
- const wanted = maxTokens || config.maxOutputTokens;
177
- const refused = cacheRefused.get(cacheKey(config, model.id));
204
+ // (a provider model's own limit, from models.dev, when it is lower than the default)
205
+ const wanted = maxTokens || (model.maxOutput ? Math.min(model.maxOutput, config.maxOutputTokens) : config.maxOutputTokens);
206
+ const refused = cacheRefused.get(cacheKey(config, model));
178
207
  const caching = !config.promptCachingDisabled();
179
208
  const ttl = refused?.has('ttl') ? '5m' : config.cacheTtl(cacheBucket);
180
209
  const mark = (place) => (caching && !refused?.has(place) ? { ...cacheControl(ttl) } : null);
181
210
  const systemMark = mark('system');
182
211
  // GPT models are handled by the gateway's Codex backend.
183
- const toCodex = /^gpt-/i.test(model.id);
212
+ const provider = providerOf(model);
213
+ const toCodex = provider === GATEWAY_PROVIDER && /^gpt-/i.test(model.id);
184
214
  let turnLostThinking = false;
185
- if (!toCodex) ({ messages, inTurn: turnLostThinking } = withoutCodexThinking(messages));
215
+ ({ messages, inTurn: turnLostThinking } = withoutForeignThinking(messages, provider, toCodex));
186
216
  const params = {
187
217
  model: model.id,
188
- max_tokens: outputCaps.has(model.id) ? Math.min(wanted, outputCaps.get(model.id)) : wanted,
218
+ max_tokens: outputCaps.has(keyOf(model)) ? Math.min(wanted, outputCaps.get(keyOf(model))) : wanted,
189
219
  // An empty system prompt (an empty profile chosen with /prompts) is left out: Anthropic refuses an empty text
190
220
  // block ("cache_control cannot be set for empty text blocks"), and DeepSeek and the others take none as well.
191
221
  ...(typeof system === 'string' && system.trim() ? { system: [{ type: 'text', text: system, ...(systemMark ? { cache_control: systemMark } : {}) }] } : {}),
@@ -197,7 +227,7 @@ export function buildParams(config, { model, system, messages, tools, maxTokens,
197
227
  params.tools = tools.map((t, i) => (i === tools.length - 1 && toolMark ? { ...t, cache_control: toolMark } : t));
198
228
  }
199
229
  // A GPT model with no effort set gets its default from the gateway's model metadata.
200
- const eff = effortToSend(config, model.id, (effort === undefined ? config.effort : effort) || (/^gpt-/i.test(model.id) ? defaultEffort(model.id, config) : null));
230
+ const eff = effortToSend(config, model.id, (effort === undefined ? config.effort : effort) || (toCodex ? defaultEffort(model.id, config) : null));
201
231
  if (eff && !noEffort.has(model.id)) params.output_config = { effort: eff };
202
232
  const budget = config.thinkingBudget;
203
233
  if (budget === 0 && !thinkingStaysOn.has(model.id)) params.thinking = { type: 'disabled' };
@@ -221,14 +251,15 @@ export class APIError extends Error {
221
251
  }
222
252
  }
223
253
 
224
- function describeError(err, config) {
254
+ function describeError(err, config, ep = null) {
225
255
  if (err?.name === 'AbortError' || (Anthropic && err instanceof Anthropic.APIUserAbortError)) return err;
226
256
  const status = err?.status;
227
257
  let msg = err?.error?.error?.message || err?.error?.message || err?.message || String(err);
228
258
  const promptTooLong = /prompt is too long|context length|maximum context|too many tokens|context_length_exceeded|exceeds the context window/i.test(msg);
229
259
  if (err instanceof APIError) return err;
230
- if (status === 401) msg = `The gateway refused the login (401). Run /login to log in again. ${msg}`;
231
- if (status === 402) msg = `The gateway account's balance is too low for this request. Top up at ${config.gatewayUrl}/user (or run /login to check the balance). ${msg}`;
260
+ const gateway = !ep || ep.provider === GATEWAY_PROVIDER;
261
+ if (status === 401) msg = gateway ? `The gateway refused the key (401). Run /connect 7bit.fun to enter another. ${msg}` : `${ep.name} refused the key (401). Run /connect ${ep.provider} to enter it again. ${msg}`;
262
+ if (status === 402 && gateway) msg = `The gateway account's balance is too low for this request. Top up at ${config.gatewayUrl}/user (/cost shows the balance). ${msg}`;
232
263
  // A prompt over the window fails the same way every time, so it is not retried: the agent compacts at once. Through
233
264
  // the gateway a GPT overflow comes in the stream, without a 4xx: "Your input exceeds the context window of this
234
265
  // model. ... (context_length_exceeded)", and was sent 6 more times, with the waits in between, before compacting.
@@ -247,8 +278,9 @@ export function isAbort(err) {
247
278
 
248
279
  // USD for a request at the list prices (see pricing.js), by the model that answered, else the one asked for;
249
280
  // null when neither has a price. A cost goes to config.onCost.
250
- function charge(config, requested, served, usage) {
251
- const cost = costOf(served, usage) ?? costOf(requested, usage);
281
+ function charge(config, requested, served, usage, model = null) {
282
+ // A provider's model at the price models.dev gives it; the gateway's (and a Claude model anywhere) at pricing.js's.
283
+ const cost = (model?.price ? priceCost(model.price, usage) : null) ?? costOf(served, usage) ?? costOf(requested, usage);
252
284
  if (cost > 0) config.onCost?.(cost);
253
285
  return cost;
254
286
  }
@@ -277,13 +309,16 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
277
309
  // Load gateway model metadata before the synchronous parameter builder; the cache is keyed by gateway and key,
278
310
  // so changing accounts or gateway URLs cannot leak a model's effort levels into another context. A gateway that
279
311
  // does not answer costs at most a few seconds once (see fetchGatewayModels), not the request.
280
- await loadGatewayModels(config, signal);
312
+ if (providerOf(request.model) === GATEWAY_PROVIDER) await loadGatewayModels(config, signal);
281
313
  if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
282
- const client = await getClient(config);
314
+ // The provider of the request's model: another one after a pause when the user chose another model (afterPause).
315
+ let ep = endpointFor(config, request.model);
316
+ let client = await getClient(config, request.model);
283
317
  let params = buildParams(config, request);
284
318
  // The gateway keeps a conversation on the upstream account that served it, where its prompt cache is; the
285
- // session id names the conversation, in the header Claude Code sends it in.
286
- const options = { signal, ...(config.sessionId ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) };
319
+ // session id names the conversation, in the header Claude Code sends it in. (The gateway's business alone.)
320
+ const optionsFor = (e) => ({ signal, ...(config.sessionId && e.provider === GATEWAY_PROVIDER ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) });
321
+ let options = optionsFor(ep);
287
322
  let imagesFitted = false;
288
323
  const refused = new Set(); // what the endpoint refused for this request: remembered once a request got through
289
324
  const retryState = { attempt: 0, rateLimitHits: 0, waitedMs: 0, overloaded: 0, overloadedWaitMs: 0 };
@@ -320,6 +355,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
320
355
  if (b.type === 'tool_use' || b.type === 'server_tool_use') { b.input = {}; jsonBufs[ev.index] = ''; }
321
356
  if (b.type === 'text') b.text = b.text || '';
322
357
  if (b.type === 'thinking') { b.thinking = b.thinking || ''; b.signature = b.signature || ''; }
358
+ if (isThinking(b)) b.origin = ep.provider; // it goes back to this provider alone (see withoutForeignThinking)
323
359
  blocks[ev.index] = b;
324
360
  emitted = true;
325
361
  onEvent({ type: 'block_start', index: ev.index, block: b });
@@ -367,10 +403,10 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
367
403
  if (!stopped && !stopReason) throw Object.assign(new Error('The response stream ended unexpectedly'), { status: 503 });
368
404
  const content = blocks.filter(Boolean).filter((b) => !(b.type === 'text' && !b.text));
369
405
  if (refused.size) { // it got through without what the endpoint refused: leave that off from now on
370
- const key = cacheKey(config, params.model);
406
+ const key = cacheKey(config, request.model);
371
407
  cacheRefused.set(key, new Set([...(cacheRefused.get(key) || []), ...refused]));
372
408
  }
373
- const cost = charge(config, params.model, model, usage);
409
+ const cost = charge(config, params.model, model, usage, request.model);
374
410
  return { message: { role: 'assistant', content }, usage, stopReason, model, cost, cache: { ...cachePlanOf(params), fingerprint: fingerprint(params), at: startedAt } };
375
411
  } catch (raw) {
376
412
  // A reply cut off (interrupted, or failed on the way: a stream error, a stream that ended early) is billed for
@@ -379,14 +415,14 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
379
415
  const chargeCut = () => {
380
416
  if (usage.input_tokens == null) return;
381
417
  const written = blocks.reduce((n, b) => n + (b?.text?.length || 0) + (b?.thinking?.length || 0), 0) + jsonBufs.join('').length;
382
- charge(config, params.model, model, { ...usage, output_tokens: Math.max(usage.output_tokens || 0, Math.ceil(written / 4)) });
418
+ charge(config, params.model, model, { ...usage, output_tokens: Math.max(usage.output_tokens || 0, Math.ceil(written / 4)) }, request.model);
383
419
  };
384
420
  if (signal?.aborted || isAbort(raw)) {
385
421
  chargeCut();
386
422
  throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: raw?.partial || [] });
387
423
  }
388
424
  chargeCut();
389
- const err = describeError(raw, config);
425
+ const err = describeError(raw, config, ep);
390
426
  // Not every model takes an effort level. Leave it out for this one, and for the rest of the session.
391
427
  if (err.status === 400 && params.output_config && /does not support the effort parameter/i.test(err.message)) {
392
428
  noEffort.add(params.model);
@@ -421,7 +457,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
421
457
  // The default max_tokens is generous: if this API allows less, learn its limit and retry at once.
422
458
  const limit = err.status === 400 ? parseMaxTokensLimit(err.message) : null;
423
459
  if (limit && limit < params.max_tokens) {
424
- outputCaps.set(params.model, limit);
460
+ outputCaps.set(keyOf(request.model), limit);
425
461
  params.max_tokens = limit;
426
462
  if (params.thinking?.budget_tokens) params.thinking.budget_tokens = Math.min(params.thinking.budget_tokens, limit - 1);
427
463
  continue;
@@ -449,7 +485,13 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
449
485
  }
450
486
  retryState.attempt = 0; // the pause is a fresh start: quick retries made before it do not count after it
451
487
  const next = afterPause?.({ woken });
452
- if (next) params = buildParams(config, next);
488
+ if (next) {
489
+ request = next;
490
+ ep = endpointFor(config, request.model);
491
+ client = await getClient(config, request.model);
492
+ options = optionsFor(ep);
493
+ params = buildParams(config, next);
494
+ }
453
495
  } else {
454
496
  onEvent({ type: 'retry', attempt: plan.attempt, error: err, delayMs: plan.delayMs, maxRetries: plan.maxRetries });
455
497
  await sleepUntil(plan.resumeAt, signal);
@@ -866,7 +866,17 @@ class BrowserSession {
866
866
  const fn = isFn ? `function() { return (${script})(this); }` : `function() { return (${script}); }`;
867
867
  r = await this.untilDialog(tab, this.send(tab, 'Runtime.callFunctionOn', { objectId, functionDeclaration: fn, returnByValue: true, awaitPromise: true, userGesture: true }, { timeoutMs: browserLimits.evalMs }));
868
868
  } else {
869
- r = await this.untilDialog(tab, this.send(tab, 'Runtime.evaluate', { expression: isFn ? `(${script})()` : script, returnByValue: true, awaitPromise: true, userGesture: true, replMode: !isFn }, { timeoutMs: browserLimits.evalMs }));
869
+ r = await this.untilDialog(tab, this.send(tab, 'Runtime.evaluate', { expression: isFn ? `(${script})()` : script, returnByValue: !!isFn, awaitPromise: true, userGesture: true, replMode: !isFn }, { timeoutMs: browserLimits.evalMs }));
870
+ // REPL mode waits for the statements, not for a promise they end with (fetch(…).then(…)): that one is
871
+ // awaited here, and an object result is read by value afterwards
872
+ const objectId = !isFn && !r?.exceptionDetails ? r?.result?.objectId : null;
873
+ if (objectId) {
874
+ const read = r.result.subtype === 'promise'
875
+ ? this.send(tab, 'Runtime.awaitPromise', { promiseObjectId: objectId, returnByValue: true }, { timeoutMs: browserLimits.evalMs })
876
+ : this.send(tab, 'Runtime.callFunctionOn', { objectId, functionDeclaration: 'function() { return this; }', returnByValue: true }, { timeoutMs: browserLimits.evalMs });
877
+ r = await this.untilDialog(tab, read);
878
+ this.send(tab, 'Runtime.releaseObject', { objectId }).catch(() => {});
879
+ }
870
880
  }
871
881
  if (!r) return `(no value yet: the script opened ${tab.dialog?.type === 'alert' ? 'an' : 'a'} ${tab.dialog?.type || ''} dialog, ${JSON.stringify(tab.dialog?.message ?? '')}; answer it with dialog)`;
872
882
  if (r.exceptionDetails) throw new BrowserError(`the script threw: ${exceptionText(r.exceptionDetails)}`);