基于哈雷彗星大佬 原帖 #1991311 的优化版。原方案用 AST 补丁改 cli.js,每次 Claude Code 升级都得重打;本版不动 Claude Code 本体,外挂一个本地反向代理,Claude Code 升级自动生效,还顺带兼容 v2.1.116+ 新的请求形态。
问题回顾(两种形态)
Claude Code 的 SubAgent 请求在不同版本里,发给 AnyRouter 的 thinking 字段有两种错配形态,AnyRouter(new-api 后端)对 Haiku / Opus 4.7 [1M] / Sonnet 4.6 这些 reasoning 模型都会 500(nil pointer dereference):
-
v2.1.112 ~ v2.1.115:cli.js 里 SubAgent 启动器
_u把 thinking 硬编码为{type:"disabled"}:thinkingConfig: D ? _.options.thinkingConfig : { type: "disabled" }D = useExactTools只有 Fork agent 为 true,所有带subagent_type的 SubAgent 永远走 disabled 分支。 -
v2.1.116+:SubAgent 请求完全不带 thinking 字段(
thinking absent)。但 AnyRouter 对 Haiku 仍要求 thinking 字段存在 —— 缺失就直接 crash。
AST 补丁只修得了第一种(而且每次升级要重打),新版本格式变了就匹配不到。
新思路:本地代理拦截改写
claude → 127.0.0.1:8787 (proxy) → https://anyrouter.top
│
└─ thinking 缺失 / null / disabled 都按模型归一化补上
重写规则(对齐 Claude Code 内部 API 层的归一化逻辑):
模型 改写为opus-4-[67] / sonnet-4-6
{type:"adaptive"}
claude-3-*
删除 thinking(legacy 模型不支持)
其它(Haiku 4.x / Sonnet 4-5)
{type:"enabled", budget_tokens: min(31999, max_tokens-1)}
关键:不只改 thinking 字段。启用 thinking 时还得一并归一化:
temperature强设为1(扩展 thinking 硬性要求)- 删除
top_p/top_k(扩展 thinking 不支持) - 兜底
max_tokens > budget_tokens - 注入
interleaved-thinking-2025-05-14到anthropic-beta头(SubAgent 几乎都会tool_use,thinking 和 tool_use 共存需要这个 beta)
我一开始没做这一步,结果 new-api 因参数冲突继续 nil pointer。加上之后就好了。
架构(三个文件)
~/.anyrouter/
├── anyrouter-launch.sh ← 启动逻辑(起 proxy / 注入 env / 调 claude / 退出清理)
└── anyrouter-proxy.js ← Node 反向代理(无 npm 依赖)
~/.zshrc
└── claude-anyrouter() ← 极简入口函数,source 启动脚本
安装(三步)
- 放两个脚本到
~/.anyrouter/:
mkdir -p ~/.anyrouter
cp anyrouter-launch.sh anyrouter-proxy.js ~/.anyrouter/
~/.zshrc末尾加入函数:
function claude-anyrouter() {
local API_KEY="sk-xxxxxxxxx" # 填你的 AnyRouter Key
local ANYROUTER_DIR="$HOME/.anyrouter"
source "$ANYROUTER_DIR/anyrouter-launch.sh"
}
- 新开终端:
claude-anyrouter # 启动
claude-anyrouter --continue # 参数透传给 claude
几个关键优势
- Claude Code 升级自动生效,不用重打补丁
- 兼容 v2.1.112 ~ v2.1.116+ 两种 thinking 形态
- 与原生
claude共存:只有claude-anyrouter走代理 /exit/ Ctrl+C / 关终端 都会 trap 清理 proxy,无残留- 纯 Node 内置模块 +
nc,macOS / Linux 开箱即用 - 上游 ≥400 会 dump 完整 OUTBOUND body + UPSTREAM resp 进日志,debug 不抓瞎
- 改
UPSTREAM_URL即可切换到任何 Anthropic 兼容网关
与 AST 补丁方案对比
AST 改 cli.js 本方案(本地代理) 修改位置cli.js 源码
无,外挂代理
Claude Code 升级后
需重打
自动生效
兼容新版(thinking absent)
claude 调用
只影响 claude-anyrouter
依赖
需 acorn 解析器
Node 内置 + nc
可与原生 claude 共存
完整代码与文档
完整源码 (12.9 KB)
文件夹里包含三个文件的完整实现,以及 12 节的 README(配置项 / 调试 / 常见问题 / 卸载等)。
再次感谢 @哈雷彗星 定位问题 + 给出 AST 补丁方案,本帖只是把思路换到代理层做零侵入,并顺手把 v2.1.116+ 的新形态也处理了。
1 个帖子 - 1 位参与者